File: userdatabase.cc

package info (click to toggle)
qdmr 0.13.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 22,420 kB
  • sloc: cpp: 95,929; xml: 10,749; python: 1,108; makefile: 78; sh: 9
file content (284 lines) | stat: -rw-r--r-- 7,638 bytes parent folder | download
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
#include "userdatabase.hh"
#include <QJsonDocument>
#include <QJsonArray>
#include <QStandardPaths>
#include <QFile>
#include <QDir>
#include <QNetworkReply>
#include <QtConcurrent>
#include <algorithm>
#include "logger.hh"
#include <cmath>


/* ********************************************************************************************* *
 * Implementation of User
 * ********************************************************************************************* */
UserDatabase::User::User()
  : id(0)
{
  // pass...
}

UserDatabase::User::User(const QJsonObject &obj)
  : id(obj.value("id").toInt()), call(obj.value("callsign").toString()),
    name(obj.value("fname").toString()), surname(obj.value("surname").toString()),
    city(obj.value("city").toString()), state(obj.value("state").toString()),
    country(obj.value("country").toString()), comment(obj.value("remarks").toString())
{
  // pass...
}

unsigned
UserDatabase::User::distance(unsigned id) const {
  // Fix number of digits
  int a = this->id, b = id;
  int ad = std::ceil(std::log10(a));
  int bd = std::ceil(std::log10(b));
  if (ad > bd)
    b *= std::pow(10u, (ad-bd));
  else if (bd > ad)
    a *= std::pow(10u, (bd-ad));
  // Distance is just the difference between these two numbers
  // this ensures a small distance between two numbers with the same
  // prefix.
  return std::abs(a-b);
}


/* ********************************************************************************************* *
 * Implementation of UserDatabase
 * ********************************************************************************************* */
UserDatabase::UserDatabase(bool parallel, unsigned updatePeriodDays, QObject *parent)
  : QAbstractTableModel(parent), _user(), _network()
{
  connect(&_network, SIGNAL(finished(QNetworkReply*)),
          this, SLOT(downloadFinished(QNetworkReply*)));

  if ((! exists()) || (updatePeriodDays < dbAge()))
    download();
  else {
    if (parallel)
      _parsing = QtConcurrent::run([this]() { return this->load(); });
    else
      load();
  }
}

qint64
UserDatabase::count() const {
  return _user.size();
}

bool
UserDatabase::exists() const {
  QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
  QFileInfo info(path + "/user.json");
  return info.isFile() && info.isReadable();
}

bool
UserDatabase::ready() const {
  return ! _user.empty();
}

bool
UserDatabase::load() {
  QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
  return load(path+"/user.json");
}

const UserDatabase::User &
UserDatabase::user(int idx) const {
  return _user[idx];
}

bool
UserDatabase::load(const QString &filename) {
  QFile file(filename);
  if (! file.open(QIODevice::ReadOnly)) {
    QString msg = QString("Cannot open user list '%1': %2").arg(filename).arg(file.errorString());
    logError() << msg;
    emit error(msg);
    return false;
  }
  QByteArray data = file.readAll();
  file.close();

  QJsonParseError err;
  QJsonDocument doc = QJsonDocument::fromJson(data, &err);
  if (doc.isEmpty()) {
    QString msg = "Failed to load user DB: " + err.errorString();
    logError() << msg;
    emit error(msg);
    return false;
  }

  if (! doc.isObject()) {
    QString msg = "Failed to load user DB: JSON document is not an object!";
    logError() << msg;
    emit error(msg);
    return false;
  }
  if (! doc.object().contains("users")) {
    QString msg = "Failed to load user DB: JSON object does not contain 'users' item.";
    logError() << msg;
    emit error(msg);
    return false;
  }
  if (! doc.object()["users"].isArray()) {
    QString msg = "Failed to load user DB: 'users' item is not an array.";
    logError() << msg;
    emit error(msg);
    return false;
  }

  beginResetModel();
  _user.clear(); emit readyChanged(false);

  QJsonArray array = doc.object()["users"].toArray();
  _user.reserve(array.size());
  for (int i=0; i<array.size(); i++) {
    User user(array.at(i).toObject());
    if (user.isValid())
      _user.append(user);
  }
  // Sort repeater w.r.t. their IDs
  std::stable_sort(_user.begin(), _user.end(), [](const User &a, const User &b){ return a.id < b.id; });
  // Done.
  endResetModel();

  logDebug() << "Loaded user database with " << _user.size() << " entries from " << filename << ".";

  if (ready())
    emit readyChanged(ready());
  emit loaded();
  return true;
}

void
UserDatabase::sortUsers(unsigned id) {
  // Sort repeater w.r.t. distance to ID
  std::stable_sort(_user.begin(), _user.end(), [id](const User &a, const User &b){
    return a.distance(id) < b.distance(id);
  });
}

void
UserDatabase::sortUsers(const QSet<unsigned> &ids) {
  if (0 == ids.count())
    return;

  // Sort repeater w.r.t. distance to each ID
  std::stable_sort(_user.begin(), _user.end(), [ids](const User &a, const User &b){
    QSet<unsigned>::const_iterator id=ids.begin();
    unsigned min_a = a.distance(*id), min_b = b.distance(*id);
    id++;
    for (; id!=ids.end(); id++) {
      min_a = std::min(min_a, a.distance(*id));
      min_b = std::min(min_b, b.distance(*id));
    }
    return min_a < min_b;
  });
}

void
UserDatabase::download() {
  QUrl url("https://database.radioid.net/static/users.json");
  QNetworkRequest request(url);
  _network.get(request);
}

void
UserDatabase::downloadFinished(QNetworkReply *reply) {
  if (reply->error()) {
    QString msg = QString("Cannot download user database: %1").arg(reply->errorString());
    logError() << msg;
    emit error(msg);
    return;
  }

  QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
  QFile file(path+"/user.json");
  QDir directory;
  if ((! directory.exists(path)) && (!directory.mkpath(path))) {
    QString msg = QString("Cannot create path '%1'.").arg(path);
    logError() << msg;
    emit error(msg);
    return;
  }
  if (! file.open(QIODevice::WriteOnly)) {
    QString msg = QString("Cannot save user database at '%1'.").arg(path+"/user.json");
    logError() << msg;
    emit error(msg);
    return;
  }

  file.write(reply->readAll());
  file.flush();
  file.close();

  load();
  reply->deleteLater();
}

unsigned
UserDatabase::dbAge() const {
  QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/user.json";
  QFileInfo info(path);
  if (! info.exists())
    return -1;
  return info.lastModified().daysTo(QDateTime::currentDateTime());
}

int
UserDatabase::rowCount(const QModelIndex &parent) const {
  Q_UNUSED(parent);
  return _user.size();
}

int
UserDatabase::columnCount(const QModelIndex &parent) const {
  Q_UNUSED(parent);
  return 3;
}

QVariant
UserDatabase::data(const QModelIndex &index, int role) const {
  if ((Qt::EditRole != role) && ((Qt::DisplayRole != role)))
    return QVariant();

  if (index.row() >= _user.size())
    return QVariant();

  if (0 == index.column()) {
    // Call
    if (Qt::DisplayRole == role) {
      if (_user[index.row()].surname.isEmpty()) {
        if (_user[index.row()].name.isEmpty()) {
          return _user[index.row()].call;
        } else {
          return tr("%1 (%2)")
              .arg(_user[index.row()].call)
              .arg(_user[index.row()].name);
        }
      } else {
        return tr("%1 (%2, %3)")
            .arg(_user[index.row()].call)
            .arg(_user[index.row()].name)
            .arg(_user[index.row()].surname);
      }
    } else {
      return _user[index.row()].call;
    }
  } else if (1 == index.column()) {
    // ID
    return _user[index.row()].id;
  } else if (2 == index.column()) {
    // Country
    return _user[index.column()].country;
  }

  return QVariant();
}