aboutsummaryrefslogtreecommitdiff
path: root/src/widgets/MoreApps/moreapps.cpp
blob: b28476a4e0aaeca6b6284049eb6a64f431ebf51a (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
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#include "moreapps.h"
#include "ui_moreapps.h"

#include <QDesktopServices>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QPushButton>
#include <QRandomGenerator>
#include <algorithm>
#include <cstdlib>
#include <ctime>

MoreApps::MoreApps(QWidget *parent, QNetworkAccessManager *nam,
                   const QString &publisherName, const QUrl &remoteFilterUrl,
                   bool uIdebugMode, bool remoteIconPreCaching)
    : QWidget(parent), ui(new Ui::MoreApps),
      mFields("publisher,summary,title,media"), mPublisherName(publisherName),
      mRemoteFilterUrl(remoteFilterUrl), mUiDebugMode(uIdebugMode),
      mRemoteIconPreCaching(remoteIconPreCaching) {

  init(nam);
}

void MoreApps::initNetworkManager(QNetworkAccessManager *nam) {

  ui->setupUi(this);

  // set to use external nam
  mNetworkManager = nam;

  QString diskCachePath =
      QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);

  // use internal nam
  if (mNetworkManager == nullptr) {
    mNetworkManager = new QNetworkAccessManager(this);
    mNetworkManager->setObjectName("internal_nm");

    QNetworkDiskCache *diskCache = new QNetworkDiskCache(this);
    diskCache->setCacheDirectory(diskCachePath);
    mNetworkManager->setCache(diskCache);
  } else {
    qDebug() << QT_STRINGIFY(MoreApps) << "using external network manager";
  }

  if (mNetworkManager->cache() == nullptr) {
    QString nmType = (mNetworkManager->objectName() == "internal_nm")
                         ? "internal"
                         : "external";
    qWarning() << "no cache set on" << nmType << "network manager"
               << Q_FUNC_INFO;
  }
}

void MoreApps::init(QNetworkAccessManager *nam) {

  initNetworkManager(nam);

  getAppsMeta();
}

void MoreApps::getAppsMeta() {

  qDebug() << "getting apps meta...";

  QUrlQuery query;
  query.addQueryItem("q", mPublisherName);
  query.addQueryItem("fields", mFields);

  // TODO: check if snapcraft api provinding list by publisher name
  QUrl reqUrl = QUrl("https://api.snapcraft.io/v2/snaps/find");
  reqUrl.setQuery(query);

  QNetworkRequest request(reqUrl);
  request.setRawHeader("Snap-Device-Series", "16");
  request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
                       QNetworkRequest::PreferCache);

  QNetworkReply *reply = mNetworkManager->get(request);
  ui->loadingLabel->show();
  connect(reply, &QNetworkReply::finished, this, [=]() {
    if (reply->error() == QNetworkReply::NoError) {
      mAppMeta = reply->readAll();
    } else {
      qDebug() << "Error getting app meta from store";
      this->hide();
    }
    reply->deleteLater();
    applyFilter();
    ui->loadingLabel->hide();
  });
}

QList<AppItem> MoreApps::prepareAppsToShow(const QByteArray &bytes) {

  QList<AppItem> appList;

  QJsonDocument jsonResponse = QJsonDocument::fromJson(bytes);
  if (jsonResponse.isEmpty()) {
    return appList;
  }

  QJsonArray jsonArray = jsonResponse.object().value("results").toArray();
  foreach (const QJsonValue &val, jsonArray) {
    QJsonObject object = val.toObject();

    // publisher
    QString publisher = object.value("snap")
                            .toObject()
                            .value("publisher")
                            .toObject()
                            .value("username")
                            .toString();
    publisher = publisher.isEmpty() ? "-" : publisher;

    // name
    QString name = object.value("name").toString();

    // title
    QString title = object.value("snap").toObject().value("title").toString();
    title = title.isEmpty() ? "-" : title;

    // icon
    QJsonArray mediaArr =
        object.value("snap").toObject().value("media").toArray();
    QString iconUrl;
    foreach (const QJsonValue &mediaItem, mediaArr) {
      if (mediaItem.toObject().value("type") == "icon")
        iconUrl = mediaItem.toObject().value("url").toString();
    }

    // summary
    QString summary =
        object.value("snap").toObject().value("summary").toString();
    summary = summary.isEmpty() ? "-" : summary;

    // link
    QString storeUrl = "https://snapcraft.io/" + name;

    // if filterList is set show only filtered items
    if (mFilterList.isEmpty() == false && (publisher == mPublisherName) &&
        (!name.isEmpty() || !storeUrl.isEmpty() || !iconUrl.isEmpty())) {
      if (mFilterList.contains(name)) {
        AppItem app(name, title, summary, QUrl(iconUrl), QUrl(storeUrl));
        appList.append(app);
      }
    } else { // else show all items returned
      AppItem app(name, title, summary, QUrl(iconUrl), QUrl(storeUrl));
      appList.append(app);
    }
  }

  return appList;
}

void MoreApps::applyFilter() {

  if (mRemoteFilterUrl.isEmpty() == false) {

    applyRemoteFilter(mRemoteFilterUrl);

  } else {

    mAppList = prepareAppsToShow(mAppMeta);

    showApps();
  }
}

void MoreApps::applyRemoteFilter(const QUrl &remoteFilterUrl) {

  qDebug() << "getting remote filter...";

  QNetworkRequest request(remoteFilterUrl);
  request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
                       QNetworkRequest::PreferCache);

  QNetworkReply *reply = mNetworkManager->get(QNetworkRequest(request));
  ui->loadingLabel->show();

  connect(reply, &QNetworkReply::finished, this, [=]() {
    if (reply->error() == QNetworkReply::NoError) {
      auto replyBytes = reply->readAll();
      foreach (QString line, replyBytes.split('\n')) {
        // ignore commented line
        if (line.startsWith("#")) {
          continue;
        }
        addToAppFilterList(line.trimmed());
      }
    } else {
      qDebug() << "Error getting filter list";
    }

    ui->loadingLabel->hide();

    reply->deleteLater();

    mAppList = prepareAppsToShow(mAppMeta);

    showApps();
  });
}

void MoreApps::setRemoteIcon(const QUrl &iconUrl, QLabel *lb) {

  QNetworkRequest request(iconUrl);
  request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
                       QNetworkRequest::PreferCache);

  QNetworkReply *reply = mNetworkManager->get(QNetworkRequest(request));
  connect(reply, &QNetworkReply::finished, this, [=]() {
    if (reply->error() == QNetworkReply::NoError) {
      if (lb != nullptr) {
        auto replyBytes = reply->readAll();
        QPixmap pixmap;
        pixmap.loadFromData(replyBytes);
        qDebug() << "after load" << lb->size();
        lb->setPixmap(pixmap.scaled(lb->size(), Qt::KeepAspectRatio,
                                    Qt::SmoothTransformation));
      }
    } else {
      qDebug() << "Error getting icon" << iconUrl.toString();
      if (lb != nullptr) {
        QByteArray data = QByteArray::fromBase64(mSnapIconBin.toLatin1());
        QPixmap pixmap;
        pixmap.loadFromData(data, "PNG");
        lb->setPixmap(QPixmap(pixmap.scaled(lb->size(), Qt::KeepAspectRatio,
                                            Qt::SmoothTransformation)));
      }
    }
    reply->deleteLater();
  });
}

void MoreApps::showApps() {

  qDebug() << "showing apps...";

  std::srand(unsigned(std::time(0)));
  // rand generator
  auto rand = [](auto i) { return std::rand() % i; };
  // shuffle appList before adding
  std::random_shuffle(mAppList.begin(), mAppList.end(), rand);

  auto fallbackIconUrl =
      QUrl("https://dashboard.snapcraft.io/site_media/appmedia/"
           "2019/09/snapd.png");

  if (mRemoteIconPreCaching) {
    // cache fallback icon
    setRemoteIcon(fallbackIconUrl, nullptr);
    foreach (auto a, mAppList) {
      auto iconUrl = a.getIconUrl();
      qDebug() << "pre-caching icon for" << a.getName();
      setRemoteIcon(iconUrl, nullptr);
    }
  }

  // calculate icon height width
  double pheight = this->height();
  double ratio = pheight / pheight;
  double height = this->height() / 1.8;
  double width = ratio * height;

  // add appItem to appItemWidget
  for (int i = 0; i < getAppsToShowCount(); ++i) {

    auto appItem = mAppList.at(i);

    QLabel *iconLabel = new QLabel();
    iconLabel->setFixedSize(width, height);
    if (appItem.getIconUrl().isEmpty() == false) {
      setRemoteIcon(appItem.getIconUrl(), iconLabel);
    } else {
      qDebug() << "icon empty for " << appItem.getName();
      setRemoteIcon(fallbackIconUrl, iconLabel);
    }

    QPushButton *pb = new QPushButton();
    pb->setText(appItem.getTitle());
    connect(pb, &QPushButton::clicked, this,
            [=]() { QDesktopServices::openUrl(appItem.getStoreUrl()); });

    QVBoxLayout *vl = new QVBoxLayout();
    vl->addWidget(iconLabel);
    vl->addWidget(pb);
    vl->setAlignment(iconLabel, Qt::AlignCenter);
    vl->setContentsMargins(0, 0, 0, 0);
    vl->setSpacing(6);

    QWidget *appItemWidget = new QWidget();
    if (mUiDebugMode)
      appItemWidget->setStyleSheet("border: 1px solid red;");
    appItemWidget->setToolTip(appItem.getSummary());
    appItemWidget->setLayout(vl);
    appItemWidget->setMaximumWidth(
        getMaxWidth(iconLabel->sizeHint().width(), pb->sizeHint().width()) +
        (2 * 3));
    appItemWidget->setMinimumWidth(
        getMaxWidth(iconLabel->sizeHint().width(), pb->sizeHint().width()));
    appItemWidget->setMinimumHeight(iconLabel->sizeHint().height() +
                                    pb->sizeHint().height() + (2 * 3));
    ui->horizontalLayout->setSpacing(9);
    ui->horizontalLayout->addWidget(appItemWidget);
  }
}

int MoreApps::getMaxWidth(int x, int y) {
  int z = x;
  x > y ? z = x : z = y;
  return z;
}

int MoreApps::getAppsToShowCount() {

  int min = 0;
  int max = mAppList.count();
  int proposed = 3;

  if (max > min && max >= proposed) {
    return proposed;
  } else {
    return max;
  }
}

void MoreApps::addToAppFilterList(const QString &appName) {

  // filter out if appname string contains running application name substring
  // or appname is empty or already added to filter list
  if (mFilterList.contains(appName) == false &&
      appName.trimmed().isEmpty() == false &&
      appName.contains(QApplication::applicationName(), Qt::CaseInsensitive) ==
          false)
    mFilterList.append(appName);
}

MoreApps::~MoreApps() { delete ui; }

QString AppItem::getName() const { return name; }

void AppItem::setName(const QString &newName) { name = newName; }

QString AppItem::getSummary() const {
  return QString(summary).replace(" & ", " and ");
}

void AppItem::setSummary(const QString &newSummary) { summary = newSummary; }

QUrl AppItem::getIconUrl() const { return iconUrl; }

void AppItem::setIconUrl(const QUrl &newIconUrl) { iconUrl = newIconUrl; }

QUrl AppItem::getStoreUrl() const { return storeUrl; }

void AppItem::setStoreUrl(const QUrl &newLink) { storeUrl = newLink; }

QString AppItem::getTitle() const {
  return QString(title).replace(" & ", " and ");
}

void AppItem::setTitle(const QString &newTitle) { title = newTitle; }

AppItem::AppItem() {}

AppItem::AppItem(const QString &name, const QString &title,
                 const QString &summary, const QUrl &iconUrl,
                 const QUrl &storeUrl)
    : name(name), title(title), summary(summary), iconUrl(iconUrl),
      storeUrl(storeUrl) {}