Debian Codegraph @

online-accounts/lib/qml/Lomiri/OnlineAccounts/account_model.cpp

raw symbols SCIP
1 /*
2 * This file is part of OnlineAccountsModule
3 *
4 * Copyright (C) 2015 Canonical Ltd.
5 *
6 * Contact: Alberto Mardegan <[email protected]>
7 *
8 * This program is free software: you can redistribute it and/or modify it
9 * under the terms of the GNU Lesser General Public License version 3, as
10 * published by the Free Software Foundation.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranties of
14 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "account_model.h"
22
23 #include "account.h"
24 #include "authentication_data.h"
25
26 #include <LomiriOnlineAccounts/Account>
27 #include <LomiriOnlineAccounts/AuthenticationData>
28 #include <LomiriOnlineAccounts/Manager>
29 #include <LomiriOnlineAccounts/PendingCall>
30 #include <QDebug>
31 #include <QQmlEngine>
32 #include <QVariantMap>
33 #include <QtQml>
34
35 using namespace OnlineAccountsModule;
36
37 namespace OnlineAccountsModule {
38
39 class AccountModelPrivate: public QObject
40 {
41 Q_OBJECT
42 Q_DECLARE_PUBLIC(AccountModel)
43
44 public:
45 AccountModelPrivate(AccountModel *q);
46
47 void queueUpdate();
48 Account *handleAccount(OnlineAccounts::Account *account);
49
50 private Q_SLOTS:
51 void update();
52 void updateAccountList();
53 void onAccountAvailable(OnlineAccounts::Account *account);
54 void onAccessRequestFinished();
55 void onAccountValidChanged();
56 void onAccountChanged();
57
58 private:
59 QHash<int, QByteArray> roleNames;
60 OnlineAccounts::Manager *m_manager;
61 QList<Account*> m_accounts;
62 QString m_applicationId;
63 QString m_serviceId;
64 bool m_isReady;
65 bool m_updateQueued;
66 bool m_applicationIdChanged;
67 bool m_serviceIdChanged;
68 mutable AccountModel *q_ptr;
69 };
70
71 } // namespace
72
73 AccountModelPrivate::AccountModelPrivate(AccountModel *q):
74 QObject(q),
75 m_manager(0),
76 m_isReady(false),
77 m_updateQueued(true), // because componentComplete will be called
78 m_applicationIdChanged(false),
79 m_serviceIdChanged(false),
80 q_ptr(q)
81 {
82 roleNames[AccountModel::DisplayNameRole] = "displayName";
83 roleNames[AccountModel::ValidRole] = "valid";
84 roleNames[AccountModel::AccountIdRole] = "accountId";
85 roleNames[AccountModel::ServiceIdRole] = "serviceId";
86 roleNames[AccountModel::AuthenticationMethodRole] = "authenticationMethod";
87 roleNames[AccountModel::SettingsRole] = "settings";
88 roleNames[AccountModel::AccountRole] = "account";
89 roleNames[AccountModel::ServiceRole] = "service";
90 }
91
92 void AccountModelPrivate::queueUpdate()
93 {
94 Q_Q(AccountModel);
95
96 if (m_updateQueued) return;
97
98 m_updateQueued = true;
99 QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection);
100
101 if (m_isReady) {
102 m_isReady = false;
103 Q_EMIT q->isReadyChanged();
104 }
105 }
106
107 void AccountModelPrivate::updateAccountList()
108 {
109 Q_Q(AccountModel);
110
111 m_serviceIdChanged = false;
112 auto accountObjects = m_manager->availableAccounts(m_serviceId);
113 q->beginResetModel();
114 m_accounts.clear();
115 Q_FOREACH(OnlineAccounts::Account *account, accountObjects) {
116 handleAccount(account);
117 }
118 q->endResetModel();
119 Q_EMIT q->accountListChanged();
120
121 m_isReady = true;
122 Q_EMIT q->isReadyChanged();
123 }
124
125 Account *AccountModelPrivate::handleAccount(OnlineAccounts::Account *account)
126 {
127 Q_Q(AccountModel);
128
129 /* First, check if the account is already handled */
130 Q_FOREACH(Account *a, m_accounts) {
131 if (account == a->internalObject()) {
132 return a;
133 }
134 }
135
136 QQmlEngine *engine = qmlEngine(q);
137 Account *a = new Account(account, engine, this);
138 QQmlEngine::setObjectOwnership(a, QQmlEngine::CppOwnership);
139 QObject::connect(a, SIGNAL(validChanged()),
140 this, SLOT(onAccountValidChanged()));
141 QObject::connect(a, SIGNAL(accountChanged()),
142 this, SLOT(onAccountChanged()));
143 m_accounts.append(a);
144 return a;
145 }
146
147 void AccountModelPrivate::update()
148 {
149 m_updateQueued = false;
150
151 if (m_applicationId.isEmpty()) {
152 QStringList parts = QString::fromUtf8(qgetenv("APP_ID")).split('_');
153 if (parts.count() == 3) {
154 m_applicationId = QStringList(parts.mid(0, 2)).join('_');
155 m_applicationIdChanged = true;
156 } else {
157 qWarning() << "Lomiri.OnlineAccounts: No APP_ID defined "
158 "and no applicationId given!";
159 return;
160 }
161 }
162
163 if (m_applicationIdChanged) {
164 delete m_manager;
165 m_manager = new OnlineAccounts::Manager(m_applicationId);
166 QObject::connect(m_manager, SIGNAL(ready()),
167 this, SLOT(updateAccountList()));
168 QObject::connect(m_manager,
169 SIGNAL(accountAvailable(OnlineAccounts::Account*)),
170 this,
171 SLOT(onAccountAvailable(OnlineAccounts::Account*)));
172 m_applicationIdChanged = false;
173 }
174
175 if (m_serviceIdChanged && m_manager->isReady()) {
176 updateAccountList();
177 }
178 }
179
180 void AccountModelPrivate::onAccountAvailable(OnlineAccounts::Account *account)
181 {
182 Q_Q(AccountModel);
183
184 if (!m_serviceId.isEmpty() && account->serviceId() != m_serviceId) {
185 // ignore this account
186 return;
187 }
188
189 int index = m_accounts.count();
190 q->beginInsertRows(QModelIndex(), index, index);
191 handleAccount(account);
192 q->endInsertRows();
193 Q_EMIT q->accountListChanged();
194 }
195
196 void AccountModelPrivate::onAccessRequestFinished()
197 {
198 Q_Q(AccountModel);
199
200 auto watcher = qobject_cast<OnlineAccounts::PendingCallWatcher*>(sender());
201
202 OnlineAccounts::RequestAccessReply reply(*watcher);
203 QVariantMap accountData;
204 QVariantMap authenticationData;
205 if (reply.hasError()) {
206 accountData["errorCode"] = reply.error().code();
207 accountData["errorText"] = reply.error().text();
208 } else {
209 OnlineAccounts::Account *account = reply.account();
210 accountData["account"] =
211 QVariant::fromValue<QObject*>(handleAccount(account));
212 authenticationData = replyToMap(*watcher);
213 }
214
215 Q_EMIT q->accessReply(accountData, authenticationData);
216 }
217
218 void AccountModelPrivate::onAccountValidChanged()
219 {
220 Q_Q(AccountModel);
221
222 Account *account = qobject_cast<Account*>(sender());
223 int i = m_accounts.indexOf(account);
224 if (Q_UNLIKELY(i < 0)) {
225 qWarning() << "Got signal from unhandled account!";
226 return;
227 }
228
229 Q_ASSERT(!account->isValid());
230 q->beginRemoveRows(QModelIndex(), i, i);
231 QObject::disconnect(account, 0, this, 0);
232 account->deleteLater();
233 m_accounts.removeAt(i);
234 q->endRemoveRows();
235 Q_EMIT q->accountListChanged();
236 }
237
238 void AccountModelPrivate::onAccountChanged()
239 {
240 Q_Q(AccountModel);
241
242 Account *account = qobject_cast<Account*>(sender());
243 int i = m_accounts.indexOf(account);
244 if (Q_UNLIKELY(i < 0)) {
245 qWarning() << "Got signal from unhandled account!";
246 return;
247 }
248
249 QModelIndex idx = q->index(i, 0);
250 q->dataChanged(idx, idx);
251 }
252
253 /*!
254 * \qmltype AccountModel
255 * \inqmlmodule Lomiri.OnlineAccounts 2.0
256 * \ingroup Lomiri
257 * \brief Model of available online accounts.
258 *
259 * The AccountModel lists all the accounts available to the application.
260 * \qml
261 * import QtQuick 2.0
262 * import Lomiri.OnlineAccounts 2.0
263 *
264 * ListView {
265 * model: AccountModel {
266 * applicationId: "myapp.developer_myapp"
267 * }
268 * delegate: Text {
269 * text: model.displayName
270 * }
271 * }
272 * \endqml
273 *
274 * The model defines the following roles:
275 *
276 * \list
277 * \li \c displayName is the name of the account (usually the user's login)
278 * \li \c accountId is a numeric ID for the account
279 * \li \c serviceId is a service identifier (e.g., "myapp.developer_myapp_google")
280 * \li \c authenticationMethod is the authentication method used on this
281 * account; \sa Account::authenticationMethod
282 * \li \c settings is a dictionary of the settings stored into the account
283 * \li \c account is the \l Account object
284 * \endlist
285 *
286 * \sa Account
287 */
288
289 AccountModel::AccountModel(QObject *parent):
290 QAbstractListModel(parent),
291 d_ptr(new AccountModelPrivate(this))
292 {
293 QObject::connect(this, SIGNAL(modelReset()),
294 this, SIGNAL(countChanged()));
295 QObject::connect(this, SIGNAL(rowsInserted(const QModelIndex &,int,int)),
296 this, SIGNAL(countChanged()));
297 QObject::connect(this, SIGNAL(rowsRemoved(const QModelIndex &,int,int)),
298 this, SIGNAL(countChanged()));
299 }
300
301 AccountModel::~AccountModel()
302 {
303 delete d_ptr;
304 }
305
306 void AccountModel::classBegin()
307 {
308 }
309
310 void AccountModel::componentComplete()
311 {
312 Q_D(AccountModel);
313 d->update();
314 }
315
316 /*!
317 * \qmlproperty bool AccountModel::ready
318 *
319 * Whether the model is up to date: retrieving the account list is an
320 * asynchronous operation, and therefore short delays are expected between
321 * changing one model parameter and receiving the updated account list.
322 * Applications should not rely on the model contents while this property is
323 * false.
324 */
325 bool AccountModel::isReady() const
326 {
327 Q_D(const AccountModel);
328 return d->m_isReady;
329 }
330
331 /*!
332 * \qmlproperty string AccountModel::applicationId
333 *
334 * The short application identifier (that is, the \c APP_ID minus the version
335 * component) of the client. If not given, the identifier will be deduced from
336 * the APP_ID environment variable.
337 */
338 void AccountModel::setApplicationId(const QString &applicationId)
339 {
340 Q_D(AccountModel);
341 if (applicationId == d->m_applicationId) return;
342
343 d->m_applicationId = applicationId;
344 d->m_applicationIdChanged = true;
345 d->queueUpdate();
346 Q_EMIT applicationIdChanged();
347 }
348
349 QString AccountModel::applicationId() const
350 {
351 Q_D(const AccountModel);
352 return d->m_applicationId;
353 }
354
355 /*!
356 * \qmlproperty string AccountModel::serviceId
357 *
358 * If this property is set, only accounts providing the given service will be
359 * returned.
360 */
361 void AccountModel::setServiceId(const QString &serviceId)
362 {
363 Q_D(AccountModel);
364 if (serviceId == d->m_serviceId) return;
365
366 d->m_serviceId = serviceId;
367 d->m_serviceIdChanged = true;
368 d->queueUpdate();
369 Q_EMIT serviceIdChanged();
370 }
371
372 QString AccountModel::serviceId() const
373 {
374 Q_D(const AccountModel);
375 return d->m_serviceId;
376 }
377
378 /*!
379 * \qmlproperty list<Account> AccountModel::accountList
380 *
381 * List of accounts in the model. This list has exactly the same contents as
382 * the model data, and is provided as a property just as a convenience for
383 * those cases when a model is not required.
384 */
385 QList<QObject*> AccountModel::accountList() const
386 {
387 Q_D(const AccountModel);
388 QList<QObject*> objects;
389 Q_FOREACH(Account *a, d->m_accounts) {
390 objects.append(a);
391 }
392 return objects;
393 }
394
395 QJSValue AccountModel::serviceList() const
396 {
397 Q_D(const AccountModel);
398 QJSEngine *engine = qmlEngine(this);
399 QJSValue ret = engine->newArray();
400 if (!d->m_manager) return ret;
401 int i = 0;
402 Q_FOREACH(const auto &service, d->m_manager->availableServices()) {
403 #if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
404 QJSValue v = engine->toScriptValue(service);
405 #else
406 QJSValue v = engine->toScriptValue(service.toMap());
407 #endif
408 ret.setProperty(i++, v);
409 }
410 return ret;
411 }
412
413 /*!
414 * \qmlsignal AccountModel::accessReply(jsobject reply, jsobject authenticationData)
415 *
416 * Emitted when the request initiated with \l AccountModel::requestAccess()
417 * completes. The \a reply object contains the access reply:
418 * \list
419 * \li \c account if access to an account was granted, this property will hold
420 * an \l Account object
421 * \li \c errorCode \l {errorCode} {error code}, if an error occurred
422 * \li \c errorText is a textual description of the error, not meant for the
423 * end-user; it can be used for debugging purposes
424 * \endlist
425 *
426 * The second parameter, the \a authenticationData object, will contain the
427 * authentication reply.
428 */
429
430 /*!
431 * \qmlmethod void AccountModel::requestAccess(string serviceId,
432 * jsobject parameters)
433 *
434 * Requests the user to grant this application access to an account providing
435 * the given service. The user will be asked whether this application should be
436 * given access to the desired account; if no such accounts are currently
437 * registered in the system, the user will be guided to create a new one.
438 *
439 * It should be noted that account authorizations persist across application
440 * restart; therefore, this method should be called only when the application
441 * needs a new account to appear in the model.
442 *
443 * Each call to this method will cause the \l accessReply signal to be
444 * emitted at some time later. Note that the operation will involve
445 * interactions with the end-user, so don't expect a reply to be emitted
446 * immediately.
447 *
448 * The \a parameters parameter can be used to pass authentication data
449 * (similarly to how the \l Account::authenticate() method works), if it's
450 * desired to perform the authentication at the same time.
451 *
452 * \sa accessReply
453 */
454 void AccountModel::requestAccess(const QString &service,
455 const QVariantMap &parameters)
456 {
457 Q_D(AccountModel);
458 OnlineAccounts::PendingCall call =
459 d->m_manager->requestAccess(service,
460 authenticationDataFromMap(parameters));
461 OnlineAccounts::PendingCallWatcher *watcher =
462 new OnlineAccounts::PendingCallWatcher(call, this);
463 QObject::connect(watcher, SIGNAL(finished()),
464 d, SLOT(onAccessRequestFinished()));
465 }
466
467 /*!
468 * \qmlmethod variant AccountModel::get(int row, string roleName)
469 *
470 * Returns the data at \a row for the role \a roleName.
471 */
472 QVariant AccountModel::get(int row, const QString &roleName) const
473 {
474 int role = roleNames().key(roleName.toLatin1(), -1);
475 return data(index(row), role);
476 }
477
478 int AccountModel::rowCount(const QModelIndex &parent) const
479 {
480 Q_D(const AccountModel);
481 Q_UNUSED(parent);
482 return d->m_accounts.count();
483 }
484
485 QVariant AccountModel::data(const QModelIndex &index, int role) const
486 {
487 Q_D(const AccountModel);
488
489 int i = index.row();
490 if (i < 0 || i >= d->m_accounts.count()) return QVariant();
491
492 Account *account = d->m_accounts.at(i);
493 QVariant ret;
494
495 switch (role) {
496 case Qt::DisplayRole:
497 ret = QString("%1 - %2").
498 arg(account->displayName()).
499 arg(account->serviceId());
500 break;
501 case DisplayNameRole:
502 ret = account->displayName();
503 break;
504 case ValidRole:
505 ret = account->isValid();
506 break;
507 case AccountIdRole:
508 ret = account->accountId();
509 break;
510 case ServiceIdRole:
511 ret = account->serviceId();
512 break;
513 case AuthenticationMethodRole:
514 ret = account->authenticationMethod();
515 break;
516 case SettingsRole:
517 ret = account->settings();
518 break;
519 case AccountRole:
520 ret = QVariant::fromValue<QObject*>(account);
521 break;
522 case ServiceRole:
523 ret = QVariant::fromValue(account->service());
524 break;
525 }
526
527 return ret;
528 }
529
530 QHash<int, QByteArray> AccountModel::roleNames() const
531 {
532 Q_D(const AccountModel);
533 return d->roleNames;
534 }
535
536 #include "account_model.moc"