File: CharmCommandSession.cpp

package info (click to toggle)
charmtimetracker 1.12.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,340 kB
  • sloc: cpp: 19,176; xml: 284; python: 120; makefile: 14
file content (355 lines) | stat: -rw-r--r-- 10,563 bytes parent folder | download | duplicates (2)
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
  CharmCommandSession.cpp

  This file is part of Charm, a task-based time tracking application.

  Copyright (C) 2015-2018 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com

  Author: Guillermo A. Amaral <gamaral@kdab.com>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "CharmCommandSession.h"

#include <QBuffer>
#include <QIODevice>
#include <QStringList>

#include "Core/CharmDataModel.h"

#include "ViewHelpers.h"

#include "CharmCommandProtocol.h"
#include "CharmCMake.h"

#ifndef CHARM_CI_SUPPORT
#error Build system error: CHARM_CI_SUPPORT should be defined
#endif

CharmCommandSession::CharmCommandSession(QObject *parent)
    : QObject(parent)
    , m_device(nullptr)
    , m_state(InvalidState)
{
    qDebug("Command interface created.");

    DATAMODEL->registerAdapter(this);
}

CharmCommandSession::~CharmCommandSession()
{
    DATAMODEL->unregisterAdapter(this);

    qDebug("Command interface destroyed.");
}

QIODevice *CharmCommandSession::device() const
{
    return m_device;
}

void CharmCommandSession::setDevice(QIODevice *device)
{
    if (m_device)
        disconnect(m_device, SIGNAL(readyRead()), this, SLOT(onReadyRead()));

    m_device = device;

    if (m_device)
        connect(m_device, SIGNAL(readyRead()), this, SLOT(onReadyRead()));

    reset();
}

void CharmCommandSession::resetTasks()
{
    if (!m_device)
        return;

    m_device->write(CHARM_CI_EVENT_TASK_RESET);
    m_device->write("\n");
}

void CharmCommandSession::taskAdded(TaskId id)
{
    if (!m_device)
        return;

    m_device->write(QStringLiteral("%1 %2\n")
                    .arg(QStringLiteral(CHARM_CI_EVENT_TASK_ADDED))
                    .arg(DATAMODEL->taskIdAndSmartNameString(id))
                    .toLatin1());
}

void CharmCommandSession::taskModified(TaskId id)
{
    if (!m_device)
        return;

    m_device->write(QStringLiteral("%1 %2\n")
                    .arg(QStringLiteral(CHARM_CI_EVENT_TASK_MODIFIED))
                    .arg(DATAMODEL->taskIdAndSmartNameString(id))
                    .toLatin1());
}

void CharmCommandSession::eventActivated(EventId id)
{
    if (!m_device)
        return;

    const Event &event = DATAMODEL->eventForId(id);
    m_device->write(QStringLiteral("%1 %2\n")
                    .arg(QStringLiteral(CHARM_CI_EVENT_TASK_ACTIVATED))
                    .arg(DATAMODEL->taskIdAndSmartNameString(event.taskId()))
                    .toLatin1());
}

void CharmCommandSession::eventDeactivated(EventId id)
{
    if (!m_device)
        return;

    const Event &event = DATAMODEL->eventForId(id);
    m_device->write(QStringLiteral("%1 %2\n")
                    .arg(QStringLiteral(CHARM_CI_EVENT_TASK_DEACTIVATED))
                    .arg(DATAMODEL->taskIdAndSmartNameString(event.taskId()))
                    .toLatin1());
}

void CharmCommandSession::reset()
{
    m_state = InvalidState;
    startHandshake();
}

void CharmCommandSession::onReadyRead()
{
    QByteArray payload = m_device->readAll();

    switch (m_state) {
    case HandshakeState:
        handleHandshare(payload);
        break;
    case CommandState:
        handleCommand(payload);
        break;
    case InvalidState:
        qDebug("Received data while in invalid state. Discarding.");
        break;
    }
}

void CharmCommandSession::sendAck(const QString &comment)
{
    m_device->write(QStringLiteral("%1 %2\n")
                    .arg(QStringLiteral(CHARM_CI_SERVER_ACK))
                    .arg(comment)
                    .toLatin1());
}

void CharmCommandSession::sendNak(const QString &comment)
{
    m_device->write(QStringLiteral("%1 %2\n")
                    .arg(QStringLiteral(CHARM_CI_SERVER_NAK))
                    .arg(comment)
                    .toLatin1());
}

void CharmCommandSession::sendComment(const QString &comment)
{
    m_device->write(QStringLiteral("%1 %2\n")
                    .arg(QStringLiteral(CHARM_CI_SERVER_COMMENT))
                    .arg(comment)
                    .toLatin1());
}

void CharmCommandSession::startHandshake()
{
    sendComment(QStringLiteral("Charm Command Line Interface"));

    m_device->write(QStringLiteral("%1 %2\n")
                    .arg(QStringLiteral(CHARM_CI_HANDSHAKE_SEND))
                    .arg(QString::number(CHARM_CI_VERSION))
                    .toLatin1());

    m_state = HandshakeState;
}

void CharmCommandSession::startCommand()
{
    /*
     * simulate event activated events
     */
    EventIdList activeEvents = DATAMODEL->activeEvents();
    foreach (EventId id, activeEvents)
        eventActivated(id);

    m_state = CommandState;
}

void CharmCommandSession::handleHandshare(QByteArray payload)
{
    QBuffer buffer(&payload);
    buffer.open(QIODevice::ReadOnly);

    if (!buffer.canReadLine()) {
        buffer.close();
        return;
    }

    QString reply = QLatin1String(buffer.readLine());

    if (reply.startsWith(QStringLiteral(CHARM_CI_HANDSHAKE_RECV), Qt::CaseInsensitive)) {
        sendAck(QStringLiteral("Entering Command Mode"));
        startCommand();
    } else if (reply.startsWith(QStringLiteral(CHARM_CI_COMMAND_DISCONNECT), Qt::CaseInsensitive)) {
        qDebug("BYE command received. Closing connection.");
        m_device->close();
    }
}

void CharmCommandSession::handleCommand(QByteArray payload)
{
    QBuffer buffer(&payload);
    buffer.open(QIODevice::ReadOnly);

    if (!buffer.canReadLine()) {
        buffer.close();
        return;
    }

    const QString command = QLatin1String(buffer.readLine().trimmed());

    const QStringList segment
        = command.split(QChar::Space, QString::SkipEmptyParts);

    if (segment.isEmpty()) {
        qDebug("Received empty command...");
        return;
    }

    if (segment[0].compare(QStringLiteral(CHARM_CI_COMMAND_START), Qt::CaseInsensitive) == 0) {
        bool tid_ok;
        TaskId tid;

        if (segment.count() == 2) {
            tid = segment[1].toInt(&tid_ok);
        } else {
            EventMap::const_reverse_iterator i = DATAMODEL->eventMap().rbegin();
            tid_ok = (i != DATAMODEL->eventMap().rend());
            tid = i->second.taskId();
        }

        if (tid_ok && DATAMODEL->taskExists(tid)) {
            if (!DATAMODEL->isTaskActive(tid)) {
                qDebug("START command received. Starting task %d", tid);
                DATAMODEL->startEventRequested(DATAMODEL->getTask(tid));
            }
        } else {
            sendNak(QStringLiteral("UNKNOWN TASK"));
        }
    } else if (segment[0].compare(QStringLiteral(CHARM_CI_COMMAND_STOP), Qt::CaseInsensitive) == 0) {
        bool tid_ok;
        TaskId tid;

        if (segment.count() == 2) {
            tid = segment[1].toInt(&tid_ok);
        } else {
            tid = DATAMODEL->activeEventCount() > 0
                  ? DATAMODEL->eventForId(DATAMODEL->activeEvents().last()).taskId() : 0;
            tid_ok = (tid > 0);
        }

        if (tid_ok && DATAMODEL->taskExists(tid) && DATAMODEL->isTaskActive(tid)) {
            qDebug("STOP command received. Stopping task %d", tid);
            DATAMODEL->endEventRequested(DATAMODEL->getTask(tid));
        } else {
            sendNak(QStringLiteral("UNKNOWN TASK"));
        }
    } else if (segment[0].compare(QStringLiteral(CHARM_CI_COMMAND_TASK), Qt::CaseInsensitive) == 0) {
        bool tid_ok;
        TaskId tid;

        if (segment.count() == 2) {
            tid = segment[1].toInt(&tid_ok);
        } else {
            tid_ok = false;
        }

        if (tid_ok && DATAMODEL->taskExists(tid)) {
            qDebug("TASK command received. Task %d requested", tid);
            m_device->write(DATAMODEL->taskIdAndSmartNameString(tid).toLatin1());
            m_device->write("\n");
        } else {
            sendNak(QStringLiteral("UNKNOWN TASK"));
        }
    } else if (segment[0].compare(QStringLiteral(CHARM_CI_COMMAND_STATUS), Qt::CaseInsensitive) == 0) {
        qDebug("STATUS command received.");

        const EventIdList activeEvents = DATAMODEL->activeEvents();
        if (!activeEvents.isEmpty()) {
            foreach (EventId id, activeEvents) {
                const Event &event = DATAMODEL->eventForId(id);
                m_device->write(QStringLiteral("%0 %1\n")
                                .arg(event.taskId(), 4, 10, QLatin1Char('0'))
                                .arg(event.duration()).toLatin1());
            }
        } else {
            sendNak(QStringLiteral("WORK HARDER"));
        }
    } else if (segment[0].compare(QStringLiteral(CHARM_CI_COMMAND_RECENT), Qt::CaseInsensitive) == 0) {
        bool offset_ok;
        bool count_ok;
        int offset;
        int count;
        const EventIdList recent = DATAMODEL->mostRecentlyUsedTasks();

        /* default params */

        offset_ok = true;
        offset = 0;

        count_ok = true;
        count = 5;

        if (segment.count() > 1) {
            offset = segment[1].toInt(&offset_ok);
            if (segment.count() > 2)
                count = segment[2].toInt(&count_ok);
        }

        if (offset_ok && count_ok && offset >= 0 && count >= 1 && recent.size() > offset) {
            qDebug("RECENT command received. Sending %d entries starting from offset %d", count,
                   offset);

            if ((offset + count) > recent.size())
                count = recent.size() - offset;

            for (int i = 0; i < count; ++i) {
                m_device->write(DATAMODEL->taskIdAndSmartNameString(recent[offset + i]).toLatin1());
                m_device->write("\n");
            }
        } else {
            sendNak(QStringLiteral("INVALID REQUEST"));
        }
    } else if (segment[0].compare(QStringLiteral(CHARM_CI_COMMAND_DISCONNECT), Qt::CaseInsensitive) == 0) {
        qDebug("BYE command received. Closing connection.");
        m_device->close();
    }
    /* unknown command sent */
    else {
        sendNak(QStringLiteral("UNKNOWN COMMAND"));
    }
}