Welcome to mirror list, hosted at ThFree Co, Russian Federation.

usermodel.cpp « tray « gui « src - github.com/nextcloud/desktop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c7d71ec3bd3df10ba84d03831b510c8eb9acce9d (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
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
#include "notificationhandler.h"
#include "usermodel.h"

#include "accountmanager.h"
#include "owncloudgui.h"
#include <pushnotifications.h>
#include "userstatusselectormodel.h"
#include "syncengine.h"
#include "ocsjob.h"
#include "configfile.h"
#include "notificationconfirmjob.h"
#include "logger.h"
#include "guiutility.h"
#include "syncfileitem.h"
#include "systray.h"
#include "tray/activitylistmodel.h"
#include "tray/unifiedsearchresultslistmodel.h"
#include "tray/talkreply.h"
#include "userstatusconnector.h"
#include "thumbnailjob.h"

#include <QDesktopServices>
#include <QIcon>
#include <QMessageBox>
#include <QSvgRenderer>
#include <QPainter>
#include <QPushButton>

// time span in milliseconds which has to be between two
// refreshes of the notifications
#define NOTIFICATION_REQUEST_FREE_PERIOD 15000

namespace {
constexpr qint64 expiredActivitiesCheckIntervalMsecs = 1000 * 60;
constexpr qint64 activityDefaultExpirationTimeMsecs = 1000 * 60 * 10;
}

namespace OCC {

User::User(AccountStatePtr &account, const bool &isCurrent, QObject *parent)
    : QObject(parent)
    , _account(account)
    , _isCurrentUser(isCurrent)
    , _activityModel(new ActivityListModel(_account.data(), this))
    , _unifiedSearchResultsModel(new UnifiedSearchResultsListModel(_account.data(), this))
    , _notificationRequestsRunning(0)
{
    connect(ProgressDispatcher::instance(), &ProgressDispatcher::progressInfo,
        this, &User::slotProgressInfo);
    connect(ProgressDispatcher::instance(), &ProgressDispatcher::itemCompleted,
        this, &User::slotItemCompleted);
    connect(ProgressDispatcher::instance(), &ProgressDispatcher::syncError,
        this, &User::slotAddError);
    connect(ProgressDispatcher::instance(), &ProgressDispatcher::addErrorToGui,
        this, &User::slotAddErrorToGui);

    connect(&_notificationCheckTimer, &QTimer::timeout,
        this, &User::slotRefresh);

    connect(&_expiredActivitiesCheckTimer, &QTimer::timeout,
        this, &User::slotCheckExpiredActivities);

    connect(_account.data(), &AccountState::stateChanged,
            [=]() { if (isConnected()) {slotRefreshImmediately();} });
    connect(_account.data(), &AccountState::stateChanged, this, &User::accountStateChanged);
    connect(_account.data(), &AccountState::hasFetchedNavigationApps,
        this, &User::slotRebuildNavigationAppList);
    connect(_account->account().data(), &Account::accountChangedDisplayName, this, &User::nameChanged);

    connect(FolderMan::instance(), &FolderMan::folderListChanged, this, &User::hasLocalFolderChanged);

    connect(_account->account().data(), &Account::accountChangedAvatar, this, &User::avatarChanged);
    connect(_account->account().data(), &Account::userStatusChanged, this, &User::statusChanged);
    connect(_account.data(), &AccountState::desktopNotificationsAllowedChanged, this, &User::desktopNotificationsAllowedChanged);

    connect(_account->account().data(), &Account::capabilitiesChanged, this, &User::headerColorChanged);
    connect(_account->account().data(), &Account::capabilitiesChanged, this, &User::headerTextColorChanged);
    connect(_account->account().data(), &Account::capabilitiesChanged, this, &User::accentColorChanged);

    connect(_activityModel, &ActivityListModel::sendNotificationRequest, this, &User::slotSendNotificationRequest);
    
    connect(this, &User::sendReplyMessage, this, &User::slotSendReplyMessage);
}

void User::showDesktopNotification(const QString &title, const QString &message, const long notificationId)
{
    // Notification ids are uints, which are 4 bytes. Error activities don't have ids, however, so we generate one.
    // To avoid possible collisions between the activity ids which are actually the notification ids received from
    // the server (which are always positive) and our "fake" error activity ids, we assign a negative id to the
    // error notification.
    //
    // To ensure that we can still treat an unsigned int as normal, we use a long, which is 8 bytes.

    ConfigFile cfg;
    if (!cfg.optionalServerNotifications() || !isDesktopNotificationsAllowed()) {
        return;
    }

    // after one hour, clear the gui log notification store
    constexpr qint64 clearGuiLogInterval = 60 * 60 * 1000;
    if (_guiLogTimer.elapsed() > clearGuiLogInterval) {
        _notifiedNotifications.clear();
    }

    if (_notifiedNotifications.contains(notificationId)) {
        return;
    }

    _notifiedNotifications.insert(notificationId);
    Logger::instance()->postGuiLog(title, message);
    // restart the gui log timer now that we show a new notification
    _guiLogTimer.start();
}

void User::slotBuildNotificationDisplay(const ActivityList &list)
{
    const auto multipleAccounts = AccountManager::instance()->accounts().count() > 1;
    ActivityList toNotifyList;

    std::copy_if(list.constBegin(), list.constEnd(), std::back_inserter(toNotifyList), [&](const Activity &activity) {

        if (_blacklistedNotifications.contains(activity)) {
            qCInfo(lcActivity) << "Activity in blacklist, skip";
            return false;
        } else if(_notifiedNotifications.contains(activity._id)) {
            qCInfo(lcActivity) << "Activity already notified, skip";
            return false;
        }

        return true;
    });

    if(toNotifyList.count() > 2) {
        const auto subject = QStringLiteral("%1 notifications").arg(toNotifyList.count());
        const auto message = multipleAccounts ? toNotifyList.constFirst()._accName : QString();
        showDesktopNotification(subject, message, -static_cast<int>(qHash(subject)));

        // Set these activities as notified here, rather than in showDesktopNotification
        for(const auto &activity : toNotifyList) {
            _notifiedNotifications.insert(activity._id);
            _activityModel->addNotificationToActivityList(activity);
        }

        return;
    }

    for(const auto &activity : toNotifyList) {
        const auto message = activity._objectType == QStringLiteral("chat")
            ? activity._message : AccountManager::instance()->accounts().count() == 1 ? "" : activity._accName;

        showDesktopNotification(activity._subject, message, activity._id); // We assigned the notif. id to the activity id
        _activityModel->addNotificationToActivityList(activity);
    }
}

void User::slotBuildIncomingCallDialogs(const ActivityList &list)
{
    const ConfigFile cfg;
    const auto userStatus = _account->account()->userStatusConnector()->userStatus().state();
    if (userStatus == OCC::UserStatus::OnlineStatus::DoNotDisturb ||
            !cfg.optionalServerNotifications() ||
            !cfg.showCallNotifications() ||
            !isDesktopNotificationsAllowed()) {
        return;
    }

    const auto systray = Systray::instance();

    if(systray) {
        for(const auto &activity : list) {
            systray->createCallDialog(activity, _account);
        }
    }
}

void User::setNotificationRefreshInterval(std::chrono::milliseconds interval)
{
    if (!checkPushNotificationsAreReady()) {
        qCDebug(lcActivity) << "Starting Notification refresh timer with " << interval.count() / 1000 << " sec interval";
        _notificationCheckTimer.start(interval.count());
    }
}

void User::slotPushNotificationsReady()
{
    qCInfo(lcActivity) << "Push notifications are ready";

    if (_notificationCheckTimer.isActive()) {
        // as we are now able to use push notifications - let's stop the polling timer
        _notificationCheckTimer.stop();
    }

    connectPushNotifications();
}

void User::slotDisconnectPushNotifications()
{
    disconnect(_account->account()->pushNotifications(), &PushNotifications::notificationsChanged, this, &User::slotReceivedPushNotification);
    disconnect(_account->account()->pushNotifications(), &PushNotifications::activitiesChanged, this, &User::slotReceivedPushActivity);

    disconnect(_account->account().data(), &Account::pushNotificationsDisabled, this, &User::slotDisconnectPushNotifications);

    // connection to WebSocket may have dropped or an error occured, so we need to bring back the polling until we have re-established the connection
    setNotificationRefreshInterval(ConfigFile().notificationRefreshInterval());
}

void User::slotReceivedPushNotification(Account *account)
{
    if (account->id() == _account->account()->id()) {
        slotRefreshNotifications();
    }
}

void User::slotReceivedPushActivity(Account *account)
{
    if (account->id() == _account->account()->id()) {
        slotRefreshActivities();
    }
}

void User::slotCheckExpiredActivities()
{
    for (const Activity &activity : _activityModel->errorsList()) {
        if (activity._expireAtMsecs > 0 && QDateTime::currentDateTime().toMSecsSinceEpoch() >= activity._expireAtMsecs) {
            _activityModel->removeActivityFromActivityList(activity);
        }
    }

    if (_activityModel->errorsList().size() == 0) {
        _expiredActivitiesCheckTimer.stop();
    }
}

void User::connectPushNotifications() const
{
    connect(_account->account().data(), &Account::pushNotificationsDisabled, this, &User::slotDisconnectPushNotifications, Qt::UniqueConnection);

    connect(_account->account()->pushNotifications(), &PushNotifications::notificationsChanged, this, &User::slotReceivedPushNotification, Qt::UniqueConnection);
    connect(_account->account()->pushNotifications(), &PushNotifications::activitiesChanged, this, &User::slotReceivedPushActivity, Qt::UniqueConnection);
}

bool User::checkPushNotificationsAreReady() const
{
    const auto pushNotifications = _account->account()->pushNotifications();

    const auto pushActivitiesAvailable = _account->account()->capabilities().availablePushNotifications() & PushNotificationType::Activities;
    const auto pushNotificationsAvailable = _account->account()->capabilities().availablePushNotifications() & PushNotificationType::Notifications;

    const auto pushActivitiesAndNotificationsAvailable = pushActivitiesAvailable && pushNotificationsAvailable;

    if (pushActivitiesAndNotificationsAvailable && pushNotifications && pushNotifications->isReady()) {
        connectPushNotifications();
        return true;
    } else {
        connect(_account->account().data(), &Account::pushNotificationsReady, this, &User::slotPushNotificationsReady, Qt::UniqueConnection);
        return false;
    }
}

void User::slotRefreshImmediately() {
    if (_account.data() && _account.data()->isConnected() && Systray::instance()->isOpen()) {
        slotRefreshActivities();
    }
    slotRefreshNotifications();
}

void User::slotRefresh()
{
    slotRefreshUserStatus();
    
    if (checkPushNotificationsAreReady()) {
        // we are relying on WebSocket push notifications - ignore refresh attempts from UI
        slotRefreshActivitiesInitial();
        _timeSinceLastCheck[_account.data()].invalidate();
        return;
    }

    // QElapsedTimer isn't actually constructed as invalid.
    if (!_timeSinceLastCheck.contains(_account.data())) {
        _timeSinceLastCheck[_account.data()].invalidate();
    }
    QElapsedTimer &timer = _timeSinceLastCheck[_account.data()];

    // Fetch Activities only if visible and if last check is longer than 15 secs ago
    if (timer.isValid() && timer.elapsed() < NOTIFICATION_REQUEST_FREE_PERIOD) {
        qCDebug(lcActivity) << "Do not check as last check is only secs ago: " << timer.elapsed() / 1000;
        return;
    }
    if (_account.data() && _account.data()->isConnected()) {
        slotRefreshActivitiesInitial();
        slotRefreshNotifications();
        timer.start();
    }
}

void User::slotRefreshActivitiesInitial()
{
    if (_account.data()->isConnected() && Systray::instance()->isOpen()) {
        _activityModel->slotRefreshActivityInitial();
    }
}

void User::slotRefreshActivities()
{
    if (_account.data()->isConnected() && Systray::instance()->isOpen()) {
        _activityModel->slotRefreshActivity();
    }
}

void User::slotRefreshUserStatus()
{
    if (_account.data() && _account.data()->isConnected()) {
        _account->account()->userStatusConnector()->fetchUserStatus();
    }
}

void User::slotRefreshNotifications()
{
    // start a server notification handler if no notification requests
    // are running
    if (_notificationRequestsRunning == 0) {
        auto *snh = new ServerNotificationHandler(_account.data());
        connect(snh, &ServerNotificationHandler::newNotificationList,
            this, &User::slotBuildNotificationDisplay);
        connect(snh, &ServerNotificationHandler::newIncomingCallsList,
            this, &User::slotBuildIncomingCallDialogs);

        snh->slotFetchNotifications();
    } else {
        qCWarning(lcActivity) << "Notification request counter not zero.";
    }
}

void User::slotRebuildNavigationAppList()
{
    emit serverHasTalkChanged();
    // Rebuild App list
    UserAppsModel::instance()->buildAppList();
}

void User::slotNotificationRequestFinished(int statusCode)
{
    int row = sender()->property("activityRow").toInt();

    // the ocs API returns stat code 100 or 200 or 202 inside the xml if it succeeded.
    if (statusCode != OCS_SUCCESS_STATUS_CODE
        && statusCode != OCS_SUCCESS_STATUS_CODE_V2
        && statusCode != OCS_ACCEPTED_STATUS_CODE) {
        qCWarning(lcActivity) << "Notification Request to Server failed, leave notification visible.";
    } else {
        // to do use the model to rebuild the list or remove the item
        qCWarning(lcActivity) << "Notification Request to Server successed, rebuilding list.";
        _activityModel->removeActivityFromActivityList(row);
    }
}

void User::slotEndNotificationRequest(int replyCode)
{
    _notificationRequestsRunning--;
    slotNotificationRequestFinished(replyCode);
}

void User::slotSendNotificationRequest(const QString &accountName, const QString &link, const QByteArray &verb, int row)
{
    qCInfo(lcActivity) << "Server Notification Request " << verb << link << "on account" << accountName;

    const QStringList validVerbs = QStringList() << "GET"
                                                 << "PUT"
                                                 << "POST"
                                                 << "DELETE";

    if (validVerbs.contains(verb)) {
        AccountStatePtr acc = AccountManager::instance()->account(accountName);
        if (acc) {
            auto *job = new NotificationConfirmJob(acc->account());
            QUrl l(link);
            job->setLinkAndVerb(l, verb);
            job->setProperty("activityRow", QVariant::fromValue(row));
            connect(job, &AbstractNetworkJob::networkError,
                this, &User::slotNotifyNetworkError);
            connect(job, &NotificationConfirmJob::jobFinished,
                this, &User::slotNotifyServerFinished);
            job->start();

            // count the number of running notification requests. If this member var
            // is larger than zero, no new fetching of notifications is started
            _notificationRequestsRunning++;
        }
    } else {
        qCWarning(lcActivity) << "Notification Links: Invalid verb:" << verb;
    }
}

void User::slotNotifyNetworkError(QNetworkReply *reply)
{
    auto *job = qobject_cast<NotificationConfirmJob *>(sender());
    if (!job) {
        return;
    }

    int resultCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    slotEndNotificationRequest(resultCode);
    qCWarning(lcActivity) << "Server notify job failed with code " << resultCode;
}

void User::slotNotifyServerFinished(const QString &reply, int replyCode)
{
    auto *job = qobject_cast<NotificationConfirmJob *>(sender());
    if (!job) {
        return;
    }

    slotEndNotificationRequest(replyCode);
    qCInfo(lcActivity) << "Server Notification reply code" << replyCode << reply;
}

void User::slotProgressInfo(const QString &folder, const ProgressInfo &progress)
{
    if (progress.status() == ProgressInfo::Reconcile) {
        // Wipe all non-persistent entries - as well as the persistent ones
        // in cases where a local discovery was done.
        auto f = FolderMan::instance()->folder(folder);
        if (!f)
            return;
        const auto &engine = f->syncEngine();
        const auto style = engine.lastLocalDiscoveryStyle();
        foreach (Activity activity, _activityModel->errorsList()) {
            if (activity._expireAtMsecs != -1) {
                // we process expired activities in a different slot
                continue;
            }
            if (activity._folder != folder) {
                continue;
            }

            if (style == LocalDiscoveryStyle::FilesystemOnly) {
                _activityModel->removeActivityFromActivityList(activity);
                continue;
            }

            if (activity._syncFileItemStatus == SyncFileItem::Conflict && !QFileInfo(f->path() + activity._file).exists()) {
                _activityModel->removeActivityFromActivityList(activity);
                continue;
            }

            if (activity._syncFileItemStatus == SyncFileItem::FileLocked && !QFileInfo(f->path() + activity._file).exists()) {
                _activityModel->removeActivityFromActivityList(activity);
                continue;
            }


            if (activity._syncFileItemStatus == SyncFileItem::FileIgnored && !QFileInfo(f->path() + activity._file).exists()) {
                _activityModel->removeActivityFromActivityList(activity);
                continue;
            }


            if (!QFileInfo(f->path() + activity._file).exists()) {
                _activityModel->removeActivityFromActivityList(activity);
                continue;
            }

            auto path = QFileInfo(activity._file).dir().path().toUtf8();
            if (path == ".")
                path.clear();

            if (engine.shouldDiscoverLocally(path))
                _activityModel->removeActivityFromActivityList(activity);
        }
    }

    if (progress.status() == ProgressInfo::Done) {
        // We keep track very well of pending conflicts.
        // Inform other components about them.
        QStringList conflicts;
        foreach (Activity activity, _activityModel->errorsList()) {
            if (activity._folder == folder
                && activity._syncFileItemStatus == SyncFileItem::Conflict) {
                conflicts.append(activity._file);
            }
        }

        emit ProgressDispatcher::instance()->folderConflicts(folder, conflicts);
    }
}

void User::slotAddError(const QString &folderAlias, const QString &message, ErrorCategory category)
{
    auto folderInstance = FolderMan::instance()->folder(folderAlias);
    if (!folderInstance)
        return;

    if (folderInstance->accountState() == _account.data()) {
        qCWarning(lcActivity) << "Item " << folderInstance->shortGuiLocalPath() << " retrieved resulted in " << message;

        Activity activity;
        activity._type = Activity::SyncResultType;
        activity._syncResultStatus = SyncResult::Error;
        activity._dateTime = QDateTime::fromString(QDateTime::currentDateTime().toString(), Qt::ISODate);
        activity._subject = message;
        activity._message = folderInstance->shortGuiLocalPath();
        activity._link = folderInstance->shortGuiLocalPath();
        activity._accName = folderInstance->accountState()->account()->displayName();
        activity._folder = folderAlias;


        if (category == ErrorCategory::InsufficientRemoteStorage) {
            ActivityLink link;
            link._label = tr("Retry all uploads");
            link._link = folderInstance->path();
            link._verb = "";
            link._primary = true;
            activity._links.append(link);
        }

        // add 'other errors' to activity list
        _activityModel->addErrorToActivityList(activity);
    }
}

void User::slotAddErrorToGui(const QString &folderAlias, SyncFileItem::Status status, const QString &errorMessage, const QString &subject)
{
    const auto folderInstance = FolderMan::instance()->folder(folderAlias);
    if (!folderInstance) {
        return;
    }

    if (folderInstance->accountState() == _account.data()) {
        qCWarning(lcActivity) << "Item " << folderInstance->shortGuiLocalPath() << " retrieved resulted in " << errorMessage;

        Activity activity;
        activity._type = Activity::SyncFileItemType;
        activity._syncFileItemStatus = status;
        const auto currentDateTime = QDateTime::currentDateTime();
        activity._dateTime = QDateTime::fromString(currentDateTime.toString(), Qt::ISODate);
        activity._expireAtMsecs = currentDateTime.addMSecs(activityDefaultExpirationTimeMsecs).toMSecsSinceEpoch();
        activity._subject = !subject.isEmpty() ? subject : folderInstance->shortGuiLocalPath();
        activity._message = errorMessage;
        activity._link = folderInstance->shortGuiLocalPath();
        activity._accName = folderInstance->accountState()->account()->displayName();
        activity._folder = folderAlias;

        // Error notifications don't have ids by themselves so we will create one for it
        activity._id = -static_cast<int>(qHash(activity._subject + activity._message));

        // add 'other errors' to activity list
        _activityModel->addErrorToActivityList(activity);

        showDesktopNotification(activity._subject, activity._message, activity._id);

        if (!_expiredActivitiesCheckTimer.isActive()) {
            _expiredActivitiesCheckTimer.start(expiredActivitiesCheckIntervalMsecs);
        }
    }
}

bool User::isActivityOfCurrentAccount(const Folder *folder) const
{
    return folder->accountState() == _account.data();
}

bool User::isUnsolvableConflict(const SyncFileItemPtr &item) const
{
    // We just care about conflict issues that we are able to resolve
    return item->_status == SyncFileItem::Conflict && !Utility::isConflictFile(item->_file);
}

void User::processCompletedSyncItem(const Folder *folder, const SyncFileItemPtr &item)
{
    const auto fileActionFromInstruction = [](const int instruction) {
        if (instruction == CSYNC_INSTRUCTION_REMOVE) {
            return QStringLiteral("file_deleted");
        } else if (instruction == CSYNC_INSTRUCTION_NEW) {
            return QStringLiteral("file_created");
        } else if (instruction == CSYNC_INSTRUCTION_RENAME) {
            return QStringLiteral("file_renamed");
        } else {
            return QStringLiteral("file_changed");
        }
    };

    const auto messageFromFileAction = [](const QString &fileAction, const QString &fileName) {
        if (fileAction == QStringLiteral("file_renamed")) {
            return QObject::tr("You renamed %1").arg(fileName);
        } else if (fileAction == QStringLiteral("file_deleted")) {
            return QObject:: tr("You deleted %1").arg(fileName);
        } else if (fileAction == QStringLiteral("file_created")) {
            return QObject::tr("You created %1").arg(fileName);
        } else {
            return QObject::tr("You changed %1").arg(fileName);
        }
    };

    Activity activity;
    activity._type = Activity::SyncFileItemType; //client activity
    activity._syncFileItemStatus = item->_status;
    activity._dateTime = QDateTime::currentDateTime();
    activity._message = item->_originalFile;
    activity._link = account()->url();
    activity._accName = account()->displayName();
    activity._file = item->_file;
    activity._folder = folder->alias();
    activity._fileAction = "";

    const auto fileName = QFileInfo(item->_originalFile).fileName();

    activity._fileAction = fileActionFromInstruction(item->_instruction);

    if (item->_status == SyncFileItem::NoStatus || item->_status == SyncFileItem::Success) {
        qCWarning(lcActivity) << "Item " << item->_file << " retrieved successfully.";

        if (item->_direction != SyncFileItem::Up) {
            activity._message = QObject::tr("Synced %1").arg(fileName);
        } else {
            activity._message = messageFromFileAction(activity._fileAction, fileName);
        }

        if(activity._fileAction != "file_deleted" && !item->isEmpty()) {
            auto remotePath = folder->remotePath();
            remotePath.append(activity._fileAction == "file_renamed" ? item->_renameTarget : activity._file);

            const auto localFiles = FolderMan::instance()->findFileInLocalFolders(item->_file, account());
            if (!localFiles.isEmpty()) {
                const auto firstFilePath = localFiles.constFirst();
                const auto itemJournalRecord = item->toSyncJournalFileRecordWithInode(firstFilePath);

                if(!itemJournalRecord.isVirtualFile()) {
                    const auto mimeType = _mimeDb.mimeTypeForFile(QFileInfo(localFiles.constFirst()));

                    // Set the preview data, though for now we can skip setting file ID, link, and view
                    PreviewData preview;
                    preview._mimeType = mimeType.name();
                    preview._filename = fileName;
                    preview._isMimeTypeIcon = true;

                    if(item->isDirectory()) {
                        preview._source = account()->url().toString() + QStringLiteral("/index.php/apps/theming/img/core/filetypes/folder.svg");
                    } else {
                        preview._source = account()->url().toString() + Activity::relativeServerFileTypeIconPath(mimeType);
                    }
                    activity._previews.append(preview);
                }
            }
        }

        _activityModel->addSyncFileItemToActivityList(activity);
    } else {
        qCWarning(lcActivity) << "Item " << item->_file << " retrieved resulted in error " << item->_errorString;

        activity._subject = item->_errorString;
        activity._id = -static_cast<int>(qHash(activity._subject + activity._message));

        if (item->_status == SyncFileItem::Status::FileIgnored) {
            _activityModel->addIgnoredFileToList(activity);
        } else {
            // add 'protocol error' to activity list
            if (item->_status == SyncFileItem::Status::FileNameInvalid) {
                showDesktopNotification(item->_file, activity._subject, activity._id);
            }
            _activityModel->addErrorToActivityList(activity);
        }
    }
}

void User::slotItemCompleted(const QString &folder, const SyncFileItemPtr &item)
{
    auto folderInstance = FolderMan::instance()->folder(folder);

    if (!folderInstance || !isActivityOfCurrentAccount(folderInstance) || isUnsolvableConflict(item)) {
        return;
    }

    qCWarning(lcActivity) << "Item " << item->_file << " retrieved resulted in " << item->_errorString;
    processCompletedSyncItem(folderInstance, item);
}

AccountPtr User::account() const
{
    return _account->account();
}

AccountStatePtr User::accountState() const
{
    return _account;
}

void User::setCurrentUser(const bool &isCurrent)
{
    _isCurrentUser = isCurrent;
}

Folder *User::getFolder() const
{
    foreach (Folder *folder, FolderMan::instance()->map()) {
        if (folder->accountState() == _account.data()) {
            return folder;
        }
    }

    return nullptr;
}

ActivityListModel *User::getActivityModel()
{
    return _activityModel;
}

UnifiedSearchResultsListModel *User::getUnifiedSearchResultsListModel() const
{
    return _unifiedSearchResultsModel;
}

void User::openLocalFolder()
{
    const auto folder = getFolder();

    if (folder) {
        QDesktopServices::openUrl(QUrl::fromLocalFile(folder->path()));
    }
}

void User::login() const
{
    _account->account()->resetRejectedCertificates();
    _account->signIn();
}

void User::logout() const
{
    _account->signOutByUi();
}

QString User::name() const
{
    return _account->account()->prettyName();
}

QString User::server(bool shortened) const
{
    QString serverUrl = _account->account()->url().toString();
    if (shortened) {
        serverUrl.replace(QLatin1String("https://"), QLatin1String(""));
        serverUrl.replace(QLatin1String("http://"), QLatin1String(""));
    }
    return serverUrl;
}

UserStatus::OnlineStatus User::status() const
{
    return _account->account()->userStatusConnector()->userStatus().state();
}

QString User::statusMessage() const
{
    return _account->account()->userStatusConnector()->userStatus().message();
}

QUrl User::statusIcon() const
{
    return _account->account()->userStatusConnector()->userStatus().stateIcon();
}

QString User::statusEmoji() const
{
    return _account->account()->userStatusConnector()->userStatus().icon();
}

bool User::serverHasUserStatus() const
{
    return _account->account()->capabilities().userStatus();
}

QImage User::avatar() const
{
    return AvatarJob::makeCircularAvatar(_account->account()->avatar());
}

QString User::avatarUrl() const
{
    if (avatar().isNull()) {
        return QString();
    }

    return QStringLiteral("image://avatars/") + _account->account()->id();
}

bool User::hasLocalFolder() const
{
    return getFolder() != nullptr;
}

bool User::serverHasTalk() const
{
    return talkApp() != nullptr;
}

AccountApp *User::talkApp() const
{
    return _account->findApp(QStringLiteral("spreed"));
}

bool User::hasActivities() const
{
    return _account->account()->capabilities().hasActivities();
}

QColor User::headerColor() const
{
    return _account->account()->headerColor();
}

QColor User::headerTextColor() const
{
    return _account->account()->headerTextColor();
}

QColor User::accentColor() const
{
    return _account->account()->accentColor();
}

AccountAppList User::appList() const
{
    return _account->appList();
}

bool User::isCurrentUser() const
{
    return _isCurrentUser;
}

bool User::isConnected() const
{
    return (_account->connectionStatus() == AccountState::ConnectionStatus::Connected);
}


bool User::isDesktopNotificationsAllowed() const
{
    return _account.data()->isDesktopNotificationsAllowed();
}

void User::removeAccount() const
{
    AccountManager::instance()->deleteAccount(_account.data());
    AccountManager::instance()->save();
}

void User::slotSendReplyMessage(const int activityIndex, const QString &token, const QString &message, const QString &replyTo)
{
    QPointer<TalkReply> talkReply = new TalkReply(_account.data(), this);
    talkReply->sendReplyMessage(token, message, replyTo);
    connect(talkReply, &TalkReply::replyMessageSent, this, [&, activityIndex](const QString &message) {
        _activityModel->setReplyMessageSent(activityIndex, message);
    });
}

void User::forceSyncNow() const
{
    FolderMan::instance()->forceSyncForFolder(getFolder());
}

/*-------------------------------------------------------------------------------------*/

UserModel *UserModel::_instance = nullptr;

UserModel *UserModel::instance()
{
    if (!_instance) {
        _instance = new UserModel();
    }
    return _instance;
}

UserModel::UserModel(QObject *parent)
    : QAbstractListModel(parent)
{
    // TODO: Remember selected user from last quit via settings file
    if (AccountManager::instance()->accounts().size() > 0) {
        buildUserList();
    }

    connect(AccountManager::instance(), &AccountManager::accountAdded,
        this, &UserModel::buildUserList);
}

void UserModel::buildUserList()
{
    for (int i = 0; i < AccountManager::instance()->accounts().size(); i++) {
        auto user = AccountManager::instance()->accounts().at(i);
        addUser(user);
    }
    if (_init) {
        _users.first()->setCurrentUser(true);
        _init = false;
    }
}

int UserModel::numUsers()
{
    return _users.size();
}

int UserModel::currentUserId() const
{
    return _currentUserId;
}

bool UserModel::isUserConnected(const int id)
{
    if (id < 0 || id >= _users.size())
        return false;

    return _users[id]->isConnected();
}

QImage UserModel::avatarById(const int id)
{
    if (id < 0 || id >= _users.size())
        return {};

    return _users[id]->avatar();
}

QString UserModel::currentUserServer()
{
    if (_currentUserId < 0 || _currentUserId >= _users.size())
        return {};

    return _users[_currentUserId]->server();
}

void UserModel::addUser(AccountStatePtr &user, const bool &isCurrent)
{
    bool containsUser = false;
    for (const auto &u : qAsConst(_users)) {
        if (u->account() == user->account()) {
            containsUser = true;
            continue;
        }
    }

    if (!containsUser) {
        int row = rowCount();
        beginInsertRows(QModelIndex(), row, row);

        User *u = new User(user, isCurrent);

        connect(u, &User::avatarChanged, this, [this, row] {
           emit dataChanged(index(row, 0), index(row, 0), {UserModel::AvatarRole});
        });

        connect(u, &User::statusChanged, this, [this, row] {
            emit dataChanged(index(row, 0), index(row, 0), {UserModel::StatusIconRole, 
			    				    UserModel::StatusEmojiRole,     
                                                            UserModel::StatusMessageRole});
        });
        
        connect(u, &User::desktopNotificationsAllowedChanged, this, [this, row] {
            emit dataChanged(index(row, 0), index(row, 0), { UserModel::DesktopNotificationsAllowedRole });
        });
        
        connect(u, &User::accountStateChanged, this, [this, row] {
            emit dataChanged(index(row, 0), index(row, 0), { UserModel::IsConnectedRole });
        });

        _users << u;
        if (isCurrent || _currentUserId < 0) {
            setCurrentUserId(_users.size() - 1);
        }

        endInsertRows();
        ConfigFile cfg;
        u->setNotificationRefreshInterval(cfg.notificationRefreshInterval());
        emit currentUserChanged();
    }
}

int UserModel::currentUserIndex()
{
    return _currentUserId;
}

void UserModel::openCurrentAccountLocalFolder()
{
    if (_currentUserId < 0 || _currentUserId >= _users.size())
        return;

    _users[_currentUserId]->openLocalFolder();
}

void UserModel::openCurrentAccountTalk()
{
    if (!currentUser())
        return;

    const auto talkApp = currentUser()->talkApp();
    if (talkApp) {
        Utility::openBrowser(talkApp->url());
    } else {
        qCWarning(lcActivity) << "The Talk app is not enabled on" << currentUser()->server();
    }
}

void UserModel::openCurrentAccountServer()
{
    if (_currentUserId < 0 || _currentUserId >= _users.size())
        return;

    QString url = _users[_currentUserId]->server(false);
    if (!url.startsWith("http://") && !url.startsWith("https://")) {
        url = "https://" + _users[_currentUserId]->server(false);
    }

    QDesktopServices::openUrl(url);
}

void UserModel::setCurrentUserId(const int id)
{
    if (_currentUserId == id) {
        // order has changed, index remained the same
        if (id >= 0 && id < _users.size() && !_users[id]->isCurrentUser()) {
            for (auto &user : _users) {
                user->setCurrentUser(false);
            }
            _users[id]->setCurrentUser(true);
            emit currentUserChanged();
        }
        return;
    }
    _currentUserId = id;

    if (_users.isEmpty()) {
        emit currentUserChanged();
        return;
    }

    if (id >= 0 && id < _users.size()) {
        for (auto &user : _users) {
            user->setCurrentUser(false);
        }
        _users[id]->setCurrentUser(true);
    }

    emit currentUserChanged();
}

void UserModel::login(const int id)
{
    if (id < 0 || id >= _users.size())
        return;

    _users[id]->login();
}

void UserModel::logout(const int id)
{
    if (id < 0 || id >= _users.size())
        return;

    _users[id]->logout();
}

void UserModel::removeAccount(const int id)
{
    if (id < 0 || id >= _users.size()) {
        return;
    }

    QMessageBox messageBox(QMessageBox::Question,
        tr("Confirm Account Removal"),
        tr("<p>Do you really want to remove the connection to the account <i>%1</i>?</p>"
           "<p><b>Note:</b> This will <b>not</b> delete any files.</p>")
            .arg(_users[id]->name()), QMessageBox::NoButton);
    QPushButton *yesButton = messageBox.addButton(tr("Remove connection"), QMessageBox::YesRole);
    messageBox.addButton(tr("Cancel"), QMessageBox::NoRole);

    messageBox.exec();
    if (messageBox.clickedButton() != yesButton) {
        return;
    }

    _users[id]->logout();
    _users[id]->removeAccount();

    beginRemoveRows(QModelIndex(), id, id);
    _users.removeAt(id);
    endRemoveRows();

    if (_users.isEmpty()) {
        setCurrentUserId(-1);
    } else if (_users.size() == 1) {
        setCurrentUserId(0);
    } else {
        if (currentUserId() != id && currentUserId() < id) {
            return;
        }
        setCurrentUserId(id < _users.size() ? id : id - 1);
    }
}

std::shared_ptr<OCC::UserStatusConnector> UserModel::userStatusConnector(int id)
{
    if (id < 0 || id >= _users.size()) {
        return nullptr;
    }

    return _users[id]->account()->userStatusConnector();
}

int UserModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return _users.count();
}

QVariant UserModel::data(const QModelIndex &index, int role) const
{
    if (index.row() < 0 || index.row() >= _users.count()) {
        return QVariant();
    }

    if (role == NameRole) {
        return _users[index.row()]->name();
    } else if (role == ServerRole) {
        return _users[index.row()]->server();
    } else if (role == ServerHasUserStatusRole) {
        return _users[index.row()]->serverHasUserStatus();
    } else if (role == StatusIconRole) {
        return _users[index.row()]->statusIcon();
    } else if (role == StatusEmojiRole) {
        return _users[index.row()]->statusEmoji();
    } else if (role == StatusMessageRole) {
        return _users[index.row()]->statusMessage();
    } else if (role == DesktopNotificationsAllowedRole) {
        return _users[index.row()]->isDesktopNotificationsAllowed();
    } else if (role == AvatarRole) {
        return _users[index.row()]->avatarUrl();
    } else if (role == IsCurrentUserRole) {
        return _users[index.row()]->isCurrentUser();
    } else if (role == IsConnectedRole) {
        return _users[index.row()]->isConnected();
    } else if (role == IdRole) {
        return index.row();
    }
    return QVariant();
}

QHash<int, QByteArray> UserModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[NameRole] = "name";
    roles[ServerRole] = "server";
    roles[ServerHasUserStatusRole] = "serverHasUserStatus";
    roles[StatusIconRole] = "statusIcon";
    roles[StatusEmojiRole] = "statusEmoji";
    roles[StatusMessageRole] = "statusMessage";
    roles[DesktopNotificationsAllowedRole] = "desktopNotificationsAllowed";
    roles[AvatarRole] = "avatar";
    roles[IsCurrentUserRole] = "isCurrentUser";
    roles[IsConnectedRole] = "isConnected";
    roles[IdRole] = "id";
    return roles;
}

ActivityListModel *UserModel::currentActivityModel()
{
    if (currentUserIndex() < 0 || currentUserIndex() >= _users.size())
        return nullptr;

    return _users[currentUserIndex()]->getActivityModel();
}

void UserModel::fetchCurrentActivityModel()
{
    if (currentUserId() < 0 || currentUserId() >= _users.size())
        return;

    _users[currentUserId()]->slotRefresh();
}

AccountAppList UserModel::appList() const
{
    if (_currentUserId < 0 || _currentUserId >= _users.size())
        return {};

    return _users[_currentUserId]->appList();
}

User *UserModel::currentUser() const
{
    if (currentUserId() < 0 || currentUserId() >= _users.size())
        return nullptr;

    return _users[currentUserId()];
}

int UserModel::findUserIdForAccount(AccountState *account) const
{
    const auto it = std::find_if(std::cbegin(_users), std::cend(_users), [=](const User *user) {
        return user->account()->id() == account->account()->id();
    });

    if (it == std::cend(_users)) {
        return -1;
    }

    const auto id = std::distance(std::cbegin(_users), it);
    return id;
}

/*-------------------------------------------------------------------------------------*/

ImageProvider::ImageProvider()
    : QQuickImageProvider(QQuickImageProvider::Image)
{
}

QImage ImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize)
{
    Q_UNUSED(size)
    Q_UNUSED(requestedSize)

    const auto makeIcon = [](const QString &path) {
        QImage image(128, 128, QImage::Format_ARGB32);
        image.fill(Qt::GlobalColor::transparent);
        QPainter painter(&image);
        QSvgRenderer renderer(path);
        renderer.render(&painter);
        return image;
    };

    if (id == QLatin1String("fallbackWhite")) {
        return makeIcon(QStringLiteral(":/client/theme/white/user.svg"));
    }

    if (id == QLatin1String("fallbackBlack")) {
        return makeIcon(QStringLiteral(":/client/theme/black/user.svg"));
    }

    const int uid = id.toInt();
    return UserModel::instance()->avatarById(uid);
}

/*-------------------------------------------------------------------------------------*/

UserAppsModel *UserAppsModel::_instance = nullptr;

UserAppsModel *UserAppsModel::instance()
{
    if (!_instance) {
        _instance = new UserAppsModel();
    }
    return _instance;
}

UserAppsModel::UserAppsModel(QObject *parent)
    : QAbstractListModel(parent)
{
}

void UserAppsModel::buildAppList()
{
    if (rowCount() > 0) {
        beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
        _apps.clear();
        endRemoveRows();
    }

    if (UserModel::instance()->appList().count() > 0) {
        const auto talkApp = UserModel::instance()->currentUser()->talkApp();
        foreach (AccountApp *app, UserModel::instance()->appList()) {
            // Filter out Talk because we have a dedicated button for it
            if (talkApp && app->id() == talkApp->id())
                continue;

            beginInsertRows(QModelIndex(), rowCount(), rowCount());
            _apps << app;
            endInsertRows();
        }
    }
}

void UserAppsModel::openAppUrl(const QUrl &url)
{
    Utility::openBrowser(url);
}

int UserAppsModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return _apps.count();
}

QVariant UserAppsModel::data(const QModelIndex &index, int role) const
{
    if (index.row() < 0 || index.row() >= _apps.count()) {
        return QVariant();
    }

    if (role == NameRole) {
        return _apps[index.row()]->name();
    } else if (role == UrlRole) {
        return _apps[index.row()]->url();
    } else if (role == IconUrlRole) {
        return _apps[index.row()]->iconUrl().toString();
    }
    return QVariant();
}

QHash<int, QByteArray> UserAppsModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[NameRole] = "appName";
    roles[UrlRole] = "appUrl";
    roles[IconUrlRole] = "appIconUrl";
    return roles;
}
}