示例#1
0
void my::GateServer::on_http_req(http::Connection* connPtr, Json::Value& reqJson)
{
	//proto 和 player_id可夹带在header中带过来   
	//如何判断是gm后台的请求还是玩家请求!remote_ip?加密?session_id
	int protoId = 0;
	int playerId = 0;
	try 
	{
		protoId = boost::lexical_cast<int, std::string>(reqJson["proto"].asString());
		playerId = boost::lexical_cast<int, std::string>(reqJson["playerId"].asString());
	}
	catch (std::exception& e)
	{
		LogE << "caught exception:" << e.what() << LogEnd;
	}
	
	LogW << "playerId:" << playerId << LogEnd;
	NetMessage msg;
	msg.setProto(protoId);
	msg.setNetId(connPtr->get_connection_id());
	msg.setPlayerId(playerId);
	reqJson.removeMember("proto");
	reqJson.removeMember("player_id");
	std::string msgStr = reqJson.toStyledString();
	LogW << msgStr << LogEnd;
	msg.setMessage(msgStr);
	m_pGameConn->sendMessage(msg);
}
示例#2
0
void SignalingWebSocketPeer::sendLocalSDP(std::string type, std::string sdp) {
	Json::StyledWriter writer;
	Json::Value message;

	message["type"] = type;

	if(sdp.length() > 800) {
		for(int i=0; i<sdp.length(); i+=800) {
			int n = MIN(sdp.length()-i+1,800);
			message["sdpPartial"] = sdp.substr(i, n);

			std::string msg = writer.write(message);
			send(msg.c_str());
		}
		message.removeMember("sdpPartial");
		message["endSdp"] = "yes";
		std::string msg = writer.write(message);
		send(msg.c_str());
	}
	else {
		message["sdp"] = sdp;
		std::string msg = writer.write(message);
		send(msg.c_str());
	}
}
示例#3
0
std::vector<Stage *> PipelineReaderJSON::extractInputs(Json::Value& node,
    TagMap& tags)
{
    std::vector<Stage *> inputs;
    std::string filename;

    if (node.isMember("inputs"))
    {
        Json::Value& val = node["inputs"];
        if (val.isString())
            handleInputTag(val.asString(), tags, inputs);
        else if (val.isArray())
        {
            for (const Json::Value& input : node["inputs"])
            {
                if (!input.isString())
                    throw pdal_error("JSON pipeline: 'inputs' tag must "
                            " be specified as a string or array of strings.");
                handleInputTag(input.asString(), tags, inputs);
            }
        }
        else
            throw pdal_error("JSON pipeline: 'inputs' tag must "
                    " be specified as a string or array of strings.");
        node.removeMember("inputs");
        if (node.isMember("inputs"))
            throw pdal_error("JSON pipeline: found duplicate 'inputs' "
               "entry in stage definition.");
    }
    return inputs;
}
/***************************
 * get stream by id
 * on a specific port 
 * 
 **************************/
trex_rpc_cmd_rc_e
TrexRpcCmdGetStream::_run(const Json::Value &params, Json::Value &result) {

    uint8_t port_id = parse_port(params, result);
    TrexStatelessPort *port = get_stateless_obj()->get_port_by_id(port_id);

    bool     get_pkt   = parse_bool(params, "get_pkt", result);
    uint32_t stream_id = parse_int(params, "stream_id", result);

    TrexStream *stream = port->get_stream_by_id(stream_id);

    if (!stream) {
        std::stringstream ss;
        ss << "stream id " << stream_id << " on port " << (int)port_id << " does not exists";
        generate_execute_err(result, ss.str());
    }

    /* return the stored stream json (instead of decoding it all over again) */
    Json::Value j = stream->get_stream_json();
    if (!get_pkt) {
        j.removeMember("packet");
    }

    result["result"]["stream"] = j;

    return (TREX_RPC_CMD_OK);

}
示例#5
0
//Makes a JSON file that contains only the fieldnames and their corresponding bubble counts.
bool MarkupForm::outputFieldCounts(const char* bubbleVals, const char* outputPath){
	return false; //I don't think this gets used.
	Json::Value bvRoot;
	
	if( !parseJsonFromFile(bubbleVals, bvRoot) ) return false;
	
	Json::Value fields = bvRoot["fields"];
	for ( size_t i = 0; i < fields.size(); i++ ) {

		Json::Value field = fields[i];
		Json::Value segments = field["segments"];
		int counter = 0;
		for ( size_t j = 0; j < segments.size(); j++ ) {
			
			Json::Value segment = segments[j];
			const Json::Value bubbles = segment["bubbles"];
			
			for ( size_t k = 0; k < bubbles.size(); k++ ) {
				const Json::Value bubble = bubbles[k];
				if(bubble["value"].asBool()){
					counter++;
				}
			}
		}
		field["count"] = counter;
		field.removeMember("segments");
	}
	
	ofstream outfile(outputPath, ios::out | ios::binary);
	outfile << bvRoot;
	outfile.close();
	return true;
}
Json::Value MongoDbAdapter::GetSchemaCollection()
{
	mongocxx::instance inst{};
	mongocxx::client conn{mongocxx::uri{}};
	bsoncxx::stdx::string_view dbName("StorageTestDB");

	mongocxx::database database = conn[dbName];

	auto cursor = database["schemas"].find({});

	Json::Value schemas;
	Json::Value array;

	for (auto&& doc : cursor) {

		string json  =bsoncxx::to_json(doc);
		std::cout << json << std::endl;
		Json::Value parsedFromString;
		Json::Reader reader;
		bool parsingSuccessful = reader.parse(json, parsedFromString);
		if (parsingSuccessful)
		{
			parsedFromString.removeMember("_id"); // Hide the BSON id.
			array.append(parsedFromString);
		}
	}

	schemas["Schemas"] = array;
	return schemas;
}
/***************************
 * get all streams
 * 
 **************************/
trex_rpc_cmd_rc_e
TrexRpcCmdGetAllStreams::_run(const Json::Value &params, Json::Value &result) {
    
    uint8_t port_id = parse_port(params, result);
    TrexStatelessPort *port = get_stateless_obj()->get_port_by_id(port_id);

    bool    get_pkt = parse_bool(params, "get_pkt", result);

    std::vector <TrexStream *> streams;
    port->get_object_list(streams);

    Json::Value streams_json = Json::objectValue;
    for (auto stream : streams) {

        Json::Value j = stream->get_stream_json();

        /* should we include the packet as well ? */
        if (!get_pkt) {
            j.removeMember("packet");
        }

        std::stringstream ss;
        ss << stream->m_stream_id;

        streams_json[ss.str()] = j;
    }

    result["result"]["streams"] = streams_json;

    return (TREX_RPC_CMD_OK);
}
Json::Value MongoDbAdapter::GetSchema(string name)
{
	mongocxx::instance inst{};
	mongocxx::client conn{mongocxx::uri{}};
	bsoncxx::stdx::string_view dbName("StorageTestDB");

	mongocxx::database database = conn[dbName];

	auto cursor = database["schemas"].find( bsoncxx::builder::stream::document{} << "SchemaName" << name<<  bsoncxx::builder::stream::finalize);

	for (auto&& doc : cursor) {
		string json  =bsoncxx::to_json(doc);
		std::cout << json << std::endl;
		Json::Value parsedFromString;
		Json::Reader reader;
		bool parsingSuccessful = reader.parse(json, parsedFromString);
		if (parsingSuccessful)
		{
			parsedFromString.removeMember("_id"); // Hide the BSON id.
			return parsedFromString;
		}
	}

	return Json::nullValue;
}
示例#9
0
std::vector<Stage *> PipelineReaderJSON::extractInputs(Json::Value& node,
    TagMap& tags)
{
    std::vector<Stage *> inputs;
    std::string filename;

    if (node.isMember("inputs"))
    {
        Json::Value& val = node["filename"];
        if (!val.isNull())
        {
            for (const Json::Value& input : node["inputs"])
            {
                if (input.isString())
                {
                    std::string tag = input.asString();
                    auto ii = tags.find(tag);
                    if (ii == tags.end())
                        throw pdal_error("JSON pipeline: Invalid pipeline: "
                            "undefined stage tag '" + tag + "'.");
                    else
                        inputs.push_back(ii->second);
                }
                else
                    throw pdal_error("JSON pipeline: 'inputs' tag must "
                        " be specified as a string.");
            }
        }
        node.removeMember("inputs");
        if (node.isMember("inputs"))
            throw pdal_error("JSON pipeline: found duplicate 'inputs' "
               "entry in stage definition.");
    }
    return inputs;
}
示例#10
0
std::string PipelineReaderJSON::extractTag(Json::Value& node, TagMap& tags)
{
    std::string tag;

    if (node.isMember("tag"))
    {
        Json::Value& val = node["tag"];
        if (!val.isNull())
        {
            if (val.isString())
            {
                tag = val.asString();
                if (tags.find(tag) != tags.end())
                    throw pdal_error("JSON pipeline: duplicate tag '" +
                        tag + "'.");
            }
            else
                throw pdal_error("JSON pipeline: 'tag' must be "
                    "specified as a string.");
        }
        node.removeMember("tag");
        if (node.isMember("tag"))
            throw pdal_error("JSON pipeline: found duplicate 'tag' "
               "entry in stage definition.");
    }
    return tag;
}
示例#11
0
std::string PipelineReaderJSON::extractTag(Json::Value& node, TagMap& tags)
{
    std::string tag;

    if (node.isMember("tag"))
    {
        Json::Value& val = node["tag"];
        if (!val.isNull())
        {
            if (val.isString())
            {
                tag = val.asString();
                if (tags.find(tag) != tags.end())
                    throw pdal_error("JSON pipeline: duplicate tag '" +
                        tag + "'.");
            }
            else
                throw pdal_error("JSON pipeline: tag must be "
                    "specified as a string.");
        }
        node.removeMember("tag");
        if (node.isMember("tag"))
            throw pdal_error("JSON pipeline: found duplicate 'tag' "
               "entry in stage definition.");
        std::string::size_type pos = 0;
        if (!Stage::parseTagName(tag, pos) || pos != tag.size())
            throw pdal_error("JSON pipeline: Invalid tag name '" + tag + "'.  "
                "Must start with letter.  Remainder can be letters, "
                "digits or underscores.");
    }
    return tag;
}
示例#12
0
Json::Value RPCHandler::CommandToMethod(Json::Value params) {
	const std::string commandName = "command";
	Json::Value newParams;
	newParams["method"] = params[commandName];
	params.removeMember(commandName);
	newParams["params"] = Json::arrayValue;
	newParams["params"].append(params);
	return newParams;
}
示例#13
0
reObject* reAssetLoader::loadObject( std::string& fileName, bool asRef )
{
	reObject* node = NULL;
	ifstream fs(filePath(fileName).c_str(), ios::in);
	if (!fs.fail())
	{
		Json::Reader reader;
		Json::Value root;
		reader.parse(fs, root);
		if (!asRef)
		{
			root.removeMember("path");
			root.removeMember("isReference");
		}		
		node = loadObject(reVar(root));
		fs.close();
	}	
	return node;
}
示例#14
0
std::string PipelineReaderJSON::extractFilename(Json::Value& node)
{
    std::string filename;

    if (node.isMember("filename"))
    {
        Json::Value& val = node["filename"];
        if (!val.isNull())
        {
            if (val.isString())
                filename = val.asString();
            else
                throw pdal_error("JSON pipeline: 'filename' must be "
                    "specified as a string.");
        }
        node.removeMember("filename");
        if (node.isMember("filename"))
            throw pdal_error("JSON pipeline: found duplicate 'filename' "
               "entry in stage definition.");
    }
    return filename;
}
示例#15
0
std::string PipelineReaderJSON::extractType(Json::Value& node)
{
    std::string type;

    if (node.isMember("type"))
    {
        Json::Value& val = node["type"];
        if (!val.isNull())
        {
            if (val.isString())
                type = val.asString();
            else
                throw pdal_error("JSON pipeline: 'type' must be specified as "
                        "a string.");
        }
        node.removeMember("type");
        if (node.isMember("type"))
            throw pdal_error("JSON pipeline: found duplicate 'type' "
               "entry in stage definition.");
    }
    return type;
}
示例#16
0
/***************************
 * get all streams
 * 
 **************************/
trex_rpc_cmd_rc_e
TrexRpcCmdGetAllStreams::_run(const Json::Value &params, Json::Value &result) {
    uint8_t port_id = parse_byte(params, "port_id", result);
    bool    get_pkt = parse_bool(params, "get_pkt", result);
     
    if (port_id >= get_stateless_obj()->get_port_count()) {
        std::stringstream ss;
        ss << "invalid port id - should be between 0 and " << (int)get_stateless_obj()->get_port_count() - 1;
        generate_execute_err(result, ss.str());
    }

    TrexStatelessPort *port = get_stateless_obj()->get_port_by_id(port_id);

    std::vector <TrexStream *> streams;
    port->get_stream_table()->get_object_list(streams);

    Json::Value streams_json = Json::objectValue;
    for (auto stream : streams) {

        Json::Value j = stream->get_stream_json();

        /* should we include the packet as well ? */
        if (!get_pkt) {
            j.removeMember("packet");
        }

        std::stringstream ss;
        ss << stream->m_stream_id;

        streams_json[ss.str()] = j;
    }

    result["result"]["streams"] = streams_json;

    return (TREX_RPC_CMD_OK);
}
	void deleteContributor(StaticFunctionTag*, BSFixedString characterName)
	{
		Json::Value jsonDisplayList = ReadDisplayData();
		
		for (auto & jsonDisplay : jsonDisplayList.getMemberNames())
		{
			Json::Value jsonDisplayData = jsonDisplayList[jsonDisplay.c_str()];
			Json::Value jsonContributors;
			if (jsonDisplayData.isMember("contributors"))
				jsonContributors = jsonDisplayData["contributors"];
			
			//Remove this character as a contributor
			for (int index = 0; index < jsonContributors.size(); ++index)
			{
				if (jsonContributors[index].asString() == characterName.data)
				{
					_MESSAGE("Removing %s from list of contributors.", characterName.data);
					Json::Value removed;
					jsonContributors.removeIndex(index, &removed);
					index--; //duplicate names shouldn't be a thing, but you never know
					jsonDisplayData["contributors"] = jsonContributors;
				}
			}

			//If this character was the only contributor, remove the entry entirely
			if (!jsonDisplayData.isMember("contributors") || (jsonDisplayData.isMember("contributors") && !jsonContributors.size()))
			{
				_MESSAGE("Last contributor was removed, deleting entry for %s!", jsonDisplay.c_str());
				jsonDisplayList.removeMember(jsonDisplay.c_str());
			}
			else {
				jsonDisplayList[jsonDisplay.c_str()] = jsonDisplayData;
			}
		}
		WriteDisplayData(jsonDisplayList);
	}
示例#18
0
void DimBuilder::extractDim(Json::Value& dim)
{
    DimSpec d;

    // Get dimension name.
    Json::Value name = dim.removeMember("name");
    if (name.isNull())
        throw dimbuilder_error("Dimension missing name.");
    if (!name.isString())
        throw dimbuilder_error("Dimension name must be a string.");
    d.m_name = name.asString();
    validateDimension(d.m_name);

    // Get dimension description.
    Json::Value description = dim.removeMember("description");
    if (description.isNull())
    {
        std::ostringstream oss;

        oss << "Dimension '" << d.m_name << "' must have a description.";
        throw dimbuilder_error(oss.str());
    }
    if (!description.isString())
    {
        std::ostringstream oss;

        oss << "Description of dimension '" << d.m_name << "' must be a "
            "string.";
        throw dimbuilder_error(oss.str());
    }
    d.m_description = description.asString();

    // Get dimension type
    Json::Value type = dim.removeMember("type");
    if (type.isNull())
    {
        std::ostringstream oss;

        oss << "Dimension '" << d.m_name << "' must have a type.";
        throw dimbuilder_error(oss.str());
    }
    d.m_type = Dimension::type(type.asString());
    if (d.m_type == Dimension::Type::None)
    {
        std::ostringstream oss;

        oss << "Invalid type '" << type.asString() << "' specified for "
            "dimension '" << d.m_name << "'.";
        throw dimbuilder_error(oss.str());
    }

    Json::Value altNames = dim.removeMember("alt_names");
    if (!altNames.isNull())
    {
        if (!altNames.isString())
        {
            std::ostringstream oss;

            oss << "Alternate names for dimension '" << d.m_name << "' must "
                "be a string.";
            throw dimbuilder_error(oss.str());
        }
        d.m_altNames = Utils::split2(altNames.asString(), ',');
        for (auto& s : d.m_altNames)
        {
            Utils::trim(s);
            validateDimension(s);
        }
    }
    if (dim.size() > 0)
    {
        std::ostringstream oss;

        oss << "Unexpected member '" << dim.getMemberNames()[0] << "' when "
            "reading dimension '" << d.m_name << "'.";
        throw dimbuilder_error(oss.str());
    }
    m_dims.push_back(d);
}
示例#19
0
  ///\brief Reads a DTSC file and attempts to fix the metadata in it.
  ///\param conf The current configuration of the program.
  ///\return The return code for the fixed program.
  int DTSCFix(Util::Config & conf){
    DTSC::File F(conf.getString("filename"));
    F.seek_bpos(0);
    F.parseNext();
    JSON::Value oriheader = F.getJSON();
    JSON::Value meta = F.getMeta();
    JSON::Value pack;

    if ( !oriheader.isMember("moreheader")){
      std::cerr << "This file is too old to fix - please reconvert." << std::endl;
      return 1;
    }
    if (DTSC::isFixed(meta) && !conf.getBool("force")){
      std::cerr << "This file was already fixed or doesn't need fixing - cancelling." << std::endl;
      return 0;
    }
    meta.removeMember("isFixed");
    meta.removeMember("keytime");
    meta.removeMember("keybpos");
    meta.removeMember("moreheader");

    std::map<std::string,int> trackIDs;
    std::map<std::string,HeaderEntryDTSC> trackData;


    long long int nowpack = 0;
    
    std::string currentID;
    int nextFreeID = 0;

    for (JSON::ObjIter it = meta["tracks"].ObjBegin(); it != meta["tracks"].ObjEnd(); it++){
      trackIDs.insert(std::pair<std::string,int>(it->first,it->second["trackid"].asInt()));
      trackData[it->first].type = it->second["type"].asString();
      trackData[it->first].trackID = it->second["trackid"].asInt();
      trackData[it->first].type = it->second["type"].asString();
      if (it->second["trackid"].asInt() >= nextFreeID){
        nextFreeID = it->second["trackid"].asInt() + 1;
      }
      it->second.removeMember("keylen");
      it->second.removeMember("keybpos");
      it->second.removeMember("frags");
      it->second.removeMember("keytime");
      it->second.removeMember("keynum");
      it->second.removeMember("keydata");
      it->second.removeMember("keyparts");
      it->second.removeMember("keys");
    }

    F.parseNext();
    while ( !F.getJSON().isNull()){
      currentID = "";
      if (F.getJSON()["trackid"].asInt() == 0){
        if (F.getJSON()["datatype"].asString() == "video"){
          currentID = "video0";
          if (trackData[currentID].trackID == 0){
            trackData[currentID].trackID = nextFreeID++;
          }
          if (meta.isMember("video")){
            meta["tracks"][currentID] = meta["video"];
            meta.removeMember("video");
          }
          trackData[currentID].type = F.getJSON()["datatype"].asString();
        }else{
          if (F.getJSON()["datatype"].asString() == "audio"){
            currentID = "audio0";
            if (trackData[currentID].trackID == 0){
              trackData[currentID].trackID = nextFreeID++;
            }
            if (meta.isMember("audio")){
              meta["tracks"][currentID] = meta["audio"];
              meta.removeMember("audio");
            }
            trackData[currentID].type = F.getJSON()["datatype"].asString();
          }else{
            //fprintf(stderr, "Found an unknown package with packetid 0 and datatype %s\n",F.getJSON()["datatype"].asString().c_str());
            F.parseNext();
            continue;
          }
        }
      }else{
        for( std::map<std::string,int>::iterator it = trackIDs.begin(); it != trackIDs.end(); it++ ) {
          if( it->second == F.getJSON()["trackid"].asInt() ) {
            currentID = it->first;
            break;
          }
        }
        if( currentID == "" ) {
          //fprintf(stderr, "Found an unknown v2 packet with id %d\n", F.getJSON()["trackid"].asInt());
          F.parseNext();
          continue;
          //should create new track but this shouldnt be needed...
        }
      }
      if (F.getJSON()["time"].asInt() < trackData[currentID].firstms){
        trackData[currentID].firstms = F.getJSON()["time"].asInt();
      }
      if (F.getJSON()["time"].asInt() >= nowpack){
        nowpack = F.getJSON()["time"].asInt();
      }
      if (trackData[currentID].type == "video"){
        if (F.getJSON().isMember("keyframe")){
          int newNum = meta["tracks"][currentID]["keys"].size();
          meta["tracks"][currentID]["keys"][newNum]["num"] = ++trackData[currentID].keynum;
          meta["tracks"][currentID]["keys"][newNum]["time"] = F.getJSON()["time"];
          meta["tracks"][currentID]["keys"][newNum]["bpos"] = F.getLastReadPos();
          if (meta["tracks"][currentID]["keys"].size() > 1){
            meta["tracks"][currentID]["keys"][newNum - 1]["len"] = F.getJSON()["time"].asInt() - meta["tracks"][currentID]["keys"][newNum - 1]["time"].asInt();
            meta["tracks"][currentID]["keys"][newNum - 1]["size"] = trackData[currentID].totalSize;
            trackData[currentID].totalSize = 0;
            std::string encodeVec = JSON::encodeVector( trackData[currentID].parts.begin(), trackData[currentID].parts.end() );
            meta["tracks"][currentID]["keys"][newNum - 1]["parts"] = encodeVec;
            meta["tracks"][currentID]["keys"][newNum - 1]["partsize"] = (long long int)trackData[currentID].parts.size();
            trackData[currentID].parts.clear();
          }
        }
      }else{
        if ((F.getJSON()["time"].asInt() - trackData[currentID].lastKeyTime) > 1000){
          trackData[currentID].lastKeyTime = F.getJSON()["time"].asInt();
          int newNum = meta["tracks"][currentID]["keys"].size();
          meta["tracks"][currentID]["keys"][newNum]["num"] = ++trackData[currentID].keynum;
          meta["tracks"][currentID]["keys"][newNum]["time"] = F.getJSON()["time"];
          meta["tracks"][currentID]["keys"][newNum]["bpos"] = F.getLastReadPos();
          if (meta["tracks"][currentID]["keys"].size() > 1){
            meta["tracks"][currentID]["keys"][newNum - 1]["len"] = F.getJSON()["time"].asInt() - meta["tracks"][currentID]["keys"][newNum - 1]["time"].asInt();
            meta["tracks"][currentID]["keys"][newNum - 1]["size"] = trackData[currentID].totalSize;
            trackData[currentID].totalSize = 0;
            std::string encodeVec = JSON::encodeVector( trackData[currentID].parts.begin(), trackData[currentID].parts.end() );
            meta["tracks"][currentID]["keys"][newNum - 1]["parts"] = encodeVec;
            meta["tracks"][currentID]["keys"][newNum - 1]["partsize"] = (long long int)trackData[currentID].parts.size();
            trackData[currentID].parts.clear();
          }
        }
      }
      trackData[currentID].totalSize += F.getJSON()["data"].asString().size();
      trackData[currentID].lastms = nowpack;
      trackData[currentID].parts.push_back(F.getJSON()["data"].asString().size());
      F.parseNext();
    }

    long long int firstms = 0x7fffffff;
    long long int lastms = -1;

    for (std::map<std::string,HeaderEntryDTSC>::iterator it = trackData.begin(); it != trackData.end(); it++){
      if (it->second.firstms < firstms){
        firstms = it->second.firstms;
      }
      if (it->second.lastms > lastms){
        lastms = it->second.lastms;
      }
      meta["tracks"][it->first]["firstms"] = it->second.firstms;
      meta["tracks"][it->first]["lastms"] = it->second.lastms;
      meta["tracks"][it->first]["length"] = (it->second.lastms - it->second.firstms) / 1000;
      if ( !meta["tracks"][it->first].isMember("bps")){
        meta["tracks"][it->first]["bps"] = (long long int)(it->second.lastms / ((it->second.lastms - it->second.firstms) / 1000));
      }
      if (it->second.trackID != 0){
        meta["tracks"][it->first]["trackid"] = trackIDs[it->first];
      }else{
        meta["tracks"][it->first]["trackid"] = nextFreeID ++;
      }
      meta["tracks"][it->first]["type"] = it->second.type;
      int tmp = meta["tracks"][it->first]["keys"].size();
      if (tmp > 0){
        if (tmp > 1){
          meta["tracks"][it->first]["keys"][tmp - 1]["len"] = it->second.lastms - meta["tracks"][it->first]["keys"][tmp - 2]["time"].asInt();
        }else{
          meta["tracks"][it->first]["keys"][tmp - 1]["len"] = it->second.lastms;
        }
        meta["tracks"][it->first]["keys"][tmp - 1]["size"] = it->second.totalSize;
        std::string encodeVec = JSON::encodeVector( trackData[it->first].parts.begin(), trackData[it->first].parts.end() );
        meta["tracks"][it->first]["keys"][tmp - 1]["parts"] = encodeVec;
        meta["tracks"][it->first]["keys"][tmp - 1]["partsize"] = (long long int)trackData[it->first].parts.size();
      }else{
        meta["tracks"][it->first]["keys"][tmp]["len"] = it->second.lastms;
        meta["tracks"][it->first]["keys"][tmp]["size"] = it->second.totalSize;
        std::string encodeVec = JSON::encodeVector( trackData[it->first].parts.begin(), trackData[it->first].parts.end() );
        meta["tracks"][it->first]["keys"][tmp]["parts"] = encodeVec;
        meta["tracks"][it->first]["keys"][tmp]["partsize"] = (long long int)trackData[it->first].parts.size();
        meta["tracks"][it->first]["keys"][tmp]["time"] = it->second.firstms;
      }
      //calculate fragments
      meta["tracks"][it->first]["frags"].null();
      long long int currFrag = -1;
      long long int maxBps = 0;
      for (JSON::ArrIter arrIt = meta["tracks"][it->first]["keys"].ArrBegin(); arrIt != meta["tracks"][it->first]["keys"].ArrEnd(); arrIt++) {
        if ((*arrIt)["time"].asInt() / 10000 > currFrag){
          currFrag = (*arrIt)["time"].asInt() / 10000;
          long long int fragLen = 1;
          long long int fragDur = (*arrIt)["len"].asInt();
          long long int fragSize = (*arrIt)["size"].asInt();
          for (JSON::ArrIter it2 = arrIt + 1; it2 != meta["tracks"][it->first]["keys"].ArrEnd(); it2++){
            if ((*it2)["time"].asInt() / 10000 > currFrag || (it2 + 1) == meta["tracks"][it->first]["keys"].ArrEnd()){
              JSON::Value thisFrag;
              thisFrag["num"] = (*arrIt)["num"].asInt();
              thisFrag["time"] = (*arrIt)["time"].asInt();
              thisFrag["len"] = fragLen;
              thisFrag["dur"] = fragDur;
              thisFrag["size"] = fragSize;
              if (fragDur / 1000){
                thisFrag["bps"] = fragSize / (fragDur / 1000);
                if (maxBps < (fragSize / (fragDur / 1000))){
                  maxBps = (fragSize / (fragDur / 999));
                }
              } else {
                thisFrag["bps"] = 1;
              }
              meta["tracks"][it->first]["frags"].append(thisFrag);
              break;
            }
            fragLen ++;
            fragDur += (*it2)["len"].asInt();
            fragSize += (*it2)["size"].asInt();
          }
        }
      }
      meta["tracks"][it->first]["maxbps"] = maxBps;
    }

    meta["firstms"] = firstms;
    meta["lastms"] = lastms;
    meta["length"] = (lastms - firstms) / 1000;

    //append the revised header
    std::string loader = meta.toPacked();
    long long int newHPos = F.addHeader(loader);
    if ( !newHPos){
      std::cerr << "Failure appending new header." << std::endl;
      return -1;
    }
    //re-write the original header with information about the location of the new one
    oriheader["moreheader"] = newHPos;
    loader = oriheader.toPacked();
    if (F.writeHeader(loader)){
      return 0;
    }else{
      std::cerr << "Failure rewriting header." << std::endl;
      return -1;
    }
  } //DTSCFix
示例#20
0
///\brief Starts a single stream
///\param name The name of the stream
///\param data The corresponding configuration values.
void startStream(std::string name, JSON::Value & data) {
    data["online"] = (std::string)"Checking...";
    data.removeMember("error");
    std::string URL;
    if (data.isMember("channel") && data["channel"].isMember("URL")) {
        URL = data["channel"]["URL"].asString();
    }
    if (data.isMember("source")) {
        URL = data["source"].asString();
    }
    std::string cmd1, cmd2, cmd3;
    if (URL == "") {
        Log("STRM", "Error for stream " + name + "! Source parameter missing.");
        data["error"] = "Missing source parameter!";
        return;
    }
    if (URL.substr(0, 4) == "push") {
        std::string pusher = URL.substr(7);
        if (data.isMember("DVR") && data["DVR"].asInt() > 0) {
            data["DVR"] = data["DVR"].asInt();
            cmd2 = "MistBuffer -t " + data["DVR"].asString() + " -s " + name + " " + pusher;
        } else {
            cmd2 = "MistBuffer -s " + name + " " + pusher;
        }
        Util::Procs::Start(name, Util::getMyPath() + cmd2);
        Log("BUFF", "(re)starting stream buffer " + name + " for push data from " + pusher);
    } else {
        if (URL.substr(0, 1) == "/") {
            struct stat fileinfo;
            if (stat(URL.c_str(), &fileinfo) != 0 || S_ISDIR(fileinfo.st_mode)) {
                Log("BUFF", "Warning for VoD stream " + name + "! File not found: " + URL);
                data["error"] = "Not found: " + URL;
                data["online"] = 0;
                return;
            }
            cmd1 = "cat " + URL;
            if (Util::epoch() - lastBuffer[name] > 5) {
                data["error"] = "Available";
                data["online"] = 2;
            } else {
                data["online"] = 1;
                data.removeMember("error");
            }
            return; //MistPlayer handles VoD
        } else {
            cmd1 = "ffmpeg -re -async 2 -i " + URL + " -f flv -";
            cmd2 = "MistFLV2DTSC";
        }
        if (data.isMember("DVR") && data["DVR"].asInt() > 0) {
            data["DVR"] = data["DVR"].asInt();
            cmd3 = "MistBuffer -t " + data["DVR"].asString() + " -s " + name;
        } else {
            cmd3 = "MistBuffer -s " + name;
        }
        if (cmd2 != "") {
            Util::Procs::Start(name, cmd1, Util::getMyPath() + cmd2, Util::getMyPath() + cmd3);
            Log("BUFF", "(re)starting stream buffer " + name + " for ffmpeg data: " + cmd1);
        } else {
            Util::Procs::Start(name, cmd1, Util::getMyPath() + cmd3);
            Log("BUFF", "(re)starting stream buffer " + name + " using input file " + URL);
        }
    }
}
示例#21
0
void GeneralizedTransform::pushLevelBack(Json::Value level) {
    if (level.isMember(routing_keys::child())) {
        level.removeMember(routing_keys::child());
    }
    container().emplace_back(std::move(level));
}
void
ClientHandler::check_create_pipeline_call()
{
  Json::Value request;
  Json::Value response;
  std::string pipeId;
  std::string objId;

  Json::Value params;
  Json::Value constructorParams;
  Json::Value operationParams;

  request["jsonrpc"] = "2.0";
  request["id"] = getId();
  request["method"] = "create";

  params["type"] = "MediaPipeline";
  params["sessionId"] = "123456";

  request["params"] = params;
  request["sessionId"] = "sessionId";

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("value") );
  BOOST_CHECK (response["result"]["value"].isString() );

  pipeId = response["result"]["value"].asString();

  params["type"] = "WebRtcEndpoint";
  constructorParams ["mediaPipeline"] = pipeId;
  params["constructorParams"] = constructorParams;
  params["sessionId"] = "123456";

  request["id"] = getId();
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("value") );
  BOOST_CHECK (response["result"]["value"].isString() );

  objId = response["result"]["value"].asString();

  request["method"] = "invoke";
  params.clear();
  params["object"] = objId;
  params["operation"] = "getName";
  params["sessionId"] = "123456";

  params["operationParams"] = operationParams;
  request["id"] = getId();
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );

  request["id"] = getId();
  request["method"] = "ref";
  params.clear();
  params["object"] = objId;
  params["sessionId"] = "12345";
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );

  request["id"] = getId();
  request["method"] = "describe";
  params.clear();
  params["object"] = objId;
  params["sessionId"] = "12345";
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isMember ("type") );
  BOOST_CHECK (response["result"]["type"].asString () == "WebRtcEndpoint" );

  std::string sessionId = "123456";
  request.removeMember ("id");
  request["id"] = getId();
  request["method"] = "release";
  params.clear();
  params["object"] = objId;
  params["sessionId"] = sessionId;

  params["operationParams"] = operationParams;
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isMember ("sessionId") );
  BOOST_CHECK (response["result"]["sessionId"].asString () == sessionId );
}
示例#23
0
/* 
This is just a test function, believe it or not. It doesn't return anything (unless, of course, it fails). 
It does print stuff to the console, if you're interested. 
*/
bool itemID::testRead(unsigned long int id)
{
	char* resname = new char[256];
	sprintf(resname, "%s/%u.json", JSON_DIR, id);

	ifstream t(resname, ifstream::in); 
	if (!t) {return false;}
	string json((istreambuf_iterator<char>(t)), istreambuf_iterator<char>()); 
	t >> json;
	t.close();
	
	Json::Value root;
	Json::Reader reader;
	const char* key = "daily";

	bool success = reader.parse(json, root);
	if (!success)
	{
		printf("Failed to parse JSON for item %u!\r\n", id);
		return false;
	}

/*	vector<string> mem = root.getMemberNames();

	for (int i = 0; i<mem.size(); ++i)
	{
		cout << mem.at(i) << endl;
	} */


	/* extract the object member with key "daily" as we don't care about "average" */
	Json::Value daily = root.removeMember(key);
	/* fill this string vector with what are ultimately representations of daily price over time */
	vector<string> dm = daily.getMemberNames();

	/* 
	DEBUGGING PURPOSES ONLY - these commented-out blocks are only for testing purposes. Basically they tell you
	exactly what is going on behind the scenes, which was really useful while I was writing this...figuring out
	how to use jsoncpp without much help or documentation at all!
	
	This just spits out a bunch of long numbers (seconds since UNIX epoch actually)
	for (int i = 0; i<dm.size(); ++i)
	{
		cout << dm.at(i) << endl;
	} 

	if (daily.isArray())
	{
		// I don't think you should/will ever see this, actually. 
		cout << "It is an array - enum: " << daily.type() << endl;
	}
	else
	{
		// should say "7" which is "objectValue" a.k.a key/value pairs 
		cout << "It is NOT an array - enum: " << daily.type() << endl;
	}

	// This prints out ALL the information you could want to know, finally.
	// "Pos" is position in the vector (NOT array, a vector!)
	// "Date" is the amount of seconds since midnight on 1 Jan 1970 - no, seriously, it is.
	// "Price" is the amount of licks it takes to get to the centre of a Tootsie Pop. 
	for (int i = 0; i<dm.size(); i++)
	{
		cout << "Pos: " << i << " Date: " << dm.at(i) << " Price: " << daily[dm.at(i)] << endl;
	} */
	
	/* The database only contains prices for the last 180 days, meaning that we want the price contained in daily[dm.at(180)] :)*/

	cout << "Latest price for this item: " << daily[dm.at(180)] << endl;
	
	return true;
}
bool saveDisplayStatus(Json::Value &jsonDisplayList, TESObjectREFR* pObject, const char * playerName = nullptr)
{
	std::string formString = GetJCFormString(pObject);

	Json::Value jsonDisplayData;
	if (jsonDisplayList.isMember(formString.c_str()))
		jsonDisplayData = jsonDisplayList[formString.c_str()];
	
	
	//kFlagUnk_0x800 is the Disabled flag
	if ((pObject->flags & TESForm::kFlagUnk_0x800) && jsonDisplayList.isMember(formString.c_str()))
	{
		//_MESSAGE("Display %s is disabled, but exists on the list.", formString.c_str());
		//Display is disabled, but exists on the list
		Json::Value jsonContributors;
		if (jsonDisplayData.isMember("contributors"))
			jsonContributors = jsonDisplayData["contributors"];

		//Remove this character as a contributor
		for (int index = 0; index < jsonContributors.size(); ++index)
		{
			if (jsonContributors[index].asString() == playerName)
			{
				_MESSAGE("Removing %s from list of contributors.", playerName);
				Json::Value removed;
				jsonContributors.removeIndex(index, &removed);
				index--; //duplicate names shouldn't be a thing, but you never know
				jsonDisplayData["contributors"] = jsonContributors;
			}
		}

		//If this character was the only contributor, remove the entry entirely
		if (!jsonDisplayData.isMember("contributors") || (jsonDisplayData.isMember("contributors") && !jsonContributors.size()))
		{
			_MESSAGE("Last contributor was removed, deleting entry for %s!", formString.c_str());
			jsonDisplayList.removeMember(formString.c_str());
		}
		else {
			jsonDisplayList[formString.c_str()] = jsonDisplayData;
		}
	}
	else if (!(pObject->flags & TESForm::kFlagUnk_0x800)) //If the display is NOT disabled
	{
		_MESSAGE("Display %s is enabled.", formString.c_str());
		
		std::string name = getName(pObject);
		if (name.length() > 0)
		{
			jsonDisplayData["name"] = name.c_str();
		}

		//If playerName is set, add the player's name to the list
		if (playerName)
		{
			Json::Value jsonContributors;
			if (jsonDisplayData.isMember("contributors"))
				jsonContributors = jsonDisplayData["contributors"];
			bool addMe = true;
			for (int index = 0; index < jsonContributors.size(); ++index)
			{
				if (jsonContributors[index].asString() == playerName)
				{
					_MESSAGE("  %s is already in the contributor list.", playerName);
					addMe = false;
				}
			}
			if (addMe)
			{
				_MESSAGE("  Adding %s to the contributor list.", playerName);
				jsonContributors.append(playerName);
				jsonDisplayData["contributors"] = jsonContributors;
			}
		}

		jsonDisplayList[formString.c_str()] = jsonDisplayData;
	}
	return true;
}
void
ClientHandler::check_create_pipeline_call()
{
  Json::Value request;
  Json::Value response;
  std::string pipeId;
  std::string objId;

  Json::Value params;
  Json::Value constructorParams;
  Json::Value operationParams;

  request["jsonrpc"] = "2.0";
  request["id"] = getId();
  request["method"] = "create";

  params["type"] = "MediaPipeline";
  params["sessionId"] = "123456";

  request["params"] = params;
  request["sessionId"] = "sessionId";

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("value") );
  BOOST_CHECK (response["result"]["value"].isString() );

  pipeId = response["result"]["value"].asString();

  params["type"] = "WebRtcEndpoint";
  constructorParams ["mediaPipeline"] = pipeId;
  params["constructorParams"] = constructorParams;
  params["sessionId"] = "123456";

  request["id"] = getId();
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("value") );
  BOOST_CHECK (response["result"]["value"].isString() );

  objId = response["result"]["value"].asString();

  request["method"] = "invoke";
  params.clear();
  params["object"] = objId;
  params["operation"] = "getName";
  params["sessionId"] = "123456";

  params["operationParams"] = operationParams;
  request["id"] = getId();
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );

  request["id"] = getId();
  request["method"] = "ref";
  params.clear();
  params["object"] = objId;
  params["sessionId"] = "12345";
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );

  request["id"] = getId();
  request["method"] = "describe";
  params.clear();
  params["object"] = objId;
  params["sessionId"] = "12345";
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isMember ("type") );
  BOOST_CHECK (response["result"]["type"].asString () == "WebRtcEndpoint" );
  BOOST_CHECK (response["result"].isMember ("qualifiedType") );
  BOOST_CHECK (response["result"]["qualifiedType"].asString () ==
               "kurento.WebRtcEndpoint" );
  BOOST_CHECK (response["result"].isMember ("hierarchy") );
  Json::Value hierarchy = response["result"]["hierarchy"];
  std::vector <std::string> expected_hierarchy;

  expected_hierarchy.emplace_back("kurento.BaseRtpEndpoint");
  expected_hierarchy.emplace_back("kurento.SdpEndpoint");
  expected_hierarchy.emplace_back("kurento.SessionEndpoint");
  expected_hierarchy.emplace_back("kurento.Endpoint");
  expected_hierarchy.emplace_back("kurento.MediaElement");
  expected_hierarchy.emplace_back("kurento.MediaObject");

  BOOST_REQUIRE (hierarchy.isArray() );

  for (uint i = 0; i < hierarchy.size(); i++) {
    BOOST_REQUIRE (hierarchy[i].isString() );
    BOOST_CHECK (hierarchy[i].asString() == expected_hierarchy[i]);
  }

  std::string sessionId = "123456";
  request.removeMember ("id");
  request["id"] = getId();
  request["method"] = "release";
  params.clear();
  params["object"] = objId;
  params["sessionId"] = sessionId;

  params["operationParams"] = operationParams;
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (!response.isMember ("error") );
  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isMember ("sessionId") );
  BOOST_CHECK (response["result"]["sessionId"].asString () == sessionId );
}
示例#26
0
void processAndLogNewSpawnException(SpawnException &e, const Options &options,
	const SpawningKit::ConfigPtr &config)
{
	TRACE_POINT();
	UnionStation::TransactionPtr transaction;
	ErrorRenderer renderer(*config->resourceLocator);
	string appMessage = e.getErrorPage();
	string errorId;
	char filename[PATH_MAX];
	stringstream stream;

	if (options.analytics && config->unionStationCore != NULL) {
		try {
			UPDATE_TRACE_POINT();
			transaction = config->unionStationCore->newTransaction(
				options.getAppGroupName(),
				"exceptions",
				options.unionStationKey);
			errorId = transaction->getTxnId();
		} catch (const tracable_exception &e2) {
			transaction.reset();
			P_WARN("Cannot log to Union Station: " << e2.what() <<
				"\n  Backtrace:\n" << e2.backtrace());
		}
	}

	UPDATE_TRACE_POINT();
	if (appMessage.empty()) {
		appMessage = "none";
	}
	if (errorId.empty()) {
		errorId = config->randomGenerator->generateHexString(4);
	}
	e.set("error_id", errorId);

	try {
		int fd = -1;
		string errorPage;

		UPDATE_TRACE_POINT();
		errorPage = renderer.renderWithDetails(appMessage, options, &e);

		#if (defined(__linux__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 11))) || defined(__APPLE__) || defined(__FreeBSD__)
			snprintf(filename, PATH_MAX, "%s/passenger-error-XXXXXX.html",
				getSystemTempDir());
			fd = mkstemps(filename, sizeof(".html") - 1);
		#else
			snprintf(filename, PATH_MAX, "%s/passenger-error.XXXXXX",
				getSystemTempDir());
			fd = mkstemp(filename);
		#endif
		FdGuard guard(fd, NULL, 0, true);
		if (fd == -1) {
			int e = errno;
			throw SystemException("Cannot generate a temporary filename",
				e);
		}

		UPDATE_TRACE_POINT();
		writeExact(fd, errorPage);
	} catch (const SystemException &e2) {
		filename[0] = '\0';
		P_ERROR("Cannot render an error page: " << e2.what() << "\n" <<
			e2.backtrace());
	}

	if (transaction != NULL) {
		try {
			UPDATE_TRACE_POINT();
			transaction->message("Context: spawning");
			transaction->message("Message: " +
				jsonString(e.what()));
			transaction->message("App message: " +
				jsonString(appMessage));

			const char *kind;
			switch (e.getErrorKind()) {
			case SpawnException::PRELOADER_STARTUP_ERROR:
				kind = "PRELOADER_STARTUP_ERROR";
				break;
			case SpawnException::PRELOADER_STARTUP_PROTOCOL_ERROR:
				kind = "PRELOADER_STARTUP_PROTOCOL_ERROR";
				break;
			case SpawnException::PRELOADER_STARTUP_TIMEOUT:
				kind = "PRELOADER_STARTUP_TIMEOUT";
				break;
			case SpawnException::PRELOADER_STARTUP_EXPLAINABLE_ERROR:
				kind = "PRELOADER_STARTUP_EXPLAINABLE_ERROR";
				break;
			case SpawnException::APP_STARTUP_ERROR:
				kind = "APP_STARTUP_ERROR";
				break;
			case SpawnException::APP_STARTUP_PROTOCOL_ERROR:
				kind = "APP_STARTUP_PROTOCOL_ERROR";
				break;
			case SpawnException::APP_STARTUP_TIMEOUT:
				kind = "APP_STARTUP_TIMEOUT";
				break;
			case SpawnException::APP_STARTUP_EXPLAINABLE_ERROR:
				kind = "APP_STARTUP_EXPLAINABLE_ERROR";
				break;
			default:
				kind = "UNDEFINED_ERROR";
				break;
			}
			transaction->message(string("Kind: ") + kind);

			Json::Value details;
			const map<string, string> &annotations = e.getAnnotations();
			map<string, string>::const_iterator it, end = annotations.end();

			for (it = annotations.begin(); it != end; it++) {
				details[it->first] = it->second;
			}

			// This information is not very useful. Union Station
			// already collects system metrics.
			details.removeMember("system_metrics");
			// Don't include environment variables because they may
			// contain sensitive information.
			details.removeMember("envvars");

			transaction->message("Details: " + stringifyJson(details));
		} catch (const tracable_exception &e2) {
			P_WARN("Cannot log to Union Station: " << e2.what() <<
				"\n  Backtrace:\n" << e2.backtrace());
		}
	}

	UPDATE_TRACE_POINT();
	stream << "Could not spawn process for application " << options.appRoot <<
		": " << e.what() << "\n" <<
		"  Error ID: " << errorId << "\n";
	if (filename[0] != '\0') {
		stream << "  Error details saved to: " << filename << "\n";
	}
	stream << "  Message from application: " << appMessage << "\n";
	P_ERROR(stream.str());

	if (config->agentsOptions != NULL) {
		HookScriptOptions hOptions;
		hOptions.name = "spawn_failed";
		hOptions.spec = config->agentsOptions->get("hook_spawn_failed", false);
		hOptions.agentsOptions = config->agentsOptions;
		hOptions.environment.push_back(make_pair("PASSENGER_APP_ROOT", options.appRoot));
		hOptions.environment.push_back(make_pair("PASSENGER_APP_GROUP_NAME", options.getAppGroupName()));
		hOptions.environment.push_back(make_pair("PASSENGER_ERROR_MESSAGE", e.what()));
		hOptions.environment.push_back(make_pair("PASSENGER_ERROR_ID", errorId));
		hOptions.environment.push_back(make_pair("PASSENGER_APP_ERROR_MESSAGE", appMessage));
		oxt::thread(boost::bind(runHookScripts, hOptions),
			"Hook: spawn_failed", 256 * 1024);
	}
}
示例#27
0
 int getInfo(int argc, char* argv[]) {
   if (argc < 2){
     fprintf( stderr, "Usage: %s <filename>\n", argv[0] );
     return 1;
   }
   DTSC::File F(argv[1]);
   JSON::Value fileSpecs = F.getMeta().toJSON();
   if( !fileSpecs ) {
     char ** cmd = (char**)malloc(3*sizeof(char*));
     cmd[0] = (char*)"ffprobe";
     cmd[1] = argv[1];
     cmd[2] = NULL;
     int outFD = -1;
     Util::Procs::StartPiped("FFProbe", cmd, 0, 0, &outFD);
     while( Util::Procs::isActive("FFProbe")){ Util::sleep(100); }
     FILE * outFile = fdopen( outFD, "r" );
     char * fileBuf = 0;
     size_t fileBufLen = 0;
     while ( !(feof(outFile) || ferror(outFile)) && (getline(&fileBuf, &fileBufLen, outFile) != -1)){
       std::string line = fileBuf;
       if (line.find("Input") != std::string::npos){
         std::string tmp = line.substr(line.find(", ") + 2);
         fileSpecs["format"] = tmp.substr(0, tmp.find(","));
       }
       if (line.find("Duration") != std::string::npos){
         std::string tmp = line.substr(line.find(": ", line.find("Duration")) + 2);
         tmp = tmp.substr(0, tmp.find(","));
         int length = (((atoi(tmp.substr(0,2).c_str()) * 60) + atoi(tmp.substr(3,2).c_str())) * 60) + atoi(tmp.substr(6,2).c_str());
         fileSpecs["length"] = length;
         length *= 100;
         length += atoi(tmp.substr(9,2).c_str());
         fileSpecs["lastms"] = length * 10;
       }
       if (line.find("bitrate") != std::string::npos ){
         std::string tmp = line.substr(line.find(": ", line.find("bitrate")) + 2);
         fileSpecs["bps"] = atoi(tmp.substr(0, tmp.find(" ")).c_str()) * 128;
       }
       if (line.find("Stream") != std::string::npos ){
         std::string tmp = line.substr(line.find(" ", line.find("Stream")) + 1);
         int strmIdx = fileSpecs["streams"].size();
         int curPos = 0;
         curPos = tmp.find(": ", curPos) + 2;
         fileSpecs["streams"][strmIdx]["type"] = tmp.substr(curPos, tmp.find(":", curPos) - curPos);
         curPos = tmp.find(":", curPos) + 2;
         fileSpecs["streams"][strmIdx]["codec"] = tmp.substr(curPos, tmp.find_first_of(", ", curPos) - curPos);
         curPos = tmp.find(",", curPos) + 2;
         if (fileSpecs["streams"][strmIdx]["type"] == "Video"){
           fileSpecs["streams"][strmIdx]["encoding"] = tmp.substr(curPos, tmp.find(",", curPos) - curPos);
           curPos = tmp.find(",", curPos) + 2;
           fileSpecs["streams"][strmIdx]["width"] = atoi(tmp.substr(curPos, tmp.find("x", curPos) - curPos).c_str());
           curPos = tmp.find("x", curPos) + 1;
           fileSpecs["streams"][strmIdx]["height"] = atoi(tmp.substr(curPos, tmp.find(",", curPos) - curPos).c_str());
           curPos = tmp.find(",", curPos) + 2;
           fileSpecs["streams"][strmIdx]["bps"] = atoi(tmp.substr(curPos, tmp.find(" ", curPos) - curPos).c_str()) * 128;
           curPos = tmp.find(",", curPos) + 2;
           fileSpecs["streams"][strmIdx]["fpks"] = (int)(atof(tmp.substr(curPos, tmp.find(" ", curPos) - curPos).c_str()) * 1000);
           fileSpecs["streams"][strmIdx].removeMember( "type" );
           fileSpecs["video"] = fileSpecs["streams"][strmIdx];
         }else if (fileSpecs["streams"][strmIdx]["type"] == "Audio"){
           fileSpecs["streams"][strmIdx]["samplerate"] = atoi(tmp.substr(curPos, tmp.find(" ", curPos) - curPos).c_str());
           curPos = tmp.find(",", curPos) + 2;
           if (tmp.substr(curPos, tmp.find(",", curPos) - curPos) == "stereo"){
             fileSpecs["streams"][strmIdx]["channels"] = 2;
           }else if (tmp.substr(curPos, tmp.find(",", curPos) - curPos) == "mono"){
             fileSpecs["streams"][strmIdx]["channels"] = 1;
           }else{
             fileSpecs["streams"][strmIdx]["channels"] = tmp.substr(curPos, tmp.find(",", curPos) - curPos);
           }
           curPos = tmp.find(",", curPos) + 2;
           fileSpecs["streams"][strmIdx]["samplewidth"] = tmp.substr(curPos, tmp.find(",", curPos) - curPos);
           curPos = tmp.find(",", curPos) + 2;
           fileSpecs["streams"][strmIdx]["bps"] = atoi(tmp.substr(curPos, tmp.find(" ", curPos) - curPos).c_str()) * 128;
           fileSpecs["streams"][strmIdx].removeMember( "type" );
           fileSpecs["audio"] = fileSpecs["streams"][strmIdx];
         }
       }
     }
     fclose( outFile );
     fileSpecs.removeMember( "streams" );
   } else {
     fileSpecs["format"] = "dtsc";
     if (DTSC::isFixed(fileSpecs)){
       fileSpecs["is_fixed"] = 1ll;
     }
     JSON::Value tracks = fileSpecs["tracks"];
     for(JSON::ObjIter trackIt = tracks.ObjBegin(); trackIt != tracks.ObjEnd(); trackIt++){
       fileSpecs["tracks"][trackIt->first].removeMember("fragments");
       fileSpecs["tracks"][trackIt->first].removeMember("keys");
       fileSpecs["tracks"][trackIt->first].removeMember("parts");
     }
   }
   printf( "%s", fileSpecs.toString().c_str() );
   return 0;
 }
示例#28
0
void UpdateUserData::handle(Manager* manager, SharedManager* sManager) {
    bool validation = this->validateInput();
    if(validation) {
        struct mg_str *cl_header = mg_get_http_header(hm, "Token");
        if(!cl_header) {
            this->response(1, "Token Missing ", returnEmptyJsonObject());
            return;
        }
        Json::Reader r = Json::Reader();
        Json::Value value = Json::Value();
        r.parse(hm->body.p, value);
        // Local user update
        User* user = manager->getUser(value.get("username","").asString());
        if(!user) {
            this->response(1, "User could not be modified", returnEmptyJsonObject());
            return;
        }
        std::string token(getHeaderParam(cl_header->p));
        if(token.compare(user->getToken()) != 0) {
            this->response(2, "Invalid Token", returnEmptyJsonObject());
            return;
        }
        user->updateWithJson(value);
        bool updateUser = manager->updateUser(user);
        if(updateUser) {
            value["id"] = user->getId();
            if(value.isMember("photoProfile") || value.isMember("photo_profile")) {
                // Photo Profile Upload
                std::string key = "";
                value.isMember("photoProfile") ? key = "photoProfile" : key = "photo_profile";
                Json::Value uploadP = Json::Value();
                uploadP["photo"] = value.get(key, "").asString();
                uploadP["id"] = user->getId();
                value.removeMember(key);
                int photoUp = sManager->putUserPhoto(uploadP);
                if(!photoUp) {
                    this->response(1, "User photo profile could not be uploaded", returnEmptyJsonObject());
                    return;
                }
            }
            // Rest of user data to update on Shared Server
            // TODO: Falta subir los intereses nuevos que haya!
            if(value.isMember("interests")) {
                Json::Value interests = value.get("interests", Json::Value(Json::arrayValue));
                Json::ValueConstIterator interestsIt = interests.begin();
                while(interestsIt != interests.end()) {
                    Json::Value response = sManager->postInterest(*interestsIt);
                    // TODO: Alguna cola para reupload de intereses que debieron subir
                    // pero no pudieron por algun problema (que no sea duplicado)
                    interestsIt++;
                }
            }
            if(value.isMember("edad")) value["age"] = value.get("edad", 18).asInt();
            int sharedUpdate = sManager->putUser(value);
            if(sharedUpdate) {
                this->response(0, "Modified", user->getJson());
            } else {
                this->response(1, "User could not be modified", returnEmptyJsonObject());
            }
        } else {
            this->response(1, "User could not be modified", returnEmptyJsonObject());
        }
        delete user;
    }
}