Esempio n. 1
0
void JsonApiHandlerHttp::sendJson(const Json &json)
{
    string data = json.dump();

    Params headers;
    headers.Add("Connection", "Close");
    headers.Add("Cache-Control", "no-cache, must-revalidate");
    headers.Add("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
    headers.Add("Content-Type", "application/json");
    headers.Add("Content-Length", Utils::to_string(data.size()));
    string res = httpClient->buildHttpResponse(HTTP_200, headers, data);
    sendData.emit(res);
}
void ActivityAudioListView::browserShowPlaylistTracks(Params &infos, Params pl_infos)
{
    if (!infos.Exists("count")) return;

    EmitSignal("browser,loading,stop", "calaos");

    cDebug() << "RESULT infos: " << pl_infos.toString();

    pl_infos.Add("count", infos["count"]);
    int count;
    from_string(infos["count"], count);

    int pl_id;
    from_string(pl_infos["id"], pl_id);

    CREATE_GENLIST_HELPER(glist);

    GenlistItemPlaylistHeader *header = new GenlistItemPlaylistHeader(evas, parent, player_current->getPlayer(), pl_infos, pl_id);
    header->Append(glist);

    for (int i = 0;i < count;i++)
    {
        GenlistItemTrack *item = new GenlistItemTrack(evas, parent, player_current->getPlayer(), i, GenlistItemTrack::TRACK_PLAYLIST, pl_id);
        item->Append(glist);
    }

    elm_naviframe_item_push(pager_browser, NULL, NULL, NULL, glist, "calaos");
}
void ActivityAudioListView::browserShowYearAlbum(Params &infos, Params year_infos)
{
    if (!infos.Exists("count")) return;

    EmitSignal("browser,loading,stop", "calaos");

    cDebug() << "RESULT infos: " << year_infos.toString();

    year_infos.Add("count", infos["count"]);
    int count;
    from_string(infos["count"], count);

    int year_id;
    from_string(year_infos["year"], year_id);

    CREATE_GENLIST_HELPER(glist);

    for (int i = 0;i < count;i++)
    {
        GenlistItemAlbum *item = new GenlistItemAlbum(evas, parent, player_current->getPlayer(), i, GenlistItemAlbum::ALBUM_YEAR, year_id);
        item->Append(glist);
        item->setUserData(item);
        item->item_selected.connect(sigc::mem_fun(*this, &ActivityAudioListView::albumSelected));
    }

    elm_naviframe_item_push(pager_browser, NULL, NULL, NULL, glist, "calaos");
}
Esempio n. 4
0
void AudioPlayer::db_album_track_count_get_cb(bool success, vector<string> result, void *data)
{
    PlayerInfoData *user_data = reinterpret_cast<PlayerInfoData *>(data);
    if (!user_data) return; //Probably leaking here !

    if (result.size() < 5) return;

    Params infos;

    for (uint b = 4;b < result.size();b++)
    {
        vector<string> tmp;
        Utils::split(result[b], tmp, ":", 2);

        if (tmp.size() < 2) continue;

        if (tmp[0] == "count")
        {
            infos.Add(tmp[0], tmp[1]);
            break;
        }
    }

    PlayerInfo_signal sig;
    sig.connect(user_data->callback);
    sig.emit(infos);

    delete user_data;
}
Esempio n. 5
0
void Utils::parseParamsItemList(std::string l, std::vector<Params> &res, int start_at)
{
    std::vector<std::string> tokens;
    split(l, tokens);
    Params item;

    for (unsigned int i = start_at;i < tokens.size();i++)
    {
        std::string tmp = tokens[i];
        std::vector<std::string> tk;
        split(tmp, tk, ":", 2);

        if (tk.size() != 2) continue;

        if (item.Exists(tk[0]))
        {
            res.push_back(item);
            item.clear();
        }

        item.Add(tk[0], tk[1]);
    }

    if (item.size() > 0)
        res.push_back(item);
}
Esempio n. 6
0
bool Utils::get_config_options(Params &options)
{
    TiXmlDocument document(getConfigFile(LOCAL_CONFIG).c_str());

    if (!document.LoadFile())
    {
        cError() <<  "There was an exception in XML parsing.";
        cError() <<  "Parse error: " << document.ErrorDesc();
        cError() <<  "In file " << getConfigFile(LOCAL_CONFIG) << " At line " << document.ErrorRow();

        return false;
    }

    TiXmlHandle docHandle(&document);

    TiXmlElement *key_node = docHandle.FirstChildElement("calaos:config").FirstChildElement().ToElement();
    if (key_node)
    {
        for(; key_node; key_node = key_node->NextSiblingElement())
        {
            if (key_node->ValueStr() == "calaos:option" &&
                key_node->Attribute("name") &&
                key_node->Attribute("value"))
            {
                options.Add(key_node->Attribute("name"), key_node->Attribute("value"));
            }
        }
    }

    return true;
}
Esempio n. 7
0
void JsonApiHandlerHttp::sendJson(json_t *json)
{
    char *d = json_dumps(json, JSON_COMPACT | JSON_ENSURE_ASCII /*| JSON_ESCAPE_SLASH*/);
    if (!d)
    {
        json_decref(json);
        cDebugDom("network") << "json_dumps failed!";

        Params headers;
        headers.Add("Connection", "close");
        headers.Add("Content-Type", "text/html");
        string res = httpClient->buildHttpResponse(HTTP_500, headers, HTTP_500_BODY);
        sendData.emit(res);
        closeConnection.emit(0, string());

        return;
    }
    json_decref(json);

    string data(d);
    free(d);

    Params headers;
    headers.Add("Connection", "Close");
    headers.Add("Cache-Control", "no-cache, must-revalidate");
    headers.Add("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
    headers.Add("Content-Type", "application/json");
    headers.Add("Content-Length", Utils::to_string(data.size()));
    string res = httpClient->buildHttpResponse(HTTP_200, headers, data);
    sendData.emit(res);
}
Esempio n. 8
0
void DialogNewAudio::on_buttonBox_accepted()
{
    if (ui->edit_name->text().isEmpty())
    {
        ui->label_error_empty->show();
        return;
    }

    Params p;
    p.Add("name", ui->edit_name->text().toUtf8().constData());
    p.Add("host", ui->edit_ip->text().toUtf8().constData());
    p.Add("id", ui->edit_mac->text().toUtf8().constData());
    p.Add("type", "slim");

    output = ListeRoom::Instance().createAudio(p, room);

    accept();
}
void DialogNewAVReceiver::on_buttonBox_accepted()
{
    if (ui->lineEditName->text().isEmpty())
    {
        ui->labelError->show();
        return;
    }

    Params p;
    p.Add("name", ui->lineEditName->text().toUtf8().constData());
    p.Add("model", ui->comboBoxType->itemData(ui->comboBoxType->currentIndex()).toString().toUtf8().constData());
    p.Add("host", ui->lineEditHost->text().toUtf8().constData());
    p.Add("visible", "true");
    p.Add("type", "AVReceiver");

    output = ListeRoom::Instance().createOutput(p, room);

    accept();
}
Esempio n. 10
0
void JsonApiClient::handleRequest()
{
    jsonParam.clear();

    //parse the json data
    json_error_t jerr;
    json_t *jroot = json_loads(bodymessage.c_str(), 0, &jerr);

    if (!jroot || !json_is_object(jroot))
    {
        cDebugDom("network") << "Error loading json : " << jerr.text;

        Params headers;
        headers.Add("Connection", "close");
        headers.Add("Content-Type", "text/html");
        string res = buildHttpResponse(HTTP_400, headers, HTTP_400_BODY);
        sendToClient(res);
        CloseConnection();

        return;
    }

    cDebug() << json_dumps(jroot, JSON_INDENT(4));

    const char *key;
    json_t *value;

    //decode the json root object into jsonParam
    json_object_foreach(jroot, key, value)
    {
        string svalue;

        if (json_is_string(value))
            svalue = json_string_value(value);
        else if (json_is_boolean(value))
            svalue = json_is_true(value)?"true":"false";
        else if (json_is_number(value))
            svalue = Utils::to_string(json_number_value(value));

        jsonParam.Add(key, svalue);
    }
void DialogNewScenario::on_buttonBox_accepted()
{
    if (ui->edit_name->text().isEmpty())
    {
        ui->label_error_empty->show();
        return;
    }

    Params p;
    p.Add("name", ui->edit_name->text().toUtf8().constData());
    p.Add("type", "scenario");

    if (ui->checkBox_visible->isChecked())
        p.Add("visible", "true");
    else
        p.Add("visible", "false");

    IOBase *in = ListeRoom::Instance().createInput(p, room);
    output = in;

    accept();
}
Esempio n. 12
0
string JsonApiClient::buildHttpResponse(string code, Params &headers, string body)
{
    stringstream res;

    //HTTP code
    res << code << "\r\n";

    if (!headers.Exists("Content-Length"))
        headers.Add("Content-Length", Utils::to_string(body.length()));

    if (request_headers["Connection"] == "close" ||
        request_headers["Connection"] == "Close")
    {
        headers.Add("Connection", "Close");
        cDebugDom("network")
                << "Client requested Connection: Close";
    }

    if (headers["Connection"] == "Close" || headers["Connection"] == "close")
        conn_close = true;
    else
        conn_close = false;

    //headers
    for (int i = 0;i < headers.size();i++)
    {
        string key, value;
        headers.get_item(i, key, value);
        res << key << ": " << value << "\r\n";
    }

    res << "\r\n";

    //body
    res << body;

    return res.str();
}
Esempio n. 13
0
void AudioModel::executableDone(Ecore_Exe_Event_Del *event)
{
    if (!event) return;
    PlayerInfoData *data = reinterpret_cast<PlayerInfoData *>(ecore_exe_data_get(event->exe));
    if (!data) return;
    if (data->thumb_exe != event->exe) return;

    PlayerInfo_signal sig;
    sig.connect(data->callback);
    Params p;
    p.Add("filename", data->cover_fname);
    sig.emit(p);

    delete data;
}
Esempio n. 14
0
void AudioPlayer::getDBAlbumCoverItem(Params &item, PlayerInfo_cb callback, int size)
{
    if (!item.Exists("cover_url")) return;

    string fname = Utils::getCacheFile(".cover_cache/album_") + item["cover_id"];

    string cmdsize;
    switch (size)
    {
    default:
    case AUDIO_COVER_SIZE_SMALL: cmdsize = "40x40"; fname += "_small.jpg"; break;
    case AUDIO_COVER_SIZE_MEDIUM: cmdsize = "100x100"; fname += "_medium.jpg"; break;
    case AUDIO_COVER_SIZE_BIG: cmdsize = "250x250"; fname += "_big.jpg"; break;
    }

    if (ecore_file_exists(fname.c_str()))
    {
        PlayerInfo_signal sig;
        sig.connect(callback);
        Params p;
        p.Add("filename", fname);
        sig.emit(p);

        return;
    }

    PlayerInfoData *data = new PlayerInfoData();
    data->cover_fname = fname;
    data->callback = callback;
    data->item = item;

    string cmd;
    cmd = Prefix::Instance().binDirectoryGet();
    cmd += "calaos_thumb " + item["cover_url"] + " " + fname + " " + cmdsize;
    data->thumb_exe = ecore_exe_run(cmd.c_str(), data);
    if (!data->thumb_exe)
    {
        PlayerInfo_signal sig;
        sig.connect(callback);
        Params p;
        sig.emit(p);

        delete data;
    }
}
Esempio n. 15
0
void AudioPlayer::cover_cb(bool success, vector<string> result, void *data)
{
    PlayerInfoData *user_data = reinterpret_cast<PlayerInfoData *>(data);
    if (!user_data) return; //Probably leaking here !

    if (result.size() < 3) return;

    Params infos;

    vector<string> tmp;
    Utils::split(result[2], tmp, ":", 2);
    if (tmp.size() < 2) return;

    infos.Add("cover", tmp[1]);

    PlayerInfo_signal sig;
    sig.connect(user_data->callback);
    sig.emit(infos);

    delete user_data;
}
Esempio n. 16
0
void ActivityAudioListView::browserShowAlbumTracks(Params &infos, int album_id, Params album_infos)
{
    if (!infos.Exists("count")) return;

    EmitSignal("browser,loading,stop", "calaos");

    album_infos.Add("count", infos["count"]);
    int count;
    from_string(infos["count"], count);

    CREATE_GENLIST_HELPER(glist);

    GenlistItemAlbumHeader *header = new GenlistItemAlbumHeader(evas, parent, player_current->getPlayer(), album_infos, album_id);
    header->Append(glist);
    for (int i = 0;i < count;i++)
    {
        GenlistItemTrack *item = new GenlistItemTrack(evas, parent, player_current->getPlayer(), i, GenlistItemTrack::TRACK_ALBUM, album_id);
        item->Append(glist, NULL);
    }

    elm_naviframe_item_push(pager_browser, NULL, NULL, NULL, glist, "calaos");
}
Esempio n. 17
0
void AudioPlayer::db_default_item_list_get_cb(bool success, vector<string> result, void *data)
{
    PlayerInfoData *user_data = reinterpret_cast<PlayerInfoData *>(data);
    if (!user_data) return; //Probably leaking here !

    if (result.size() < 4) return;

    list<Params> infos;
    Params item;
    int cpt = 0;

    for (uint b = 4;b < result.size();b++)
    {
        string tmp = result[b];
        vector<string> tk;
        split(tmp, tk, ":", 2);
        if (tk.size() != 2) continue;

        if (tk[0] == "id")
        {
            if (cpt > 0) infos.push_back(item);
            item.clear();
            cpt++;
        }

        item.Add(tk[0], url_decode2(tk[1]));
    }

    if (item.size() > 0) infos.push_back(item);

    PlayerInfoList_signal sig;
    sig.connect(user_data->callback_list);
    sig.emit(infos);

    delete user_data;
}
Esempio n. 18
0
void DialogNewTime::on_buttonBox_accepted()
{
    if (ui->edit_name->text().isEmpty())
    {
        ui->label_error_empty->show();
        return;
    }

    Params p;
    p.Add("name", ui->edit_name->text().toUtf8().constData());

    if (ui->tab_model->currentIndex() == 0) //Time/DateTime
    {
        p.Add("type", "InputTime");

        if (ui->check_time->isChecked())
        {
            p.Add("hour", to_string(ui->heure->time().hour()));
            p.Add("min", to_string(ui->heure->time().minute()));
            p.Add("sec", to_string(ui->heure->time().second()));
        }
        else if (ui->check_datetime->isChecked())
        {
            p.Add("hour", to_string(ui->date_heure->time().hour()));
            p.Add("min", to_string(ui->date_heure->time().minute()));
            p.Add("sec", to_string(ui->date_heure->time().second()));
            p.Add("day", to_string(ui->date_heure->date().day()));
            p.Add("month", to_string(ui->date_heure->date().month()));
            p.Add("year", to_string(ui->date_heure->date().year()));
        }
    }
    else if (ui->tab_model->currentIndex() == 1) //Timer
    {
        p.Add("type", "InputTimer");
        p.Add("hour", to_string(ui->timer->time().hour()));
        p.Add("min", to_string(ui->timer->time().minute()));
        p.Add("sec", to_string(ui->timer->time().second()));
        p.Add("msec", to_string(ui->timer->time().msec()));
        p.Add("autostart", ui->checkBoxAutoBoot->isChecked()?"true":"false");
        p.Add("autorestart", ui->checkBoxAutoRestart->isChecked()?"true":"false");
    }
    else if (ui->tab_model->currentIndex() == 2) //Plage
    {
        p.Add("type", "InPlageHoraire");
    }
    else
    {
        QMessageBox::warning(this, tr("Calaos Installer"), tr("Unknown type!"));

        return;
    }

    input = ListeRoom::Instance().createInput(p, room);

    accept();
}
Esempio n. 19
0
void TCPConnection::ScenarioCommand(Params &request, ProcessDone_cb callback)
{
    Params result = request;

    if (request["0"] != "scenario")
    {
        cDebugDom("network") << "Wrong command !";

        ProcessDone_signal sig;
        sig.connect(callback);
        sig.emit(result);

        return;
    }

    if (request["1"] == "list")
    {
        cDebugDom("network") << "list";

        list<Scenario *> l = ListeRoom::Instance().getAutoScenarios();
        list<Scenario *>::iterator it = l.begin();

        for (int i = 2;it != l.end();it++, i++)
            result.Add(Utils::to_string(i), (*it)->get_param("id"));
    }
    else if (request["1"] == "get")
    {
        cDebugDom("network") << "get";

        Scenario *sc = dynamic_cast<Scenario *>(ListeRoom::Instance().get_input(request["2"]));
        if (sc && sc->getAutoScenario())
        {
            AutoScenario *a = sc->getAutoScenario();
            int cpt = 3;
            result.Add(Utils::to_string(cpt), "cycle:" + string(a->isCycling()?"true":"false"));
            cpt++;
            result.Add(Utils::to_string(cpt), "enabled:" + string(a->isDisabled()?"false":"true"));
            cpt++;
            if (a->isScheduled())
                result.Add(Utils::to_string(cpt), string("schedule:") + a->getIOPlage()->get_param("id"));
            else
                result.Add(Utils::to_string(cpt), "schedule:false");
            cpt++;
            result.Add(Utils::to_string(cpt), "category:" + a->getCategory());
            cpt++;

            result.Add(Utils::to_string(cpt), "steps_count:" + Utils::to_string(a->getRuleSteps().size()));
            cpt++;

            for (uint i = 0;i < a->getRuleSteps().size();i++)
            {
                result.Add(Utils::to_string(cpt), "step:" + Utils::to_string(a->getStepPause(i)));
                cpt++;
                for (int j = 0;j < a->getStepActionCount(i);j++)
                {
                    ScenarioAction sa = a->getStepAction(i, j);
                    result.Add(Utils::to_string(cpt), sa.io->get_param("id") + ":" + sa.action);
                    cpt++;
                }
            }

            //End step
            result.Add(Utils::to_string(cpt), "step_end");
            cpt++;
            for (int j = 0;j < a->getEndStepActionCount();j++)
            {
                ScenarioAction sa = a->getEndStepAction(j);
                result.Add(Utils::to_string(cpt), sa.io->get_param("id") + ":" + sa.action);
                cpt++;
            }
        }
    }
    else if (request["1"] == "create")
    {
        cDebugDom("network") << "create";

        Params params;
        string room_name;
        Room *room = NULL;
        params.Add("auto_scenario", Calaos::get_new_scenario_id());
        int s = -1;
        Scenario *scenario = NULL;
        for (int i = 2;i < request.size();i++)
        {
            vector<string> tokens;
            split(request[Utils::to_string(i)], tokens, ":", 2);

            if (tokens[0] == "name") params.Add("name", url_decode(tokens[1]));
            else if (tokens[0] == "visible") params.Add("visible", tokens[1]);
            else if (tokens[0] == "room_name") room_name = url_decode(tokens[1]);
            else if (tokens[0] == "room_type") room = ListeRoom::Instance().searchRoomByNameAndType(room_name, url_decode(tokens[1]));
            else if (tokens[0] == "cycle") params.Add("cycle", tokens[1]);
            else if (tokens[0] == "disabled") params.Add("disabled", tokens[1]);
            else if (tokens[0] == "step")
            {
                if (!scenario)
                {
                    params.Add("type", "scenario");
                    if (!room) room = ListeRoom::Instance().get_room(0);
                    Input *in = ListeRoom::Instance().createInput(params, room);
                    scenario = dynamic_cast<Scenario *>(in);
                    scenario->getAutoScenario()->checkScenarioRules();

                    string sig = "new_scenario id:";
                    sig += scenario->get_param("id");
                    IPC::Instance().SendEvent("events", sig);
                }

                double pause;
                from_string(tokens[1], pause);

                s++;

                scenario->getAutoScenario()->addStep(pause);
            }
            else if (tokens[0] == "step_end")
            {
                if (!scenario)
                {
                    params.Add("type", "scenario");
                    if (!room) ListeRoom::Instance().get_room(0);
                    Input *in = ListeRoom::Instance().createInput(params, room);
                    scenario = dynamic_cast<Scenario *>(in);
                    scenario->getAutoScenario()->checkScenarioRules();

                    string sig = "new_scenario id:";
                    sig += scenario->get_param("id");
                    IPC::Instance().SendEvent("events", sig);
                }

                s = AutoScenario::END_STEP;
            }
            else if (s >= 0)
            {
                Output *out = ListeRoom::Instance().get_output(url_decode(tokens[0]));
                if (out)
                    scenario->getAutoScenario()->addStepAction(s, out, url_decode(tokens[1]));
            }
        }

        //Resave config, auto scenarios have probably created/deleted ios and rules
        Config::Instance().SaveConfigIO();
        Config::Instance().SaveConfigRule();
    }
    else if (request["1"] == "delete")
    {
        cDebugDom("network") << "delete";

        Scenario *sc = dynamic_cast<Scenario *>(ListeRoom::Instance().get_input(request["2"]));
        if (sc && sc->getAutoScenario())
        {
            sc->getAutoScenario()->deleteAll();

            //delete the scenario IO
            ListeRoom::Instance().deleteIO(dynamic_cast<Input *>(sc));

            string sig = "delete_scenario id:";
            sig += request["2"];
            IPC::Instance().SendEvent("events", sig);

            //Resave config
            Config::Instance().SaveConfigIO();
            Config::Instance().SaveConfigRule();
        }
    }
    else if (request["1"] == "modify")
    {
        cDebugDom("network") << "modify";

        Scenario *scenario = dynamic_cast<Scenario *>(ListeRoom::Instance().get_input(request["2"]));
        if (scenario && scenario->getAutoScenario())
        {
            scenario->getAutoScenario()->deleteRules();

            Params params;
            string room_name;
            Room *room = NULL;
            int s = -1;

            for (int i = 2;i < request.size();i++)
            {
                vector<string> tokens;
                split(request[Utils::to_string(i)], tokens, ":", 2);

                if (tokens[0] == "name") params.Add("name", url_decode(tokens[1]));
                else if (tokens[0] == "visible") params.Add("visible", tokens[1]);
                else if (tokens[0] == "room_name") room_name = url_decode(tokens[1]);
                else if (tokens[0] == "room_type") room = ListeRoom::Instance().searchRoomByNameAndType(room_name, url_decode(tokens[1]));
                else if (tokens[0] == "cycle") params.Add("cycle", tokens[1]);
                else if (tokens[0] == "disabled") params.Add("disabled", tokens[1]);
                else if (tokens[0] == "step")
                {
                    double pause;
                    from_string(tokens[1], pause);
                    s++;
                    scenario->getAutoScenario()->addStep(pause);
                }
                else if (tokens[0] == "step_end")
                {
                    s = AutoScenario::END_STEP;
                }
                else if (s >= 0)
                {
                    Output *out = ListeRoom::Instance().get_output(url_decode(tokens[0]));
                    if (out)
                        scenario->getAutoScenario()->addStepAction(s, out, url_decode(tokens[1]));
                }
            }

            //Check for changes
            if (params["name"] != scenario->get_param("name"))
            {
                scenario->set_param("name", params["name"]);

                string sig = "output ";
                sig += scenario->get_param("id") + " ";
                sig += url_encode("name" + string(":") + params["name"]) + " ";
                IPC::Instance().SendEvent("events", sig);

                sig = "input ";
                sig += scenario->get_param("id") + " ";
                sig += url_encode("name" + string(":") + params["name"]) + " ";
                IPC::Instance().SendEvent("events", sig);
            }

            if (params["visible"] != scenario->get_param("visible"))
            {
                scenario->set_param("visible", params["visible"]);

                string sig = "output ";
                sig += scenario->get_param("id") + " ";
                sig += url_encode("visible" + string(":") + params["visible"]) + " ";
                IPC::Instance().SendEvent("events", sig);

                sig = "input ";
                sig += scenario->get_param("id") + " ";
                sig += url_encode("visible" + string(":") + params["visible"]) + " ";
                IPC::Instance().SendEvent("events", sig);
            }

            Room *old_room = ListeRoom::Instance().getRoomByInput(scenario);
            if (room != old_room)
            {
                if (room)
                {
                    old_room->RemoveInputFromRoom(dynamic_cast<Input *>(scenario));
                    old_room->RemoveOutputFromRoom(dynamic_cast<Output *>(scenario));
                    room->AddInput(dynamic_cast<Input *>(scenario));
                    room->AddOutput(dynamic_cast<Output *>(scenario));

                    string sig = "modify_room ";
                    sig += url_encode(string("input_add:") + scenario->get_param("id")) + " ";
                    sig += url_encode(string("room_name:") + room->get_name()) + " ";
                    sig += url_encode(string("room_type:") + room->get_type());
                    IPC::Instance().SendEvent("events", sig);
                    sig = "modify_room ";
                    sig += url_encode(string("output_add:") + scenario->get_param("id")) + " ";
                    sig += url_encode(string("room_name:") + room->get_name()) + " ";
                    sig += url_encode(string("room_type:") + room->get_type());
                    IPC::Instance().SendEvent("events", sig);
                }
            }

            if (params["cycle"] != scenario->get_param("cycle"))
            {
                if (params["cycle"] == "true")
                    scenario->getAutoScenario()->setCycling(true);
                else
                    scenario->getAutoScenario()->setCycling(false);
            }

            if (params["disabled"] != scenario->get_param("disabled"))
            {
                if (params["disabled"] == "true")
                    scenario->getAutoScenario()->setDisabled(true);
                else
                    scenario->getAutoScenario()->setDisabled(false);
            }

            scenario->getAutoScenario()->checkScenarioRules();

            //Resave config
            Config::Instance().SaveConfigIO();
            Config::Instance().SaveConfigRule();

            string sig = "modify_scenario id:";
            sig += request["2"];
            IPC::Instance().SendEvent("events", sig);
        }
    }
    else if (request["1"] == "add_schedule")
    {
        cDebugDom("network") << "add_schedule";

        Scenario *sc = dynamic_cast<Scenario *>(ListeRoom::Instance().get_input(request["2"]));
        if (sc && sc->getAutoScenario())
        {
            sc->getAutoScenario()->addSchedule();

            //Resave config
            Config::Instance().SaveConfigIO();
            Config::Instance().SaveConfigRule();

            result.clear();
            result.Add("0", "scenario");
            result.Add("1", request["2"]);
            result.Add("2", string("schedule_id:") + sc->getAutoScenario()->getIOPlage()->get_param("id"));

            string sig = "modify_scenario id:";
            sig += request["2"];
            IPC::Instance().SendEvent("events", sig);
        }
    }
    else if (request["1"] == "del_schedule")
    {
        cDebugDom("network") << "add_schedule";

        Scenario *sc = dynamic_cast<Scenario *>(ListeRoom::Instance().get_input(request["2"]));
        if (sc && sc->getAutoScenario())
        {
            sc->getAutoScenario()->deleteSchedule();

            //Resave config
            Config::Instance().SaveConfigIO();
            Config::Instance().SaveConfigRule();

            result.clear();
            result.Add("0", "scenario");
            result.Add("1", "ok");

            string sig = "modify_scenario id:";
            sig += request["2"];
            IPC::Instance().SendEvent("events", sig);
        }
    }

    ProcessDone_signal sig;
    sig.connect(callback);
    sig.emit(result);
}
void DialogNewInternal::on_buttonBox_accepted()
{
    if (ui->edit_name->text().isEmpty())
    {
        ui->label_error_empty->show();
        return;
    }

    Params p;
    p.Add("name", ui->edit_name->text().toUtf8().constData());

    if (ui->radioButton_bool->isChecked())
    {
        p.Add("type", "InternalBool");
        if (ui->value_bool->isChecked())
            p.Add("value", "true");
        else
            p.Add("value", "false");
    }
    else if (ui->radioButton_int->isChecked())
    {
        p.Add("type", "InternalInt");
        p.Add("value", to_string(ui->value_int->value()));
    }
    else if (ui->radioButton_text->isChecked())
    {
        p.Add("type", "InternalString");
        p.Add("value", ui->value_text->text().toUtf8().constData());
    }

    if (ui->checkBox_rw->isChecked())
        p.Add("rw", "true");
    else
        p.Add("rw", "false");

    if (ui->checkBox_save->isChecked())
        p.Add("save", "true");
    else
        p.Add("save", "false");

    if (ui->checkBox_visible->isChecked())
        p.Add("visible", "true");
    else
        p.Add("visible", "false");

    IOBase *in = ListeRoom::Instance().createInput(p, room);
    output = in;

    accept();
}
Esempio n. 21
0
void JsonApiHandlerHttp::processApi(const string &data, const Params &paramsGET)
{
    jsonParam.clear();

    //parse the json data
    json_error_t jerr;
    json_t *jroot = json_loads(data.c_str(), 0, &jerr);

    if (!jroot || !json_is_object(jroot))
    {
        cDebugDom("network") << "Error loading json : " << jerr.text << ". No JSON, trying with GET parameters.";

        jsonParam = paramsGET;

        if (jroot)
        {
            json_decref(jroot);
            jroot = nullptr;
        }
    }
    else
    {
        char *d = json_dumps(jroot, JSON_INDENT(4));
        if (d)
        {
            cDebugDom("network") << d;
            free(d);
        }

        //decode the json root object into jsonParam
        jansson_decode_object(jroot, jsonParam);
    }


    //check for if username/password matches
    string user = Utils::get_config_option("calaos_user");
    string pass = Utils::get_config_option("calaos_password");

    if (Utils::get_config_option("cn_user") != "" &&
            Utils::get_config_option("cn_pass") != "")
    {
        user = Utils::get_config_option("cn_user");
        pass = Utils::get_config_option("cn_pass");
    }

    if (user != jsonParam["cn_user"] || pass != jsonParam["cn_pass"])
    {
        cDebugDom("network") << "Login failed!";

        Params headers;
        headers.Add("Connection", "close");
        headers.Add("Content-Type", "text/html");
        string res = httpClient->buildHttpResponse(HTTP_400, headers, HTTP_400_BODY);
        sendData.emit(res);
        closeConnection.emit(0, string());

        if (jroot)
        {
            json_decref(jroot);
            jroot = nullptr;
        }

        return;
    }

    //check action now
    if (jsonParam["action"] == "get_home")
        processGetHome();
    else if (jsonParam["action"] == "get_state")
        processGetState(jroot);
    else if (jsonParam["action"] == "get_states")
        processGetStates();
    else if (jsonParam["action"] == "query")
        processQuery();
    else if (jsonParam["action"] == "get_param")
        processGetParam();
    else if (jsonParam["action"] == "set_param")
        processSetParam();
    else if (jsonParam["action"] == "del_param")
        processDelParam();
    else if (jsonParam["action"] == "set_state")
        processSetState();
    else if (jsonParam["action"] == "get_playlist")
        processGetPlaylist();
    else if (jsonParam["action"] == "poll_listen")
        processPolling();
    else if (jsonParam["action"] == "get_cover")
        processGetCover();
    else if (jsonParam["action"] == "get_camera_pic")
        processGetCameraPic();
    else if (jsonParam["action"] == "get_timerange")
        processGetTimerange();
    else if (jsonParam["action"] == "camera")
        processCamera();
    else
    {
        if (!jroot)
        {
            Params headers;
            headers.Add("Connection", "close");
            headers.Add("Content-Type", "text/html");
            string res = httpClient->buildHttpResponse(HTTP_400, headers, HTTP_400_BODY);
            sendData.emit(res);
            closeConnection.emit(0, string());

            if (jroot)
                json_decref(jroot);

            return;
        }

        if (jsonParam["action"] == "config")
            processConfig(jroot);
        else if (jsonParam["action"] == "get_io")
            processGetIO(jroot);
        else if (jsonParam["action"] == "audio")
            processAudio(jroot);
        else if (jsonParam["action"] == "audio_db")
            processAudioDb(jroot);
        else if (jsonParam["action"] == "set_timerange")
            processSetTimerange(jroot);
        else if (jsonParam["action"] == "autoscenario")
            processAutoscenario(jroot);
    }

    if (jroot)
        json_decref(jroot);
}
Esempio n. 22
0
void DialogNewCamera::on_buttonBox_accepted()
{
    if (ui->edit_name->text().isEmpty())
    {
        ui->label_error_empty->show();
        return;
    }

    Params p;
    p.Add("name", ui->edit_name->text().toUtf8().constData());

    if (ui->tab_camera_model->currentIndex() == 0) //Axis
    {
        p.Add("type", "axis");
        p.Add("port", "80");
        p.Add("host", ui->axis_ip->text().toUtf8().constData());
        p.Add("model", ui->axis_cam->text().toUtf8().constData());
    }
    else if (ui->tab_camera_model->currentIndex() == 1) //Planet
    {
        p.Add("type", "planet");
        p.Add("port", "80");
        p.Add("host", ui->planet_ip->text().toUtf8().constData());
        p.Add("model", ui->planet_model->currentItem()->text().toUtf8().constData());
    }
    else if (ui->tab_camera_model->currentIndex() == 2) //Gadspot
    {
        p.Add("type", "gadspot");
        p.Add("port", "80");
        p.Add("host", ui->gadspot_ip->text().toUtf8().constData());
    }
    else if (ui->tab_camera_model->currentIndex() == 3) //Standard
    {
        p.Add("type", "standard_mjpeg");
        p.Add("port", "80");
        p.Add("host", ui->std_ip->text().toUtf8().constData());
        p.Add("url_jpeg", ui->std_url_jpeg->text().toUtf8().constData());
        p.Add("url_mjpeg", ui->std_url_mjpeg->text().toUtf8().constData());
        p.Add("url_mpeg", ui->std_url_mpeg4->text().toUtf8().constData());
    }
    else if (ui->tab_camera_model->currentIndex() == 4) //Synology
    {
        p.Add("type", "SynoSurveillanceStation");
        p.Add("url", ui->dsm_url->text().toUtf8().constData());
        p.Add("username", ui->dsm_username->text().toUtf8().constData());
        p.Add("password", ui->dsm_password->text().toUtf8().constData());

        auto sel = ui->treeWidgetDsmCam->selectedItems();
        if (sel.count() <= 0)
            p.Add("camera_id", "0");
        else
        {
            auto item = sel.at(0);
            p.Add("camera_id", item->text(0).toUtf8().constData());
        }
    }
    else
    {
        QMessageBox::warning(this, tr("Calaos Installer"), QString::fromUtf8("Type de caméra inconnu!"));

        return;
    }

    output = ListeRoom::Instance().createCamera(p, room);

    accept();
}
Esempio n. 23
0
void TCPConnection::BaseCommand(Params &request, ProcessDone_cb callback)
{
    Params result = request;
    if (request["0"] == "version")
    {
        cDebugDom("network") << "version";
        if (request["1"] == "?")
            result.Add("1", Utils::get_config_option("fw_version"));
    }
    else if (request["0"] == "save")
    {
        cDebugDom("network") << "save";

        Config::Instance().SaveConfigIO();
        Config::Instance().SaveConfigRule();

        if (request["1"] == "default")
        {
            //copy the default config files
            Utils::file_copy(ETC_DIR"io.xml", "/mnt/ext3/calaos/io.default");
            Utils::file_copy(ETC_DIR"rules.xml", "/mnt/ext3/calaos/rules.default");
        }
    }
    else if (request["0"] == "system")
    {
        cDebugDom("network") << "system";

        if (request["1"] == "reboot")
        {
            if (request["2"] == "calaos_gui")
            {
                int unused = system("killall -9 calaos_gui");
                unused = system("killall -9 calaos_thumb");
                (void)unused;
            }
            else if (request["2"] == "calaosd")
            {
                int unused = system("killall -9 calaosd");
                (void)unused;
            }
            else if (request["2"] == "all")
            {
                int unused = system("reboot");
                (void)unused;
            }
        }
        else if(request["1"] == "date")
        {
            vector<string> vcmd;
            for(int i=0;i<request.size();i++)
            {
                string s = Utils::to_string(i);
                vcmd.push_back(request[s]);

            }
            NTPClock::Instance().setNetworkCmdCalendarApply(vcmd);
            NTPClock::Instance().setRestartWhenApply(false);
            IPC::Instance().SendEvent("CalaosCommon::NTPClock","applyCalendar",NULL);

            result.Add("2", "ok");

            string cmd = "";
            for(int i=0;i<9;i++)
                cmd+=request[Utils::to_string(i)]+" ";
            //envoie de la commandes aux clients
            TCPSocket *sock;
            sock = new TCPSocket;
            sock->Create(UDP);
            sock->Broadcast(cmd, BCAST_UDP_PORT);
            sock->Close();
            delete sock;
        }
    }
    else if (request["0"] == "firmware")
    {
        cDebugDom("network") << "firmware";

        if (request["1"] == "webupdate")
        {
            //try to update firmware from /tmp/image.tar.bz2
            cDebugDom("network") << "save: Firmware update requested by web.";
            int unused = system("fw_update.sh");
            (void)unused;
        }
    }
    else if (request["0"] == "poll_listen")
    {
        cDebugDom("network") << "poll_listen";

        if (request["1"] == "register")
        {
            string uuid = PollListenner::Instance().Register();
            result.Add("2", uuid);
        }
        else if (request["1"] == "unregister")
        {
            if (PollListenner::Instance().Unregister(request["2"]))
                result.Add("2", "true");
            else
                result.Add("2", "false");
        }
        else if (request["1"] == "get")
        {
            Params events;

            bool res = PollListenner::Instance().GetEvents(request["2"], events);

            result.Add("2", "");

            if (!res)
            {
                result.Add("2", "error");
            }
            else
            {
                int c = 2;

                for (int i = 0;i < events.size();i++)
                {
                    string key, value;
                    events.get_item(i, key, value);

                    result.Add(Utils::to_string(c), key + ":" + url_encode(value));

                    c++;
                }
            }
        }
    }

    ProcessDone_signal sig;
    sig.connect(callback);
    sig.emit(result);
}
Esempio n. 24
0
void JsonApiClient::ProcessData(string request)
{
    size_t nparsed;

    nparsed = http_parser_execute(parser, &parser_settings, request.c_str(), request.size());

    if (parser->upgrade)
    {
        /* handle new protocol */
        cDebugDom("network") << "Protocol Upgrade not supported, closing connection.";
        CloseConnection();

        return;
    }
    else if (nparsed != request.size())
    {
        /* Handle error. Usually just close the connection. */
        CloseConnection();

        return;
    }

    if (parse_done)
    {
        //Finally parsing of request is done, we can search for
        //a response for the requested path


        cDebugDom("network") << "Client headers: HTTP/" << Utils::to_string(parser->http_major) << "." << Utils::to_string(parser->http_minor);
        for (auto it = request_headers.begin();it!= request_headers.end();++it)
            cDebugDom("network") << it->first << ": " << it->second;

        //init parser again
        http_parser_init(parser, HTTP_REQUEST);
        parser->data = this;

        hef::HfURISyntax req_url("http://0.0.0.0" + parse_url);

        if (req_url.getPath() == "/" ||
            req_url.getPath() == "/index.html" ||
            req_url.getPath() == "/debug.html")
        {
            Params headers;
            headers.Add("Connection", "Close");
            headers.Add("Content-Type", "text/html");
            string fileName = Prefix::Instance().dataDirectoryGet() + "/debug.html";
            cDebug() << "send file " << fileName << "to Client";
            string res = buildHttpResponseFromFile(HTTP_200, headers, fileName);
            sendToClient(res);

            return;
        }

        if (req_url.getPath() != "/api" &&
            req_url.getPath() != "/api.php" &&
            req_url.getPath() != "/api/v1" /*&&
                        req_url.getPath() != "/api/v1.5" &&
                        req_url.getPath() != "/api/v2"*/)
        {
            Params headers;
            headers.Add("Connection", "close");
            headers.Add("Content-Type", "text/html");
            string res = buildHttpResponse(HTTP_400, headers, HTTP_400_BODY);
            sendToClient(res);

            return;
        }


        //get protocol version, if nothing is set default to v1
        proto_ver = APIV1;
        if (req_url.getPath() == "/api/v1.5") proto_ver = APIV1_5;
        if (req_url.getPath() == "/api/v2") proto_ver = APIV2;

        //TODO: get url parameters here?
        //for example get username/password as a url parameter

        //Handle CORS here
        if (jsonParam.Exists("Origin"))
        {
            resHeaders.Add("Access-Control-Allow-Origin", jsonParam["Origin"]);
            resHeaders.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        }

        if (request_method == HTTP_OPTIONS)
        {
            if (jsonParam.Exists("Access-Control-Request-Method"))
                resHeaders.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");

            if (jsonParam.Exists("Access-Control-Request-Headers"))
                resHeaders.Add("Access-Control-Allow-Headers", "{" + jsonParam["Access-Control-Request-Headers"] + "}");

            Params headers;
            headers.Add("Connection", "Close");
            headers.Add("Cache-Control", "no-cache, must-revalidate");
            headers.Add("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
            headers.Add("Content-Type", "text/html");
            string res = buildHttpResponse(HTTP_200, headers, "");
            sendToClient(res);

            return;
        }

        //handle request now
        handleRequest();
    }
}
Esempio n. 25
0
void DialogNewWebIO::on_buttonBox_accepted()
{
    if (ui->edit_name->text().isEmpty())
    {
        ui->label_error_empty->show();
        return;
    }
    else if (ui->label_error_path_empty->text().isEmpty())
    {
        ui->label_error_path_empty->show();
        return;
    }
    else if (ui->label_error_url_empty->text().isEmpty())
    {
        ui->label_error_url_empty->show();
        return;
    }

    Params p;
    p.Add("name", ui->edit_name->text().toUtf8().constData());



    p.Add("url", to_string(ui->edit_url->text().toUtf8().constData()));
    p.Add("path", to_string(ui->edit_path->text().toUtf8().constData()));
    p.Add("file_type", to_string(ui->data_type->currentText().toLower().toUtf8().constData()));
    p.Add("frequency", QString::number(ui->spin_frequency->value()).toUtf8().constData());
    if (analogWidget)
    {
        p.Add("unit", analogWidget->getUnit().toUtf8().constData());
        p.Add("coeff_a",  QString::number(analogWidget->getCoeff()).toUtf8().constData());
        p.Add("coeff_b",  QString::number(analogWidget->getOffset()).toUtf8().constData());
        p.Add("step",  QString::number(analogWidget->getStep()).toUtf8().constData());
        p.Add("min",  QString::number(analogWidget->getMin()).toUtf8().constData());
        p.Add("max",  QString::number(analogWidget->getMax()).toUtf8().constData());
    }
    switch (ui->io_type->currentIndex())
      {
      case 0:
      case 1:
        type = "WebOutputLight";
        p.Add("on_value", to_string(ui->edit_value_on->text().toUtf8().constData()));
        p.Add("off_value", to_string(ui->edit_value_off->text().toUtf8().constData()));
        p.Add("type", type);
        io = ListeRoom::Instance().createOutput(p, room);
        break;
      case 2:
        type = "WebOutputLightRGB";
        p.Add("type", type);
        io = ListeRoom::Instance().createOutput(p, room);
        break;
      case 4:
        type = "WebInputTemp";
        p.Add("type", type);
        io = ListeRoom::Instance().createInput(p, room);
        break;
      case 5:
        type = "WebInputAnalog";
        p.Add("type", type);
        io = ListeRoom::Instance().createInput(p, room);
        break;
      case 7:
        type = "WebInputString";
        p.Add("type", type);
        io = ListeRoom::Instance().createInput(p, room);
        break;
      case 8:
        type = "WebOutputString";
        p.Add("type", type);
        io = ListeRoom::Instance().createOutput(p, room);
        break;
      default:
        break;
      }
    accept();
}