data_peer.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816
  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_peer.h"
  8. #include "api/api_sensitive_content.h"
  9. #include "data/data_user.h"
  10. #include "data/data_chat.h"
  11. #include "data/data_chat_participant_status.h"
  12. #include "data/data_channel.h"
  13. #include "data/data_changes.h"
  14. #include "data/data_emoji_statuses.h"
  15. #include "data/data_message_reaction_id.h"
  16. #include "data/data_photo.h"
  17. #include "data/data_folder.h"
  18. #include "data/data_forum.h"
  19. #include "data/data_forum_topic.h"
  20. #include "data/data_saved_messages.h"
  21. #include "data/data_session.h"
  22. #include "data/data_file_origin.h"
  23. #include "data/data_histories.h"
  24. #include "data/data_cloud_themes.h"
  25. #include "base/unixtime.h"
  26. #include "base/crc32hash.h"
  27. #include "lang/lang_keys.h"
  28. #include "apiwrap.h"
  29. #include "api/api_chat_participants.h"
  30. #include "ui/boxes/confirm_box.h"
  31. #include "main/main_session.h"
  32. #include "main/main_session_settings.h"
  33. #include "main/main_domain.h"
  34. #include "main/main_app_config.h"
  35. #include "mtproto/mtproto_config.h"
  36. #include "core/application.h"
  37. #include "core/click_handler_types.h"
  38. #include "window/window_session_controller.h"
  39. #include "window/main_window.h" // Window::LogoNoMargin.
  40. #include "ui/image/image.h"
  41. #include "ui/chat/chat_style.h"
  42. #include "ui/empty_userpic.h"
  43. #include "ui/text/text_options.h"
  44. #include "ui/painter.h"
  45. #include "ui/unread_badge.h"
  46. #include "ui/ui_utility.h"
  47. #include "history/history.h"
  48. #include "history/view/history_view_element.h"
  49. #include "history/history_item.h"
  50. #include "storage/file_download.h"
  51. #include "storage/storage_account.h"
  52. #include "storage/storage_facade.h"
  53. #include "storage/storage_shared_media.h"
  54. namespace {
  55. constexpr auto kUpdateFullPeerTimeout = crl::time(5000); // Not more than once in 5 seconds.
  56. constexpr auto kUserpicSize = 160;
  57. using UpdateFlag = Data::PeerUpdate::Flag;
  58. [[nodiscard]] const std::vector<QString> &IgnoredReasons(
  59. not_null<Main::Session*> session) {
  60. return session->appConfig().ignoredRestrictionReasons();
  61. }
  62. [[nodiscard]] int ParseRegistrationDate(const QString &text) {
  63. // MM.YYYY
  64. if (text.size() != 7 || text[2] != '.') {
  65. return 0;
  66. }
  67. const auto month = text.mid(0, 2).toInt();
  68. const auto year = text.mid(3, 4).toInt();
  69. return (year > 2012 && year < 2100 && month > 0 && month <= 12)
  70. ? (year * 100) + month
  71. : 0;
  72. }
  73. [[nodiscard]] int RegistrationYear(int date) {
  74. const auto year = date / 100;
  75. return (year > 2012 && year < 2100) ? year : 0;
  76. }
  77. [[nodiscard]] int RegistrationMonth(int date) {
  78. const auto month = date % 100;
  79. return (month > 0 && month <= 12) ? month : 0;
  80. }
  81. } // namespace
  82. namespace Data {
  83. uint8 DecideColorIndex(PeerId peerId) {
  84. return Ui::DecideColorIndex(peerId.value & PeerId::kChatTypeMask);
  85. }
  86. PeerId FakePeerIdForJustName(const QString &name) {
  87. constexpr auto kShift = (0xFEULL << 32);
  88. const auto base = name.isEmpty()
  89. ? 777
  90. : base::crc32(name.constData(), name.size() * sizeof(QChar));
  91. return peerFromUser(kShift + std::abs(base));
  92. }
  93. bool UnavailableReason::sensitive() const {
  94. return reason == u"sensitive"_q;
  95. }
  96. UnavailableReason UnavailableReason::Sensitive() {
  97. return { u"sensitive"_q };
  98. }
  99. QString UnavailableReason::Compute(
  100. not_null<Main::Session*> session,
  101. const std::vector<UnavailableReason> &list) {
  102. const auto &skip = IgnoredReasons(session);
  103. auto &&filtered = ranges::views::all(
  104. list
  105. ) | ranges::views::filter([&](const Data::UnavailableReason &reason) {
  106. return !reason.sensitive()
  107. && !ranges::contains(skip, reason.reason);
  108. });
  109. const auto first = filtered.begin();
  110. return (first != filtered.end()) ? first->text : QString();
  111. }
  112. bool UnavailableReason::IgnoreSensitiveMark(
  113. not_null<Main::Session*> session) {
  114. return ranges::contains(
  115. IgnoredReasons(session),
  116. UnavailableReason::Sensitive().reason);
  117. }
  118. // We should get a full restriction in "{full}: {reason}" format and we
  119. // need to find an "-all" tag in {full}, otherwise ignore this restriction.
  120. std::vector<UnavailableReason> UnavailableReason::Extract(
  121. const MTPvector<MTPRestrictionReason> *list) {
  122. if (!list) {
  123. return {};
  124. }
  125. return ranges::views::all(
  126. list->v
  127. ) | ranges::views::filter([](const MTPRestrictionReason &restriction) {
  128. return restriction.match([&](const MTPDrestrictionReason &data) {
  129. const auto platform = data.vplatform().v;
  130. return false
  131. #ifdef OS_MAC_STORE
  132. || (platform == "ios"_q)
  133. #elif defined OS_WIN_STORE // OS_MAC_STORE
  134. || (platform == "ms"_q)
  135. #endif // OS_MAC_STORE || OS_WIN_STORE
  136. || (platform == "all"_q);
  137. });
  138. }) | ranges::views::transform([](const MTPRestrictionReason &restriction) {
  139. return restriction.match([&](const MTPDrestrictionReason &data) {
  140. return UnavailableReason{ qs(data.vreason()), qs(data.vtext()) };
  141. });
  142. }) | ranges::to_vector;
  143. }
  144. bool ApplyBotMenuButton(
  145. not_null<BotInfo*> info,
  146. const MTPBotMenuButton *button) {
  147. auto text = QString();
  148. auto url = QString();
  149. if (button) {
  150. button->match([&](const MTPDbotMenuButton &data) {
  151. text = qs(data.vtext());
  152. url = qs(data.vurl());
  153. }, [&](const auto &) {
  154. });
  155. }
  156. const auto changed = (info->botMenuButtonText != text)
  157. || (info->botMenuButtonUrl != url);
  158. info->botMenuButtonText = text;
  159. info->botMenuButtonUrl = url;
  160. return changed;
  161. }
  162. AllowedReactions Parse(
  163. const MTPChatReactions &value,
  164. int maxCount,
  165. bool paidEnabled) {
  166. return value.match([&](const MTPDchatReactionsNone &) {
  167. return AllowedReactions{
  168. .maxCount = maxCount,
  169. .paidEnabled = paidEnabled,
  170. };
  171. }, [&](const MTPDchatReactionsAll &data) {
  172. return AllowedReactions{
  173. .maxCount = maxCount,
  174. .type = (data.is_allow_custom()
  175. ? AllowedReactionsType::All
  176. : AllowedReactionsType::Default),
  177. .paidEnabled = paidEnabled,
  178. };
  179. }, [&](const MTPDchatReactionsSome &data) {
  180. return AllowedReactions{
  181. .some = ranges::views::all(
  182. data.vreactions().v
  183. ) | ranges::views::transform(
  184. ReactionFromMTP
  185. ) | ranges::to_vector,
  186. .maxCount = maxCount,
  187. .type = AllowedReactionsType::Some,
  188. .paidEnabled = paidEnabled,
  189. };
  190. });
  191. }
  192. PeerData *PeerFromInputMTP(
  193. not_null<Session*> owner,
  194. const MTPInputPeer &input) {
  195. return input.match([&](const MTPDinputPeerUser &data) {
  196. const auto user = owner->user(data.vuser_id().v);
  197. user->setAccessHash(data.vaccess_hash().v);
  198. return (PeerData*)user;
  199. }, [&](const MTPDinputPeerChat &data) {
  200. return (PeerData*)owner->chat(data.vchat_id().v);
  201. }, [&](const MTPDinputPeerChannel &data) {
  202. const auto channel = owner->channel(data.vchannel_id().v);
  203. channel->setAccessHash(data.vaccess_hash().v);
  204. return (PeerData*)channel;
  205. }, [&](const MTPDinputPeerSelf &data) {
  206. return (PeerData*)owner->session().user();
  207. }, [&](const auto &data) {
  208. return (PeerData*)nullptr;
  209. });
  210. }
  211. UserData *UserFromInputMTP(
  212. not_null<Session*> owner,
  213. const MTPInputUser &input) {
  214. return input.match([&](const MTPDinputUser &data) {
  215. const auto user = owner->user(data.vuser_id().v);
  216. user->setAccessHash(data.vaccess_hash().v);
  217. return user.get();
  218. }, [&](const MTPDinputUserSelf &data) {
  219. return owner->session().user().get();
  220. }, [](const auto &data) {
  221. return (UserData*)nullptr;
  222. });
  223. }
  224. } // namespace Data
  225. PeerClickHandler::PeerClickHandler(not_null<PeerData*> peer)
  226. : _peer(peer) {
  227. setProperty(kPeerLinkPeerIdProperty, peer->id.value);
  228. }
  229. void PeerClickHandler::onClick(ClickContext context) const {
  230. if (context.button != Qt::LeftButton) {
  231. return;
  232. }
  233. const auto my = context.other.value<ClickHandlerContext>();
  234. const auto window = [&]() -> Window::SessionController* {
  235. if (const auto controller = my.sessionWindow.get()) {
  236. return controller;
  237. }
  238. const auto &windows = _peer->session().windows();
  239. if (windows.empty()) {
  240. _peer->session().domain().activate(&_peer->session().account());
  241. if (windows.empty()) {
  242. return nullptr;
  243. }
  244. }
  245. return windows.front();
  246. }();
  247. if (window) {
  248. window->showPeer(_peer);
  249. }
  250. }
  251. PeerData::PeerData(not_null<Data::Session*> owner, PeerId id)
  252. : id(id)
  253. , _owner(owner)
  254. , _colorIndex(Data::DecideColorIndex(id)) {
  255. }
  256. Data::Session &PeerData::owner() const {
  257. return *_owner;
  258. }
  259. Main::Session &PeerData::session() const {
  260. return _owner->session();
  261. }
  262. Main::Account &PeerData::account() const {
  263. return session().account();
  264. }
  265. void PeerData::updateNameDelayed(
  266. const QString &newName,
  267. const QString &newNameOrPhone,
  268. const QString &newUsername) {
  269. if (_name == newName && _nameVersion > 1) {
  270. if (isUser()) {
  271. if (asUser()->nameOrPhone == newNameOrPhone
  272. && asUser()->editableUsername() == newUsername) {
  273. return;
  274. }
  275. } else if (isChannel()) {
  276. if (asChannel()->editableUsername() == newUsername) {
  277. return;
  278. }
  279. } else if (isChat()) {
  280. return;
  281. }
  282. }
  283. _name = newName;
  284. invalidateEmptyUserpic();
  285. auto flags = UpdateFlag::None | UpdateFlag::None;
  286. auto oldFirstLetters = base::flat_set<QChar>();
  287. const auto nameUpdated = (_nameVersion++ > 1);
  288. if (nameUpdated) {
  289. oldFirstLetters = nameFirstLetters();
  290. flags |= UpdateFlag::Name;
  291. }
  292. if (isUser()) {
  293. if (asUser()->editableUsername() != newUsername) {
  294. asUser()->setUsername(newUsername);
  295. flags |= UpdateFlag::Username;
  296. }
  297. asUser()->setNameOrPhone(newNameOrPhone);
  298. } else if (isChannel()) {
  299. if (asChannel()->editableUsername() != newUsername) {
  300. asChannel()->setUsername(newUsername);
  301. if (asChannel()->username().isEmpty()) {
  302. asChannel()->removeFlags(ChannelDataFlag::Username);
  303. } else {
  304. asChannel()->addFlags(ChannelDataFlag::Username);
  305. }
  306. flags |= UpdateFlag::Username;
  307. }
  308. }
  309. fillNames();
  310. if (nameUpdated) {
  311. session().changes().nameUpdated(this, std::move(oldFirstLetters));
  312. }
  313. if (flags) {
  314. session().changes().peerUpdated(this, flags);
  315. }
  316. }
  317. not_null<Ui::EmptyUserpic*> PeerData::ensureEmptyUserpic() const {
  318. if (!_userpicEmpty) {
  319. const auto user = asUser();
  320. _userpicEmpty = std::make_unique<Ui::EmptyUserpic>(
  321. Ui::EmptyUserpic::UserpicColor(colorIndex()),
  322. ((user && user->isInaccessible())
  323. ? Ui::EmptyUserpic::InaccessibleName()
  324. : name()));
  325. }
  326. return _userpicEmpty.get();
  327. }
  328. void PeerData::invalidateEmptyUserpic() {
  329. _userpicEmpty = nullptr;
  330. }
  331. void PeerData::checkTrustedPayForMessage() {
  332. if (!_checkedTrustedPayForMessage
  333. && !starsPerMessage()
  334. && session().local().peerTrustedPayForMessageRead()) {
  335. _checkedTrustedPayForMessage = 1;
  336. if (session().local().hasPeerTrustedPayForMessageEntry(id)) {
  337. session().local().clearPeerTrustedPayForMessage(id);
  338. }
  339. }
  340. }
  341. ClickHandlerPtr PeerData::createOpenLink() {
  342. return std::make_shared<PeerClickHandler>(this);
  343. }
  344. void PeerData::setUserpic(
  345. PhotoId photoId,
  346. const ImageLocation &location,
  347. bool hasVideo) {
  348. _userpicPhotoId = photoId;
  349. _userpicHasVideo = hasVideo ? 1 : 0;
  350. _userpic.set(&session(), ImageWithLocation{ .location = location });
  351. }
  352. void PeerData::setUserpicPhoto(const MTPPhoto &data) {
  353. const auto photoId = data.match([&](const MTPDphoto &data) {
  354. const auto photo = owner().processPhoto(data);
  355. photo->peer = this;
  356. return photo->id;
  357. }, [](const MTPDphotoEmpty &data) {
  358. return PhotoId(0);
  359. });
  360. if (_userpicPhotoId != photoId) {
  361. _userpicPhotoId = photoId;
  362. session().changes().peerUpdated(this, UpdateFlag::Photo);
  363. }
  364. }
  365. QImage *PeerData::userpicCloudImage(Ui::PeerUserpicView &view) const {
  366. if (!_userpic.isCurrentView(view.cloud)) {
  367. if (!_userpic.empty()) {
  368. view.cloud = _userpic.createView();
  369. _userpic.load(&session(), userpicOrigin());
  370. } else {
  371. view.cloud = nullptr;
  372. }
  373. view.cached = QImage();
  374. }
  375. if (const auto image = view.cloud.get(); image && !image->isNull()) {
  376. _userpicEmpty = nullptr;
  377. return image;
  378. } else if (isNotificationsUser()) {
  379. static auto result = Window::LogoNoMargin().scaledToWidth(
  380. kUserpicSize,
  381. Qt::SmoothTransformation);
  382. return &result;
  383. }
  384. return nullptr;
  385. }
  386. void PeerData::paintUserpic(
  387. Painter &p,
  388. Ui::PeerUserpicView &view,
  389. int x,
  390. int y,
  391. int size,
  392. bool forceCircle) const {
  393. const auto cloud = userpicCloudImage(view);
  394. const auto ratio = style::DevicePixelRatio();
  395. Ui::ValidateUserpicCache(
  396. view,
  397. cloud,
  398. cloud ? nullptr : ensureEmptyUserpic().get(),
  399. size * ratio,
  400. !forceCircle && isForum());
  401. p.drawImage(QRect(x, y, size, size), view.cached);
  402. }
  403. void PeerData::loadUserpic() {
  404. _userpic.load(&session(), userpicOrigin());
  405. }
  406. bool PeerData::hasUserpic() const {
  407. return !_userpic.empty();
  408. }
  409. Ui::PeerUserpicView PeerData::activeUserpicView() {
  410. return { .cloud = _userpic.empty() ? nullptr : _userpic.activeView() };
  411. }
  412. Ui::PeerUserpicView PeerData::createUserpicView() {
  413. if (_userpic.empty()) {
  414. return {};
  415. }
  416. auto result = _userpic.createView();
  417. _userpic.load(&session(), userpicPhotoOrigin());
  418. return { .cloud = result };
  419. }
  420. bool PeerData::useEmptyUserpic(Ui::PeerUserpicView &view) const {
  421. return !userpicCloudImage(view);
  422. }
  423. InMemoryKey PeerData::userpicUniqueKey(Ui::PeerUserpicView &view) const {
  424. return useEmptyUserpic(view)
  425. ? ensureEmptyUserpic()->uniqueKey()
  426. : inMemoryKey(_userpic.location());
  427. }
  428. QImage PeerData::GenerateUserpicImage(
  429. not_null<PeerData*> peer,
  430. Ui::PeerUserpicView &view,
  431. int size,
  432. std::optional<int> radius) {
  433. if (const auto userpic = peer->userpicCloudImage(view)) {
  434. auto image = userpic->scaled(
  435. { size, size },
  436. Qt::IgnoreAspectRatio,
  437. Qt::SmoothTransformation);
  438. const auto round = [&](int radius) {
  439. return Images::Round(
  440. std::move(image),
  441. Images::CornersMask(radius / style::DevicePixelRatio()));
  442. };
  443. if (radius == 0) {
  444. return image;
  445. } else if (radius) {
  446. return round(*radius);
  447. } else if (peer->isForum()) {
  448. return round(size * Ui::ForumUserpicRadiusMultiplier());
  449. } else {
  450. return Images::Circle(std::move(image));
  451. }
  452. }
  453. auto result = QImage(
  454. QSize(size, size),
  455. QImage::Format_ARGB32_Premultiplied);
  456. result.fill(Qt::transparent);
  457. Painter p(&result);
  458. if (radius == 0) {
  459. peer->ensureEmptyUserpic()->paintSquare(p, 0, 0, size, size);
  460. } else if (radius) {
  461. const auto r = *radius;
  462. peer->ensureEmptyUserpic()->paintRounded(p, 0, 0, size, size, r);
  463. } else if (peer->isForum()) {
  464. peer->ensureEmptyUserpic()->paintRounded(
  465. p,
  466. 0,
  467. 0,
  468. size,
  469. size,
  470. size * Ui::ForumUserpicRadiusMultiplier());
  471. } else {
  472. peer->ensureEmptyUserpic()->paintCircle(p, 0, 0, size, size);
  473. }
  474. p.end();
  475. return result;
  476. }
  477. ImageLocation PeerData::userpicLocation() const {
  478. return _userpic.location();
  479. }
  480. bool PeerData::userpicPhotoUnknown() const {
  481. return (_userpicPhotoId == kUnknownPhotoId);
  482. }
  483. PhotoId PeerData::userpicPhotoId() const {
  484. return userpicPhotoUnknown() ? 0 : _userpicPhotoId;
  485. }
  486. bool PeerData::userpicHasVideo() const {
  487. return _userpicHasVideo != 0;
  488. }
  489. Data::FileOrigin PeerData::userpicOrigin() const {
  490. return Data::FileOriginPeerPhoto(id);
  491. }
  492. Data::FileOrigin PeerData::userpicPhotoOrigin() const {
  493. return (isUser() && userpicPhotoId())
  494. ? Data::FileOriginUserPhoto(peerToUser(id).bare, userpicPhotoId())
  495. : Data::FileOrigin();
  496. }
  497. void PeerData::updateUserpic(
  498. PhotoId photoId,
  499. MTP::DcId dcId,
  500. bool hasVideo) {
  501. setUserpicChecked(
  502. photoId,
  503. ImageLocation(
  504. { StorageFileLocation(
  505. dcId,
  506. isSelf() ? peerToUser(id) : UserId(),
  507. MTP_inputPeerPhotoFileLocation(
  508. MTP_flags(0),
  509. input,
  510. MTP_long(photoId))) },
  511. kUserpicSize,
  512. kUserpicSize),
  513. hasVideo);
  514. }
  515. void PeerData::clearUserpic() {
  516. setUserpicChecked(PhotoId(), ImageLocation(), false);
  517. }
  518. void PeerData::setUserpicChecked(
  519. PhotoId photoId,
  520. const ImageLocation &location,
  521. bool hasVideo) {
  522. if (_userpicPhotoId != photoId
  523. || _userpic.location() != location
  524. || _userpicHasVideo != (hasVideo ? 1 : 0)) {
  525. const auto known = !userpicPhotoUnknown();
  526. setUserpic(photoId, location, hasVideo);
  527. session().changes().peerUpdated(this, UpdateFlag::Photo);
  528. if (known && isPremium() && userpicPhotoUnknown()) {
  529. updateFull();
  530. }
  531. }
  532. }
  533. auto PeerData::unavailableReasons() const
  534. -> const std::vector<Data::UnavailableReason> & {
  535. static const auto result = std::vector<Data::UnavailableReason>();
  536. return result;
  537. }
  538. QString PeerData::computeUnavailableReason() const {
  539. return Data::UnavailableReason::Compute(
  540. &session(),
  541. unavailableReasons());
  542. }
  543. bool PeerData::hasSensitiveContent() const {
  544. return _sensitiveContent == 1;
  545. }
  546. void PeerData::setUnavailableReasonsList(
  547. std::vector<Data::UnavailableReason> &&reasons) {
  548. Unexpected("PeerData::setUnavailableReasonsList.");
  549. }
  550. void PeerData::setUnavailableReasons(
  551. std::vector<Data::UnavailableReason> &&reasons) {
  552. const auto i = ranges::find(
  553. reasons,
  554. true,
  555. &Data::UnavailableReason::sensitive);
  556. const auto sensitive = (i != end(reasons));
  557. if (sensitive) {
  558. reasons.erase(i);
  559. }
  560. auto changed = (sensitive != hasSensitiveContent());
  561. if (changed) {
  562. setHasSensitiveContent(sensitive);
  563. }
  564. if (reasons != unavailableReasons()) {
  565. setUnavailableReasonsList(std::move(reasons));
  566. changed = true;
  567. }
  568. if (changed) {
  569. session().changes().peerUpdated(
  570. this,
  571. UpdateFlag::UnavailableReason);
  572. }
  573. }
  574. void PeerData::setHasSensitiveContent(bool has) {
  575. _sensitiveContent = has ? 1 : 0;
  576. if (has) {
  577. session().api().sensitiveContent().preload();
  578. }
  579. }
  580. // This is duplicated in CanPinMessagesValue().
  581. bool PeerData::canPinMessages() const {
  582. if (const auto user = asUser()) {
  583. return !user->amRestricted(ChatRestriction::PinMessages);
  584. } else if (const auto chat = asChat()) {
  585. return chat->amIn()
  586. && !chat->amRestricted(ChatRestriction::PinMessages);
  587. } else if (const auto channel = asChannel()) {
  588. return channel->isMegagroup()
  589. ? !channel->amRestricted(ChatRestriction::PinMessages)
  590. : ((channel->amCreator()
  591. || channel->adminRights() & ChatAdminRight::EditMessages));
  592. }
  593. Unexpected("Peer type in PeerData::canPinMessages.");
  594. }
  595. bool PeerData::canCreatePolls() const {
  596. if (const auto user = asUser()) {
  597. return user->isBot()
  598. && !user->isSupport()
  599. && !user->isRepliesChat()
  600. && !user->isVerifyCodes();
  601. }
  602. return Data::CanSend(this, ChatRestriction::SendPolls);
  603. }
  604. bool PeerData::canCreateTopics() const {
  605. if (const auto channel = asChannel()) {
  606. return channel->isForum()
  607. && !channel->amRestricted(ChatRestriction::CreateTopics);
  608. }
  609. return false;
  610. }
  611. bool PeerData::canManageTopics() const {
  612. if (const auto channel = asChannel()) {
  613. return channel->isForum()
  614. && (channel->amCreator()
  615. || (channel->adminRights() & ChatAdminRight::ManageTopics));
  616. }
  617. return false;
  618. }
  619. bool PeerData::canManageGifts() const {
  620. if (const auto channel = asChannel()) {
  621. return channel->canPostMessages();
  622. }
  623. return isSelf();
  624. }
  625. bool PeerData::canTransferGifts() const {
  626. if (const auto channel = asChannel()) {
  627. return channel->amCreator();
  628. }
  629. return isSelf();
  630. }
  631. bool PeerData::canEditMessagesIndefinitely() const {
  632. if (const auto user = asUser()) {
  633. return user->isSelf();
  634. } else if (const auto chat = asChat()) {
  635. return false;
  636. } else if (const auto channel = asChannel()) {
  637. return channel->isMegagroup()
  638. ? channel->canPinMessages()
  639. : channel->canEditMessages();
  640. }
  641. Unexpected("Peer type in PeerData::canEditMessagesIndefinitely.");
  642. }
  643. bool PeerData::canExportChatHistory() const {
  644. if (isRepliesChat() || isVerifyCodes() || !allowsForwarding()) {
  645. return false;
  646. } else if (const auto channel = asChannel()) {
  647. if (!channel->amIn() && channel->invitePeekExpires()) {
  648. return false;
  649. }
  650. }
  651. for (const auto &block : _owner->history(id)->blocks) {
  652. for (const auto &message : block->messages) {
  653. if (!message->data()->isService()) {
  654. return true;
  655. }
  656. }
  657. }
  658. if (const auto from = migrateFrom()) {
  659. return from->canExportChatHistory();
  660. }
  661. return false;
  662. }
  663. bool PeerData::setAbout(const QString &newAbout) {
  664. if (_about == newAbout) {
  665. return false;
  666. }
  667. _about = newAbout;
  668. session().changes().peerUpdated(this, UpdateFlag::About);
  669. return true;
  670. }
  671. void PeerData::checkFolder(FolderId folderId) {
  672. const auto folder = folderId
  673. ? owner().folderLoaded(folderId)
  674. : nullptr;
  675. if (const auto history = owner().historyLoaded(this)) {
  676. if (folder && history->folder() != folder) {
  677. owner().histories().requestDialogEntry(history);
  678. }
  679. }
  680. }
  681. void PeerData::clearBusinessBot() {
  682. if (const auto details = _barDetails.get()) {
  683. if (details->requestChatDate
  684. || details->paysPerMessage
  685. || !details->phoneCountryCode.isEmpty()) {
  686. details->businessBot = nullptr;
  687. details->businessBotManageUrl = QString();
  688. } else {
  689. _barDetails = nullptr;
  690. }
  691. }
  692. if (const auto settings = barSettings()) {
  693. setBarSettings(*settings
  694. & ~PeerBarSetting::BusinessBotPaused
  695. & ~PeerBarSetting::BusinessBotCanReply
  696. & ~PeerBarSetting::HasBusinessBot);
  697. }
  698. }
  699. void PeerData::setTranslationDisabled(bool disabled) {
  700. const auto flag = disabled
  701. ? TranslationFlag::Disabled
  702. : TranslationFlag::Enabled;
  703. if (_translationFlag != flag) {
  704. _translationFlag = flag;
  705. session().changes().peerUpdated(
  706. this,
  707. UpdateFlag::TranslationDisabled);
  708. }
  709. }
  710. PeerData::TranslationFlag PeerData::translationFlag() const {
  711. return _translationFlag;
  712. }
  713. void PeerData::saveTranslationDisabled(bool disabled) {
  714. setTranslationDisabled(disabled);
  715. using Flag = MTPmessages_TogglePeerTranslations::Flag;
  716. session().api().request(MTPmessages_TogglePeerTranslations(
  717. MTP_flags(disabled ? Flag::f_disabled : Flag()),
  718. input
  719. )).send();
  720. }
  721. void PeerData::setBarSettings(const MTPPeerSettings &data) {
  722. data.match([&](const MTPDpeerSettings &data) {
  723. const auto wasPaysPerMessage = paysPerMessage();
  724. if (!data.vbusiness_bot_id()
  725. && !data.vrequest_chat_title()
  726. && !data.vcharge_paid_message_stars()
  727. && !data.vphone_country()
  728. && !data.vregistration_month()
  729. && !data.vname_change_date()
  730. && !data.vphoto_change_date()) {
  731. _barDetails = nullptr;
  732. } else if (!_barDetails) {
  733. _barDetails = std::make_unique<PeerBarDetails>();
  734. }
  735. if (_barDetails) {
  736. _barDetails->phoneCountryCode
  737. = qs(data.vphone_country().value_or_empty());
  738. _barDetails->registrationDate = ParseRegistrationDate(
  739. data.vregistration_month().value_or_empty());
  740. _barDetails->nameChangeDate
  741. = data.vname_change_date().value_or_empty();
  742. _barDetails->photoChangeDate
  743. = data.vphoto_change_date().value_or_empty();
  744. _barDetails->requestChatTitle
  745. = qs(data.vrequest_chat_title().value_or_empty());
  746. _barDetails->requestChatDate
  747. = data.vrequest_chat_date().value_or_empty();
  748. _barDetails->businessBot = data.vbusiness_bot_id()
  749. ? _owner->user(data.vbusiness_bot_id()->v).get()
  750. : nullptr;
  751. _barDetails->businessBotManageUrl
  752. = qs(data.vbusiness_bot_manage_url().value_or_empty());
  753. _barDetails->paysPerMessage
  754. = data.vcharge_paid_message_stars().value_or_empty();
  755. }
  756. using Flag = PeerBarSetting;
  757. setBarSettings((data.is_add_contact() ? Flag::AddContact : Flag())
  758. | (data.is_autoarchived() ? Flag::AutoArchived : Flag())
  759. | (data.is_block_contact() ? Flag::BlockContact : Flag())
  760. //| (data.is_invite_members() ? Flag::InviteMembers : Flag())
  761. | (data.is_need_contacts_exception()
  762. ? Flag::NeedContactsException
  763. : Flag())
  764. //| (data.is_report_geo() ? Flag::ReportGeo : Flag())
  765. | (data.is_report_spam() ? Flag::ReportSpam : Flag())
  766. | (data.is_share_contact() ? Flag::ShareContact : Flag())
  767. | (data.vrequest_chat_title() ? Flag::RequestChat : Flag())
  768. | (data.vbusiness_bot_id() ? Flag::HasBusinessBot : Flag())
  769. | (data.is_request_chat_broadcast()
  770. ? Flag::RequestChatIsBroadcast
  771. : Flag())
  772. | (data.is_business_bot_paused()
  773. ? Flag::BusinessBotPaused
  774. : Flag())
  775. | (data.is_business_bot_can_reply()
  776. ? Flag::BusinessBotCanReply
  777. : Flag()));
  778. if (wasPaysPerMessage != paysPerMessage()) {
  779. session().changes().peerUpdated(
  780. this,
  781. UpdateFlag::PaysPerMessage);
  782. }
  783. });
  784. }
  785. int PeerData::paysPerMessage() const {
  786. return _barDetails ? _barDetails->paysPerMessage : 0;
  787. }
  788. void PeerData::clearPaysPerMessage() {
  789. if (const auto details = _barDetails.get()) {
  790. if (details->paysPerMessage) {
  791. if (details->businessBot
  792. || details->requestChatDate
  793. || !details->phoneCountryCode.isEmpty()) {
  794. details->paysPerMessage = 0;
  795. } else {
  796. _barDetails = nullptr;
  797. }
  798. session().changes().peerUpdated(
  799. this,
  800. UpdateFlag::PaysPerMessage);
  801. }
  802. }
  803. }
  804. QString PeerData::requestChatTitle() const {
  805. return _barDetails ? _barDetails->requestChatTitle : QString();
  806. }
  807. TimeId PeerData::requestChatDate() const {
  808. return _barDetails ? _barDetails->requestChatDate : 0;
  809. }
  810. UserData *PeerData::businessBot() const {
  811. return _barDetails ? _barDetails->businessBot : nullptr;
  812. }
  813. QString PeerData::businessBotManageUrl() const {
  814. return _barDetails ? _barDetails->businessBotManageUrl : QString();
  815. }
  816. QString PeerData::phoneCountryCode() const {
  817. return _barDetails ? _barDetails->phoneCountryCode : QString();
  818. }
  819. int PeerData::registrationMonth() const {
  820. return _barDetails
  821. ? RegistrationMonth(_barDetails->registrationDate)
  822. : 0;
  823. }
  824. int PeerData::registrationYear() const {
  825. return _barDetails ? RegistrationYear(_barDetails->registrationDate) : 0;
  826. }
  827. TimeId PeerData::nameChangeDate() const {
  828. return _barDetails ? _barDetails->nameChangeDate : 0;
  829. }
  830. TimeId PeerData::photoChangeDate() const {
  831. return _barDetails ? _barDetails->photoChangeDate : 0;
  832. }
  833. bool PeerData::changeColorIndex(
  834. const tl::conditional<MTPint> &cloudColorIndex) {
  835. return cloudColorIndex
  836. ? changeColorIndex(cloudColorIndex->v)
  837. : clearColorIndex();
  838. }
  839. bool PeerData::changeBackgroundEmojiId(
  840. const tl::conditional<MTPlong> &cloudBackgroundEmoji) {
  841. return changeBackgroundEmojiId(cloudBackgroundEmoji
  842. ? cloudBackgroundEmoji->v
  843. : DocumentId());
  844. }
  845. bool PeerData::changeColor(
  846. const tl::conditional<MTPPeerColor> &cloudColor) {
  847. const auto changed1 = cloudColor
  848. ? changeColorIndex(cloudColor->data().vcolor())
  849. : clearColorIndex();
  850. const auto changed2 = changeBackgroundEmojiId(cloudColor
  851. ? cloudColor->data().vbackground_emoji_id().value_or_empty()
  852. : DocumentId());
  853. return changed1 || changed2;
  854. }
  855. void PeerData::fillNames() {
  856. _nameWords.clear();
  857. _nameFirstLetters.clear();
  858. auto toIndexList = QStringList();
  859. auto appendToIndex = [&](const QString &value) {
  860. if (!value.isEmpty()) {
  861. toIndexList.push_back(TextUtilities::RemoveAccents(value));
  862. }
  863. };
  864. appendToIndex(name());
  865. const auto appendTranslit = !toIndexList.isEmpty()
  866. && cRussianLetters().match(toIndexList.front()).hasMatch();
  867. if (appendTranslit) {
  868. appendToIndex(translitRusEng(toIndexList.front()));
  869. }
  870. if (const auto user = asUser()) {
  871. if (user->nameOrPhone != name()) {
  872. appendToIndex(user->nameOrPhone);
  873. }
  874. appendToIndex(user->username());
  875. if (isSelf()) {
  876. const auto english = u"Saved messages"_q;
  877. const auto localized = tr::lng_saved_messages(tr::now);
  878. appendToIndex(english);
  879. if (localized != english) {
  880. appendToIndex(localized);
  881. }
  882. } else if (isRepliesChat()) {
  883. const auto english = u"Replies"_q;
  884. const auto localized = tr::lng_replies_messages(tr::now);
  885. appendToIndex(english);
  886. if (localized != english) {
  887. appendToIndex(localized);
  888. }
  889. } else if (isVerifyCodes()) {
  890. const auto english = u"Verification Codes"_q;
  891. const auto localized = tr::lng_verification_codes(tr::now);
  892. appendToIndex(english);
  893. if (localized != english) {
  894. appendToIndex(localized);
  895. }
  896. }
  897. } else if (const auto channel = asChannel()) {
  898. appendToIndex(channel->username());
  899. }
  900. auto toIndex = toIndexList.join(' ');
  901. toIndex += ' ' + rusKeyboardLayoutSwitch(toIndex);
  902. const auto namesList = TextUtilities::PrepareSearchWords(toIndex);
  903. for (const auto &name : namesList) {
  904. _nameWords.insert(name);
  905. _nameFirstLetters.insert(name[0]);
  906. }
  907. }
  908. PeerData::~PeerData() = default;
  909. void PeerData::updateFull() {
  910. if (!_lastFullUpdate
  911. || crl::now() > _lastFullUpdate + kUpdateFullPeerTimeout) {
  912. updateFullForced();
  913. }
  914. }
  915. void PeerData::updateFullForced() {
  916. session().api().requestFullPeer(this);
  917. if (const auto channel = asChannel()) {
  918. if (!channel->amCreator() && !channel->inviter) {
  919. session().api().chatParticipants().requestSelf(channel);
  920. }
  921. }
  922. }
  923. void PeerData::fullUpdated() {
  924. _lastFullUpdate = crl::now();
  925. setLoadedStatus(LoadedStatus::Full);
  926. }
  927. UserData *PeerData::asBot() {
  928. return isBot() ? static_cast<UserData*>(this) : nullptr;
  929. }
  930. const UserData *PeerData::asBot() const {
  931. return isBot()
  932. ? static_cast<const UserData*>(this)
  933. : nullptr;
  934. }
  935. UserData *PeerData::asUser() {
  936. return isUser() ? static_cast<UserData*>(this) : nullptr;
  937. }
  938. const UserData *PeerData::asUser() const {
  939. return isUser() ? static_cast<const UserData*>(this) : nullptr;
  940. }
  941. ChatData *PeerData::asChat() {
  942. return isChat() ? static_cast<ChatData*>(this) : nullptr;
  943. }
  944. const ChatData *PeerData::asChat() const {
  945. return isChat() ? static_cast<const ChatData*>(this) : nullptr;
  946. }
  947. ChannelData *PeerData::asChannel() {
  948. return isChannel() ? static_cast<ChannelData*>(this) : nullptr;
  949. }
  950. const ChannelData *PeerData::asChannel() const {
  951. return isChannel()
  952. ? static_cast<const ChannelData*>(this)
  953. : nullptr;
  954. }
  955. ChannelData *PeerData::asMegagroup() {
  956. return isMegagroup() ? static_cast<ChannelData*>(this) : nullptr;
  957. }
  958. const ChannelData *PeerData::asMegagroup() const {
  959. return isMegagroup()
  960. ? static_cast<const ChannelData*>(this)
  961. : nullptr;
  962. }
  963. ChannelData *PeerData::asBroadcast() {
  964. return isBroadcast() ? static_cast<ChannelData*>(this) : nullptr;
  965. }
  966. const ChannelData *PeerData::asBroadcast() const {
  967. return isBroadcast()
  968. ? static_cast<const ChannelData*>(this)
  969. : nullptr;
  970. }
  971. ChatData *PeerData::asChatNotMigrated() {
  972. if (const auto chat = asChat()) {
  973. return chat->migrateTo() ? nullptr : chat;
  974. }
  975. return nullptr;
  976. }
  977. const ChatData *PeerData::asChatNotMigrated() const {
  978. if (const auto chat = asChat()) {
  979. return chat->migrateTo() ? nullptr : chat;
  980. }
  981. return nullptr;
  982. }
  983. ChannelData *PeerData::asChannelOrMigrated() {
  984. if (const auto channel = asChannel()) {
  985. return channel;
  986. }
  987. return migrateTo();
  988. }
  989. const ChannelData *PeerData::asChannelOrMigrated() const {
  990. if (const auto channel = asChannel()) {
  991. return channel;
  992. }
  993. return migrateTo();
  994. }
  995. ChatData *PeerData::migrateFrom() const {
  996. if (const auto megagroup = asMegagroup()) {
  997. return megagroup->amIn()
  998. ? megagroup->getMigrateFromChat()
  999. : nullptr;
  1000. }
  1001. return nullptr;
  1002. }
  1003. ChannelData *PeerData::migrateTo() const {
  1004. if (const auto chat = asChat()) {
  1005. if (const auto result = chat->getMigrateToChannel()) {
  1006. return result->amIn() ? result : nullptr;
  1007. }
  1008. }
  1009. return nullptr;
  1010. }
  1011. not_null<PeerData*> PeerData::migrateToOrMe() {
  1012. if (const auto channel = migrateTo()) {
  1013. return channel;
  1014. }
  1015. return this;
  1016. }
  1017. not_null<const PeerData*> PeerData::migrateToOrMe() const {
  1018. if (const auto channel = migrateTo()) {
  1019. return channel;
  1020. }
  1021. return this;
  1022. }
  1023. const QString &PeerData::topBarNameText() const {
  1024. if (const auto to = migrateTo()) {
  1025. return to->topBarNameText();
  1026. } else if (const auto user = asUser()) {
  1027. if (!user->nameOrPhone.isEmpty()) {
  1028. return user->nameOrPhone;
  1029. }
  1030. }
  1031. return _name;
  1032. }
  1033. int PeerData::nameVersion() const {
  1034. return _nameVersion;
  1035. }
  1036. const QString &PeerData::name() const {
  1037. if (const auto to = migrateTo()) {
  1038. return to->name();
  1039. }
  1040. return _name;
  1041. }
  1042. const QString &PeerData::shortName() const {
  1043. if (const auto user = asUser()) {
  1044. return user->firstName.isEmpty() ? user->lastName : user->firstName;
  1045. }
  1046. return _name;
  1047. }
  1048. QString PeerData::username() const {
  1049. if (const auto user = asUser()) {
  1050. return user->username();
  1051. } else if (const auto channel = asChannel()) {
  1052. return channel->username();
  1053. }
  1054. return QString();
  1055. }
  1056. QString PeerData::editableUsername() const {
  1057. if (const auto user = asUser()) {
  1058. return user->editableUsername();
  1059. } else if (const auto channel = asChannel()) {
  1060. return channel->editableUsername();
  1061. }
  1062. return QString();
  1063. }
  1064. const std::vector<QString> &PeerData::usernames() const {
  1065. if (const auto user = asUser()) {
  1066. return user->usernames();
  1067. } else if (const auto channel = asChannel()) {
  1068. return channel->usernames();
  1069. }
  1070. static const auto kEmpty = std::vector<QString>();
  1071. return kEmpty;
  1072. }
  1073. bool PeerData::isUsernameEditable(QString username) const {
  1074. if (const auto user = asUser()) {
  1075. return user->isUsernameEditable(username);
  1076. } else if (const auto channel = asChannel()) {
  1077. return channel->isUsernameEditable(username);
  1078. }
  1079. return false;
  1080. }
  1081. bool PeerData::changeColorIndex(uint8 index) {
  1082. index %= Ui::kColorIndexCount;
  1083. if (_colorIndexCloud && _colorIndex == index) {
  1084. return false;
  1085. }
  1086. _colorIndexCloud = 1;
  1087. _colorIndex = index;
  1088. return true;
  1089. }
  1090. bool PeerData::clearColorIndex() {
  1091. if (!_colorIndexCloud) {
  1092. return false;
  1093. }
  1094. _colorIndexCloud = 0;
  1095. _colorIndex = Data::DecideColorIndex(id);
  1096. return true;
  1097. }
  1098. DocumentId PeerData::backgroundEmojiId() const {
  1099. return _backgroundEmojiId;
  1100. }
  1101. bool PeerData::changeBackgroundEmojiId(DocumentId id) {
  1102. if (_backgroundEmojiId == id) {
  1103. return false;
  1104. }
  1105. _backgroundEmojiId = id;
  1106. return true;
  1107. }
  1108. void PeerData::setEmojiStatus(const MTPEmojiStatus &status) {
  1109. const auto parsed = owner().emojiStatuses().parse(status);
  1110. setEmojiStatus(parsed.id, parsed.until);
  1111. }
  1112. void PeerData::setEmojiStatus(EmojiStatusId emojiStatusId, TimeId until) {
  1113. if (_emojiStatusId != emojiStatusId) {
  1114. _emojiStatusId = emojiStatusId;
  1115. session().changes().peerUpdated(this, UpdateFlag::EmojiStatus);
  1116. }
  1117. owner().emojiStatuses().registerAutomaticClear(this, until);
  1118. }
  1119. EmojiStatusId PeerData::emojiStatusId() const {
  1120. return _emojiStatusId;
  1121. }
  1122. bool PeerData::isBot() const {
  1123. if (const auto user = asUser()) {
  1124. return user->isBot();
  1125. }
  1126. return false;
  1127. }
  1128. bool PeerData::isSelf() const {
  1129. if (const auto user = asUser()) {
  1130. return (user->flags() & UserDataFlag::Self);
  1131. }
  1132. return false;
  1133. }
  1134. bool PeerData::isVerified() const {
  1135. if (const auto user = asUser()) {
  1136. return user->isVerified();
  1137. } else if (const auto channel = asChannel()) {
  1138. return channel->isVerified();
  1139. }
  1140. return false;
  1141. }
  1142. bool PeerData::isPremium() const {
  1143. if (const auto user = asUser()) {
  1144. return user->isPremium();
  1145. }
  1146. return false;
  1147. }
  1148. bool PeerData::isScam() const {
  1149. if (const auto user = asUser()) {
  1150. return user->isScam();
  1151. } else if (const auto channel = asChannel()) {
  1152. return channel->isScam();
  1153. }
  1154. return false;
  1155. }
  1156. bool PeerData::isFake() const {
  1157. if (const auto user = asUser()) {
  1158. return user->isFake();
  1159. } else if (const auto channel = asChannel()) {
  1160. return channel->isFake();
  1161. }
  1162. return false;
  1163. }
  1164. bool PeerData::isMegagroup() const {
  1165. if (const auto channel = asChannel()) {
  1166. return channel->isMegagroup();
  1167. }
  1168. return false;
  1169. }
  1170. bool PeerData::isBroadcast() const {
  1171. if (const auto channel = asChannel()) {
  1172. return channel->isBroadcast();
  1173. }
  1174. return false;
  1175. }
  1176. bool PeerData::isForum() const {
  1177. if (const auto channel = asChannel()) {
  1178. return channel->isForum();
  1179. }
  1180. return false;
  1181. }
  1182. bool PeerData::isGigagroup() const {
  1183. if (const auto channel = asChannel()) {
  1184. return channel->isGigagroup();
  1185. }
  1186. return false;
  1187. }
  1188. bool PeerData::isRepliesChat() const {
  1189. constexpr auto kProductionId = peerFromUser(1271266957);
  1190. constexpr auto kTestId = peerFromUser(708513);
  1191. if (id != kTestId && id != kProductionId) {
  1192. return false;
  1193. }
  1194. return ((session().mtp().environment() == MTP::Environment::Production)
  1195. ? kProductionId
  1196. : kTestId) == id;
  1197. }
  1198. bool PeerData::isVerifyCodes() const {
  1199. constexpr auto kVerifyCodesId = peerFromUser(489000);
  1200. return (id == kVerifyCodesId);
  1201. }
  1202. bool PeerData::sharedMediaInfo() const {
  1203. return isSelf() || isRepliesChat();
  1204. }
  1205. bool PeerData::savedSublistsInfo() const {
  1206. return isSelf() && owner().savedMessages().supported();
  1207. }
  1208. bool PeerData::hasStoriesHidden() const {
  1209. if (const auto user = asUser()) {
  1210. return user->hasStoriesHidden();
  1211. } else if (const auto channel = asChannel()) {
  1212. return channel->hasStoriesHidden();
  1213. }
  1214. return false;
  1215. }
  1216. void PeerData::setStoriesHidden(bool hidden) {
  1217. if (const auto user = asUser()) {
  1218. user->setFlags(hidden
  1219. ? (user->flags() | UserDataFlag::StoriesHidden)
  1220. : (user->flags() & ~UserDataFlag::StoriesHidden));
  1221. } else if (const auto channel = asChannel()) {
  1222. channel->setFlags(hidden
  1223. ? (channel->flags() | ChannelDataFlag::StoriesHidden)
  1224. : (channel->flags() & ~ChannelDataFlag::StoriesHidden));
  1225. } else {
  1226. Unexpected("PeerData::setStoriesHidden for non-user/non-channel.");
  1227. }
  1228. }
  1229. Ui::BotVerifyDetails *PeerData::botVerifyDetails() const {
  1230. if (const auto user = asUser()) {
  1231. return user->botVerifyDetails();
  1232. } else if (const auto channel = asChannel()) {
  1233. return channel->botVerifyDetails();
  1234. }
  1235. return nullptr;
  1236. }
  1237. Data::Forum *PeerData::forum() const {
  1238. if (const auto channel = asChannel()) {
  1239. return channel->forum();
  1240. }
  1241. return nullptr;
  1242. }
  1243. Data::ForumTopic *PeerData::forumTopicFor(MsgId rootId) const {
  1244. if (!rootId) {
  1245. return nullptr;
  1246. } else if (const auto forum = this->forum()) {
  1247. return forum->topicFor(rootId);
  1248. }
  1249. return nullptr;
  1250. }
  1251. bool PeerData::allowsForwarding() const {
  1252. if (const auto user = asUser()) {
  1253. return true;
  1254. } else if (const auto channel = asChannel()) {
  1255. return channel->allowsForwarding();
  1256. } else if (const auto chat = asChat()) {
  1257. return chat->allowsForwarding();
  1258. }
  1259. return false;
  1260. }
  1261. Data::RestrictionCheckResult PeerData::amRestricted(
  1262. ChatRestriction right) const {
  1263. using Result = Data::RestrictionCheckResult;
  1264. const auto allowByAdminRights = [](auto right, auto chat) -> bool {
  1265. if (right == ChatRestriction::AddParticipants) {
  1266. return chat->adminRights() & ChatAdminRight::InviteByLinkOrAdd;
  1267. } else if (right == ChatRestriction::ChangeInfo) {
  1268. return chat->adminRights() & ChatAdminRight::ChangeInfo;
  1269. } else if (right == ChatRestriction::CreateTopics) {
  1270. return chat->adminRights() & ChatAdminRight::ManageTopics;
  1271. } else if (right == ChatRestriction::PinMessages) {
  1272. return chat->adminRights() & ChatAdminRight::PinMessages;
  1273. } else {
  1274. return chat->hasAdminRights();
  1275. }
  1276. };
  1277. if (const auto user = asUser()) {
  1278. if (user->requiresPremiumToWrite() && !user->session().premium()) {
  1279. return Result::Explicit();
  1280. }
  1281. return (right == ChatRestriction::SendVoiceMessages
  1282. || right == ChatRestriction::SendVideoMessages)
  1283. ? ((user->flags() & UserDataFlag::VoiceMessagesForbidden)
  1284. ? Result::Explicit()
  1285. : Result::Allowed())
  1286. : (right == ChatRestriction::PinMessages)
  1287. ? ((user->flags() & UserDataFlag::CanPinMessages)
  1288. ? Result::Allowed()
  1289. : Result::Explicit())
  1290. : Result::Allowed();
  1291. } else if (const auto channel = asChannel()) {
  1292. const auto defaultRestrictions = channel->defaultRestrictions()
  1293. | (channel->isPublic()
  1294. ? (ChatRestriction::PinMessages
  1295. | ChatRestriction::ChangeInfo)
  1296. : ChatRestrictions(0));
  1297. return (channel->amCreator() || allowByAdminRights(right, channel))
  1298. ? Result::Allowed()
  1299. : ((defaultRestrictions & right)
  1300. && !channel->unrestrictedByBoosts())
  1301. ? Result::WithEveryone()
  1302. : (channel->restrictions() & right)
  1303. ? Result::Explicit()
  1304. : Result::Allowed();
  1305. } else if (const auto chat = asChat()) {
  1306. return (chat->amCreator() || allowByAdminRights(right, chat))
  1307. ? Result::Allowed()
  1308. : (chat->defaultRestrictions() & right)
  1309. ? Result::WithEveryone()
  1310. : Result::Allowed();
  1311. }
  1312. return Result::Allowed();
  1313. }
  1314. bool PeerData::amAnonymous() const {
  1315. if (const auto channel = asChannel()) {
  1316. return channel->isBroadcast()
  1317. ? !channel->signatureProfiles()
  1318. : (channel->adminRights() & ChatAdminRight::Anonymous);
  1319. }
  1320. return false;
  1321. }
  1322. bool PeerData::canRevokeFullHistory() const {
  1323. if (const auto user = asUser()) {
  1324. return !isSelf()
  1325. && (!user->isBot() || user->isSupport())
  1326. && !user->isInaccessible()
  1327. && session().serverConfig().revokePrivateInbox
  1328. && (session().serverConfig().revokePrivateTimeLimit == 0x7FFFFFFF);
  1329. } else if (const auto chat = asChat()) {
  1330. return chat->amCreator();
  1331. } else if (const auto megagroup = asMegagroup()) {
  1332. return megagroup->amCreator()
  1333. && megagroup->membersCountKnown()
  1334. && megagroup->canDelete();
  1335. }
  1336. return false;
  1337. }
  1338. bool PeerData::slowmodeApplied() const {
  1339. if (const auto channel = asChannel()) {
  1340. return !channel->amCreator()
  1341. && !channel->hasAdminRights()
  1342. && (channel->flags() & ChannelDataFlag::SlowmodeEnabled);
  1343. }
  1344. return false;
  1345. }
  1346. rpl::producer<bool> PeerData::slowmodeAppliedValue() const {
  1347. using namespace rpl::mappers;
  1348. const auto channel = asChannel();
  1349. if (!channel) {
  1350. return rpl::single(false);
  1351. }
  1352. auto hasAdminRights = channel->adminRightsValue(
  1353. ) | rpl::map([=] {
  1354. return channel->hasAdminRights();
  1355. }) | rpl::distinct_until_changed();
  1356. auto slowmodeEnabled = channel->flagsValue(
  1357. ) | rpl::filter([=](const ChannelData::Flags::Change &change) {
  1358. return (change.diff & ChannelDataFlag::SlowmodeEnabled) != 0;
  1359. }) | rpl::map([=](const ChannelData::Flags::Change &change) {
  1360. return (change.value & ChannelDataFlag::SlowmodeEnabled) != 0;
  1361. }) | rpl::distinct_until_changed();
  1362. return rpl::combine(
  1363. std::move(hasAdminRights),
  1364. std::move(slowmodeEnabled),
  1365. !_1 && _2);
  1366. }
  1367. int PeerData::slowmodeSecondsLeft() const {
  1368. if (const auto channel = asChannel()) {
  1369. if (const auto seconds = channel->slowmodeSeconds()) {
  1370. if (const auto last = channel->slowmodeLastMessage()) {
  1371. const auto now = base::unixtime::now();
  1372. return std::max(seconds - (now - last), 0);
  1373. }
  1374. }
  1375. }
  1376. return 0;
  1377. }
  1378. bool PeerData::canManageGroupCall() const {
  1379. if (const auto chat = asChat()) {
  1380. return chat->amCreator()
  1381. || (chat->adminRights() & ChatAdminRight::ManageCall);
  1382. } else if (const auto group = asChannel()) {
  1383. return group->amCreator()
  1384. || (group->adminRights() & ChatAdminRight::ManageCall);
  1385. }
  1386. return false;
  1387. }
  1388. int PeerData::starsPerMessage() const {
  1389. if (const auto user = asUser()) {
  1390. return user->starsPerMessage();
  1391. } else if (const auto channel = asChannel()) {
  1392. return channel->starsPerMessage();
  1393. }
  1394. return 0;
  1395. }
  1396. int PeerData::starsPerMessageChecked() const {
  1397. if (const auto channel = asChannel()) {
  1398. return (channel->adminRights() || channel->amCreator())
  1399. ? 0
  1400. : channel->starsPerMessage();
  1401. }
  1402. return starsPerMessage();
  1403. }
  1404. Data::GroupCall *PeerData::groupCall() const {
  1405. if (const auto chat = asChat()) {
  1406. return chat->groupCall();
  1407. } else if (const auto group = asChannel()) {
  1408. return group->groupCall();
  1409. }
  1410. return nullptr;
  1411. }
  1412. PeerId PeerData::groupCallDefaultJoinAs() const {
  1413. if (const auto chat = asChat()) {
  1414. return chat->groupCallDefaultJoinAs();
  1415. } else if (const auto group = asChannel()) {
  1416. return group->groupCallDefaultJoinAs();
  1417. }
  1418. return 0;
  1419. }
  1420. void PeerData::setThemeEmoji(const QString &emoticon) {
  1421. if (_themeEmoticon == emoticon) {
  1422. return;
  1423. }
  1424. if (Ui::Emoji::Find(_themeEmoticon) == Ui::Emoji::Find(emoticon)) {
  1425. _themeEmoticon = emoticon;
  1426. return;
  1427. }
  1428. _themeEmoticon = emoticon;
  1429. if (!emoticon.isEmpty()
  1430. && !owner().cloudThemes().themeForEmoji(emoticon)) {
  1431. owner().cloudThemes().refreshChatThemes();
  1432. }
  1433. session().changes().peerUpdated(this, UpdateFlag::ChatThemeEmoji);
  1434. }
  1435. const QString &PeerData::themeEmoji() const {
  1436. return _themeEmoticon;
  1437. }
  1438. void PeerData::setWallPaper(
  1439. std::optional<Data::WallPaper> paper,
  1440. bool overriden) {
  1441. const auto paperChanged = (paper || _wallPaper)
  1442. && (!paper || !_wallPaper || !_wallPaper->equals(*paper));
  1443. if (paperChanged) {
  1444. _wallPaper = paper
  1445. ? std::make_unique<Data::WallPaper>(std::move(*paper))
  1446. : nullptr;
  1447. }
  1448. const auto overridenValue = overriden ? 1 : 0;
  1449. const auto overridenChanged = (_wallPaperOverriden != overridenValue);
  1450. if (overridenChanged) {
  1451. _wallPaperOverriden = overridenValue;
  1452. }
  1453. if (paperChanged || overridenChanged) {
  1454. session().changes().peerUpdated(this, UpdateFlag::ChatWallPaper);
  1455. }
  1456. }
  1457. bool PeerData::wallPaperOverriden() const {
  1458. return _wallPaperOverriden != 0;
  1459. }
  1460. const Data::WallPaper *PeerData::wallPaper() const {
  1461. return _wallPaper.get();
  1462. }
  1463. bool PeerData::hasActiveStories() const {
  1464. if (const auto user = asUser()) {
  1465. return user->hasActiveStories();
  1466. } else if (const auto channel = asChannel()) {
  1467. return channel->hasActiveStories();
  1468. }
  1469. return false;
  1470. }
  1471. bool PeerData::hasUnreadStories() const {
  1472. if (const auto user = asUser()) {
  1473. return user->hasUnreadStories();
  1474. } else if (const auto channel = asChannel()) {
  1475. return channel->hasUnreadStories();
  1476. }
  1477. return false;
  1478. }
  1479. void PeerData::setStoriesState(StoriesState state) {
  1480. if (const auto user = asUser()) {
  1481. return user->setStoriesState(state);
  1482. } else if (const auto channel = asChannel()) {
  1483. return channel->setStoriesState(state);
  1484. } else {
  1485. Unexpected("PeerData::setStoriesState for non-user/non-channel.");
  1486. }
  1487. }
  1488. int PeerData::peerGiftsCount() const {
  1489. if (const auto user = asUser()) {
  1490. return user->peerGiftsCount();
  1491. } else if (const auto channel = asChannel()) {
  1492. return channel->peerGiftsCount();
  1493. }
  1494. return 0;
  1495. }
  1496. void PeerData::setIsBlocked(bool is) {
  1497. const auto status = is
  1498. ? BlockStatus::Blocked
  1499. : BlockStatus::NotBlocked;
  1500. if (_blockStatus != status) {
  1501. _blockStatus = status;
  1502. if (const auto user = asUser()) {
  1503. const auto flags = user->flags();
  1504. if (is) {
  1505. user->setFlags(flags | UserDataFlag::Blocked);
  1506. } else {
  1507. user->setFlags(flags & ~UserDataFlag::Blocked);
  1508. }
  1509. }
  1510. session().changes().peerUpdated(this, UpdateFlag::IsBlocked);
  1511. }
  1512. }
  1513. void PeerData::setLoadedStatus(LoadedStatus status) {
  1514. _loadedStatus = status;
  1515. }
  1516. TimeId PeerData::messagesTTL() const {
  1517. return _ttlPeriod;
  1518. }
  1519. void PeerData::setMessagesTTL(TimeId period) {
  1520. if (_ttlPeriod != period) {
  1521. _ttlPeriod = period;
  1522. session().changes().peerUpdated(
  1523. this,
  1524. Data::PeerUpdate::Flag::MessagesTTL);
  1525. }
  1526. }
  1527. namespace Data {
  1528. void SetTopPinnedMessageId(
  1529. not_null<PeerData*> peer,
  1530. MsgId messageId) {
  1531. if (const auto channel = peer->asChannel()) {
  1532. if (messageId <= channel->availableMinId()) {
  1533. return;
  1534. }
  1535. }
  1536. auto &session = peer->session();
  1537. const auto hiddenId = session.settings().hiddenPinnedMessageId(peer->id);
  1538. if (hiddenId != 0 && hiddenId != messageId) {
  1539. session.settings().setHiddenPinnedMessageId(
  1540. peer->id,
  1541. MsgId(0), // topicRootId
  1542. 0);
  1543. session.saveSettingsDelayed();
  1544. }
  1545. session.storage().add(Storage::SharedMediaAddExisting(
  1546. peer->id,
  1547. MsgId(0), // topicRootId
  1548. Storage::SharedMediaType::Pinned,
  1549. messageId,
  1550. { messageId, ServerMaxMsgId }));
  1551. peer->owner().history(peer)->setHasPinnedMessages(true);
  1552. }
  1553. FullMsgId ResolveTopPinnedId(
  1554. not_null<PeerData*> peer,
  1555. MsgId topicRootId,
  1556. PeerData *migrated) {
  1557. const auto slice = peer->session().storage().snapshot(
  1558. Storage::SharedMediaQuery(
  1559. Storage::SharedMediaKey(
  1560. peer->id,
  1561. topicRootId,
  1562. Storage::SharedMediaType::Pinned,
  1563. ServerMaxMsgId - 1),
  1564. 1,
  1565. 1));
  1566. const auto old = (!topicRootId && migrated)
  1567. ? migrated->session().storage().snapshot(
  1568. Storage::SharedMediaQuery(
  1569. Storage::SharedMediaKey(
  1570. migrated->id,
  1571. MsgId(0), // topicRootId
  1572. Storage::SharedMediaType::Pinned,
  1573. ServerMaxMsgId - 1),
  1574. 1,
  1575. 1))
  1576. : Storage::SharedMediaResult{
  1577. .count = 0,
  1578. .skippedBefore = 0,
  1579. .skippedAfter = 0,
  1580. };
  1581. if (!slice.messageIds.empty()) {
  1582. return FullMsgId(peer->id, slice.messageIds.back());
  1583. } else if (!migrated || slice.count != 0 || old.messageIds.empty()) {
  1584. return FullMsgId();
  1585. } else {
  1586. return FullMsgId(migrated->id, old.messageIds.back());
  1587. }
  1588. }
  1589. FullMsgId ResolveMinPinnedId(
  1590. not_null<PeerData*> peer,
  1591. MsgId topicRootId,
  1592. PeerData *migrated) {
  1593. const auto slice = peer->session().storage().snapshot(
  1594. Storage::SharedMediaQuery(
  1595. Storage::SharedMediaKey(
  1596. peer->id,
  1597. topicRootId,
  1598. Storage::SharedMediaType::Pinned,
  1599. 1),
  1600. 1,
  1601. 1));
  1602. const auto old = (!topicRootId && migrated)
  1603. ? migrated->session().storage().snapshot(
  1604. Storage::SharedMediaQuery(
  1605. Storage::SharedMediaKey(
  1606. migrated->id,
  1607. MsgId(0), // topicRootId
  1608. Storage::SharedMediaType::Pinned,
  1609. 1),
  1610. 1,
  1611. 1))
  1612. : Storage::SharedMediaResult{
  1613. .count = 0,
  1614. .skippedBefore = 0,
  1615. .skippedAfter = 0,
  1616. };
  1617. if (!old.messageIds.empty()) {
  1618. return FullMsgId(migrated->id, old.messageIds.front());
  1619. } else if (old.count == 0 && !slice.messageIds.empty()) {
  1620. return FullMsgId(peer->id, slice.messageIds.front());
  1621. } else {
  1622. return FullMsgId();
  1623. }
  1624. }
  1625. } // namespace Data