usermodel.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634
  1. #include "notificationhandler.h"
  2. #include "usermodel.h"
  3. #include "accountmanager.h"
  4. #include "owncloudgui.h"
  5. #include <pushnotifications.h>
  6. #include "userstatusselectormodel.h"
  7. #include "syncengine.h"
  8. #include "ocsjob.h"
  9. #include "configfile.h"
  10. #include "notificationconfirmjob.h"
  11. #include "logger.h"
  12. #include "guiutility.h"
  13. #include "syncfileitem.h"
  14. #include "systray.h"
  15. #include "tray/activitylistmodel.h"
  16. #include "tray/unifiedsearchresultslistmodel.h"
  17. #include "tray/talkreply.h"
  18. #include "userstatusconnector.h"
  19. #include "thumbnailjob.h"
  20. #include <QDesktopServices>
  21. #include <QIcon>
  22. #include <QMessageBox>
  23. #include <QSvgRenderer>
  24. #include <QPainter>
  25. #include <QPushButton>
  26. // time span in milliseconds which has to be between two
  27. // refreshes of the notifications
  28. #define NOTIFICATION_REQUEST_FREE_PERIOD 15000
  29. namespace {
  30. constexpr qint64 expiredActivitiesCheckIntervalMsecs = 1000 * 60;
  31. constexpr qint64 activityDefaultExpirationTimeMsecs = 1000 * 60 * 10;
  32. }
  33. namespace OCC {
  34. TrayFolderInfo::TrayFolderInfo(const QString &name, const QString &parentPath, const QString &fullPath, FolderType folderType)
  35. : _name(name)
  36. , _parentPath(parentPath)
  37. , _fullPath(fullPath)
  38. , _folderType(folderType)
  39. {
  40. }
  41. bool TrayFolderInfo::isGroupFolder() const
  42. {
  43. return _folderType == GroupFolder;
  44. }
  45. User::User(AccountStatePtr &account, const bool &isCurrent, QObject *parent)
  46. : QObject(parent)
  47. , _account(account)
  48. , _isCurrentUser(isCurrent)
  49. , _activityModel(new ActivityListModel(_account.data(), this))
  50. , _unifiedSearchResultsModel(new UnifiedSearchResultsListModel(_account.data(), this))
  51. {
  52. connect(ProgressDispatcher::instance(), &ProgressDispatcher::progressInfo,
  53. this, &User::slotProgressInfo);
  54. connect(ProgressDispatcher::instance(), &ProgressDispatcher::itemCompleted,
  55. this, &User::slotItemCompleted);
  56. connect(ProgressDispatcher::instance(), &ProgressDispatcher::syncError,
  57. this, &User::slotAddError);
  58. connect(ProgressDispatcher::instance(), &ProgressDispatcher::addErrorToGui,
  59. this, &User::slotAddErrorToGui);
  60. connect(&_notificationCheckTimer, &QTimer::timeout,
  61. this, &User::slotRefresh);
  62. connect(&_expiredActivitiesCheckTimer, &QTimer::timeout,
  63. this, &User::slotCheckExpiredActivities);
  64. connect(_account.data(), &AccountState::stateChanged,
  65. [=]() { if (isConnected()) {slotRefreshImmediately();} });
  66. connect(_account.data(), &AccountState::stateChanged, this, &User::accountStateChanged);
  67. connect(_account.data(), &AccountState::hasFetchedNavigationApps,
  68. this, &User::slotRebuildNavigationAppList);
  69. connect(_account->account().data(), &Account::accountChangedDisplayName, this, &User::nameChanged);
  70. connect(FolderMan::instance(), &FolderMan::folderListChanged, this, &User::hasLocalFolderChanged);
  71. connect(_account->account().data(), &Account::accountChangedAvatar, this, &User::avatarChanged);
  72. connect(_account->account().data(), &Account::userStatusChanged, this, &User::statusChanged);
  73. connect(_account.data(), &AccountState::desktopNotificationsAllowedChanged, this, &User::desktopNotificationsAllowedChanged);
  74. connect(_account->account().data(), &Account::capabilitiesChanged, this, &User::headerColorChanged);
  75. connect(_account->account().data(), &Account::capabilitiesChanged, this, &User::headerTextColorChanged);
  76. connect(_account->account().data(), &Account::capabilitiesChanged, this, &User::accentColorChanged);
  77. connect(_account->account().data(), &Account::capabilitiesChanged, this, &User::slotAccountCapabilitiesChangedRefreshGroupFolders);
  78. connect(_activityModel, &ActivityListModel::sendNotificationRequest, this, &User::slotSendNotificationRequest);
  79. connect(this, &User::sendReplyMessage, this, &User::slotSendReplyMessage);
  80. }
  81. void User::checkNotifiedNotifications()
  82. {
  83. // after one hour, clear the gui log notification store
  84. constexpr qint64 clearGuiLogInterval = 60 * 60 * 1000;
  85. if (_guiLogTimer.elapsed() > clearGuiLogInterval) {
  86. _notifiedNotifications.clear();
  87. }
  88. }
  89. bool User::notificationAlreadyShown(const long notificationId)
  90. {
  91. checkNotifiedNotifications();
  92. return _notifiedNotifications.contains(notificationId);
  93. }
  94. bool User::canShowNotification(const long notificationId)
  95. {
  96. ConfigFile cfg;
  97. return cfg.optionalServerNotifications() &&
  98. isDesktopNotificationsAllowed() &&
  99. !notificationAlreadyShown(notificationId);
  100. }
  101. void User::showDesktopNotification(const QString &title, const QString &message, const long notificationId)
  102. {
  103. if(!canShowNotification(notificationId)) {
  104. return;
  105. }
  106. _notifiedNotifications.insert(notificationId);
  107. Logger::instance()->postGuiLog(title, message);
  108. // restart the gui log timer now that we show a new notification
  109. _guiLogTimer.start();
  110. }
  111. void User::showDesktopNotification(const Activity &activity)
  112. {
  113. const auto notificationId = activity._id;
  114. const auto message = AccountManager::instance()->accounts().count() == 1 ? "" : activity._accName;
  115. // the user needs to interact with this notification
  116. if (activity._links.size() > 0) {
  117. _activityModel->addNotificationToActivityList(activity);
  118. }
  119. showDesktopNotification(activity._subject, message, notificationId);
  120. }
  121. void User::showDesktopNotification(const ActivityList &activityList)
  122. {
  123. const auto subject = QStringLiteral("%1 notifications").arg(activityList.count());
  124. const auto notificationId = -static_cast<int>(qHash(subject));
  125. if (!canShowNotification(notificationId)) {
  126. return;
  127. }
  128. const auto multipleAccounts = AccountManager::instance()->accounts().count() > 1;
  129. const auto message = multipleAccounts ? activityList.constFirst()._accName : QString();
  130. // Notification ids are uints, which are 4 bytes. Error activities don't have ids, however, so we generate one.
  131. // To avoid possible collisions between the activity ids which are actually the notification ids received from
  132. // the server (which are always positive) and our "fake" error activity ids, we assign a negative id to the
  133. // error notification.
  134. //
  135. // To ensure that we can still treat an unsigned int as normal, we use a long, which is 8 bytes.
  136. Logger::instance()->postGuiLog(subject, message);
  137. for(const auto &activity : activityList) {
  138. _notifiedNotifications.insert(activity._id);
  139. _activityModel->addNotificationToActivityList(activity);
  140. }
  141. }
  142. void User::showDesktopTalkNotification(const Activity &activity)
  143. {
  144. const auto notificationId = activity._id;
  145. if (!canShowNotification(notificationId)) {
  146. return;
  147. }
  148. if (activity._talkNotificationData.messageId.isEmpty()) {
  149. showDesktopNotification(activity._subject, activity._message, notificationId);
  150. return;
  151. }
  152. _notifiedNotifications.insert(notificationId);
  153. _activityModel->addNotificationToActivityList(activity);
  154. Systray::instance()->showTalkMessage(activity._subject,
  155. activity._message,
  156. activity._talkNotificationData.conversationToken,
  157. activity._talkNotificationData.messageId,
  158. _account);
  159. _guiLogTimer.start();
  160. }
  161. void User::slotBuildNotificationDisplay(const ActivityList &list)
  162. {
  163. ActivityList toNotifyList;
  164. std::copy_if(list.constBegin(), list.constEnd(), std::back_inserter(toNotifyList), [&](const Activity &activity) {
  165. if (_blacklistedNotifications.contains(activity)) {
  166. qCInfo(lcActivity) << "Activity in blacklist, skip";
  167. return false;
  168. } else if(_notifiedNotifications.contains(activity._id)) {
  169. qCInfo(lcActivity) << "Activity already notified, skip";
  170. return false;
  171. }
  172. if (!activity._shouldNotify) {
  173. qCDebug(lcActivity) << "Activity should not be notified";
  174. return false;
  175. }
  176. return true;
  177. });
  178. if(toNotifyList.count() > 2) {
  179. showDesktopNotification(toNotifyList);
  180. return;
  181. }
  182. auto chatNotificationsReceivedCount = 0;
  183. for(const auto &activity : qAsConst(toNotifyList)) {
  184. if (activity._objectType == QStringLiteral("chat")) {
  185. ++chatNotificationsReceivedCount;
  186. showDesktopTalkNotification(activity);
  187. } else {
  188. showDesktopNotification(activity);
  189. }
  190. }
  191. if (chatNotificationsReceivedCount < _lastChatNotificationsReceivedCount) {
  192. _activityModel->checkAndRemoveSeenActivities(toNotifyList);
  193. }
  194. _lastChatNotificationsReceivedCount = chatNotificationsReceivedCount;
  195. }
  196. void User::slotBuildIncomingCallDialogs(const ActivityList &list)
  197. {
  198. const ConfigFile cfg;
  199. const auto userStatus = _account->account()->userStatusConnector()->userStatus().state();
  200. if (userStatus == OCC::UserStatus::OnlineStatus::DoNotDisturb ||
  201. !cfg.optionalServerNotifications() ||
  202. !cfg.showCallNotifications() ||
  203. !isDesktopNotificationsAllowed()) {
  204. return;
  205. }
  206. const auto systray = Systray::instance();
  207. if(systray) {
  208. for(const auto &activity : list) {
  209. if (!activity._shouldNotify) {
  210. qCDebug(lcActivity) << "Activity should not be notified";
  211. continue;
  212. }
  213. systray->createCallDialog(activity, _account);
  214. }
  215. }
  216. }
  217. void User::setNotificationRefreshInterval(std::chrono::milliseconds interval)
  218. {
  219. if (!checkPushNotificationsAreReady()) {
  220. qCDebug(lcActivity) << "Starting Notification refresh timer with " << interval.count() / 1000 << " sec interval";
  221. _notificationCheckTimer.start(interval.count());
  222. }
  223. }
  224. void User::slotPushNotificationsReady()
  225. {
  226. qCInfo(lcActivity) << "Push notifications are ready";
  227. if (_notificationCheckTimer.isActive()) {
  228. // as we are now able to use push notifications - let's stop the polling timer
  229. _notificationCheckTimer.stop();
  230. }
  231. connectPushNotifications();
  232. }
  233. void User::slotDisconnectPushNotifications()
  234. {
  235. disconnect(_account->account()->pushNotifications(), &PushNotifications::notificationsChanged, this, &User::slotReceivedPushNotification);
  236. disconnect(_account->account()->pushNotifications(), &PushNotifications::activitiesChanged, this, &User::slotReceivedPushActivity);
  237. disconnect(_account->account().data(), &Account::pushNotificationsDisabled, this, &User::slotDisconnectPushNotifications);
  238. // connection to WebSocket may have dropped or an error occurred, so we need to bring back the polling until we have re-established the connection
  239. setNotificationRefreshInterval(ConfigFile().notificationRefreshInterval());
  240. }
  241. void User::slotReceivedPushNotification(Account *account)
  242. {
  243. if (account->id() == _account->account()->id()) {
  244. slotRefreshNotifications();
  245. }
  246. }
  247. void User::slotReceivedPushActivity(Account *account)
  248. {
  249. if (account->id() == _account->account()->id()) {
  250. slotRefreshActivities();
  251. }
  252. }
  253. void User::slotCheckExpiredActivities()
  254. {
  255. const auto errorsList = _activityModel->errorsList();
  256. for (const Activity &activity : errorsList) {
  257. if (activity._expireAtMsecs > 0 && QDateTime::currentDateTime().toMSecsSinceEpoch() >= activity._expireAtMsecs) {
  258. _activityModel->removeActivityFromActivityList(activity);
  259. }
  260. }
  261. if (_activityModel->errorsList().size() == 0) {
  262. _expiredActivitiesCheckTimer.stop();
  263. }
  264. }
  265. void User::parseNewGroupFolderPath(const QString &mountPoint)
  266. {
  267. if (mountPoint.isEmpty()) {
  268. return;
  269. }
  270. auto mountPointSplit = mountPoint.split(QLatin1Char('/'), Qt::SkipEmptyParts);
  271. if (mountPointSplit.isEmpty()) {
  272. return;
  273. }
  274. const auto groupFolderName = mountPointSplit.takeLast();
  275. const auto parentPath = mountPointSplit.join(QLatin1Char('/'));
  276. _trayFolderInfos.push_back(QVariant::fromValue(TrayFolderInfo{groupFolderName, parentPath, mountPoint, TrayFolderInfo::GroupFolder}));
  277. }
  278. void User::prePendGroupFoldersWithLocalFolder()
  279. {
  280. if (!_trayFolderInfos.isEmpty() && !_trayFolderInfos.first().value<TrayFolderInfo>().isGroupFolder()) {
  281. return;
  282. }
  283. const auto localFolderName = getFolder()->shortGuiLocalPath();
  284. auto localFolderPathSplit = getFolder()->path().split(QLatin1Char('/'), Qt::SkipEmptyParts);
  285. if (!localFolderPathSplit.isEmpty()) {
  286. localFolderPathSplit.removeLast();
  287. }
  288. const auto localFolderParentPath = !localFolderPathSplit.isEmpty() ? localFolderPathSplit.join(QLatin1Char('/')) : "/";
  289. _trayFolderInfos.push_front(QVariant::fromValue(TrayFolderInfo{localFolderName, localFolderParentPath, getFolder()->path(), TrayFolderInfo::Folder}));
  290. }
  291. void User::connectPushNotifications() const
  292. {
  293. connect(_account->account().data(), &Account::pushNotificationsDisabled, this, &User::slotDisconnectPushNotifications, Qt::UniqueConnection);
  294. connect(_account->account()->pushNotifications(), &PushNotifications::notificationsChanged, this, &User::slotReceivedPushNotification, Qt::UniqueConnection);
  295. connect(_account->account()->pushNotifications(), &PushNotifications::activitiesChanged, this, &User::slotReceivedPushActivity, Qt::UniqueConnection);
  296. }
  297. bool User::checkPushNotificationsAreReady() const
  298. {
  299. const auto pushNotifications = _account->account()->pushNotifications();
  300. const auto pushActivitiesAvailable = _account->account()->capabilities().availablePushNotifications() & PushNotificationType::Activities;
  301. const auto pushNotificationsAvailable = _account->account()->capabilities().availablePushNotifications() & PushNotificationType::Notifications;
  302. const auto pushActivitiesAndNotificationsAvailable = pushActivitiesAvailable && pushNotificationsAvailable;
  303. if (pushActivitiesAndNotificationsAvailable && pushNotifications && pushNotifications->isReady()) {
  304. connectPushNotifications();
  305. return true;
  306. } else {
  307. connect(_account->account().data(), &Account::pushNotificationsReady, this, &User::slotPushNotificationsReady, Qt::UniqueConnection);
  308. return false;
  309. }
  310. }
  311. void User::slotRefreshImmediately() {
  312. if (_account.data() && _account.data()->isConnected() && Systray::instance()->isOpen()) {
  313. slotRefreshActivities();
  314. }
  315. slotRefreshNotifications();
  316. }
  317. void User::slotRefresh()
  318. {
  319. slotRefreshUserStatus();
  320. if (checkPushNotificationsAreReady()) {
  321. // we are relying on WebSocket push notifications - ignore refresh attempts from UI
  322. slotRefreshActivitiesInitial();
  323. _timeSinceLastCheck[_account.data()].invalidate();
  324. return;
  325. }
  326. // QElapsedTimer isn't actually constructed as invalid.
  327. if (!_timeSinceLastCheck.contains(_account.data())) {
  328. _timeSinceLastCheck[_account.data()].invalidate();
  329. }
  330. QElapsedTimer &timer = _timeSinceLastCheck[_account.data()];
  331. // Fetch Activities only if visible and if last check is longer than 15 secs ago
  332. if (timer.isValid() && timer.elapsed() < NOTIFICATION_REQUEST_FREE_PERIOD) {
  333. qCDebug(lcActivity) << "Do not check as last check is only secs ago: " << timer.elapsed() / 1000;
  334. return;
  335. }
  336. if (_account.data() && _account.data()->isConnected()) {
  337. slotRefreshActivitiesInitial();
  338. slotRefreshNotifications();
  339. timer.start();
  340. }
  341. }
  342. void User::slotRefreshActivitiesInitial()
  343. {
  344. if (_account.data()->isConnected() && Systray::instance()->isOpen()) {
  345. _activityModel->slotRefreshActivityInitial();
  346. }
  347. }
  348. void User::slotRefreshActivities()
  349. {
  350. if (_account.data()->isConnected() && Systray::instance()->isOpen()) {
  351. _activityModel->slotRefreshActivity();
  352. }
  353. }
  354. void User::slotRefreshUserStatus()
  355. {
  356. if (_account.data() && _account.data()->isConnected()) {
  357. _account->account()->userStatusConnector()->fetchUserStatus();
  358. }
  359. }
  360. void User::slotRefreshNotifications()
  361. {
  362. // start a server notification handler if no notification requests
  363. // are running
  364. if (_notificationRequestsRunning == 0) {
  365. auto *snh = new ServerNotificationHandler(_account.data());
  366. connect(snh, &ServerNotificationHandler::newNotificationList,
  367. this, &User::slotBuildNotificationDisplay);
  368. connect(snh, &ServerNotificationHandler::newIncomingCallsList,
  369. this, &User::slotBuildIncomingCallDialogs);
  370. snh->slotFetchNotifications();
  371. } else {
  372. qCWarning(lcActivity) << "Notification request counter not zero.";
  373. }
  374. }
  375. void User::slotRebuildNavigationAppList()
  376. {
  377. emit serverHasTalkChanged();
  378. // Rebuild App list
  379. UserAppsModel::instance()->buildAppList();
  380. }
  381. void User::slotNotificationRequestFinished(int statusCode)
  382. {
  383. int row = sender()->property("activityRow").toInt();
  384. // the ocs API returns stat code 100 or 200 or 202 inside the xml if it succeeded.
  385. if (statusCode != OCS_SUCCESS_STATUS_CODE
  386. && statusCode != OCS_SUCCESS_STATUS_CODE_V2
  387. && statusCode != OCS_ACCEPTED_STATUS_CODE) {
  388. qCWarning(lcActivity) << "Notification Request to Server failed, leave notification visible.";
  389. } else {
  390. // to do use the model to rebuild the list or remove the item
  391. qCWarning(lcActivity) << "Notification Request to Server succeeded, rebuilding list.";
  392. _activityModel->removeActivityFromActivityList(row);
  393. }
  394. }
  395. void User::slotEndNotificationRequest(int replyCode)
  396. {
  397. _notificationRequestsRunning--;
  398. slotNotificationRequestFinished(replyCode);
  399. }
  400. void User::slotSendNotificationRequest(const QString &accountName, const QString &link, const QByteArray &verb, int row)
  401. {
  402. qCInfo(lcActivity) << "Server Notification Request " << verb << link << "on account" << accountName;
  403. const QStringList validVerbs = QStringList() << "GET"
  404. << "PUT"
  405. << "POST"
  406. << "DELETE";
  407. if (validVerbs.contains(verb)) {
  408. AccountStatePtr acc = AccountManager::instance()->account(accountName);
  409. if (acc) {
  410. auto *job = new NotificationConfirmJob(acc->account());
  411. QUrl l(link);
  412. job->setLinkAndVerb(l, verb);
  413. job->setProperty("activityRow", QVariant::fromValue(row));
  414. connect(job, &AbstractNetworkJob::networkError,
  415. this, &User::slotNotifyNetworkError);
  416. connect(job, &NotificationConfirmJob::jobFinished,
  417. this, &User::slotNotifyServerFinished);
  418. job->start();
  419. // count the number of running notification requests. If this member var
  420. // is larger than zero, no new fetching of notifications is started
  421. _notificationRequestsRunning++;
  422. }
  423. } else {
  424. qCWarning(lcActivity) << "Notification Links: Invalid verb:" << verb;
  425. }
  426. }
  427. void User::slotNotifyNetworkError(QNetworkReply *reply)
  428. {
  429. auto *job = qobject_cast<NotificationConfirmJob *>(sender());
  430. if (!job) {
  431. return;
  432. }
  433. int resultCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
  434. slotEndNotificationRequest(resultCode);
  435. qCWarning(lcActivity) << "Server notify job failed with code " << resultCode;
  436. }
  437. void User::slotNotifyServerFinished(const QString &reply, int replyCode)
  438. {
  439. auto *job = qobject_cast<NotificationConfirmJob *>(sender());
  440. if (!job) {
  441. return;
  442. }
  443. slotEndNotificationRequest(replyCode);
  444. qCInfo(lcActivity) << "Server Notification reply code" << replyCode << reply;
  445. }
  446. void User::slotProgressInfo(const QString &folder, const ProgressInfo &progress)
  447. {
  448. if (progress.status() == ProgressInfo::Reconcile) {
  449. // Wipe all non-persistent entries - as well as the persistent ones
  450. // in cases where a local discovery was done.
  451. auto f = FolderMan::instance()->folder(folder);
  452. if (!f)
  453. return;
  454. const auto &engine = f->syncEngine();
  455. const auto style = engine.lastLocalDiscoveryStyle();
  456. foreach (Activity activity, _activityModel->errorsList()) {
  457. if (activity._expireAtMsecs != -1) {
  458. // we process expired activities in a different slot
  459. continue;
  460. }
  461. if (activity._folder != folder) {
  462. continue;
  463. }
  464. if (style == LocalDiscoveryStyle::FilesystemOnly) {
  465. _activityModel->removeActivityFromActivityList(activity);
  466. continue;
  467. }
  468. if (activity._syncFileItemStatus == SyncFileItem::Conflict && !QFileInfo::exists(f->path() + activity._file)) {
  469. _activityModel->removeActivityFromActivityList(activity);
  470. continue;
  471. }
  472. if (activity._syncFileItemStatus == SyncFileItem::FileLocked && !QFileInfo::exists(f->path() + activity._file)) {
  473. _activityModel->removeActivityFromActivityList(activity);
  474. continue;
  475. }
  476. if (activity._syncFileItemStatus == SyncFileItem::FileIgnored && !QFileInfo::exists(f->path() + activity._file)) {
  477. _activityModel->removeActivityFromActivityList(activity);
  478. continue;
  479. }
  480. if (!QFileInfo::exists(f->path() + activity._file)) {
  481. _activityModel->removeActivityFromActivityList(activity);
  482. continue;
  483. }
  484. auto path = QFileInfo(activity._file).dir().path().toUtf8();
  485. if (path == ".")
  486. path.clear();
  487. if (engine.shouldDiscoverLocally(path))
  488. _activityModel->removeActivityFromActivityList(activity);
  489. }
  490. }
  491. if (progress.status() == ProgressInfo::Done) {
  492. // We keep track very well of pending conflicts.
  493. // Inform other components about them.
  494. QStringList conflicts;
  495. foreach (Activity activity, _activityModel->errorsList()) {
  496. if (activity._folder == folder
  497. && activity._syncFileItemStatus == SyncFileItem::Conflict) {
  498. conflicts.append(activity._file);
  499. }
  500. }
  501. emit ProgressDispatcher::instance()->folderConflicts(folder, conflicts);
  502. }
  503. }
  504. void User::slotAddError(const QString &folderAlias, const QString &message, ErrorCategory category)
  505. {
  506. auto folderInstance = FolderMan::instance()->folder(folderAlias);
  507. if (!folderInstance)
  508. return;
  509. if (folderInstance->accountState() == _account.data()) {
  510. qCWarning(lcActivity) << "Item " << folderInstance->shortGuiLocalPath() << " retrieved resulted in " << message;
  511. Activity activity;
  512. activity._type = Activity::SyncResultType;
  513. activity._syncResultStatus = SyncResult::Error;
  514. activity._dateTime = QDateTime::fromString(QDateTime::currentDateTime().toString(), Qt::ISODate);
  515. activity._subject = message;
  516. activity._message = folderInstance->shortGuiLocalPath();
  517. activity._link = folderInstance->shortGuiLocalPath();
  518. activity._accName = folderInstance->accountState()->account()->displayName();
  519. activity._folder = folderAlias;
  520. if (category == ErrorCategory::InsufficientRemoteStorage) {
  521. ActivityLink link;
  522. link._label = tr("Retry all uploads");
  523. link._link = folderInstance->path();
  524. link._verb = "";
  525. link._primary = true;
  526. activity._links.append(link);
  527. }
  528. auto errorType = ActivityListModel::ErrorType::SyncError;
  529. // add 'other errors' to activity list
  530. switch (category) {
  531. case ErrorCategory::GenericError:
  532. errorType = ActivityListModel::ErrorType::SyncError;
  533. break;
  534. case ErrorCategory::InsufficientRemoteStorage:
  535. errorType = ActivityListModel::ErrorType::SyncError;
  536. break;
  537. case ErrorCategory::NetworkError:
  538. errorType = ActivityListModel::ErrorType::NetworkError;
  539. break;
  540. case ErrorCategory::NoError:
  541. break;
  542. }
  543. _activityModel->addErrorToActivityList(activity, errorType);
  544. }
  545. }
  546. void User::slotAddErrorToGui(const QString &folderAlias, const SyncFileItem::Status status, const QString &errorMessage, const QString &subject, const ErrorCategory category)
  547. {
  548. const auto folderInstance = FolderMan::instance()->folder(folderAlias);
  549. if (!folderInstance) {
  550. return;
  551. }
  552. if (folderInstance->accountState() == _account.data()) {
  553. qCWarning(lcActivity) << "Item " << folderInstance->shortGuiLocalPath() << " retrieved resulted in " << errorMessage;
  554. Activity activity;
  555. activity._type = Activity::SyncFileItemType;
  556. activity._syncFileItemStatus = status;
  557. const auto currentDateTime = QDateTime::currentDateTime();
  558. activity._dateTime = QDateTime::fromString(currentDateTime.toString(), Qt::ISODate);
  559. activity._expireAtMsecs = currentDateTime.addMSecs(activityDefaultExpirationTimeMsecs).toMSecsSinceEpoch();
  560. activity._subject = !subject.isEmpty() ? subject : folderInstance->shortGuiLocalPath();
  561. activity._message = errorMessage;
  562. activity._link = folderInstance->shortGuiLocalPath();
  563. activity._accName = folderInstance->accountState()->account()->displayName();
  564. activity._folder = folderAlias;
  565. if (status == SyncFileItem::Conflict || status == SyncFileItem::FileNameClash) {
  566. ActivityLink buttonActivityLink;
  567. buttonActivityLink._label = tr("Resolve conflict");
  568. buttonActivityLink._link = activity._link.toString();
  569. buttonActivityLink._verb = "FIX_CONFLICT_LOCALLY";
  570. buttonActivityLink._primary = true;
  571. activity._links = {buttonActivityLink};
  572. }
  573. // Error notifications don't have ids by themselves so we will create one for it
  574. activity._id = -static_cast<int>(qHash(activity._subject + activity._message));
  575. // add 'other errors' to activity list
  576. auto errorType = ActivityListModel::ErrorType::SyncError;
  577. switch (category)
  578. {
  579. case ErrorCategory::GenericError:
  580. errorType = ActivityListModel::ErrorType::SyncError;
  581. break;
  582. case ErrorCategory::InsufficientRemoteStorage:
  583. errorType = ActivityListModel::ErrorType::SyncError;
  584. break;
  585. case ErrorCategory::NetworkError:
  586. errorType = ActivityListModel::ErrorType::NetworkError;
  587. break;
  588. case ErrorCategory::NoError:
  589. errorType = {};
  590. break;
  591. }
  592. _activityModel->addErrorToActivityList(activity, errorType);
  593. showDesktopNotification(activity);
  594. if (!_expiredActivitiesCheckTimer.isActive()) {
  595. _expiredActivitiesCheckTimer.start(expiredActivitiesCheckIntervalMsecs);
  596. }
  597. }
  598. }
  599. bool User::isActivityOfCurrentAccount(const Folder *folder) const
  600. {
  601. return folder->accountState() == _account.data();
  602. }
  603. bool User::isUnsolvableConflict(const SyncFileItemPtr &item) const
  604. {
  605. // We just care about conflict issues that we are able to resolve
  606. return item->_status == SyncFileItem::Conflict && !Utility::isConflictFile(item->_file);
  607. }
  608. void User::processCompletedSyncItem(const Folder *folder, const SyncFileItemPtr &item)
  609. {
  610. const auto fileActionFromInstruction = [](const int instruction) {
  611. if (instruction == CSYNC_INSTRUCTION_REMOVE) {
  612. return QStringLiteral("file_deleted");
  613. } else if (instruction == CSYNC_INSTRUCTION_NEW) {
  614. return QStringLiteral("file_created");
  615. } else if (instruction == CSYNC_INSTRUCTION_RENAME) {
  616. return QStringLiteral("file_renamed");
  617. } else {
  618. return QStringLiteral("file_changed");
  619. }
  620. };
  621. const auto messageFromFileAction = [](const QString &fileAction, const QString &fileName) {
  622. if (fileAction == QStringLiteral("file_renamed")) {
  623. return QObject::tr("You renamed %1").arg(fileName);
  624. } else if (fileAction == QStringLiteral("file_deleted")) {
  625. return QObject:: tr("You deleted %1").arg(fileName);
  626. } else if (fileAction == QStringLiteral("file_created")) {
  627. return QObject::tr("You created %1").arg(fileName);
  628. } else {
  629. return QObject::tr("You changed %1").arg(fileName);
  630. }
  631. };
  632. Activity activity;
  633. activity._type = Activity::SyncFileItemType; //client activity
  634. activity._objectType = QStringLiteral("files");
  635. activity._syncFileItemStatus = item->_status;
  636. activity._dateTime = QDateTime::currentDateTime();
  637. activity._message = item->_originalFile;
  638. activity._link = account()->url();
  639. activity._accName = account()->displayName();
  640. activity._file = item->_file;
  641. activity._folder = folder->alias();
  642. activity._fileAction = "";
  643. const auto fileName = QFileInfo(item->_originalFile).fileName();
  644. activity._fileAction = fileActionFromInstruction(item->_instruction);
  645. if (item->_status == SyncFileItem::NoStatus || item->_status == SyncFileItem::Success) {
  646. qCWarning(lcActivity) << "Item " << item->_file << " retrieved successfully.";
  647. if (item->_direction != SyncFileItem::Up) {
  648. activity._message = QObject::tr("Synced %1").arg(fileName);
  649. } else {
  650. activity._message = messageFromFileAction(activity._fileAction, fileName);
  651. }
  652. if(activity._fileAction != "file_deleted" && !item->isEmpty()) {
  653. const auto localFiles = FolderMan::instance()->findFileInLocalFolders(item->_file, account());
  654. if (!localFiles.isEmpty()) {
  655. const auto firstFilePath = localFiles.constFirst();
  656. const auto itemJournalRecord = item->toSyncJournalFileRecordWithInode(firstFilePath);
  657. if(!itemJournalRecord.isVirtualFile()) {
  658. const auto mimeType = _mimeDb.mimeTypeForFile(QFileInfo(localFiles.constFirst()));
  659. // Set the preview data, though for now we can skip setting file ID, link, and view
  660. PreviewData preview;
  661. preview._mimeType = mimeType.name();
  662. preview._filename = fileName;
  663. preview._isMimeTypeIcon = true;
  664. if(item->isDirectory()) {
  665. preview._source = account()->url().toString() + QStringLiteral("/index.php/apps/theming/img/core/filetypes/folder.svg");
  666. } else {
  667. preview._source = account()->url().toString() + Activity::relativeServerFileTypeIconPath(mimeType);
  668. }
  669. activity._previews.append(preview);
  670. }
  671. }
  672. }
  673. _activityModel->addSyncFileItemToActivityList(activity);
  674. } else {
  675. qCWarning(lcActivity) << "Item " << item->_file << " retrieved resulted in error " << item->_errorString;
  676. activity._subject = item->_errorString;
  677. activity._id = -static_cast<int>(qHash(activity._subject + activity._message));
  678. if (item->_status == SyncFileItem::Status::FileIgnored) {
  679. _activityModel->addIgnoredFileToList(activity);
  680. } else {
  681. // add 'protocol error' to activity list
  682. if (item->_status == SyncFileItem::Status::FileNameInvalid) {
  683. showDesktopNotification(item->_file, activity._subject, activity._id);
  684. } else if (item->_status == SyncFileItem::Conflict || item->_status == SyncFileItem::FileNameClash) {
  685. ActivityLink buttonActivityLink;
  686. buttonActivityLink._label = tr("Resolve conflict");
  687. buttonActivityLink._link = activity._link.toString();
  688. buttonActivityLink._verb = "FIX_CONFLICT_LOCALLY";
  689. buttonActivityLink._primary = true;
  690. activity._links = {buttonActivityLink};
  691. }
  692. _activityModel->addErrorToActivityList(activity, ActivityListModel::ErrorType::SyncError);
  693. }
  694. }
  695. }
  696. const QVariantList &User::groupFolders() const
  697. {
  698. return _trayFolderInfos;
  699. }
  700. void User::slotItemCompleted(const QString &folder, const SyncFileItemPtr &item)
  701. {
  702. auto folderInstance = FolderMan::instance()->folder(folder);
  703. if (!folderInstance || !isActivityOfCurrentAccount(folderInstance) || isUnsolvableConflict(item)) {
  704. return;
  705. }
  706. qCWarning(lcActivity) << "Item " << item->_file << " retrieved resulted in " << item->_errorString;
  707. processCompletedSyncItem(folderInstance, item);
  708. }
  709. AccountPtr User::account() const
  710. {
  711. return _account->account();
  712. }
  713. AccountStatePtr User::accountState() const
  714. {
  715. return _account;
  716. }
  717. void User::setCurrentUser(const bool &isCurrent)
  718. {
  719. _isCurrentUser = isCurrent;
  720. }
  721. Folder *User::getFolder() const
  722. {
  723. foreach (Folder *folder, FolderMan::instance()->map()) {
  724. if (folder->accountState() == _account.data()) {
  725. return folder;
  726. }
  727. }
  728. return nullptr;
  729. }
  730. ActivityListModel *User::getActivityModel()
  731. {
  732. return _activityModel;
  733. }
  734. UnifiedSearchResultsListModel *User::getUnifiedSearchResultsListModel() const
  735. {
  736. return _unifiedSearchResultsModel;
  737. }
  738. void User::openLocalFolder()
  739. {
  740. const auto folder = getFolder();
  741. if (folder) {
  742. QDesktopServices::openUrl(QUrl::fromLocalFile(folder->path()));
  743. }
  744. }
  745. void User::openFolderLocallyOrInBrowser(const QString &fullRemotePath)
  746. {
  747. const auto folder = getFolder();
  748. if (!folder) {
  749. return;
  750. }
  751. // remove remote path prefix and leading slash
  752. auto fullRemotePathToPathInDb = folder->remotePath() != QStringLiteral("/") ? fullRemotePath.mid(folder->remotePathTrailingSlash().size()) : fullRemotePath;
  753. if (fullRemotePathToPathInDb.startsWith("/")) {
  754. fullRemotePathToPathInDb = fullRemotePathToPathInDb.mid(1);
  755. }
  756. SyncJournalFileRecord rec;
  757. if (folder->journalDb()->getFileRecord(fullRemotePathToPathInDb, &rec) && rec.isValid()) {
  758. // found folder locally, going to open
  759. qCInfo(lcActivity) << "Opening locally a folder" << fullRemotePath;
  760. QDesktopServices::openUrl(QUrl::fromLocalFile(folder->path() + rec.path()));
  761. return;
  762. }
  763. // try to open it in browser
  764. auto folderUrlForBrowser = Utility::concatUrlPath(_account->account()->url(), QStringLiteral("/index.php/apps/files/"));
  765. QUrlQuery urlQuery;
  766. urlQuery.addQueryItem(QStringLiteral("dir"), fullRemotePath);
  767. folderUrlForBrowser.setQuery(urlQuery);
  768. if (!folderUrlForBrowser.scheme().startsWith(QStringLiteral("http"))) {
  769. folderUrlForBrowser.setScheme(QStringLiteral("https"));
  770. }
  771. // open https://server.com/index.php/apps/files/?dir=/group_folder/path
  772. qCInfo(lcActivity) << "Opening in browser a folder" << fullRemotePath;
  773. Utility::openBrowser(folderUrlForBrowser);
  774. return;
  775. }
  776. void User::login() const
  777. {
  778. _account->account()->resetRejectedCertificates();
  779. _account->signIn();
  780. }
  781. void User::logout() const
  782. {
  783. _account->signOutByUi();
  784. }
  785. QString User::name() const
  786. {
  787. return _account->account()->prettyName();
  788. }
  789. QString User::server(bool shortened) const
  790. {
  791. QString serverUrl = _account->account()->url().toString();
  792. if (shortened) {
  793. serverUrl.replace(QLatin1String("https://"), QLatin1String(""));
  794. serverUrl.replace(QLatin1String("http://"), QLatin1String(""));
  795. }
  796. return serverUrl;
  797. }
  798. UserStatus::OnlineStatus User::status() const
  799. {
  800. return _account->account()->userStatusConnector()->userStatus().state();
  801. }
  802. QString User::statusMessage() const
  803. {
  804. return _account->account()->userStatusConnector()->userStatus().message();
  805. }
  806. QUrl User::statusIcon() const
  807. {
  808. return _account->account()->userStatusConnector()->userStatus().stateIcon();
  809. }
  810. QString User::statusEmoji() const
  811. {
  812. return _account->account()->userStatusConnector()->userStatus().icon();
  813. }
  814. bool User::serverHasUserStatus() const
  815. {
  816. return _account->account()->capabilities().userStatus();
  817. }
  818. QImage User::avatar() const
  819. {
  820. return AvatarJob::makeCircularAvatar(_account->account()->avatar());
  821. }
  822. QString User::avatarUrl() const
  823. {
  824. if (avatar().isNull()) {
  825. return QString();
  826. }
  827. return QStringLiteral("image://avatars/") + _account->account()->id();
  828. }
  829. bool User::hasLocalFolder() const
  830. {
  831. return getFolder() != nullptr;
  832. }
  833. bool User::serverHasTalk() const
  834. {
  835. return talkApp() != nullptr;
  836. }
  837. AccountApp *User::talkApp() const
  838. {
  839. return _account->findApp(QStringLiteral("spreed"));
  840. }
  841. bool User::hasActivities() const
  842. {
  843. return _account->account()->capabilities().hasActivities();
  844. }
  845. QColor User::headerColor() const
  846. {
  847. return _account->account()->headerColor();
  848. }
  849. QColor User::headerTextColor() const
  850. {
  851. return _account->account()->headerTextColor();
  852. }
  853. QColor User::accentColor() const
  854. {
  855. return _account->account()->accentColor();
  856. }
  857. AccountAppList User::appList() const
  858. {
  859. return _account->appList();
  860. }
  861. bool User::isCurrentUser() const
  862. {
  863. return _isCurrentUser;
  864. }
  865. bool User::isConnected() const
  866. {
  867. return (_account->connectionStatus() == AccountState::ConnectionStatus::Connected);
  868. }
  869. bool User::isDesktopNotificationsAllowed() const
  870. {
  871. return _account.data()->isDesktopNotificationsAllowed();
  872. }
  873. void User::removeAccount() const
  874. {
  875. AccountManager::instance()->deleteAccount(_account.data());
  876. AccountManager::instance()->save();
  877. }
  878. void User::slotSendReplyMessage(const int activityIndex, const QString &token, const QString &message, const QString &replyTo)
  879. {
  880. QPointer<TalkReply> talkReply = new TalkReply(_account.data(), this);
  881. talkReply->sendReplyMessage(token, message, replyTo);
  882. connect(talkReply, &TalkReply::replyMessageSent, this, [&, activityIndex](const QString &message) {
  883. _activityModel->setReplyMessageSent(activityIndex, message);
  884. });
  885. }
  886. void User::forceSyncNow() const
  887. {
  888. FolderMan::instance()->forceSyncForFolder(getFolder());
  889. }
  890. void User::slotAccountCapabilitiesChangedRefreshGroupFolders()
  891. {
  892. if (!_account->account()->capabilities().groupFoldersAvailable()) {
  893. if (!_trayFolderInfos.isEmpty()) {
  894. _trayFolderInfos.clear();
  895. emit groupFoldersChanged();
  896. }
  897. return;
  898. }
  899. slotFetchGroupFolders();
  900. }
  901. void User::slotFetchGroupFolders()
  902. {
  903. QNetworkRequest req;
  904. req.setRawHeader(QByteArrayLiteral("OCS-APIREQUEST"), QByteArrayLiteral("true"));
  905. QUrlQuery query;
  906. query.addQueryItem(QLatin1String("format"), QLatin1String("json"));
  907. query.addQueryItem(QLatin1String("applicable"), QLatin1String("1"));
  908. QUrl groupFolderListUrl = Utility::concatUrlPath(_account->account()->url(), QStringLiteral("/index.php/apps/groupfolders/folders"));
  909. groupFolderListUrl.setQuery(query);
  910. const auto groupFolderListJob = _account->account()->sendRequest(QByteArrayLiteral("GET"), groupFolderListUrl, req);
  911. connect(groupFolderListJob, &SimpleNetworkJob::finishedSignal, this, &User::slotGroupFoldersFetched);
  912. }
  913. void User::slotGroupFoldersFetched(QNetworkReply *reply)
  914. {
  915. Q_ASSERT(reply);
  916. if (!reply) {
  917. qCWarning(lcActivity) << "Group folders fetch error";
  918. return;
  919. }
  920. const auto oldSize = _trayFolderInfos.size();
  921. const auto oldTrayFolderInfos = _trayFolderInfos;
  922. _trayFolderInfos.clear();
  923. const auto replyData = reply->readAll();
  924. if (reply->error() != QNetworkReply::NoError) {
  925. if (oldSize != _trayFolderInfos.size()) {
  926. emit groupFoldersChanged();
  927. }
  928. qCWarning(lcActivity) << "Group folders fetch error" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() << replyData;
  929. return;
  930. }
  931. QJsonParseError jsonParseError{};
  932. const auto json = QJsonDocument::fromJson(replyData, &jsonParseError);
  933. if (jsonParseError.error != QJsonParseError::NoError) {
  934. qCWarning(lcActivity) << "Group folders JSON parse error" << jsonParseError.error << jsonParseError.errorString();
  935. if (oldSize != _trayFolderInfos.size()) {
  936. emit groupFoldersChanged();
  937. }
  938. return;
  939. }
  940. const auto obj = json.object().toVariantMap();
  941. const auto groupFolders = obj["ocs"].toMap()["data"].toMap();
  942. for (const auto &groupFolder : groupFolders.values()) {
  943. const auto groupFolderInfo = groupFolder.toMap();
  944. const auto mountPoint = groupFolderInfo.value(QStringLiteral("mount_point"), {}).toString();
  945. parseNewGroupFolderPath(mountPoint);
  946. }
  947. std::sort(std::begin(_trayFolderInfos), std::end(_trayFolderInfos), [](const auto &leftVariant, const auto &rightVariant) {
  948. const auto folderInfoA = leftVariant.template value<TrayFolderInfo>();
  949. const auto folderInfoB = rightVariant.template value<TrayFolderInfo>();
  950. return folderInfoA._fullPath < folderInfoB._fullPath;
  951. });
  952. if (!_trayFolderInfos.isEmpty()) {
  953. if (hasLocalFolder()) {
  954. prePendGroupFoldersWithLocalFolder();
  955. }
  956. }
  957. if (oldSize != _trayFolderInfos.size()) {
  958. emit groupFoldersChanged();
  959. } else {
  960. for (int i = 0; i < oldTrayFolderInfos.size(); ++i) {
  961. const auto oldFolderInfo = oldTrayFolderInfos.at(i).template value<TrayFolderInfo>();
  962. const auto newFolderInfo = _trayFolderInfos.at(i).template value<TrayFolderInfo>();
  963. if (oldFolderInfo._folderType != newFolderInfo._folderType || oldFolderInfo._fullPath != newFolderInfo._fullPath) {
  964. break;
  965. emit groupFoldersChanged();
  966. }
  967. }
  968. }
  969. }
  970. /*-------------------------------------------------------------------------------------*/
  971. UserModel *UserModel::_instance = nullptr;
  972. UserModel *UserModel::instance()
  973. {
  974. if (!_instance) {
  975. _instance = new UserModel();
  976. }
  977. return _instance;
  978. }
  979. UserModel::UserModel(QObject *parent)
  980. : QAbstractListModel(parent)
  981. {
  982. // TODO: Remember selected user from last quit via settings file
  983. if (AccountManager::instance()->accounts().size() > 0) {
  984. buildUserList();
  985. }
  986. connect(AccountManager::instance(), &AccountManager::accountAdded,
  987. this, &UserModel::buildUserList);
  988. }
  989. void UserModel::buildUserList()
  990. {
  991. for (int i = 0; i < AccountManager::instance()->accounts().size(); i++) {
  992. auto user = AccountManager::instance()->accounts().at(i);
  993. addUser(user);
  994. }
  995. if (_init) {
  996. _users.first()->setCurrentUser(true);
  997. _init = false;
  998. }
  999. }
  1000. int UserModel::numUsers()
  1001. {
  1002. return _users.size();
  1003. }
  1004. int UserModel::currentUserId() const
  1005. {
  1006. return _currentUserId;
  1007. }
  1008. bool UserModel::isUserConnected(const int id)
  1009. {
  1010. if (id < 0 || id >= _users.size())
  1011. return false;
  1012. return _users[id]->isConnected();
  1013. }
  1014. QImage UserModel::avatarById(const int id) const
  1015. {
  1016. const auto foundUserByIdIter = std::find_if(std::cbegin(_users), std::cend(_users), [&id](const OCC::User* const user) {
  1017. return user->account()->id() == QString::number(id);
  1018. });
  1019. if (foundUserByIdIter == std::cend(_users)) {
  1020. return {};
  1021. }
  1022. return (*foundUserByIdIter)->avatar();
  1023. }
  1024. QString UserModel::currentUserServer()
  1025. {
  1026. if (_currentUserId < 0 || _currentUserId >= _users.size())
  1027. return {};
  1028. return _users[_currentUserId]->server();
  1029. }
  1030. void UserModel::addUser(AccountStatePtr &user, const bool &isCurrent)
  1031. {
  1032. bool containsUser = false;
  1033. for (const auto &u : qAsConst(_users)) {
  1034. if (u->account() == user->account()) {
  1035. containsUser = true;
  1036. continue;
  1037. }
  1038. }
  1039. if (!containsUser) {
  1040. int row = rowCount();
  1041. beginInsertRows(QModelIndex(), row, row);
  1042. User *u = new User(user, isCurrent);
  1043. connect(u, &User::avatarChanged, this, [this, row] {
  1044. emit dataChanged(index(row, 0), index(row, 0), {UserModel::AvatarRole});
  1045. });
  1046. connect(u, &User::statusChanged, this, [this, row] {
  1047. emit dataChanged(index(row, 0), index(row, 0), {UserModel::StatusIconRole,
  1048. UserModel::StatusEmojiRole,
  1049. UserModel::StatusMessageRole});
  1050. });
  1051. connect(u, &User::desktopNotificationsAllowedChanged, this, [this, row] {
  1052. emit dataChanged(index(row, 0), index(row, 0), { UserModel::DesktopNotificationsAllowedRole });
  1053. });
  1054. connect(u, &User::accountStateChanged, this, [this, row] {
  1055. emit dataChanged(index(row, 0), index(row, 0), { UserModel::IsConnectedRole });
  1056. });
  1057. _users << u;
  1058. if (isCurrent || _currentUserId < 0) {
  1059. setCurrentUserId(_users.size() - 1);
  1060. }
  1061. endInsertRows();
  1062. ConfigFile cfg;
  1063. u->setNotificationRefreshInterval(cfg.notificationRefreshInterval());
  1064. emit currentUserChanged();
  1065. }
  1066. }
  1067. int UserModel::currentUserIndex()
  1068. {
  1069. return _currentUserId;
  1070. }
  1071. void UserModel::openCurrentAccountLocalFolder()
  1072. {
  1073. if (_currentUserId < 0 || _currentUserId >= _users.size())
  1074. return;
  1075. _users[_currentUserId]->openLocalFolder();
  1076. }
  1077. void UserModel::openCurrentAccountTalk()
  1078. {
  1079. if (!currentUser())
  1080. return;
  1081. const auto talkApp = currentUser()->talkApp();
  1082. if (talkApp) {
  1083. Utility::openBrowser(talkApp->url());
  1084. } else {
  1085. qCWarning(lcActivity) << "The Talk app is not enabled on" << currentUser()->server();
  1086. }
  1087. }
  1088. void UserModel::openCurrentAccountServer()
  1089. {
  1090. if (_currentUserId < 0 || _currentUserId >= _users.size())
  1091. return;
  1092. QString url = _users[_currentUserId]->server(false);
  1093. if (!url.startsWith("http://") && !url.startsWith("https://")) {
  1094. url = "https://" + _users[_currentUserId]->server(false);
  1095. }
  1096. QDesktopServices::openUrl(url);
  1097. }
  1098. void UserModel::openCurrentAccountFolderFromTrayInfo(const QString &fullRemotePath)
  1099. {
  1100. if (_currentUserId < 0 || _currentUserId >= _users.size()) {
  1101. return;
  1102. }
  1103. _users[_currentUserId]->openFolderLocallyOrInBrowser(fullRemotePath);
  1104. }
  1105. void UserModel::setCurrentUserId(const int id)
  1106. {
  1107. Q_ASSERT(id < _users.size());
  1108. if (id < 0 || id >= _users.size()) {
  1109. if (id < 0 && _currentUserId != id) {
  1110. _currentUserId = id;
  1111. emit currentUserChanged();
  1112. }
  1113. return;
  1114. }
  1115. const auto isCurrentUserChanged = !_users[id]->isCurrentUser();
  1116. if (isCurrentUserChanged) {
  1117. for (const auto user : qAsConst(_users)) {
  1118. user->setCurrentUser(false);
  1119. }
  1120. _users[id]->setCurrentUser(true);
  1121. }
  1122. if (_currentUserId == id && isCurrentUserChanged) {
  1123. // order has changed, index remained the same
  1124. emit currentUserChanged();
  1125. } else if (_currentUserId != id) {
  1126. _currentUserId = id;
  1127. emit currentUserChanged();
  1128. }
  1129. }
  1130. void UserModel::login(const int id)
  1131. {
  1132. if (id < 0 || id >= _users.size())
  1133. return;
  1134. _users[id]->login();
  1135. }
  1136. void UserModel::logout(const int id)
  1137. {
  1138. if (id < 0 || id >= _users.size())
  1139. return;
  1140. _users[id]->logout();
  1141. }
  1142. void UserModel::removeAccount(const int id)
  1143. {
  1144. if (id < 0 || id >= _users.size()) {
  1145. return;
  1146. }
  1147. QMessageBox messageBox(QMessageBox::Question,
  1148. tr("Confirm Account Removal"),
  1149. tr("<p>Do you really want to remove the connection to the account <i>%1</i>?</p>"
  1150. "<p><b>Note:</b> This will <b>not</b> delete any files.</p>")
  1151. .arg(_users[id]->name()),
  1152. QMessageBox::NoButton);
  1153. const auto * const yesButton = messageBox.addButton(tr("Remove connection"), QMessageBox::YesRole);
  1154. messageBox.addButton(tr("Cancel"), QMessageBox::NoRole);
  1155. messageBox.exec();
  1156. if (messageBox.clickedButton() != yesButton) {
  1157. return;
  1158. }
  1159. _users[id]->logout();
  1160. _users[id]->removeAccount();
  1161. beginRemoveRows(QModelIndex(), id, id);
  1162. _users.removeAt(id);
  1163. endRemoveRows();
  1164. if (_users.size() <= 1) {
  1165. setCurrentUserId(_users.size() - 1);
  1166. } else if (currentUserId() > id) {
  1167. // an account was removed from the in-between 0 and the current one, the index of the current one needs a decrement
  1168. setCurrentUserId(currentUserId() - 1);
  1169. } else if (currentUserId() == id) {
  1170. setCurrentUserId(id < _users.size() ? id : id - 1);
  1171. }
  1172. }
  1173. std::shared_ptr<OCC::UserStatusConnector> UserModel::userStatusConnector(int id)
  1174. {
  1175. if (id < 0 || id >= _users.size()) {
  1176. return nullptr;
  1177. }
  1178. return _users[id]->account()->userStatusConnector();
  1179. }
  1180. int UserModel::rowCount(const QModelIndex &parent) const
  1181. {
  1182. Q_UNUSED(parent);
  1183. return _users.count();
  1184. }
  1185. QVariant UserModel::data(const QModelIndex &index, int role) const
  1186. {
  1187. if (index.row() < 0 || index.row() >= _users.count()) {
  1188. return QVariant();
  1189. }
  1190. if (role == NameRole) {
  1191. return _users[index.row()]->name();
  1192. } else if (role == ServerRole) {
  1193. return _users[index.row()]->server();
  1194. } else if (role == ServerHasUserStatusRole) {
  1195. return _users[index.row()]->serverHasUserStatus();
  1196. } else if (role == StatusIconRole) {
  1197. return _users[index.row()]->statusIcon();
  1198. } else if (role == StatusEmojiRole) {
  1199. return _users[index.row()]->statusEmoji();
  1200. } else if (role == StatusMessageRole) {
  1201. return _users[index.row()]->statusMessage();
  1202. } else if (role == DesktopNotificationsAllowedRole) {
  1203. return _users[index.row()]->isDesktopNotificationsAllowed();
  1204. } else if (role == AvatarRole) {
  1205. return _users[index.row()]->avatarUrl();
  1206. } else if (role == IsCurrentUserRole) {
  1207. return _users[index.row()]->isCurrentUser();
  1208. } else if (role == IsConnectedRole) {
  1209. return _users[index.row()]->isConnected();
  1210. } else if (role == IdRole) {
  1211. return index.row();
  1212. }
  1213. return QVariant();
  1214. }
  1215. QHash<int, QByteArray> UserModel::roleNames() const
  1216. {
  1217. QHash<int, QByteArray> roles;
  1218. roles[NameRole] = "name";
  1219. roles[ServerRole] = "server";
  1220. roles[ServerHasUserStatusRole] = "serverHasUserStatus";
  1221. roles[StatusIconRole] = "statusIcon";
  1222. roles[StatusEmojiRole] = "statusEmoji";
  1223. roles[StatusMessageRole] = "statusMessage";
  1224. roles[DesktopNotificationsAllowedRole] = "desktopNotificationsAllowed";
  1225. roles[AvatarRole] = "avatar";
  1226. roles[IsCurrentUserRole] = "isCurrentUser";
  1227. roles[IsConnectedRole] = "isConnected";
  1228. roles[IdRole] = "id";
  1229. return roles;
  1230. }
  1231. ActivityListModel *UserModel::currentActivityModel()
  1232. {
  1233. if (currentUserIndex() < 0 || currentUserIndex() >= _users.size())
  1234. return nullptr;
  1235. return _users[currentUserIndex()]->getActivityModel();
  1236. }
  1237. void UserModel::fetchCurrentActivityModel()
  1238. {
  1239. if (currentUserId() < 0 || currentUserId() >= _users.size())
  1240. return;
  1241. _users[currentUserId()]->slotRefresh();
  1242. }
  1243. AccountAppList UserModel::appList() const
  1244. {
  1245. if (_currentUserId < 0 || _currentUserId >= _users.size())
  1246. return {};
  1247. return _users[_currentUserId]->appList();
  1248. }
  1249. User *UserModel::currentUser() const
  1250. {
  1251. if (currentUserId() < 0 || currentUserId() >= _users.size())
  1252. return nullptr;
  1253. return _users[currentUserId()];
  1254. }
  1255. int UserModel::findUserIdForAccount(AccountState *account) const
  1256. {
  1257. const auto it = std::find_if(std::cbegin(_users), std::cend(_users), [=](const User *user) {
  1258. return user->account()->id() == account->account()->id();
  1259. });
  1260. if (it == std::cend(_users)) {
  1261. return -1;
  1262. }
  1263. const auto id = std::distance(std::cbegin(_users), it);
  1264. return id;
  1265. }
  1266. /*-------------------------------------------------------------------------------------*/
  1267. ImageProvider::ImageProvider()
  1268. : QQuickImageProvider(QQuickImageProvider::Image)
  1269. {
  1270. }
  1271. QImage ImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize)
  1272. {
  1273. Q_UNUSED(size)
  1274. Q_UNUSED(requestedSize)
  1275. const auto makeIcon = [](const QString &path) {
  1276. QImage image(128, 128, QImage::Format_ARGB32);
  1277. image.fill(Qt::GlobalColor::transparent);
  1278. QPainter painter(&image);
  1279. QSvgRenderer renderer(path);
  1280. renderer.render(&painter);
  1281. return image;
  1282. };
  1283. if (id == QLatin1String("fallbackWhite")) {
  1284. return makeIcon(QStringLiteral(":/client/theme/white/user.svg"));
  1285. }
  1286. if (id == QLatin1String("fallbackBlack")) {
  1287. return makeIcon(QStringLiteral(":/client/theme/black/user.svg"));
  1288. }
  1289. const int uid = id.toInt();
  1290. return UserModel::instance()->avatarById(uid);
  1291. }
  1292. /*-------------------------------------------------------------------------------------*/
  1293. UserAppsModel *UserAppsModel::_instance = nullptr;
  1294. UserAppsModel *UserAppsModel::instance()
  1295. {
  1296. if (!_instance) {
  1297. _instance = new UserAppsModel();
  1298. }
  1299. return _instance;
  1300. }
  1301. UserAppsModel::UserAppsModel(QObject *parent)
  1302. : QAbstractListModel(parent)
  1303. {
  1304. }
  1305. void UserAppsModel::buildAppList()
  1306. {
  1307. if (rowCount() > 0) {
  1308. beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
  1309. _apps.clear();
  1310. endRemoveRows();
  1311. }
  1312. if (UserModel::instance()->appList().count() > 0) {
  1313. const auto talkApp = UserModel::instance()->currentUser()->talkApp();
  1314. foreach (AccountApp *app, UserModel::instance()->appList()) {
  1315. // Filter out Talk because we have a dedicated button for it
  1316. if (talkApp && app->id() == talkApp->id())
  1317. continue;
  1318. beginInsertRows(QModelIndex(), rowCount(), rowCount());
  1319. _apps << app;
  1320. endInsertRows();
  1321. }
  1322. }
  1323. }
  1324. void UserAppsModel::openAppUrl(const QUrl &url)
  1325. {
  1326. Utility::openBrowser(url);
  1327. }
  1328. int UserAppsModel::rowCount(const QModelIndex &parent) const
  1329. {
  1330. Q_UNUSED(parent);
  1331. return _apps.count();
  1332. }
  1333. QVariant UserAppsModel::data(const QModelIndex &index, int role) const
  1334. {
  1335. if (index.row() < 0 || index.row() >= _apps.count()) {
  1336. return QVariant();
  1337. }
  1338. if (role == NameRole) {
  1339. return _apps[index.row()]->name();
  1340. } else if (role == UrlRole) {
  1341. return _apps[index.row()]->url();
  1342. } else if (role == IconUrlRole) {
  1343. return _apps[index.row()]->iconUrl().toString();
  1344. }
  1345. return QVariant();
  1346. }
  1347. QHash<int, QByteArray> UserAppsModel::roleNames() const
  1348. {
  1349. QHash<int, QByteArray> roles;
  1350. roles[NameRole] = "appName";
  1351. roles[UrlRole] = "appUrl";
  1352. roles[IconUrlRole] = "appIconUrl";
  1353. return roles;
  1354. }
  1355. }