Commit e1a2a82b authored by jan.koester's avatar jan.koester
Browse files

weather plugin

parent 3d85b87e
Loading
Loading
Loading
Loading
+1 −0
Changes for plugins/CMakeLists.txt: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -13,3 +13,4 @@ add_subdirectory(gtm)
add_subdirectory(social)
add_subdirectory(letsencrypt)
add_subdirectory(google)
add_subdirectory(weather)
+13 −0
Changes for plugins/weather/CMakeLists.txt: 13 added lines, 0 removed lines.
Original line number Diff line number Diff line
find_package(json-c REQUIRED)

add_library(weather SHARED weather.cpp)

add_dependencies(weather blogidev)

if(${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Windows")
    target_link_libraries(weather PUBLIC kernel32.lib blogidev json-c::json-c uuidp::uuidp)
else()
    target_link_libraries(weather PUBLIC dl blogidev json-c::json-c uuidp::uuidp)
endif()

install (TARGETS weather  DESTINATION lib/blogi/plugins)
+379 −0
Changes for plugins/weather/weather.cpp: 379 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
 * Copyright (c) 2026, Jan Koester jan.koester@gmx.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * Neither the name of the <organization> nor the
 *      names of its contributors may be used to endorse or promote products
 *      derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#include <httppp/http.h>
#include <httppp/exception.h>

#include <htmlpp/html.h>
#include <htmlpp/exception.h>

#include <dbpp/database.h>
#include <uuidp.h>

#include <json-c/json.h>
#include <json-c/json_object.h>

#include <netplus/exception.h>

#include "plugin.h"
#include "theme.h"
#include "conf.h"
#include <i18n.h>
#include <compress.h>

namespace blogi {

    // Reads the JSON status endpoint of a weatherstationd instance
    // (see weatherstation/src/webui.cpp: GET /api/status) and renders
    // one card per configured station. URL and location name are the
    // only per-station settings, matching what the weatherstationd
    // endpoint itself needs (no auth: /api/status is a public read-only
    // route).
    class Weather : public PluginApi {
    public:
        Weather(){
        }

        const std::string getName(){
            return "weather";
        }

        const std::string getVersion(){
            return "1.0";
        }

        const std::string getAuthor(){
            return "Jan Koester";
        }

        void initPlugin(){
            registerGPO("195efb24-960d-4fdf-8718-1005ec6610fb",
                        "Blogi: Weather Settings",
                        "Controls access to weather station settings",
                        true);

            dbpp::SQL      sql;
            dbpp::DBResult res;
            dbpp::SQL uuidTypeSql;
            const dbpp::SQL uuidType = Args->database[0]->getUUIDType(uuidTypeSql);

            sql << "CREATE TABLE IF NOT EXISTS weatherstations ("
                <<   "id " << uuidType << " PRIMARY KEY,"
                <<   "name character varying(255) NOT NULL,"
                <<   "url character varying(500) NOT NULL"
                << ");";
            Args->database[0]->exec(sql,res);
        }

        bool haveSettings(){
            return true;
        }

        json_object* Settings(const int tid,libhttppp::HttpRequest &req,const std::string &sessionid){
            std::string _lang = getLang(*Args->database[tid]);
            bool saved = false;

            libhttppp::HttpForm form;
            form.parse(req);

            std::string formName, formUrl, delId;
            bool hasForm = false;

            for(const auto &cur : form.urlData()){
                if(cur.key=="station_name"){
                    formName = cur.value;
                    hasForm = true;
                }else if(cur.key=="station_url"){
                    formUrl = cur.value;
                    hasForm = true;
                }else if(cur.key=="delete_id"){
                    delId = cur.value;
                }
            }

            if(!delId.empty()){
                dbpp::SQL sql;
                dbpp::DBResult res;
                std::vector<char> buf;
                sql << "DELETE FROM weatherstations WHERE id='" << sql.escaped(buf, delId.c_str()) << "'";
                Args->database[tid]->exec(sql,res);
                saved = true;
            }

            if(hasForm && !formName.empty() && !formUrl.empty()){
                dbpp::SQL sql;
                dbpp::DBResult res;
                std::vector<char> buf;
                uuid::uuid stId;
                stId.generate();
                sql << "INSERT INTO weatherstations (id,name,url) VALUES ('"
                    << stId.c_str() << "','"
                    << sql.escaped(buf, formName.c_str()) << "','"
                    << sql.escaped(buf, formUrl.c_str()) << "')";
                Args->database[tid]->exec(sql,res);
                saved = true;
            }

            json_object *jroot = json_object_new_object();
            json_object_object_add(jroot, "title", json_object_new_string(tr(_lang,"Weather Stations").c_str()));

            if(saved){
                json_object_object_add(jroot, "message", json_object_new_string(tr(_lang,"Saved!").c_str()));
                json_object_object_add(jroot, "message_type", json_object_new_string("success"));
            }

            json_object *jitems = json_object_new_array();
            {
                dbpp::SQL sql;
                dbpp::DBResult res;
                sql << "SELECT id,name,url FROM weatherstations ORDER BY name";
                int count = Args->database[tid]->exec(sql,res);
                for(int i = 0; i < count; ++i){
                    json_object *ji = json_object_new_object();
                    json_object_object_add(ji, "id",   json_object_new_string(res[i][0].c_str()));
                    json_object_object_add(ji, "name", json_object_new_string(res[i][1].c_str()));
                    json_object_object_add(ji, "url",  json_object_new_string(res[i][2].c_str()));
                    json_object_array_add(jitems, ji);
                }
            }
            json_object_object_add(jroot, "items", jitems);

            json_object *jform = json_object_new_object();
            json_object_object_add(jform, "method", json_object_new_string("POST"));
            json_object_object_add(jform, "action", json_object_new_string(
                Args->config->buildurl("settings/weather").c_str()));

            json_object *jfields = json_object_new_array();

            auto addField = [&](const char *name, const char *label, const char *placeholder){
                json_object *jf = json_object_new_object();
                json_object_object_add(jf, "name",  json_object_new_string(name));
                json_object_object_add(jf, "label", json_object_new_string(label));
                json_object_object_add(jf, "type",  json_object_new_string("text"));
                json_object_object_add(jf, "value", json_object_new_string(""));
                if(placeholder)
                    json_object_object_add(jf, "placeholder", json_object_new_string(placeholder));
                json_object_array_add(jfields, jf);
            };

            addField("station_name", tr(_lang,"Location Name").c_str(), nullptr);
            addField("station_url", tr(_lang,"Station URL").c_str(), "http://host:port");

            json_object_object_add(jform, "fields", jfields);
            json_object_object_add(jform, "submit", json_object_new_string(tr(_lang,"Add Station").c_str()));
            json_object_object_add(jroot, "form", jform);

            json_object *jdelform = json_object_new_object();
            json_object_object_add(jdelform, "method", json_object_new_string("POST"));
            json_object_object_add(jdelform, "action", json_object_new_string(
                Args->config->buildurl("settings/weather").c_str()));
            json_object *jdelfields = json_object_new_array();
            {
                json_object *jf = json_object_new_object();
                json_object_object_add(jf, "name",  json_object_new_string("delete_id"));
                json_object_object_add(jf, "label", json_object_new_string(tr(_lang,"Station ID to delete").c_str()));
                json_object_object_add(jf, "type",  json_object_new_string("text"));
                json_object_object_add(jf, "value", json_object_new_string(""));
                json_object_array_add(jdelfields, jf);
            }
            json_object_object_add(jdelform, "fields", jdelfields);
            json_object_object_add(jdelform, "submit", json_object_new_string(tr(_lang,"Delete Station").c_str()));
            json_object_object_add(jroot, "delete_form", jdelform);

            return jroot;
        }

        bool Controller(const int tid,libhttppp::HttpRequest &req,libhtmlpp::HtmlElement *page,const std::string &sessionid){
            if(req.getRequestURL().compare(0,Args->config->buildurl("weather").length(),Args->config->buildurl("weather"))!=0){
                return false;
            }

            std::string _lang = getLang(*Args->database[tid]);

            dbpp::SQL      sql;
            dbpp::DBResult res;
            sql << "SELECT name,url FROM weatherstations ORDER BY name";
            int count = Args->database[tid]->exec(sql,res);

            libhtmlpp::HtmlString condat;
            condat << "<div id=\"weather-plugin\">"
                   << "<style>"
                   << "#weather-plugin{display:flex;flex-wrap:wrap;gap:1em;}"
                   << "#weather-plugin .wcard{border:1px solid #3a3f44;border-radius:8px;padding:1em 1.5em;min-width:220px;}"
                   << "#weather-plugin .wcard h2{margin:0 0 .5em 0;font-size:1.2em;}"
                   << "#weather-plugin .wrow{display:flex;justify-content:space-between;gap:1.5em;padding:.15em 0;}"
                   << "#weather-plugin .wrow .wlabel{opacity:.7;}"
                   << "#weather-plugin .wcard.offline{opacity:.6;}"
                   << "</style>";

            if(count < 1){
                condat << "<p>" << tr(_lang,"No weather stations configured.") << "</p>";
            }

            for(int i = 0; i < count; ++i){
                condat << renderStationCard(res[i][0], res[i][1], _lang).c_str();
            }

            condat << "</div>";

            if(page->getElementbyID("main"))
                page->getElementbyID("main")->appendChild(condat.parse());

            libhtmlpp::HtmlString out;
            Args->theme->printSite(tid,out,page,req.getRequestURL(),
                                    Args->auth->isLoggedIn(tid,req,sessionid));

            libhttppp::HttpResponse curres;
            curres.setContentType("text/html");
            curres.setState(HTTP200);
            sendCompressed(req,curres,out.c_str(),out.length());
            return true;
        }

    private:
        std::string renderStationCard(const std::string &name, const std::string &baseUrl, const std::string &_lang){
            std::string nameEnc;
            libhtmlpp::HtmlEncode(name.c_str(), nameEnc);

            std::string statusUrl = baseUrl;
            while(!statusUrl.empty() && statusUrl.back()=='/')
                statusUrl.pop_back();
            statusUrl += "/api/status";

            try{
                libhttppp::HttpUrl url(statusUrl);
                libhttppp::HttpClient client(url, 1, 8); // HTTP/1.1, 8s timeout — LAN device, fail fast
                libhttppp::HttpRequest nreq;

                std::vector<char> body = client.Get(nreq);
                body.push_back('\0');

                enum json_tokener_error jerrno;
                json_object *root = json_tokener_parse_verbose(body.data(), &jerrno);
                if(jerrno != json_tokener_success || !root){
                    return offlineCard(nameEnc, tr(_lang,"Invalid response"));
                }

                auto getD = [&](const char *key) -> double {
                    json_object *v = nullptr;
                    if(json_object_object_get_ex(root,key,&v)) return json_object_get_double(v);
                    return 0.0;
                };
                auto getB = [&](const char *key) -> bool {
                    json_object *v = nullptr;
                    if(json_object_object_get_ex(root,key,&v)) return json_object_get_boolean(v);
                    return false;
                };
                auto getS = [&](const char *key) -> std::string {
                    json_object *v = nullptr;
                    if(json_object_object_get_ex(root,key,&v)){
                        const char *s = json_object_get_string(v);
                        return s ? s : "";
                    }
                    return "";
                };

                bool valid = getB("valid");

                std::ostringstream html;
                html << "<div class=\"wcard" << (valid ? "" : " offline") << "\">";
                html << "<h2>" << nameEnc << "</h2>";

                if(valid){
                    html << row(tr(_lang,"Temperature"), fmt1(getD("temperature")) + " &deg;C");
                    html << row(tr(_lang,"Pressure"), fmt1(getD("pressure")) + " hPa");

                    if(getB("has_humidity"))
                        html << row(tr(_lang,"Humidity"), fmt1(getD("humidity")) + " %");

                    if(getB("wind_speed_valid"))
                        html << row(tr(_lang,"Wind Speed"), fmt1(getD("wind_speed_kmh")) + " km/h");

                    if(getB("wind_direction_valid")){
                        std::string compassEnc;
                        libhtmlpp::HtmlEncode(getS("wind_direction_compass").c_str(), compassEnc);
                        html << row(tr(_lang,"Wind Direction"),
                                    compassEnc + " (" + fmt1(getD("wind_direction_deg")) + "&deg;)");
                    }

                    if(getB("rainfall_valid"))
                        html << row(tr(_lang,"Rainfall"), fmt1(getD("rainfall_mm")) + " mm");

                    if(getB("uv_valid"))
                        html << row(tr(_lang,"UV Index"), fmt1(getD("uv_index")));
                }else{
                    html << "<div class=\"wrow\">" << tr(_lang,"No valid sensor data") << "</div>";
                }

                html << "</div>";
                json_object_put(root);
                return html.str();

            }catch(libhttppp::HTTPException &e){
                return offlineCard(nameEnc, e.what());
            }catch(netplus::NetException &e){
                return offlineCard(nameEnc, e.what());
            }catch(const std::exception &e){
                return offlineCard(nameEnc, e.what());
            }catch(...){
                return offlineCard(nameEnc, tr(_lang,"Unknown error"));
            }
        }

        static std::string row(const std::string &label, const std::string &value){
            return "<div class=\"wrow\"><span class=\"wlabel\">" + label + "</span><span>" + value + "</span></div>";
        }

        static std::string offlineCard(const std::string &nameEnc, const std::string &reason){
            std::string reasonEnc;
            libhtmlpp::HtmlEncode(reason.c_str(), reasonEnc);
            return "<div class=\"wcard offline\"><h2>" + nameEnc + "</h2>"
                   "<div class=\"wrow\">" + reasonEnc + "</div></div>";
        }

        static std::string fmt1(double v){
            std::ostringstream ss;
            ss.setf(std::ios::fixed);
            ss.precision(1);
            ss << v;
            return ss.str();
        }
    };
};

EXPORT blogi::PluginApi* create() {
    return new blogi::Weather();
}

EXPORT void destroy(blogi::PluginApi* p) {
    delete p;
}
+36 −0
Changes for src/translations.h: 36 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -674,6 +674,24 @@ namespace blogi {
            {"Response",             "Antwort"},
            {"Options",              "Optionen"},
            {"Preview",              "Vorschau"},
            // Plugin: weather
            {"Weather Stations",     "Wetterstationen"},
            {"Location Name",        "Ortsname"},
            {"Station URL",          "Stations-URL"},
            {"Add Station",          "Station hinzuf&uuml;gen"},
            {"Delete Station",       "Station l&ouml;schen"},
            {"Station ID to delete", "Zu l&ouml;schende Stations-ID"},
            {"No weather stations configured.", "Keine Wetterstationen konfiguriert."},
            {"Temperature",          "Temperatur"},
            {"Pressure",             "Luftdruck"},
            {"Humidity",             "Luftfeuchtigkeit"},
            {"Wind Speed",           "Windgeschwindigkeit"},
            {"Wind Direction",       "Windrichtung"},
            {"Rainfall",             "Niederschlag"},
            {"UV Index",             "UV-Index"},
            {"No valid sensor data", "Keine g&uuml;ltigen Sensordaten"},
            {"Invalid response",     "Ung&uuml;ltige Antwort"},
            {"Unknown error",        "Unbekannter Fehler"},
        };
        return m;
    }
@@ -1022,6 +1040,24 @@ namespace blogi {
            {"Do you want to remove this media type? All files of this type will also be removed!", "Do you want to remove this media type? All files of this type will also be removed!"},
            {"Do you want to remove this navigation?", "Do you want to remove this navigation?"},
            {"Successfully removed navigation.", "Successfully removed navigation."},
            // Plugin: weather
            {"Weather Stations",     "Weather Stations"},
            {"Location Name",        "Location Name"},
            {"Station URL",          "Station URL"},
            {"Add Station",          "Add Station"},
            {"Delete Station",       "Delete Station"},
            {"Station ID to delete", "Station ID to delete"},
            {"No weather stations configured.", "No weather stations configured."},
            {"Temperature",          "Temperature"},
            {"Pressure",             "Pressure"},
            {"Humidity",             "Humidity"},
            {"Wind Speed",           "Wind Speed"},
            {"Wind Direction",       "Wind Direction"},
            {"Rainfall",             "Rainfall"},
            {"UV Index",             "UV Index"},
            {"No valid sensor data", "No valid sensor data"},
            {"Invalid response",     "Invalid response"},
            {"Unknown error",        "Unknown error"},
        };
        return m;
    }