/ rnrandombytesdesktop.cpp
rnrandombytesdesktop.cpp
 1  /**
 2   * Copyright (C) 2016, Canonical Ltd.
 3   * All rights reserved.
 4   *
 5   * This source code is licensed under the BSD-style license found in the
 6   * LICENSE file in the root directory of this source tree. An additional grant
 7   * of patent rights can be found in the PATENTS file in the same directory.
 8   *
 9   * Author: Justin McPherson <justin.mcpherson@canonical.com>
10   *
11   */
12  
13  #include <memory>
14  
15  #include "bridge.h"
16  #include "rnrandombytesdesktop.h"
17  #include <QCryptographicHash>
18  #include <QDateTime>
19  #include <QDebug>
20  #include <QMap>
21  #include <QNetworkDiskCache>
22  #include <QNetworkReply>
23  #include <QNetworkRequest>
24  #include <QQuickImageProvider>
25  
26  namespace {
27  struct RegisterQMLMetaType {
28      RegisterQMLMetaType() {
29          qRegisterMetaType<RNRandomBytes*>();
30      }
31  } registerMetaType;
32  } // namespace
33  
34  class RNRandomBytesPrivate {
35  
36  public:
37      RNRandomBytesPrivate() {
38          seed = generateRandomBytes(4096);
39      }
40  
41      QString generateRandomBytes(int size);
42  
43      QString seed;
44      Bridge* bridge = nullptr;
45  };
46  
47  RNRandomBytes::RNRandomBytes(QObject* parent) : QObject(parent), d_ptr(new RNRandomBytesPrivate) {}
48  
49  RNRandomBytes::~RNRandomBytes() {}
50  
51  QString RNRandomBytesPrivate::generateRandomBytes(int size) {
52      QString randomString;
53      qsrand(QDateTime::currentDateTime().currentMSecsSinceEpoch());
54      while (randomString.size() < size) {
55          randomString.append(QChar(qrand()));
56      }
57      return randomString.toUtf8().toBase64();
58  }
59  
60  void RNRandomBytes::randomBytes(int length, double funcId) {
61      Q_D(RNRandomBytes);
62      if (d->bridge) {
63          d->bridge->invokePromiseCallback(funcId, QVariantList{"", d->generateRandomBytes(length)});
64      }
65  }
66  
67  QString RNRandomBytes::moduleName() {
68      return "RNRandomBytes";
69  }
70  
71  QList<ModuleMethod*> RNRandomBytes::methodsToExport() {
72      return QList<ModuleMethod*>{};
73  }
74  
75  QVariantMap RNRandomBytes::constantsToExport() {
76      return QVariantMap{{"seed", d_ptr->seed}};
77  }
78  
79  void RNRandomBytes::setBridge(Bridge* bridge) {
80      Q_D(RNRandomBytes);
81      d->bridge = bridge;
82  }