summaryrefslogtreecommitdiffstats
path: root/src/AvatarProvider.cpp
blob: 4608aca4d7536f0de83d31ac026e50760cdfa905 (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
// SPDX-FileCopyrightText: Nheko Contributors
//
// SPDX-License-Identifier: GPL-3.0-or-later

#include <QBuffer>
#include <QPixmapCache>
#include <QPointer>
#include <memory>

#include "AvatarProvider.h"
#include "Cache.h"
#include "MxcImageProvider.h"

static QPixmapCache avatar_cache;

namespace AvatarProvider {
void
resolve(QString avatarUrl, int size, QObject *receiver, AvatarCallback callback)
{
    const auto cacheKey = QStringLiteral("%1_size_%2").arg(avatarUrl).arg(size);

    QPixmap pixmap;
    if (avatarUrl.isEmpty()) {
        callback(pixmap);
        return;
    }

    if (avatar_cache.find(cacheKey, &pixmap)) {
        callback(pixmap);
        return;
    }

    MxcImageProvider::download(avatarUrl.remove(QStringLiteral("mxc://")),
                               QSize(size, size),
                               [callback, cacheKey, recv = QPointer<QObject>(receiver)](
                                 QString, QSize, QImage img, QString) {
                                   if (!recv)
                                       return;

                                   auto proxy = std::make_shared<AvatarProxy>();
                                   QObject::connect(proxy.get(),
                                                    &AvatarProxy::avatarDownloaded,
                                                    recv,
                                                    [callback, cacheKey](QPixmap pm) {
                                                        if (!pm.isNull())
                                                            avatar_cache.insert(cacheKey, pm);
                                                        callback(pm);
                                                    });

                                   if (img.isNull()) {
                                       emit proxy->avatarDownloaded(QPixmap{});
                                       return;
                                   }

                                   auto pm = QPixmap::fromImage(std::move(img));
                                   emit proxy->avatarDownloaded(pm);
                               });
}

void
resolve(const QString &room_id,
        const QString &user_id,
        int size,
        QObject *receiver,
        AvatarCallback callback)
{
    auto avatarUrl = cache::avatarUrl(room_id, user_id);

    resolve(std::move(avatarUrl), size, receiver, callback);
}
}

#include "moc_AvatarProvider.cpp"