data_forum.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #include "data/data_forum.h"
  8. #include "data/data_channel.h"
  9. #include "data/data_histories.h"
  10. #include "data/data_changes.h"
  11. #include "data/data_session.h"
  12. #include "data/data_forum_icons.h"
  13. #include "data/data_forum_topic.h"
  14. #include "data/notify/data_notify_settings.h"
  15. #include "history/history.h"
  16. #include "history/history_item.h"
  17. #include "history/history_unread_things.h"
  18. #include "main/main_session.h"
  19. #include "base/random.h"
  20. #include "base/unixtime.h"
  21. #include "apiwrap.h"
  22. #include "lang/lang_keys.h"
  23. #include "core/application.h"
  24. #include "ui/layers/generic_box.h"
  25. #include "ui/widgets/fields/input_field.h"
  26. #include "storage/storage_facade.h"
  27. #include "storage/storage_shared_media.h"
  28. #include "window/window_session_controller.h"
  29. #include "window/notifications_manager.h"
  30. #include "styles/style_boxes.h"
  31. namespace Data {
  32. namespace {
  33. constexpr auto kTopicsFirstLoad = 20;
  34. constexpr auto kLoadedTopicsMinCount = 20;
  35. constexpr auto kTopicsPerPage = 500;
  36. constexpr auto kStalePerRequest = 100;
  37. constexpr auto kShowTopicNamesCount = 8;
  38. // constexpr auto kGeneralColorId = 0xA9A9A9;
  39. } // namespace
  40. Forum::Forum(not_null<History*> history)
  41. : _history(history)
  42. , _topicsList(&session(), {}, owner().maxPinnedChatsLimitValue(this)) {
  43. Expects(_history->peer->isChannel());
  44. if (_history->inChatList()) {
  45. preloadTopics();
  46. }
  47. if (channel()->canCreateTopics()) {
  48. owner().forumIcons().requestDefaultIfUnknown();
  49. }
  50. }
  51. Forum::~Forum() {
  52. for (const auto &request : _topicRequests) {
  53. if (request.second.id != _staleRequestId) {
  54. owner().histories().cancelRequest(request.second.id);
  55. }
  56. }
  57. if (_staleRequestId) {
  58. session().api().request(_staleRequestId).cancel();
  59. }
  60. if (_requestId) {
  61. session().api().request(_requestId).cancel();
  62. }
  63. auto &storage = session().storage();
  64. auto &changes = session().changes();
  65. const auto peerId = _history->peer->id;
  66. for (const auto &[rootId, topic] : _topics) {
  67. storage.unload(Storage::SharedMediaUnloadThread(peerId, rootId));
  68. _history->setForwardDraft(rootId, {});
  69. const auto raw = topic.get();
  70. changes.topicRemoved(raw);
  71. changes.entryRemoved(raw);
  72. }
  73. }
  74. Session &Forum::owner() const {
  75. return _history->owner();
  76. }
  77. Main::Session &Forum::session() const {
  78. return _history->session();
  79. }
  80. not_null<History*> Forum::history() const {
  81. return _history;
  82. }
  83. not_null<ChannelData*> Forum::channel() const {
  84. return _history->peer->asChannel();
  85. }
  86. not_null<Dialogs::MainList*> Forum::topicsList() {
  87. return &_topicsList;
  88. }
  89. rpl::producer<> Forum::destroyed() const {
  90. return channel()->flagsValue(
  91. ) | rpl::filter([=](const ChannelData::Flags::Change &update) {
  92. using Flag = ChannelData::Flag;
  93. return (update.diff & Flag::Forum) && !(update.value & Flag::Forum);
  94. }) | rpl::take(1) | rpl::to_empty;
  95. }
  96. rpl::producer<not_null<ForumTopic*>> Forum::topicDestroyed() const {
  97. return _topicDestroyed.events();
  98. }
  99. void Forum::preloadTopics() {
  100. if (topicsList()->indexed()->size() < kLoadedTopicsMinCount) {
  101. requestTopics();
  102. }
  103. }
  104. void Forum::reloadTopics() {
  105. _topicsList.setLoaded(false);
  106. session().api().request(base::take(_requestId)).cancel();
  107. _offset = {};
  108. for (const auto &[rootId, topic] : _topics) {
  109. if (!topic->creating()) {
  110. _staleRootIds.emplace(topic->rootId());
  111. }
  112. }
  113. requestTopics();
  114. }
  115. void Forum::requestTopics() {
  116. if (_topicsList.loaded() || _requestId) {
  117. return;
  118. }
  119. const auto firstLoad = !_offset.date;
  120. const auto loadCount = firstLoad ? kTopicsFirstLoad : kTopicsPerPage;
  121. _requestId = session().api().request(MTPchannels_GetForumTopics(
  122. MTP_flags(0),
  123. channel()->inputChannel,
  124. MTPstring(), // q
  125. MTP_int(_offset.date),
  126. MTP_int(_offset.id),
  127. MTP_int(_offset.topicId),
  128. MTP_int(loadCount)
  129. )).done([=](const MTPmessages_ForumTopics &result) {
  130. const auto previousOffset = _offset;
  131. applyReceivedTopics(result, _offset);
  132. const auto &list = result.data().vtopics().v;
  133. if (list.isEmpty()
  134. || list.size() == result.data().vcount().v
  135. || (_offset == previousOffset)) {
  136. _topicsList.setLoaded();
  137. }
  138. _requestId = 0;
  139. _chatsListChanges.fire({});
  140. if (_topicsList.loaded()) {
  141. _chatsListLoadedEvents.fire({});
  142. }
  143. reorderLastTopics();
  144. requestSomeStale();
  145. }).fail([=](const MTP::Error &error) {
  146. _requestId = 0;
  147. _topicsList.setLoaded();
  148. if (error.type() == u"CHANNEL_FORUM_MISSING"_q) {
  149. const auto flags = channel()->flags() & ~ChannelDataFlag::Forum;
  150. channel()->setFlags(flags);
  151. }
  152. }).send();
  153. }
  154. void Forum::applyTopicDeleted(MsgId rootId) {
  155. _topicsDeleted.emplace(rootId);
  156. const auto i = _topics.find(rootId);
  157. if (i != end(_topics)) {
  158. const auto raw = i->second.get();
  159. Core::App().notifications().clearFromTopic(raw);
  160. owner().removeChatListEntry(raw);
  161. if (ranges::contains(_lastTopics, not_null(raw))) {
  162. reorderLastTopics();
  163. }
  164. _topicDestroyed.fire(raw);
  165. session().changes().topicUpdated(
  166. raw,
  167. Data::TopicUpdate::Flag::Destroyed);
  168. session().changes().entryUpdated(
  169. raw,
  170. Data::EntryUpdate::Flag::Destroyed);
  171. _topics.erase(i);
  172. _history->destroyMessagesByTopic(rootId);
  173. session().storage().unload(Storage::SharedMediaUnloadThread(
  174. _history->peer->id,
  175. rootId));
  176. _history->setForwardDraft(rootId, {});
  177. }
  178. }
  179. void Forum::reorderLastTopics() {
  180. // We want first kShowChatNamesCount histories, by last message date.
  181. const auto pred = [](not_null<ForumTopic*> a, not_null<ForumTopic*> b) {
  182. const auto aItem = a->chatListMessage();
  183. const auto bItem = b->chatListMessage();
  184. const auto aDate = aItem ? aItem->date() : TimeId(0);
  185. const auto bDate = bItem ? bItem->date() : TimeId(0);
  186. return aDate > bDate;
  187. };
  188. _lastTopics.clear();
  189. _lastTopics.reserve(kShowTopicNamesCount + 1);
  190. auto &&topics = ranges::views::all(
  191. *_topicsList.indexed()
  192. ) | ranges::views::transform([](not_null<Dialogs::Row*> row) {
  193. return row->topic();
  194. });
  195. auto nonPinnedChecked = 0;
  196. for (const auto topic : topics) {
  197. const auto i = ranges::upper_bound(
  198. _lastTopics,
  199. not_null(topic),
  200. pred);
  201. if (size(_lastTopics) < kShowTopicNamesCount
  202. || i != end(_lastTopics)) {
  203. _lastTopics.insert(i, topic);
  204. }
  205. if (size(_lastTopics) > kShowTopicNamesCount) {
  206. _lastTopics.pop_back();
  207. }
  208. if (!topic->isPinnedDialog(FilterId())
  209. && ++nonPinnedChecked >= kShowTopicNamesCount) {
  210. break;
  211. }
  212. }
  213. ++_lastTopicsVersion;
  214. _history->updateChatListEntry();
  215. }
  216. int Forum::recentTopicsListVersion() const {
  217. return _lastTopicsVersion;
  218. }
  219. void Forum::recentTopicsInvalidate(not_null<ForumTopic*> topic) {
  220. if (ranges::contains(_lastTopics, topic)) {
  221. ++_lastTopicsVersion;
  222. _history->updateChatListEntry();
  223. }
  224. }
  225. const std::vector<not_null<ForumTopic*>> &Forum::recentTopics() const {
  226. return _lastTopics;
  227. }
  228. void Forum::listMessageChanged(HistoryItem *from, HistoryItem *to) {
  229. if (from || to) {
  230. reorderLastTopics();
  231. }
  232. }
  233. void Forum::applyReceivedTopics(
  234. const MTPmessages_ForumTopics &topics,
  235. ForumOffsets &updateOffsets) {
  236. applyReceivedTopics(topics, [&](not_null<ForumTopic*> topic) {
  237. if (const auto last = topic->lastServerMessage()) {
  238. updateOffsets.date = last->date();
  239. updateOffsets.id = last->id;
  240. }
  241. updateOffsets.topicId = topic->rootId();
  242. });
  243. }
  244. void Forum::applyReceivedTopics(
  245. const MTPmessages_ForumTopics &topics,
  246. Fn<void(not_null<ForumTopic*>)> callback) {
  247. const auto &data = topics.data();
  248. owner().processUsers(data.vusers());
  249. owner().processChats(data.vchats());
  250. owner().processMessages(data.vmessages(), NewMessageType::Existing);
  251. channel()->ptsReceived(data.vpts().v);
  252. applyReceivedTopics(data.vtopics(), std::move(callback));
  253. if (!_staleRootIds.empty()) {
  254. requestSomeStale();
  255. }
  256. }
  257. void Forum::applyReceivedTopics(
  258. const MTPVector<MTPForumTopic> &topics,
  259. Fn<void(not_null<ForumTopic*>)> callback) {
  260. const auto &list = topics.v;
  261. for (const auto &topic : list) {
  262. const auto rootId = topic.match([&](const auto &data) {
  263. return data.vid().v;
  264. });
  265. _staleRootIds.remove(rootId);
  266. topic.match([&](const MTPDforumTopicDeleted &data) {
  267. applyTopicDeleted(rootId);
  268. }, [&](const MTPDforumTopic &data) {
  269. _topicsDeleted.remove(rootId);
  270. const auto i = _topics.find(rootId);
  271. const auto creating = (i == end(_topics));
  272. const auto raw = creating
  273. ? _topics.emplace(
  274. rootId,
  275. std::make_unique<ForumTopic>(this, rootId)
  276. ).first->second.get()
  277. : i->second.get();
  278. raw->applyTopic(data);
  279. if (creating) {
  280. if (const auto last = _history->chatListMessage()
  281. ; last && last->topicRootId() == rootId) {
  282. _history->lastItemDialogsView().itemInvalidated(last);
  283. _history->updateChatListEntry();
  284. }
  285. }
  286. if (callback) {
  287. callback(raw);
  288. }
  289. });
  290. }
  291. }
  292. void Forum::requestSomeStale() {
  293. if (_staleRequestId
  294. || (!_offset.id && _requestId)
  295. || _staleRootIds.empty()) {
  296. return;
  297. }
  298. const auto type = Histories::RequestType::History;
  299. auto rootIds = QVector<MTPint>();
  300. rootIds.reserve(std::min(int(_staleRootIds.size()), kStalePerRequest));
  301. for (auto i = begin(_staleRootIds); i != end(_staleRootIds);) {
  302. const auto rootId = *i;
  303. i = _staleRootIds.erase(i);
  304. rootIds.push_back(MTP_int(rootId));
  305. if (rootIds.size() == kStalePerRequest) {
  306. break;
  307. }
  308. }
  309. if (rootIds.empty()) {
  310. return;
  311. }
  312. const auto call = [=] {
  313. for (const auto &id : rootIds) {
  314. finishTopicRequest(id.v);
  315. }
  316. };
  317. auto &histories = owner().histories();
  318. _staleRequestId = histories.sendRequest(_history, type, [=](
  319. Fn<void()> finish) {
  320. return session().api().request(
  321. MTPchannels_GetForumTopicsByID(
  322. channel()->inputChannel,
  323. MTP_vector<MTPint>(rootIds))
  324. ).done([=](const MTPmessages_ForumTopics &result) {
  325. _staleRequestId = 0;
  326. applyReceivedTopics(result);
  327. call();
  328. finish();
  329. }).fail([=] {
  330. _staleRequestId = 0;
  331. call();
  332. finish();
  333. }).send();
  334. });
  335. for (const auto &id : rootIds) {
  336. _topicRequests[id.v].id = _staleRequestId;
  337. }
  338. }
  339. void Forum::finishTopicRequest(MsgId rootId) {
  340. if (const auto request = _topicRequests.take(rootId)) {
  341. for (const auto &callback : request->callbacks) {
  342. callback();
  343. }
  344. }
  345. }
  346. void Forum::requestTopic(MsgId rootId, Fn<void()> done) {
  347. auto &request = _topicRequests[rootId];
  348. if (done) {
  349. request.callbacks.push_back(std::move(done));
  350. }
  351. if (!request.id
  352. && _staleRootIds.emplace(rootId).second
  353. && (_staleRootIds.size() == 1)) {
  354. crl::on_main(&session(), [peer = channel()] {
  355. if (const auto forum = peer->forum()) {
  356. forum->requestSomeStale();
  357. }
  358. });
  359. }
  360. }
  361. ForumTopic *Forum::applyTopicAdded(
  362. MsgId rootId,
  363. const QString &title,
  364. int32 colorId,
  365. DocumentId iconId,
  366. PeerId creatorId,
  367. TimeId date,
  368. bool my) {
  369. Expects(rootId != 0);
  370. const auto i = _topics.find(rootId);
  371. const auto raw = (i != end(_topics))
  372. ? i->second.get()
  373. : _topics.emplace(
  374. rootId,
  375. std::make_unique<ForumTopic>(this, rootId)
  376. ).first->second.get();
  377. raw->applyTitle(title);
  378. raw->applyColorId(colorId);
  379. raw->applyIconId(iconId);
  380. raw->applyCreator(creatorId);
  381. raw->applyCreationDate(date);
  382. raw->applyIsMy(my);
  383. if (!creating(rootId)) {
  384. raw->addToChatList(FilterId(), topicsList());
  385. _chatsListChanges.fire({});
  386. reorderLastTopics();
  387. }
  388. return raw;
  389. }
  390. MsgId Forum::reserveCreatingId(
  391. const QString &title,
  392. int32 colorId,
  393. DocumentId iconId) {
  394. const auto result = owner().nextLocalMessageId();
  395. _creatingRootIds.emplace(result);
  396. applyTopicAdded(
  397. result,
  398. title,
  399. colorId,
  400. iconId,
  401. session().userPeerId(),
  402. base::unixtime::now(),
  403. true);
  404. return result;
  405. }
  406. void Forum::discardCreatingId(MsgId rootId) {
  407. Expects(creating(rootId));
  408. const auto i = _topics.find(rootId);
  409. if (i != end(_topics)) {
  410. Assert(!i->second->inChatList());
  411. _topics.erase(i);
  412. }
  413. _creatingRootIds.remove(rootId);
  414. }
  415. bool Forum::creating(MsgId rootId) const {
  416. return _creatingRootIds.contains(rootId);
  417. }
  418. void Forum::created(MsgId rootId, MsgId realId) {
  419. if (rootId == realId) {
  420. return;
  421. }
  422. _creatingRootIds.remove(rootId);
  423. const auto i = _topics.find(rootId);
  424. Assert(i != end(_topics));
  425. auto topic = std::move(i->second);
  426. _topics.erase(i);
  427. const auto id = FullMsgId(_history->peer->id, realId);
  428. if (!_topics.contains(realId)) {
  429. _topics.emplace(
  430. realId,
  431. std::move(topic)
  432. ).first->second->setRealRootId(realId);
  433. reorderLastTopics();
  434. }
  435. owner().notifyItemIdChange({ id, rootId });
  436. }
  437. void Forum::clearAllUnreadMentions() {
  438. for (const auto &[rootId, topic] : _topics) {
  439. topic->unreadMentions().clear();
  440. }
  441. }
  442. void Forum::clearAllUnreadReactions() {
  443. for (const auto &[rootId, topic] : _topics) {
  444. topic->unreadReactions().clear();
  445. }
  446. }
  447. void Forum::enumerateTopics(Fn<void(not_null<ForumTopic*>)> action) const {
  448. for (const auto &[rootId, topic] : _topics) {
  449. action(topic.get());
  450. }
  451. }
  452. ForumTopic *Forum::topicFor(MsgId rootId) {
  453. if (!rootId) {
  454. return nullptr;
  455. }
  456. const auto i = _topics.find(rootId);
  457. return (i != end(_topics)) ? i->second.get() : nullptr;
  458. }
  459. ForumTopic *Forum::enforceTopicFor(MsgId rootId) {
  460. Expects(rootId != 0);
  461. const auto i = _topics.find(rootId);
  462. if (i != end(_topics)) {
  463. return i->second.get();
  464. }
  465. requestTopic(rootId);
  466. return applyTopicAdded(rootId, {}, {}, {}, {}, {}, {});
  467. }
  468. bool Forum::topicDeleted(MsgId rootId) const {
  469. return _topicsDeleted.contains(rootId);
  470. }
  471. rpl::producer<> Forum::chatsListChanges() const {
  472. return _chatsListChanges.events();
  473. }
  474. rpl::producer<> Forum::chatsListLoadedEvents() const {
  475. return _chatsListLoadedEvents.events();
  476. }
  477. } // namespace Data