summary refs log tree commit diff
path: root/src/timeline/PresenceEmitter.cpp
blob: da03f9bf49a09befb32ae127a1ad89471275f0c1 (plain) (blame)
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
// SPDX-FileCopyrightText: Nheko Contributors
//
// SPDX-License-Identifier: GPL-3.0-or-later

#include "PresenceEmitter.h"

#include <QCache>
#include <Utils.h>

#include "Cache.h"

namespace {
struct CacheEntry
{
    QString status;
    mtx::presence::PresenceState state;
};
}

static QCache<QString, CacheEntry> presences;

static QString
presenceToStr(mtx::presence::PresenceState state)
{
    switch (state) {
    case mtx::presence::PresenceState::offline:
        return QStringLiteral("offline");
    case mtx::presence::PresenceState::unavailable:
        return QStringLiteral("unavailable");
    case mtx::presence::PresenceState::online:
    default:
        return QStringLiteral("online");
    }
}

static CacheEntry *
pullPresence(const QString &id)
{
    auto p = cache::presence(id.toStdString());
    auto c = new CacheEntry{
      utils::replaceEmoji(QString::fromStdString(p.status_msg).toHtmlEscaped()), p.presence};
    presences.insert(id, c);
    return c;
}

void
PresenceEmitter::sync(
  const std::vector<mtx::events::Event<mtx::events::presence::Presence>> &presences_)
{
    for (const auto &p : presences_) {
        auto id = QString::fromStdString(p.sender);
        presences.remove(id);
        emit presenceChanged(std::move(id));
    }
}

QString
PresenceEmitter::userPresence(QString id) const
{
    if (id.isEmpty())
        return {};
    else if (auto p = presences[id])
        return presenceToStr(p->state);
    else
        return presenceToStr(pullPresence(id)->state);
}

QString
PresenceEmitter::userStatus(QString id) const
{
    if (id.isEmpty())
        return {};
    else if (auto p = presences[id])
        return p->status;
    else
        return pullPresence(id)->status;
}

#include "moc_PresenceEmitter.cpp"