aboutsummaryrefslogtreecommitdiff
path: root/mainwindow.cpp
blob: 37b0f19bfd1952022330349e1ac66646a4c1997f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
/*
void MainWindow::onNetworkConfigurationChanged()
{
}
*/

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->menuBar->setVisible(false);
    qDebug() << "Using: " << this->qsettings.fileName();

    this->qsystemtrayicon = new QSystemTrayIcon(this->windowIcon(), 0);
    this->qsystemtrayicon->show();
    this->qsystemtrayicon->setContextMenu(ui->menuMenu1);
    this->qsystemtrayicon->setToolTip(this->windowTitle());
    this->connect(this->qsystemtrayicon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(slotActivated(QSystemTrayIcon::ActivationReason)));

    this->updateSpaceList();
    this->updateStatus();


    this->timer = new QTimer();
    this->connect(this->timer, SIGNAL(timeout()), this, SLOT(updateStatus()));
    // update every five minutes...
    this->timer->start(60000 * 5);

    //this->pixmap = new QPixmap(120, 120);
    //this->currentIcon = new QIcon(this->pixmap);

    this->mgr = new QNetworkConfigurationManager();
    /*
    connect(this->mgr,
          SIGNAL(configurationChanged(const QNetworkConfiguration &)),
          this,
          SLOT(onNetworkConfigurationChanged()));
    */
    /*
    connect(this->mgr,
          SIGNAL(configurationChanged(const QNetworkConfiguration &)),
          this,
          SLOT(onNetworkConfigurationChanged()));
          */
    connect(this->mgr, &QNetworkConfigurationManager::configurationChanged,
            [=]
            {
                qDebug() << "configuration changed" << endl;
                if(this->mgr->isOnline())
                {
                    if(this->ui->comboBox->count() == 0)
                    {
                        this->updateSpaceList();
                        this->updateStatus();
                    }
                    else
                        this->updateStatus();
                }
            });

    connect(this->mgr, &QNetworkConfigurationManager::onlineStateChanged,
            [=] (bool b)
            {
                qDebug() << "QNetworkConfigurationManager::onlineStateChanged\n" << endl;
                if(!b)
                {
                    this->qsystemtrayicon->setIcon(QIcon::fromTheme("network-error"));
                    this->qsystemtrayicon->showMessage("Offline", "The network connection was lost :(");
                }

            });

}

MainWindow::~MainWindow()
{
    qDebug() << "unloading application";
    delete this->qsystemtrayicon;
    delete this->timer;
    delete ui;
}

void MainWindow::updateSpaceList()
{
    qDebug() << "updateSpaceList()";
    QString defaultSpace = this->qsettings.value("hackerspace").toString();
    QString defaultDirectoryURL = this->qsettings.value("directory").toString();
    if(defaultDirectoryURL == "")
    { defaultDirectoryURL = "https://raw.githubusercontent.com/SpaceApi/OpenSpaceDirectory/master/directory.json" ; }

    QUrl url(defaultDirectoryURL);
    QJsonObject json = QJsonDocument::fromJson(this->download(url)).object();

    ui->comboBox->setDisabled(true);
    QJsonObject::Iterator it;
    for(it=json.begin(); it!=json.end(); it++)
    {
        //qDebug() << it.key() << "\t" << it.value().toString();
        ui->comboBox->addItem(it.key(), it.value().toString());
        if(it.key() == defaultSpace)
            ui->comboBox->setCurrentIndex(ui->comboBox->count()-1);
    }
    ui->comboBox->setDisabled(false);

}

QJsonObject json_find(QJsonObject json, QStringList list)
{
    QJsonObject retval = json;
    foreach(const QString str, list)
        if(retval.contains(str))
            retval = retval[str].toObject();
        else
            return QJsonObject();
    return retval;
}

// lets not talk about memory leaks. yes, they are there. but it works somehow.
void MainWindow::updateStatus()
{
    //QUrl url("http://hackerspace-bielefeld.de/spacestatus/status.json");
    qDebug() << ui->comboBox->currentData().toString();
    ui->label_url_json->setText(ui->comboBox->currentData().toString());

    QUrl url(ui->comboBox->currentData().toString());
    QJsonDocument doc = QJsonDocument::fromJson(this->download(url));
    //ui->plainTextEdit->setPlainText(doc.toJson(QJsonDocument::Indented));

    //qDebug() << doc.toJson(QJsonDocument::Indented);
    QJsonObject json = doc.object();

    foreach (QLabel *label, this->findChildren<QLabel*>())
    {
        if(label->statusTip().isEmpty())
            continue;

        label->clear();
        //label->setText("");
        QStringList list = label->statusTip().split("/");
        QString name = list.takeLast();


        QJsonObject obj = json_find(json, list);
        if(!obj.isEmpty())
        {
            if(obj.value(name).isString())
            {
                QString result = obj.value(name).toString();
                if(name == "logo" || result.endsWith(".png") || result.endsWith(".jpg"))
                {
                    label->setPixmap(
                        QPixmap::fromImage(
                            QImage::fromData(
                                this->download(
                                    QUrl(result)))).scaled(120, 120, Qt::KeepAspectRatio));
                }
                else if(result.contains("http"))
                {
                    label->setText("<b>" + name + ":</b><br/><a href=\"" + result + "\">" + result + "</a> ");
                    label->setOpenExternalLinks(true);
                }
                else
                    label->setText("<b>" + name + ":</b><br/>" + result);
            }
            else
            {
                if(obj.value(name).isBool())
                    label->setText("<b>" + name + "</b>:<br/>" + (obj.value(name).toBool() ? "true" : "false"));
                else if(name == "lastchange")
                    label->setText("<b>" + name + ":</b><br/>" + QDateTime::fromTime_t(obj.value(name).toInt()).toLocalTime().toString());
            }

        }

        qDebug() << "NAME: " << name;
    }

    QString strUrl;

    strUrl = json["state"].toObject()
                 ["icon"].toObject()
                 [json["state"].toObject()["open"].toBool() ? "open" : "closed"].toString();
    if(strUrl == "")
        strUrl = json["icon"].toObject()
                     [json["state"].toObject()["open"].toBool() ? "open" : "closed"].toString();



    qDebug() << "downloading: " << strUrl;
    this->qsystemtrayicon->setIcon(QIcon(
        QPixmap::fromImage(
            QImage::fromData(
                this->download(
                    QUrl(strUrl)))).scaled(120, 120, Qt::KeepAspectRatio)));

    if(this->qsystemtrayicon->icon().isNull())
    {
        if(json["state"].toObject().contains("open"))
            if(json["state"].toObject()["open"].toBool())
                this->qsystemtrayicon->setIcon(QIcon::fromTheme("face-smile"));
            else
                this->qsystemtrayicon->setIcon(QIcon::fromTheme("face-sad"));
        else
            this->qsystemtrayicon->setIcon(QIcon::fromTheme("face-sick"));
    }
}

void MainWindow::saveSettings()
{
    this->qsettings.setValue("hackerspace", ui->comboBox->currentText());
}

QByteArray MainWindow::download(QUrl url)
{
    qDebug() << "downloading: " << url.toString();
    QNetworkAccessManager manager;
    QNetworkReply *response = manager.get(QNetworkRequest(QUrl(url)));
    QEventLoop event;
    connect(response, SIGNAL(finished()), &event, SLOT(quit()));
    connect(response, &QNetworkReply::sslErrors,
        [=](const QList<QSslError>& errors) {
        qDebug() << errors[0].errorString();
        // many of us use self-signed certificates or they have expired.
        // this should not matter here, therefore ignore...
        response->ignoreSslErrors();
    }
    );
    connect(response, static_cast<void(QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
        [=](QNetworkReply::NetworkError)
        {
            qDebug() << "NetworkError!"; // code.errorString();
            //qDebug() << ;
            qDebug() << response->errorString();

        }
    );
    event.exec();
    if (response->error() == QNetworkReply::NoError)
    {
        int statusCode = response->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

        qDebug() << "Status: " << statusCode;
        switch(statusCode)
        {
            case 301:
            case 302:
            case 303:
                return this->download(response->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl());
            break;
        }
    }
    return response->readAll();
}

void MainWindow::slotActivated(QSystemTrayIcon::ActivationReason reason)
{
    qDebug() << "trigger";
    if(reason == QSystemTrayIcon::Trigger)
    {
        if(this->isVisible())
            this->hide();
        else
        {
            this->setWindowState(Qt::WindowNoState);
            this->show();
            this->activateWindow();
        }

    }
    else
    {
        qDebug() << "activate(reason): " << reason;
    }
}

void MainWindow::exitApplication()
{
    qDebug() << "exit now!";
    QApplication::quit();
}

void MainWindow::on_comboBox_currentIndexChanged(const QString &arg1)
{
    qDebug() << arg1;
    if(ui->comboBox->isEnabled())
    {
        this->updateStatus();
        this->saveSettings();
    }
}


..