edit_participants_box.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424
  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 "boxes/peers/edit_participants_box.h"
  8. #include "api/api_chat_participants.h"
  9. #include "boxes/peers/edit_participant_box.h"
  10. #include "boxes/peers/add_participants_box.h"
  11. #include "boxes/peers/prepare_short_info_box.h" // PrepareShortInfoBox
  12. #include "boxes/peers/edit_members_visible.h"
  13. #include "ui/boxes/confirm_box.h"
  14. #include "boxes/max_invite_box.h"
  15. #include "boxes/add_contact_box.h"
  16. #include "main/main_session.h"
  17. #include "menu/menu_antispam_validator.h"
  18. #include "mtproto/mtproto_config.h"
  19. #include "apiwrap.h"
  20. #include "lang/lang_keys.h"
  21. #include "dialogs/dialogs_indexed_list.h"
  22. #include "data/data_peer_values.h"
  23. #include "data/data_session.h"
  24. #include "data/data_stories.h"
  25. #include "data/data_channel.h"
  26. #include "data/data_chat.h"
  27. #include "data/data_user.h"
  28. #include "data/data_changes.h"
  29. #include "base/unixtime.h"
  30. #include "ui/effects/outline_segments.h"
  31. #include "ui/widgets/menu/menu_multiline_action.h"
  32. #include "ui/widgets/popup_menu.h"
  33. #include "ui/text/text_utilities.h"
  34. #include "info/profile/info_profile_values.h"
  35. #include "window/window_session_controller.h"
  36. #include "history/history.h"
  37. #include "styles/style_chat.h"
  38. #include "styles/style_menu_icons.h"
  39. namespace {
  40. // How many messages from chat history server should forward to user,
  41. // that was added to this chat.
  42. constexpr auto kForwardMessagesOnAdd = 100;
  43. constexpr auto kParticipantsFirstPageCount = 16;
  44. constexpr auto kParticipantsPerPage = 200;
  45. constexpr auto kSortByOnlineDelay = crl::time(1000);
  46. void RemoveAdmin(
  47. not_null<ChannelData*> channel,
  48. not_null<UserData*> user,
  49. ChatAdminRightsInfo oldRights,
  50. Fn<void()> onDone,
  51. Fn<void()> onFail) {
  52. const auto newRights = MTP_chatAdminRights(MTP_flags(0));
  53. channel->session().api().request(MTPchannels_EditAdmin(
  54. channel->inputChannel,
  55. user->inputUser,
  56. newRights,
  57. MTP_string(QString())
  58. )).done([=](const MTPUpdates &result) {
  59. channel->session().api().applyUpdates(result);
  60. channel->applyEditAdmin(user, oldRights, ChatAdminRightsInfo(), QString());
  61. if (onDone) {
  62. onDone();
  63. }
  64. }).fail([=] {
  65. if (onFail) {
  66. onFail();
  67. }
  68. }).send();
  69. }
  70. void AddChatParticipant(
  71. std::shared_ptr<Ui::Show> show,
  72. not_null<ChatData*> chat,
  73. not_null<UserData*> user,
  74. Fn<void()> onDone,
  75. Fn<void()> onFail) {
  76. chat->session().api().request(MTPmessages_AddChatUser(
  77. chat->inputChat,
  78. user->inputUser,
  79. MTP_int(kForwardMessagesOnAdd)
  80. )).done([=](const MTPmessages_InvitedUsers &result) {
  81. const auto &data = result.data();
  82. chat->session().api().applyUpdates(data.vupdates());
  83. if (onDone) {
  84. onDone();
  85. }
  86. ChatInviteForbidden(
  87. show,
  88. chat,
  89. CollectForbiddenUsers(&chat->session(), result));
  90. }).fail([=](const MTP::Error &error) {
  91. ShowAddParticipantsError(show, error.type(), chat, user);
  92. if (onFail) {
  93. onFail();
  94. }
  95. }).send();
  96. }
  97. void SaveChatAdmin(
  98. std::shared_ptr<Ui::Show> show,
  99. not_null<ChatData*> chat,
  100. not_null<UserData*> user,
  101. bool isAdmin,
  102. Fn<void()> onDone,
  103. Fn<void()> onFail,
  104. bool retryOnNotParticipant = true) {
  105. chat->session().api().request(MTPmessages_EditChatAdmin(
  106. chat->inputChat,
  107. user->inputUser,
  108. MTP_bool(isAdmin)
  109. )).done([=] {
  110. chat->applyEditAdmin(user, isAdmin);
  111. if (onDone) {
  112. onDone();
  113. }
  114. }).fail([=](const MTP::Error &error) {
  115. const auto &type = error.type();
  116. if (retryOnNotParticipant
  117. && isAdmin
  118. && (type == u"USER_NOT_PARTICIPANT"_q)) {
  119. AddChatParticipant(show, chat, user, [=] {
  120. SaveChatAdmin(
  121. show,
  122. chat,
  123. user,
  124. isAdmin,
  125. onDone,
  126. onFail,
  127. false);
  128. }, onFail);
  129. } else if (onFail) {
  130. onFail();
  131. }
  132. }).send();
  133. }
  134. void SaveChannelAdmin(
  135. std::shared_ptr<Ui::Show> show,
  136. not_null<ChannelData*> channel,
  137. not_null<UserData*> user,
  138. ChatAdminRightsInfo oldRights,
  139. ChatAdminRightsInfo newRights,
  140. const QString &rank,
  141. Fn<void()> onDone,
  142. Fn<void()> onFail) {
  143. channel->session().api().request(MTPchannels_EditAdmin(
  144. channel->inputChannel,
  145. user->inputUser,
  146. MTP_chatAdminRights(MTP_flags(
  147. MTPDchatAdminRights::Flags::from_raw(uint32(newRights.flags)))),
  148. MTP_string(rank)
  149. )).done([=](const MTPUpdates &result) {
  150. channel->session().api().applyUpdates(result);
  151. channel->applyEditAdmin(user, oldRights, newRights, rank);
  152. if (onDone) {
  153. onDone();
  154. }
  155. }).fail([=](const MTP::Error &error) {
  156. ShowAddParticipantsError(show, error.type(), channel, user);
  157. if (onFail) {
  158. onFail();
  159. }
  160. }).send();
  161. }
  162. void SaveChatParticipantKick(
  163. not_null<ChatData*> chat,
  164. not_null<UserData*> user,
  165. Fn<void()> onDone,
  166. Fn<void()> onFail) {
  167. chat->session().api().request(MTPmessages_DeleteChatUser(
  168. MTP_flags(0),
  169. chat->inputChat,
  170. user->inputUser
  171. )).done([=](const MTPUpdates &result) {
  172. chat->session().api().applyUpdates(result);
  173. if (onDone) {
  174. onDone();
  175. }
  176. }).fail([=] {
  177. if (onFail) {
  178. onFail();
  179. }
  180. }).send();
  181. }
  182. } // namespace
  183. Fn<void(
  184. ChatAdminRightsInfo oldRights,
  185. ChatAdminRightsInfo newRights,
  186. const QString &rank)> SaveAdminCallback(
  187. std::shared_ptr<Ui::Show> show,
  188. not_null<PeerData*> peer,
  189. not_null<UserData*> user,
  190. Fn<void(
  191. ChatAdminRightsInfo newRights,
  192. const QString &rank)> onDone,
  193. Fn<void()> onFail) {
  194. return [=](
  195. ChatAdminRightsInfo oldRights,
  196. ChatAdminRightsInfo newRights,
  197. const QString &rank) {
  198. const auto done = [=] { if (onDone) onDone(newRights, rank); };
  199. const auto saveForChannel = [=](not_null<ChannelData*> channel) {
  200. SaveChannelAdmin(
  201. show,
  202. channel,
  203. user,
  204. oldRights,
  205. newRights,
  206. rank,
  207. done,
  208. onFail);
  209. };
  210. if (const auto chat = peer->asChatNotMigrated()) {
  211. const auto saveChatAdmin = [&](bool isAdmin) {
  212. SaveChatAdmin(show, chat, user, isAdmin, done, onFail);
  213. };
  214. if (newRights.flags == chat->defaultAdminRights(user).flags
  215. && rank.isEmpty()) {
  216. saveChatAdmin(true);
  217. } else if (!newRights.flags) {
  218. saveChatAdmin(false);
  219. } else {
  220. peer->session().api().migrateChat(chat, saveForChannel);
  221. }
  222. } else if (const auto channel = peer->asChannelOrMigrated()) {
  223. saveForChannel(channel);
  224. } else {
  225. Unexpected("Peer in SaveAdminCallback.");
  226. }
  227. };
  228. }
  229. Fn<void(
  230. ChatRestrictionsInfo oldRights,
  231. ChatRestrictionsInfo newRights)> SaveRestrictedCallback(
  232. not_null<PeerData*> peer,
  233. not_null<PeerData*> participant,
  234. Fn<void(ChatRestrictionsInfo newRights)> onDone,
  235. Fn<void()> onFail) {
  236. return [=](
  237. ChatRestrictionsInfo oldRights,
  238. ChatRestrictionsInfo newRights) {
  239. const auto done = [=] { if (onDone) onDone(newRights); };
  240. const auto saveForChannel = [=](not_null<ChannelData*> channel) {
  241. Api::ChatParticipants::Restrict(
  242. channel,
  243. participant,
  244. oldRights,
  245. newRights,
  246. done,
  247. onFail);
  248. };
  249. if (const auto chat = peer->asChatNotMigrated()) {
  250. if (participant->isUser()
  251. && (newRights.flags & ChatRestriction::ViewMessages)) {
  252. SaveChatParticipantKick(
  253. chat,
  254. participant->asUser(),
  255. done,
  256. onFail);
  257. } else if (!newRights.flags) {
  258. done();
  259. } else {
  260. peer->session().api().migrateChat(chat, saveForChannel);
  261. }
  262. } else if (const auto channel = peer->asChannelOrMigrated()) {
  263. saveForChannel(channel);
  264. } else {
  265. Unexpected("Peer in SaveAdminCallback.");
  266. }
  267. };
  268. }
  269. void SubscribeToMigration(
  270. not_null<PeerData*> peer,
  271. rpl::lifetime &lifetime,
  272. Fn<void(not_null<ChannelData*>)> migrate) {
  273. if (const auto chat = peer->asChat()) {
  274. if (const auto channel = peer->migrateTo()) {
  275. migrate(channel);
  276. } else if (!chat->isDeactivated()) {
  277. chat->session().changes().peerUpdates(
  278. peer,
  279. Data::PeerUpdate::Flag::Migration
  280. ) | rpl::map([](const Data::PeerUpdate &update) {
  281. return update.peer->migrateTo();
  282. }) | rpl::filter([](ChannelData *channel) {
  283. return (channel != nullptr);
  284. }) | rpl::take(
  285. 1
  286. ) | rpl::start_with_next([=](not_null<ChannelData*> channel) {
  287. const auto onstack = base::duplicate(migrate);
  288. onstack(channel);
  289. }, lifetime);
  290. }
  291. }
  292. }
  293. ParticipantsAdditionalData::ParticipantsAdditionalData(
  294. not_null<PeerData*> peer,
  295. Role role)
  296. : _peer(peer)
  297. , _role(role) {
  298. fillFromPeer();
  299. }
  300. bool ParticipantsAdditionalData::infoLoaded(
  301. not_null<PeerData*> participant) const {
  302. return _peer->isChat()
  303. || (_infoNotLoaded.find(participant) == end(_infoNotLoaded));
  304. }
  305. bool ParticipantsAdditionalData::canEditAdmin(
  306. not_null<UserData*> user) const {
  307. if (_creator && _creator->isSelf()) {
  308. return true;
  309. } else if (_creator == user || user->isSelf()) {
  310. return false;
  311. } else if (adminRights(user).has_value()) {
  312. return !_peer->isChat() && _adminCanEdit.contains(user);
  313. }
  314. return true;
  315. }
  316. bool ParticipantsAdditionalData::canAddOrEditAdmin(
  317. not_null<UserData*> user) const {
  318. if (!canEditAdmin(user)) {
  319. return false;
  320. } else if (const auto chat = _peer->asChat()) {
  321. return chat->canAddAdmins();
  322. } else if (const auto channel = _peer->asChannel()) {
  323. return channel->canAddAdmins();
  324. }
  325. Unexpected("Peer in ParticipantsAdditionalData::canAddOrEditAdmin.");
  326. }
  327. bool ParticipantsAdditionalData::canRestrictParticipant(
  328. not_null<PeerData*> participant) const {
  329. const auto user = participant->asUser();
  330. if (user && (!canEditAdmin(user) || user->isSelf())) {
  331. return false;
  332. } else if (const auto chat = _peer->asChat()) {
  333. return chat->canBanMembers();
  334. } else if (const auto channel = _peer->asChannel()) {
  335. return channel->canBanMembers();
  336. }
  337. Unexpected("Peer in ParticipantsAdditionalData::canRestrictParticipant.");
  338. }
  339. bool ParticipantsAdditionalData::canRemoveParticipant(
  340. not_null<PeerData*> participant) const {
  341. const auto user = participant->asUser();
  342. if (canRestrictParticipant(participant)) {
  343. return true;
  344. } else if (const auto chat = _peer->asChat()) {
  345. return user
  346. && !user->isSelf()
  347. && chat->invitedByMe.contains(user)
  348. && (chat->amCreator() || !_admins.contains(user));
  349. }
  350. return false;
  351. }
  352. auto ParticipantsAdditionalData::adminRights(
  353. not_null<UserData*> user) const
  354. -> std::optional<ChatAdminRightsInfo> {
  355. if (const auto chat = _peer->asChat()) {
  356. return _admins.contains(user)
  357. ? std::make_optional(chat->defaultAdminRights(user))
  358. : std::nullopt;
  359. }
  360. const auto i = _adminRights.find(user);
  361. return (i != end(_adminRights))
  362. ? std::make_optional(i->second)
  363. : std::nullopt;
  364. }
  365. QString ParticipantsAdditionalData::adminRank(
  366. not_null<UserData*> user) const {
  367. const auto i = _adminRanks.find(user);
  368. return (i != end(_adminRanks)) ? i->second : QString();
  369. }
  370. TimeId ParticipantsAdditionalData::adminPromotedSince(
  371. not_null<UserData*> user) const {
  372. const auto i = _adminPromotedSince.find(user);
  373. return (i != end(_adminPromotedSince)) ? i->second : TimeId(0);
  374. }
  375. TimeId ParticipantsAdditionalData::restrictedSince(
  376. not_null<PeerData*> peer) const {
  377. const auto i = _restrictedSince.find(peer);
  378. return (i != end(_restrictedSince)) ? i->second : TimeId(0);
  379. }
  380. TimeId ParticipantsAdditionalData::memberSince(
  381. not_null<UserData*> user) const {
  382. const auto i = _memberSince.find(user);
  383. return (i != end(_memberSince)) ? i->second : TimeId(0);
  384. }
  385. auto ParticipantsAdditionalData::restrictedRights(
  386. not_null<PeerData*> participant) const
  387. -> std::optional<ChatRestrictionsInfo> {
  388. if (_peer->isChat()) {
  389. return std::nullopt;
  390. }
  391. const auto i = _restrictedRights.find(participant);
  392. return (i != end(_restrictedRights))
  393. ? std::make_optional(i->second)
  394. : std::nullopt;
  395. }
  396. bool ParticipantsAdditionalData::isCreator(not_null<UserData*> user) const {
  397. return (_creator == user);
  398. }
  399. bool ParticipantsAdditionalData::isExternal(
  400. not_null<PeerData*> participant) const {
  401. return _peer->isChat()
  402. ? (participant->isUser()
  403. && !_members.contains(participant->asUser()))
  404. : _external.find(participant) != end(_external);
  405. }
  406. bool ParticipantsAdditionalData::isKicked(
  407. not_null<PeerData*> participant) const {
  408. return !_peer->isChat() && (_kicked.find(participant) != end(_kicked));
  409. }
  410. UserData *ParticipantsAdditionalData::adminPromotedBy(
  411. not_null<UserData*> user) const {
  412. if (_peer->isChat()) {
  413. return _admins.contains(user) ? _creator : nullptr;
  414. }
  415. const auto i = _adminPromotedBy.find(user);
  416. return (i != end(_adminPromotedBy)) ? i->second.get() : nullptr;
  417. }
  418. UserData *ParticipantsAdditionalData::restrictedBy(
  419. not_null<PeerData*> participant) const {
  420. if (_peer->isChat()) {
  421. return nullptr;
  422. }
  423. const auto i = _restrictedBy.find(participant);
  424. return (i != end(_restrictedBy)) ? i->second.get() : nullptr;
  425. }
  426. void ParticipantsAdditionalData::setExternal(
  427. not_null<PeerData*> participant) {
  428. if (const auto user = participant->asUser()) {
  429. _adminRights.erase(user);
  430. _adminCanEdit.erase(user);
  431. _adminPromotedBy.erase(user);
  432. _admins.erase(user);
  433. }
  434. _restrictedRights.erase(participant);
  435. _kicked.erase(participant);
  436. _restrictedBy.erase(participant);
  437. _infoNotLoaded.erase(participant);
  438. _external.emplace(participant);
  439. }
  440. void ParticipantsAdditionalData::checkForLoaded(
  441. not_null<PeerData*> participant) {
  442. const auto contains = [](const auto &map, const auto &value) {
  443. return map.find(value) != map.end();
  444. };
  445. const auto user = participant->asUser();
  446. if (!(user && _creator == user)
  447. && !(user && contains(_adminRights, user))
  448. && !contains(_restrictedRights, participant)
  449. && !contains(_external, participant)
  450. && !contains(_kicked, participant)) {
  451. _infoNotLoaded.emplace(participant);
  452. }
  453. }
  454. void ParticipantsAdditionalData::fillFromPeer() {
  455. if (const auto chat = _peer->asChat()) {
  456. fillFromChat(chat);
  457. } else if (const auto channel = _peer->asChannel()) {
  458. fillFromChannel(channel);
  459. } else {
  460. Unexpected("Peer in ParticipantsAdditionalData::fillFromPeer.");
  461. }
  462. }
  463. void ParticipantsAdditionalData::fillFromChat(not_null<ChatData*> chat) {
  464. if (const auto creator = chat->owner().userLoaded(chat->creator)) {
  465. _creator = creator;
  466. }
  467. if (chat->participants.empty()) {
  468. return;
  469. }
  470. _members = chat->participants;
  471. _admins = chat->admins;
  472. }
  473. void ParticipantsAdditionalData::fillFromChannel(
  474. not_null<ChannelData*> channel) {
  475. const auto information = channel->mgInfo.get();
  476. if (!information || !channel->canViewMembers()) {
  477. return;
  478. }
  479. if (information->creator) {
  480. _creator = information->creator;
  481. _adminRanks[information->creator] = information->creatorRank;
  482. }
  483. for (const auto user : information->lastParticipants) {
  484. const auto admin = information->lastAdmins.find(user);
  485. const auto rank = information->admins.find(peerToUser(user->id));
  486. const auto restricted = information->lastRestricted.find(user);
  487. if (admin != information->lastAdmins.cend()) {
  488. _restrictedRights.erase(user);
  489. _kicked.erase(user);
  490. _restrictedBy.erase(user);
  491. if (admin->second.canEdit) {
  492. _adminCanEdit.emplace(user);
  493. } else {
  494. _adminCanEdit.erase(user);
  495. }
  496. _adminRights.emplace(user, admin->second.rights);
  497. if (rank != end(information->admins)
  498. && !rank->second.isEmpty()) {
  499. _adminRanks[user] = rank->second;
  500. }
  501. } else if (restricted != information->lastRestricted.cend()) {
  502. _adminRights.erase(user);
  503. _adminCanEdit.erase(user);
  504. _adminPromotedBy.erase(user);
  505. _restrictedRights.emplace(user, restricted->second.rights);
  506. }
  507. }
  508. }
  509. void ParticipantsAdditionalData::applyAdminLocally(
  510. UserData *user,
  511. ChatAdminRightsInfo rights,
  512. const QString &rank) {
  513. if (isCreator(user) && user->isSelf()) {
  514. applyParticipant(Api::ChatParticipant(
  515. Api::ChatParticipant::Type::Creator,
  516. user->id,
  517. UserId(),
  518. ChatRestrictionsInfo(),
  519. std::move(rights),
  520. true, // As the creator is self.
  521. rank));
  522. } else if (!rights.flags) {
  523. applyParticipant(Api::ChatParticipant(
  524. Api::ChatParticipant::Type::Member,
  525. user->id,
  526. UserId(),
  527. ChatRestrictionsInfo(),
  528. ChatAdminRightsInfo()));
  529. } else {
  530. const auto alreadyPromotedBy = adminPromotedBy(user);
  531. applyParticipant(Api::ChatParticipant(
  532. Api::ChatParticipant::Type::Admin,
  533. user->id,
  534. alreadyPromotedBy
  535. ? peerToUser(alreadyPromotedBy->id)
  536. : user->session().userId(),
  537. ChatRestrictionsInfo(),
  538. std::move(rights),
  539. true,
  540. rank));
  541. }
  542. }
  543. void ParticipantsAdditionalData::applyBannedLocally(
  544. not_null<PeerData*> participant,
  545. ChatRestrictionsInfo rights) {
  546. const auto user = participant->asUser();
  547. if (!rights.flags) {
  548. if (user) {
  549. applyParticipant(Api::ChatParticipant(
  550. Api::ChatParticipant::Type::Member,
  551. user->id,
  552. UserId(),
  553. ChatRestrictionsInfo(),
  554. ChatAdminRightsInfo()));
  555. } else {
  556. setExternal(participant);
  557. }
  558. } else {
  559. const auto kicked = rights.flags & ChatRestriction::ViewMessages;
  560. const auto alreadyRestrictedBy = restrictedBy(participant);
  561. applyParticipant(Api::ChatParticipant(
  562. kicked
  563. ? Api::ChatParticipant::Type::Banned
  564. : Api::ChatParticipant::Type::Restricted,
  565. participant->id,
  566. alreadyRestrictedBy
  567. ? peerToUser(alreadyRestrictedBy->id)
  568. : participant->session().userId(),
  569. std::move(rights),
  570. ChatAdminRightsInfo()));
  571. }
  572. }
  573. PeerData *ParticipantsAdditionalData::applyParticipant(
  574. const Api::ChatParticipant &data) {
  575. return applyParticipant(data, _role);
  576. }
  577. PeerData *ParticipantsAdditionalData::applyParticipant(
  578. const Api::ChatParticipant &data,
  579. Role overrideRole) {
  580. const auto logBad = [&]() -> PeerData* {
  581. LOG(("API Error: Bad participant type %1 got "
  582. "while requesting for participants, role: %2"
  583. ).arg(static_cast<int>(data.type())
  584. ).arg(static_cast<int>(overrideRole)));
  585. return nullptr;
  586. };
  587. switch (data.type()) {
  588. case Api::ChatParticipant::Type::Creator: {
  589. if (overrideRole != Role::Profile
  590. && overrideRole != Role::Members
  591. && overrideRole != Role::Admins) {
  592. return logBad();
  593. }
  594. return applyCreator(data);
  595. }
  596. case Api::ChatParticipant::Type::Admin: {
  597. if (overrideRole != Role::Profile
  598. && overrideRole != Role::Members
  599. && overrideRole != Role::Admins) {
  600. return logBad();
  601. }
  602. return applyAdmin(data);
  603. }
  604. case Api::ChatParticipant::Type::Member: {
  605. if (overrideRole != Role::Profile
  606. && overrideRole != Role::Members) {
  607. return logBad();
  608. }
  609. return applyRegular(data.userId());
  610. }
  611. case Api::ChatParticipant::Type::Restricted:
  612. case Api::ChatParticipant::Type::Banned:
  613. if (overrideRole != Role::Profile
  614. && overrideRole != Role::Members
  615. && overrideRole != Role::Restricted
  616. && overrideRole != Role::Kicked) {
  617. return logBad();
  618. }
  619. return applyBanned(data);
  620. case Api::ChatParticipant::Type::Left:
  621. return logBad();
  622. };
  623. Unexpected("Api::ChatParticipant::type in applyParticipant.");
  624. }
  625. UserData *ParticipantsAdditionalData::applyCreator(
  626. const Api::ChatParticipant &data) {
  627. if (const auto user = applyRegular(data.userId())) {
  628. _creator = user;
  629. _adminRights[user] = data.rights();
  630. if (user->isSelf()) {
  631. _adminCanEdit.emplace(user);
  632. } else {
  633. _adminCanEdit.erase(user);
  634. }
  635. if (!data.rank().isEmpty()) {
  636. _adminRanks[user] = data.rank();
  637. } else {
  638. _adminRanks.remove(user);
  639. }
  640. return user;
  641. }
  642. return nullptr;
  643. }
  644. UserData *ParticipantsAdditionalData::applyAdmin(
  645. const Api::ChatParticipant &data) {
  646. const auto user = _peer->owner().userLoaded(data.userId());
  647. if (!user) {
  648. return nullptr;
  649. } else if (const auto chat = _peer->asChat()) {
  650. // This can come from saveAdmin callback.
  651. _admins.emplace(user);
  652. return user;
  653. }
  654. _infoNotLoaded.erase(user);
  655. _restrictedRights.erase(user);
  656. _kicked.erase(user);
  657. _restrictedBy.erase(user);
  658. _adminRights[user] = data.rights();
  659. if (data.canBeEdited()) {
  660. _adminCanEdit.emplace(user);
  661. } else {
  662. _adminCanEdit.erase(user);
  663. }
  664. if (!data.rank().isEmpty()) {
  665. _adminRanks[user] = data.rank();
  666. } else {
  667. _adminRanks.remove(user);
  668. }
  669. if (data.promotedSince()) {
  670. _adminPromotedSince[user] = data.promotedSince();
  671. } else {
  672. _adminPromotedSince.remove(user);
  673. }
  674. if (const auto by = _peer->owner().userLoaded(data.by())) {
  675. const auto i = _adminPromotedBy.find(user);
  676. if (i == _adminPromotedBy.end()) {
  677. _adminPromotedBy.emplace(user, by);
  678. } else {
  679. i->second = by;
  680. }
  681. } else {
  682. LOG(("API Error: No user %1 for admin promoted by."
  683. ).arg(data.by().bare));
  684. }
  685. return user;
  686. }
  687. UserData *ParticipantsAdditionalData::applyRegular(UserId userId) {
  688. const auto user = _peer->owner().userLoaded(userId);
  689. if (!user) {
  690. return nullptr;
  691. } else if (const auto chat = _peer->asChat()) {
  692. // This can come from saveAdmin or saveRestricted callback.
  693. _admins.erase(user);
  694. return user;
  695. }
  696. _infoNotLoaded.erase(user);
  697. _adminRights.erase(user);
  698. _adminCanEdit.erase(user);
  699. _adminPromotedBy.erase(user);
  700. _restrictedRights.erase(user);
  701. _kicked.erase(user);
  702. _restrictedBy.erase(user);
  703. return user;
  704. }
  705. PeerData *ParticipantsAdditionalData::applyBanned(
  706. const Api::ChatParticipant &data) {
  707. const auto participant = _peer->owner().peerLoaded(data.id());
  708. if (!participant) {
  709. return nullptr;
  710. }
  711. _infoNotLoaded.erase(participant);
  712. if (const auto user = participant->asUser()) {
  713. _adminRights.erase(user);
  714. _adminCanEdit.erase(user);
  715. _adminPromotedBy.erase(user);
  716. }
  717. if (data.isKicked()) {
  718. _kicked.emplace(participant);
  719. } else {
  720. _kicked.erase(participant);
  721. }
  722. if (data.restrictedSince()) {
  723. _restrictedSince[participant] = data.restrictedSince();
  724. } else {
  725. _restrictedSince.remove(participant);
  726. }
  727. _restrictedRights[participant] = data.restrictions();
  728. if (const auto by = _peer->owner().userLoaded(data.by())) {
  729. const auto i = _restrictedBy.find(participant);
  730. if (i == _restrictedBy.end()) {
  731. _restrictedBy.emplace(participant, by);
  732. } else {
  733. i->second = by;
  734. }
  735. }
  736. return participant;
  737. }
  738. void ParticipantsAdditionalData::migrate(
  739. not_null<ChatData*> chat,
  740. not_null<ChannelData*> channel) {
  741. _peer = channel;
  742. fillFromChannel(channel);
  743. for (const auto &user : _admins) {
  744. _adminRights.emplace(user, chat->defaultAdminRights(user));
  745. if (channel->amCreator()) {
  746. _adminCanEdit.emplace(user);
  747. }
  748. if (_creator) {
  749. _adminPromotedBy.emplace(user, _creator);
  750. }
  751. }
  752. }
  753. ParticipantsOnlineSorter::ParticipantsOnlineSorter(
  754. not_null<PeerData*> peer,
  755. not_null<PeerListDelegate*> delegate)
  756. : _peer(peer)
  757. , _delegate(delegate)
  758. , _sortByOnlineTimer([=] { sort(); }) {
  759. peer->session().changes().peerUpdates(
  760. Data::PeerUpdate::Flag::OnlineStatus
  761. ) | rpl::start_with_next([=](const Data::PeerUpdate &update) {
  762. const auto peerId = update.peer->id;
  763. if (const auto row = _delegate->peerListFindRow(peerId.value)) {
  764. row->refreshStatus();
  765. sortDelayed();
  766. }
  767. }, _lifetime);
  768. sort();
  769. }
  770. void ParticipantsOnlineSorter::sortDelayed() {
  771. if (!_sortByOnlineTimer.isActive()) {
  772. _sortByOnlineTimer.callOnce(kSortByOnlineDelay);
  773. }
  774. }
  775. void ParticipantsOnlineSorter::sort() {
  776. const auto channel = _peer->asChannel();
  777. if (channel
  778. && (!channel->isMegagroup()
  779. || (channel->membersCount()
  780. > channel->session().serverConfig().chatSizeMax))) {
  781. _onlineCount = 0;
  782. return;
  783. }
  784. const auto now = base::unixtime::now();
  785. _delegate->peerListSortRows([&](
  786. const PeerListRow &a,
  787. const PeerListRow &b) {
  788. return Data::SortByOnlineValue(a.peer()->asUser(), now) >
  789. Data::SortByOnlineValue(b.peer()->asUser(), now);
  790. });
  791. refreshOnlineCount();
  792. }
  793. rpl::producer<int> ParticipantsOnlineSorter::onlineCountValue() const {
  794. return _onlineCount.value();
  795. }
  796. void ParticipantsOnlineSorter::refreshOnlineCount() {
  797. const auto now = base::unixtime::now();
  798. auto left = 0, right = _delegate->peerListFullRowsCount();
  799. while (right > left) {
  800. const auto middle = (left + right) / 2;
  801. const auto row = _delegate->peerListRowAt(middle);
  802. if (Data::OnlineTextActive(row->peer()->asUser(), now)) {
  803. left = middle + 1;
  804. } else {
  805. right = middle;
  806. }
  807. }
  808. _onlineCount = left;
  809. }
  810. ParticipantsBoxController::SavedState::SavedState(
  811. const ParticipantsAdditionalData &additional)
  812. : additional(additional) {
  813. }
  814. ParticipantsBoxController::ParticipantsBoxController(
  815. not_null<Window::SessionNavigation*> navigation,
  816. not_null<PeerData*> peer,
  817. Role role)
  818. : ParticipantsBoxController(CreateTag(), navigation, peer, role) {
  819. }
  820. ParticipantsBoxController::ParticipantsBoxController(
  821. CreateTag,
  822. Window::SessionNavigation *navigation,
  823. not_null<PeerData*> peer,
  824. Role role)
  825. : PeerListController(CreateSearchController(peer, role, &_additional))
  826. , _navigation(navigation)
  827. , _peer(peer)
  828. , _api(&_peer->session().mtp())
  829. , _role(role)
  830. , _additional(peer, _role) {
  831. subscribeToMigration();
  832. if (_role == Role::Profile) {
  833. setupListChangeViewers();
  834. }
  835. if (const auto channel = _peer->asChannel()) {
  836. subscribeToCreatorChange(channel);
  837. }
  838. }
  839. Main::Session &ParticipantsBoxController::session() const {
  840. return _peer->session();
  841. }
  842. void ParticipantsBoxController::setupListChangeViewers() {
  843. const auto channel = _peer->asChannel();
  844. if (!channel || !channel->isMegagroup()) {
  845. return;
  846. }
  847. channel->owner().megagroupParticipantAdded(
  848. channel
  849. ) | rpl::start_with_next([=](not_null<UserData*> user) {
  850. if (delegate()->peerListFullRowsCount() > 0) {
  851. if (delegate()->peerListRowAt(0)->peer() == user) {
  852. return;
  853. }
  854. }
  855. if (const auto row = delegate()->peerListFindRow(user->id.value)) {
  856. delegate()->peerListPartitionRows([&](const PeerListRow &row) {
  857. return (row.peer() == user);
  858. });
  859. } else if (auto row = createRow(user)) {
  860. const auto raw = row.get();
  861. delegate()->peerListPrependRow(std::move(row));
  862. if (_stories) {
  863. _stories->process(raw);
  864. }
  865. refreshRows();
  866. if (_onlineSorter) {
  867. _onlineSorter->sort();
  868. }
  869. }
  870. }, lifetime());
  871. channel->owner().megagroupParticipantRemoved(
  872. channel
  873. ) | rpl::start_with_next([=](not_null<UserData*> user) {
  874. if (const auto row = delegate()->peerListFindRow(user->id.value)) {
  875. delegate()->peerListRemoveRow(row);
  876. }
  877. refreshRows();
  878. }, lifetime());
  879. }
  880. auto ParticipantsBoxController::CreateSearchController(
  881. not_null<PeerData*> peer,
  882. Role role,
  883. not_null<ParticipantsAdditionalData*> additional)
  884. -> std::unique_ptr<PeerListSearchController> {
  885. const auto channel = peer->asChannel();
  886. // In admins box complex search is used for adding new admins.
  887. if (channel && (role != Role::Admins || channel->canAddAdmins())) {
  888. return std::make_unique<ParticipantsBoxSearchController>(
  889. channel,
  890. role,
  891. additional);
  892. }
  893. return nullptr;
  894. }
  895. void ParticipantsBoxController::Start(
  896. not_null<Window::SessionNavigation*> navigation,
  897. not_null<PeerData*> peer,
  898. Role role) {
  899. auto controller = std::make_unique<ParticipantsBoxController>(
  900. navigation,
  901. peer,
  902. role);
  903. auto initBox = [=, controller = controller.get()](
  904. not_null<PeerListBox*> box) {
  905. box->addButton(tr::lng_close(), [=] { box->closeBox(); });
  906. const auto chat = peer->asChat();
  907. const auto channel = peer->asChannel();
  908. const auto canAddNewItem = [&] {
  909. Assert(chat != nullptr || channel != nullptr);
  910. switch (role) {
  911. case Role::Members:
  912. return chat
  913. ? chat->canAddMembers()
  914. : (channel->canAddMembers()
  915. && (channel->isMegagroup()
  916. || (channel->membersCount()
  917. < channel->session().serverConfig().chatSizeMax)));
  918. case Role::Admins:
  919. return chat
  920. ? chat->canAddAdmins()
  921. : channel->canAddAdmins();
  922. case Role::Restricted:
  923. case Role::Kicked:
  924. return chat
  925. ? chat->canBanMembers()
  926. : channel->canBanMembers();
  927. }
  928. Unexpected("Role value in ParticipantsBoxController::Start()");
  929. }();
  930. auto addNewItemText = [&] {
  931. switch (role) {
  932. case Role::Members:
  933. return (chat || channel->isMegagroup())
  934. ? tr::lng_channel_add_members()
  935. : tr::lng_channel_add_users();
  936. case Role::Admins:
  937. return tr::lng_channel_add_admin();
  938. case Role::Restricted:
  939. return tr::lng_channel_add_exception();
  940. case Role::Kicked:
  941. return tr::lng_channel_add_removed();
  942. }
  943. Unexpected("Role value in ParticipantsBoxController::Start()");
  944. }();
  945. if (canAddNewItem) {
  946. box->addLeftButton(std::move(addNewItemText), [=] {
  947. controller->addNewItem();
  948. });
  949. }
  950. };
  951. navigation->parentController()->show(
  952. Box<PeerListBox>(std::move(controller), initBox));
  953. }
  954. void ParticipantsBoxController::addNewItem() {
  955. Expects(_role != Role::Profile);
  956. if (_role == Role::Members) {
  957. addNewParticipants();
  958. return;
  959. }
  960. const auto adminDone = crl::guard(this, [=](
  961. not_null<UserData*> user,
  962. ChatAdminRightsInfo rights,
  963. const QString &rank) {
  964. editAdminDone(user, rights, rank);
  965. });
  966. const auto restrictedDone = crl::guard(this, [=](
  967. not_null<PeerData*> participant,
  968. ChatRestrictionsInfo rights) {
  969. editRestrictedDone(participant, rights);
  970. });
  971. const auto initBox = [](not_null<PeerListBox*> box) {
  972. box->addButton(tr::lng_cancel(), [=] { box->closeBox(); });
  973. };
  974. _addBox = showBox(
  975. Box<PeerListBox>(
  976. std::make_unique<AddSpecialBoxController>(
  977. _peer,
  978. _role,
  979. adminDone,
  980. restrictedDone),
  981. initBox));
  982. }
  983. void ParticipantsBoxController::addNewParticipants() {
  984. Expects(_navigation != nullptr);
  985. const auto chat = _peer->asChat();
  986. const auto channel = _peer->asChannel();
  987. if (chat) {
  988. AddParticipantsBoxController::Start(_navigation, chat);
  989. } else if (channel->isMegagroup()
  990. || (channel->membersCount()
  991. < channel->session().serverConfig().chatSizeMax)) {
  992. const auto count = delegate()->peerListFullRowsCount();
  993. auto already = std::vector<not_null<UserData*>>();
  994. already.reserve(count);
  995. for (auto i = 0; i != count; ++i) {
  996. const auto participant = delegate()->peerListRowAt(i)->peer();
  997. if (const auto user = participant->asUser()) {
  998. already.emplace_back(user);
  999. }
  1000. }
  1001. AddParticipantsBoxController::Start(
  1002. _navigation,
  1003. channel,
  1004. { already.begin(), already.end() });
  1005. } else {
  1006. showBox(Box<MaxInviteBox>(channel));
  1007. }
  1008. }
  1009. void ParticipantsBoxController::peerListSearchAddRow(
  1010. not_null<PeerData*> peer) {
  1011. PeerListController::peerListSearchAddRow(peer);
  1012. if (_role == Role::Restricted
  1013. && delegate()->peerListFullRowsCount() > 0) {
  1014. setDescriptionText(QString());
  1015. }
  1016. }
  1017. std::unique_ptr<PeerListRow> ParticipantsBoxController::createSearchRow(
  1018. not_null<PeerData*> peer) {
  1019. if (const auto user = peer->asUser()) {
  1020. return createRow(user);
  1021. }
  1022. return nullptr;
  1023. }
  1024. std::unique_ptr<PeerListRow> ParticipantsBoxController::createRestoredRow(
  1025. not_null<PeerData*> peer) {
  1026. if (const auto user = peer->asUser()) {
  1027. return createRow(user);
  1028. }
  1029. return nullptr;
  1030. }
  1031. auto ParticipantsBoxController::saveState() const
  1032. -> std::unique_ptr<PeerListState> {
  1033. Expects(_role == Role::Profile);
  1034. auto result = PeerListController::saveState();
  1035. auto my = std::make_unique<SavedState>(_additional);
  1036. my->offset = _offset;
  1037. my->allLoaded = _allLoaded;
  1038. my->wasLoading = (_loadRequestId != 0);
  1039. if (const auto search = searchController()) {
  1040. my->searchState = search->saveState();
  1041. }
  1042. const auto weak = result.get();
  1043. if (const auto chat = _peer->asChat()) {
  1044. chat->session().changes().peerUpdates(
  1045. chat,
  1046. Data::PeerUpdate::Flag::Members
  1047. ) | rpl::start_with_next([=] {
  1048. weak->controllerState = nullptr;
  1049. }, my->lifetime);
  1050. } else if (const auto channel = _peer->asMegagroup()) {
  1051. channel->owner().megagroupParticipantAdded(
  1052. channel
  1053. ) | rpl::start_with_next([=](not_null<UserData*> user) {
  1054. if (!weak->list.empty()) {
  1055. if (weak->list[0] == user) {
  1056. return;
  1057. }
  1058. }
  1059. auto pos = ranges::find(weak->list, user);
  1060. if (pos == weak->list.cend()) {
  1061. weak->list.emplace_back(user);
  1062. }
  1063. ranges::stable_partition(
  1064. weak->list,
  1065. [user](auto peer) { return (peer == user); });
  1066. }, my->lifetime);
  1067. channel->owner().megagroupParticipantRemoved(
  1068. channel
  1069. ) | rpl::start_with_next([=](not_null<UserData*> user) {
  1070. weak->list.erase(std::remove(
  1071. weak->list.begin(),
  1072. weak->list.end(),
  1073. user), weak->list.end());
  1074. weak->filterResults.erase(std::remove(
  1075. weak->filterResults.begin(),
  1076. weak->filterResults.end(),
  1077. user), weak->filterResults.end());
  1078. }, my->lifetime);
  1079. }
  1080. result->controllerState = std::move(my);
  1081. return result;
  1082. }
  1083. void ParticipantsBoxController::restoreState(
  1084. std::unique_ptr<PeerListState> state) {
  1085. auto typeErasedState = state
  1086. ? state->controllerState.get()
  1087. : nullptr;
  1088. if (const auto my = dynamic_cast<SavedState*>(typeErasedState)) {
  1089. if (const auto requestId = base::take(_loadRequestId)) {
  1090. _api.request(requestId).cancel();
  1091. }
  1092. _additional = std::move(my->additional);
  1093. _offset = my->offset;
  1094. _allLoaded = my->allLoaded;
  1095. if (const auto search = searchController()) {
  1096. search->restoreState(std::move(my->searchState));
  1097. }
  1098. if (my->wasLoading) {
  1099. loadMoreRows();
  1100. }
  1101. const auto was = _fullCountValue.current();
  1102. PeerListController::restoreState(std::move(state));
  1103. const auto now = delegate()->peerListFullRowsCount();
  1104. if (now > 0 || _allLoaded) {
  1105. refreshDescription();
  1106. if (_stories) {
  1107. for (auto i = 0; i != now; ++i) {
  1108. _stories->process(delegate()->peerListRowAt(i));
  1109. }
  1110. }
  1111. if (now != was) {
  1112. refreshRows();
  1113. }
  1114. }
  1115. if (_onlineSorter) {
  1116. _onlineSorter->sort();
  1117. }
  1118. }
  1119. }
  1120. rpl::producer<int> ParticipantsBoxController::onlineCountValue() const {
  1121. return _onlineCountValue.value();
  1122. }
  1123. rpl::producer<int> ParticipantsBoxController::fullCountValue() const {
  1124. return _fullCountValue.value();
  1125. }
  1126. void ParticipantsBoxController::setStoriesShown(bool shown) {
  1127. _stories = std::make_unique<PeerListStories>(
  1128. this,
  1129. &_navigation->session());
  1130. }
  1131. void ParticipantsBoxController::prepare() {
  1132. auto title = [&] {
  1133. switch (_role) {
  1134. case Role::Admins: return tr::lng_channel_admins();
  1135. case Role::Profile:
  1136. case Role::Members:
  1137. return ((_peer->isChannel() && !_peer->isMegagroup())
  1138. ? tr::lng_profile_subscribers_section()
  1139. : tr::lng_profile_participants_section());
  1140. case Role::Restricted: return tr::lng_exceptions_list_title();
  1141. case Role::Kicked: return tr::lng_removed_list_title();
  1142. }
  1143. Unexpected("Role in ParticipantsBoxController::prepare()");
  1144. }();
  1145. if (const auto megagroup = _peer->asMegagroup()) {
  1146. if (_role == Role::Members) {
  1147. delegate()->peerListSetAboveWidget(CreateMembersVisibleButton(
  1148. megagroup));
  1149. } else if ((_role == Role::Admins)
  1150. && (megagroup->amCreator() || megagroup->hasAdminRights())) {
  1151. const auto validator = AntiSpamMenu::AntiSpamValidator(
  1152. _navigation->parentController(),
  1153. megagroup);
  1154. delegate()->peerListSetAboveWidget(validator.createButton());
  1155. }
  1156. }
  1157. delegate()->peerListSetSearchMode(PeerListSearchMode::Enabled);
  1158. delegate()->peerListSetTitle(std::move(title));
  1159. setDescriptionText(tr::lng_contacts_loading(tr::now));
  1160. setSearchNoResultsText(tr::lng_blocked_list_not_found(tr::now));
  1161. if (_stories) {
  1162. _stories->prepare(delegate());
  1163. }
  1164. if (_role == Role::Profile) {
  1165. auto visible = _peer->isMegagroup()
  1166. ? Info::Profile::CanViewParticipantsValue(_peer->asMegagroup())
  1167. : rpl::single(true);
  1168. std::move(visible) | rpl::start_with_next([=](bool visible) {
  1169. if (!visible) {
  1170. _onlineCountValue = 0;
  1171. _onlineSorter = nullptr;
  1172. } else if (!_onlineSorter) {
  1173. _onlineSorter = std::make_unique<ParticipantsOnlineSorter>(
  1174. _peer,
  1175. delegate());
  1176. _onlineCountValue = _onlineSorter->onlineCountValue();
  1177. }
  1178. unload();
  1179. rebuild();
  1180. }, lifetime());
  1181. } else {
  1182. rebuild();
  1183. }
  1184. }
  1185. void ParticipantsBoxController::unload() {
  1186. while (delegate()->peerListFullRowsCount() > 0) {
  1187. delegate()->peerListRemoveRow(
  1188. delegate()->peerListRowAt(
  1189. delegate()->peerListFullRowsCount() - 1));
  1190. }
  1191. if (const auto requestId = base::take(_loadRequestId)) {
  1192. _api.request(requestId).cancel();
  1193. }
  1194. _allLoaded = false;
  1195. _offset = 0;
  1196. }
  1197. void ParticipantsBoxController::rebuild() {
  1198. if (const auto chat = _peer->asChat()) {
  1199. prepareChatRows(chat);
  1200. } else {
  1201. loadMoreRows();
  1202. }
  1203. refreshRows();
  1204. }
  1205. QPointer<Ui::BoxContent> ParticipantsBoxController::showBox(
  1206. object_ptr<Ui::BoxContent> box) const {
  1207. const auto weak = Ui::MakeWeak(box.data());
  1208. delegate()->peerListUiShow()->showBox(std::move(box));
  1209. return weak;
  1210. }
  1211. void ParticipantsBoxController::prepareChatRows(not_null<ChatData*> chat) {
  1212. if (_role == Role::Profile || _role == Role::Members) {
  1213. _onlineSorter = std::make_unique<ParticipantsOnlineSorter>(
  1214. chat,
  1215. delegate());
  1216. }
  1217. rebuildChatRows(chat);
  1218. if (!delegate()->peerListFullRowsCount()) {
  1219. chat->updateFullForced();
  1220. }
  1221. using UpdateFlag = Data::PeerUpdate::Flag;
  1222. chat->session().changes().peerUpdates(
  1223. chat,
  1224. UpdateFlag::Members | UpdateFlag::Admins
  1225. ) | rpl::start_with_next([=](const Data::PeerUpdate &update) {
  1226. _additional.fillFromPeer();
  1227. if ((update.flags & UpdateFlag::Members)
  1228. || (_role == Role::Admins)) {
  1229. rebuildChatRows(chat);
  1230. }
  1231. if (update.flags & UpdateFlag::Admins) {
  1232. rebuildRowTypes();
  1233. }
  1234. }, lifetime());
  1235. }
  1236. void ParticipantsBoxController::rebuildChatRows(not_null<ChatData*> chat) {
  1237. switch (_role) {
  1238. case Role::Profile:
  1239. case Role::Members: return rebuildChatParticipants(chat);
  1240. case Role::Admins: return rebuildChatAdmins(chat);
  1241. case Role::Restricted:
  1242. case Role::Kicked: return chatListReady();
  1243. }
  1244. Unexpected("Role in ParticipantsBoxController::rebuildChatRows");
  1245. }
  1246. void ParticipantsBoxController::rebuildChatParticipants(
  1247. not_null<ChatData*> chat) {
  1248. if (chat->noParticipantInfo()) {
  1249. chat->updateFullForced();
  1250. return;
  1251. }
  1252. auto &participants = chat->participants;
  1253. auto count = delegate()->peerListFullRowsCount();
  1254. for (auto i = 0; i != count;) {
  1255. auto row = delegate()->peerListRowAt(i);
  1256. Assert(row->peer()->isUser());
  1257. auto user = row->peer()->asUser();
  1258. if (participants.contains(user)) {
  1259. ++i;
  1260. } else {
  1261. delegate()->peerListRemoveRow(row);
  1262. --count;
  1263. }
  1264. }
  1265. for (const auto &user : participants) {
  1266. if (!delegate()->peerListFindRow(user->id.value)) {
  1267. if (auto row = createRow(user)) {
  1268. const auto raw = row.get();
  1269. delegate()->peerListAppendRow(std::move(row));
  1270. if (_stories) {
  1271. _stories->process(raw);
  1272. }
  1273. }
  1274. }
  1275. }
  1276. _onlineSorter->sort();
  1277. refreshRows();
  1278. chatListReady();
  1279. }
  1280. void ParticipantsBoxController::rebuildChatAdmins(
  1281. not_null<ChatData*> chat) {
  1282. if (chat->participants.empty()) {
  1283. // We get such updates often
  1284. // (when participants list was invalidated).
  1285. //while (delegate()->peerListFullRowsCount() > 0) {
  1286. // delegate()->peerListRemoveRow(
  1287. // delegate()->peerListRowAt(0));
  1288. //}
  1289. return;
  1290. }
  1291. auto list = ranges::views::all(chat->admins) | ranges::to_vector;
  1292. if (const auto creator = chat->owner().userLoaded(chat->creator)) {
  1293. list.emplace_back(creator);
  1294. }
  1295. ranges::sort(list, [](not_null<UserData*> a, not_null<UserData*> b) {
  1296. return (a->name().compare(b->name(), Qt::CaseInsensitive) < 0);
  1297. });
  1298. const auto same = [&] {
  1299. const auto count = delegate()->peerListFullRowsCount();
  1300. if (count != list.size()) {
  1301. return false;
  1302. }
  1303. for (auto i = 0; i != count; ++i) {
  1304. if (list[i] != delegate()->peerListRowAt(i)->peer()) {
  1305. return false;
  1306. }
  1307. }
  1308. return true;
  1309. }();
  1310. if (same) {
  1311. if (!_allLoaded && !delegate()->peerListFullRowsCount()) {
  1312. chatListReady();
  1313. }
  1314. return;
  1315. }
  1316. while (delegate()->peerListFullRowsCount() > 0) {
  1317. delegate()->peerListRemoveRow(
  1318. delegate()->peerListRowAt(0));
  1319. }
  1320. for (const auto user : list) {
  1321. if (auto row = createRow(user)) {
  1322. const auto raw = row.get();
  1323. delegate()->peerListAppendRow(std::move(row));
  1324. if (_stories) {
  1325. _stories->process(raw);
  1326. }
  1327. }
  1328. }
  1329. refreshRows();
  1330. chatListReady();
  1331. }
  1332. void ParticipantsBoxController::chatListReady() {
  1333. if (_allLoaded) {
  1334. return;
  1335. }
  1336. _allLoaded = true;
  1337. refreshDescription();
  1338. }
  1339. void ParticipantsBoxController::rebuildRowTypes() {
  1340. if (_role != Role::Profile) {
  1341. return;
  1342. }
  1343. const auto count = delegate()->peerListFullRowsCount();
  1344. for (auto i = 0; i != count; ++i) {
  1345. const auto row = static_cast<Row*>(
  1346. delegate()->peerListRowAt(i).get());
  1347. row->setType(computeType(row->user()));
  1348. }
  1349. refreshRows();
  1350. }
  1351. void ParticipantsBoxController::loadMoreRows() {
  1352. if (searchController() && searchController()->loadMoreRows()) {
  1353. return;
  1354. } else if (!_peer->isChannel() || _loadRequestId || _allLoaded) {
  1355. return;
  1356. }
  1357. const auto channel = _peer->asChannel();
  1358. if (feedMegagroupLastParticipants()) {
  1359. return;
  1360. }
  1361. const auto filter = [&] {
  1362. if (_role == Role::Members || _role == Role::Profile) {
  1363. return MTP_channelParticipantsRecent();
  1364. } else if (_role == Role::Admins) {
  1365. return MTP_channelParticipantsAdmins();
  1366. } else if (_role == Role::Restricted) {
  1367. return MTP_channelParticipantsBanned(MTP_string());
  1368. }
  1369. return MTP_channelParticipantsKicked(MTP_string());
  1370. }();
  1371. // First query is small and fast, next loads a lot of rows.
  1372. const auto perPage = (_offset > 0)
  1373. ? kParticipantsPerPage
  1374. : kParticipantsFirstPageCount;
  1375. const auto participantsHash = uint64(0);
  1376. _loadRequestId = _api.request(MTPchannels_GetParticipants(
  1377. channel->inputChannel,
  1378. filter,
  1379. MTP_int(_offset),
  1380. MTP_int(perPage),
  1381. MTP_long(participantsHash)
  1382. )).done([=](const MTPchannels_ChannelParticipants &result) {
  1383. auto added = false;
  1384. const auto firstLoad = !_offset;
  1385. _loadRequestId = 0;
  1386. auto wasRecentRequest = firstLoad
  1387. && (_role == Role::Members || _role == Role::Profile)
  1388. && channel->canViewMembers();
  1389. result.match([&](const MTPDchannels_channelParticipants &data) {
  1390. const auto &[availableCount, list] = wasRecentRequest
  1391. ? Api::ChatParticipants::ParseRecent(channel, data)
  1392. : Api::ChatParticipants::Parse(channel, data);
  1393. for (const auto &data : list) {
  1394. if (const auto participant = _additional.applyParticipant(
  1395. data)) {
  1396. if (appendRow(participant)) {
  1397. added = true;
  1398. }
  1399. }
  1400. }
  1401. if (const auto size = list.size()) {
  1402. _offset += size;
  1403. } else {
  1404. // To be sure - wait for a whole empty result list.
  1405. _allLoaded = true;
  1406. }
  1407. }, [](const MTPDchannels_channelParticipantsNotModified &) {
  1408. LOG(("API Error: "
  1409. "channels.channelParticipantsNotModified received!"));
  1410. });
  1411. if (_offset > 0 && _role == Role::Admins && channel->isMegagroup()) {
  1412. if (channel->mgInfo->admins.empty() && channel->mgInfo->adminsLoaded) {
  1413. channel->mgInfo->adminsLoaded = false;
  1414. }
  1415. }
  1416. if (!firstLoad && !added) {
  1417. _allLoaded = true;
  1418. }
  1419. if (_allLoaded
  1420. || (firstLoad && delegate()->peerListFullRowsCount() > 0)) {
  1421. refreshDescription();
  1422. }
  1423. if (_onlineSorter) {
  1424. _onlineSorter->sort();
  1425. }
  1426. refreshRows();
  1427. }).fail([this] {
  1428. _loadRequestId = 0;
  1429. }).send();
  1430. }
  1431. void ParticipantsBoxController::refreshDescription() {
  1432. setDescriptionText((_role == Role::Kicked)
  1433. ? ((_peer->isChat() || _peer->isMegagroup())
  1434. ? tr::lng_group_removed_list_about
  1435. : tr::lng_channel_removed_list_about)(tr::now)
  1436. : (delegate()->peerListFullRowsCount() > 0)
  1437. ? QString()
  1438. : tr::lng_blocked_list_not_found(tr::now));
  1439. }
  1440. bool ParticipantsBoxController::feedMegagroupLastParticipants() {
  1441. if ((_role != Role::Members && _role != Role::Profile)
  1442. || delegate()->peerListFullRowsCount() > 0) {
  1443. return false;
  1444. }
  1445. const auto megagroup = _peer->asMegagroup();
  1446. if (!megagroup || !megagroup->canViewMembers()) {
  1447. return false;
  1448. }
  1449. const auto info = megagroup->mgInfo.get();
  1450. //
  1451. // channelFull and channels_channelParticipants members count desynced
  1452. // so we almost always have LastParticipantsCountOutdated that is set
  1453. // inside setMembersCount() and so we almost never use lastParticipants.
  1454. //
  1455. // => disable this check temporarily.
  1456. //
  1457. //if (info->lastParticipantsStatus
  1458. // != MegagroupInfo::LastParticipantsUpToDate) {
  1459. // _channel->updateFull();
  1460. // return false;
  1461. //}
  1462. if (info->lastParticipants.empty()) {
  1463. return false;
  1464. }
  1465. auto added = false;
  1466. _additional.fillFromPeer();
  1467. for (const auto user : info->lastParticipants) {
  1468. if (appendRow(user)) {
  1469. added = true;
  1470. }
  1471. //
  1472. // Don't count lastParticipants in _offset, because we don't know
  1473. // their exact information (admin / creator / restricted), they
  1474. // could simply be added from the last messages authors.
  1475. //
  1476. //++_offset;
  1477. }
  1478. if (_onlineSorter) {
  1479. _onlineSorter->sort();
  1480. }
  1481. return added;
  1482. }
  1483. void ParticipantsBoxController::rowClicked(not_null<PeerListRow*> row) {
  1484. const auto participant = row->peer();
  1485. const auto user = participant->asUser();
  1486. if (_stories && _stories->handleClick(participant)) {
  1487. return;
  1488. }
  1489. if (_role == Role::Admins) {
  1490. Assert(user != nullptr);
  1491. showAdmin(user);
  1492. } else if (_role == Role::Restricted
  1493. && (_peer->isChat() || _peer->isMegagroup())
  1494. && user) {
  1495. showRestricted(user);
  1496. } else {
  1497. Assert(_navigation != nullptr);
  1498. if (_role != Role::Profile) {
  1499. _navigation->parentController()->show(PrepareShortInfoBox(
  1500. participant,
  1501. _navigation));
  1502. } else {
  1503. _navigation->showPeerInfo(participant);
  1504. }
  1505. }
  1506. }
  1507. void ParticipantsBoxController::rowRightActionClicked(
  1508. not_null<PeerListRow*> row) {
  1509. const auto participant = row->peer();
  1510. const auto user = participant->asUser();
  1511. if (_role == Role::Members || _role == Role::Profile) {
  1512. kickParticipant(participant);
  1513. } else if (_role == Role::Admins) {
  1514. Assert(user != nullptr);
  1515. removeAdmin(user);
  1516. } else {
  1517. removeKicked(row, participant);
  1518. }
  1519. }
  1520. base::unique_qptr<Ui::PopupMenu> ParticipantsBoxController::rowContextMenu(
  1521. QWidget *parent,
  1522. not_null<PeerListRow*> row) {
  1523. const auto channel = _peer->asChannel();
  1524. const auto participant = row->peer();
  1525. const auto user = participant->asUser();
  1526. auto result = base::make_unique_q<Ui::PopupMenu>(
  1527. parent,
  1528. st::popupMenuWithIcons);
  1529. const auto addToEnd = gsl::finally([&] {
  1530. const auto addInfoAction = [&](
  1531. not_null<PeerData*> by,
  1532. tr::phrase<lngtag_user, lngtag_date> phrase,
  1533. TimeId since) {
  1534. auto text = phrase(
  1535. tr::now,
  1536. lt_user,
  1537. Ui::Text::Bold(by->name()),
  1538. lt_date,
  1539. Ui::Text::Bold(
  1540. langDateTimeFull(base::unixtime::parse(since))),
  1541. Ui::Text::WithEntities);
  1542. auto button = base::make_unique_q<Ui::Menu::MultilineAction>(
  1543. result->menu(),
  1544. result->st().menu,
  1545. st::historyHasCustomEmoji,
  1546. st::historyHasCustomEmojiPosition,
  1547. std::move(text));
  1548. if (const auto n = _navigation) {
  1549. button->setClickedCallback([=] {
  1550. n->parentController()->show(PrepareShortInfoBox(by, n));
  1551. });
  1552. }
  1553. result->addSeparator();
  1554. result->addAction(std::move(button));
  1555. };
  1556. if (const auto by = _additional.restrictedBy(participant)) {
  1557. if (const auto since = _additional.restrictedSince(participant)) {
  1558. addInfoAction(
  1559. by,
  1560. _additional.isKicked(participant)
  1561. ? tr::lng_rights_chat_banned_by
  1562. : tr::lng_rights_chat_restricted_by,
  1563. since);
  1564. }
  1565. } else if (user) {
  1566. if (const auto by = _additional.adminPromotedBy(user)) {
  1567. if (const auto since = _additional.adminPromotedSince(user)) {
  1568. addInfoAction(by, tr::lng_rights_about_by, since);
  1569. }
  1570. }
  1571. }
  1572. });
  1573. if (_navigation) {
  1574. result->addAction(
  1575. (participant->isUser()
  1576. ? tr::lng_context_view_profile
  1577. : participant->isBroadcast()
  1578. ? tr::lng_context_view_channel
  1579. : tr::lng_context_view_group)(tr::now),
  1580. crl::guard(this, [=, this] {
  1581. _navigation->parentController()->show(
  1582. PrepareShortInfoBox(participant, _navigation));
  1583. }),
  1584. (participant->isUser()
  1585. ? &st::menuIconProfile
  1586. : &st::menuIconInfo));
  1587. }
  1588. if (_role == Role::Kicked) {
  1589. if (_peer->isMegagroup()
  1590. && _additional.canRestrictParticipant(participant)) {
  1591. if (user && channel->canAddMembers()) {
  1592. result->addAction(
  1593. tr::lng_context_add_to_group(tr::now),
  1594. crl::guard(this, [=] { unkickParticipant(user); }),
  1595. &st::menuIconInvite);
  1596. }
  1597. result->addAction(
  1598. tr::lng_profile_delete_removed(tr::now),
  1599. crl::guard(this, [=] { removeKickedWithRow(participant); }),
  1600. &st::menuIconDelete);
  1601. }
  1602. return result;
  1603. }
  1604. if (user && _additional.canAddOrEditAdmin(user)) {
  1605. const auto isAdmin = _additional.isCreator(user)
  1606. || _additional.adminRights(user).has_value();
  1607. result->addAction(
  1608. (isAdmin
  1609. ? tr::lng_context_edit_permissions
  1610. : tr::lng_context_promote_admin)(tr::now),
  1611. crl::guard(this, [=] { showAdmin(user); }),
  1612. (isAdmin
  1613. ? &st::menuIconAdmin
  1614. : &st::menuIconPromote));
  1615. }
  1616. if (user && _additional.canRestrictParticipant(participant)) {
  1617. const auto canRestrictWithoutKick = [&] {
  1618. if (const auto chat = _peer->asChat()) {
  1619. return chat->amCreator();
  1620. }
  1621. return _peer->isMegagroup() && !_peer->isGigagroup();
  1622. }();
  1623. if (canRestrictWithoutKick) {
  1624. result->addAction(
  1625. tr::lng_context_restrict_user(tr::now),
  1626. crl::guard(this, [=] { showRestricted(user); }),
  1627. &st::menuIconPermissions);
  1628. }
  1629. }
  1630. if (user && _additional.canRemoveParticipant(participant)) {
  1631. if (!_additional.isKicked(participant)) {
  1632. const auto isGroup = _peer->isChat() || _peer->isMegagroup();
  1633. result->addAction(
  1634. (isGroup
  1635. ? tr::lng_context_remove_from_group
  1636. : tr::lng_profile_kick)(tr::now),
  1637. crl::guard(this, [=] { kickParticipant(user); }),
  1638. &st::menuIconRemove);
  1639. }
  1640. }
  1641. return result;
  1642. }
  1643. void ParticipantsBoxController::showAdmin(not_null<UserData*> user) {
  1644. const auto adminRights = _additional.adminRights(user);
  1645. const auto currentRights = adminRights.value_or(ChatAdminRightsInfo());
  1646. auto box = Box<EditAdminBox>(
  1647. _peer,
  1648. user,
  1649. currentRights,
  1650. _additional.adminRank(user),
  1651. _additional.adminPromotedSince(user),
  1652. _additional.adminPromotedBy(user));
  1653. if (_additional.canAddOrEditAdmin(user)) {
  1654. const auto done = crl::guard(this, [=](
  1655. ChatAdminRightsInfo newRights,
  1656. const QString &rank) {
  1657. editAdminDone(user, newRights, rank);
  1658. });
  1659. const auto fail = crl::guard(this, [=] {
  1660. if (_editParticipantBox) {
  1661. _editParticipantBox->closeBox();
  1662. }
  1663. });
  1664. const auto show = delegate()->peerListUiShow();
  1665. box->setSaveCallback(
  1666. SaveAdminCallback(show, _peer, user, done, fail));
  1667. }
  1668. _editParticipantBox = showBox(std::move(box));
  1669. }
  1670. void ParticipantsBoxController::editAdminDone(
  1671. not_null<UserData*> user,
  1672. ChatAdminRightsInfo rights,
  1673. const QString &rank) {
  1674. _addBox = nullptr;
  1675. if (_editParticipantBox) {
  1676. _editParticipantBox->closeBox();
  1677. }
  1678. _additional.applyAdminLocally(user, rights, rank);
  1679. if (!_additional.isCreator(user) || !user->isSelf()) {
  1680. if (!rights.flags) {
  1681. if (_role == Role::Admins) {
  1682. removeRow(user);
  1683. }
  1684. } else {
  1685. if (_role == Role::Admins) {
  1686. prependRow(user);
  1687. } else if (_role == Role::Kicked || _role == Role::Restricted) {
  1688. removeRow(user);
  1689. }
  1690. }
  1691. }
  1692. recomputeTypeFor(user);
  1693. refreshRows();
  1694. }
  1695. void ParticipantsBoxController::showRestricted(not_null<UserData*> user) {
  1696. const auto restrictedRights = _additional.restrictedRights(user);
  1697. const auto currentRights = restrictedRights
  1698. ? *restrictedRights
  1699. : ChatRestrictionsInfo();
  1700. const auto hasAdminRights = _additional.adminRights(user).has_value();
  1701. auto box = Box<EditRestrictedBox>(
  1702. _peer,
  1703. user,
  1704. hasAdminRights,
  1705. currentRights,
  1706. _additional.restrictedBy(user),
  1707. _additional.restrictedSince(user));
  1708. if (_additional.canRestrictParticipant(user)) {
  1709. const auto done = crl::guard(this, [=](
  1710. ChatRestrictionsInfo newRights) {
  1711. editRestrictedDone(user, newRights);
  1712. });
  1713. const auto fail = crl::guard(this, [=] {
  1714. if (_editParticipantBox) {
  1715. _editParticipantBox->closeBox();
  1716. }
  1717. });
  1718. box->setSaveCallback(
  1719. SaveRestrictedCallback(_peer, user, done, fail));
  1720. }
  1721. _editParticipantBox = showBox(std::move(box));
  1722. }
  1723. void ParticipantsBoxController::editRestrictedDone(
  1724. not_null<PeerData*> participant,
  1725. ChatRestrictionsInfo rights) {
  1726. _addBox = nullptr;
  1727. if (_editParticipantBox) {
  1728. _editParticipantBox->closeBox();
  1729. }
  1730. _additional.applyBannedLocally(participant, rights);
  1731. if (!rights.flags) {
  1732. if (_role == Role::Kicked || _role == Role::Restricted) {
  1733. removeRow(participant);
  1734. }
  1735. } else {
  1736. const auto kicked = rights.flags & ChatRestriction::ViewMessages;
  1737. if (kicked) {
  1738. if (_role == Role::Kicked) {
  1739. prependRow(participant);
  1740. } else if (_role == Role::Admins
  1741. || _role == Role::Restricted
  1742. || _role == Role::Members) {
  1743. removeRow(participant);
  1744. }
  1745. } else {
  1746. if (_role == Role::Restricted) {
  1747. prependRow(participant);
  1748. } else if (_role == Role::Kicked
  1749. || _role == Role::Admins
  1750. || _role == Role::Members) {
  1751. removeRow(participant);
  1752. }
  1753. }
  1754. }
  1755. recomputeTypeFor(participant);
  1756. refreshRows();
  1757. }
  1758. void ParticipantsBoxController::kickParticipant(not_null<PeerData*> participant) {
  1759. const auto user = participant->asUser();
  1760. const auto text = ((_peer->isChat() || _peer->isMegagroup())
  1761. ? tr::lng_profile_sure_kick
  1762. : tr::lng_profile_sure_kick_channel)(
  1763. tr::now,
  1764. lt_user,
  1765. user ? user->firstName : participant->name());
  1766. _editBox = showBox(
  1767. Ui::MakeConfirmBox({
  1768. .text = text,
  1769. .confirmed = crl::guard(this, [=] {
  1770. kickParticipantSure(participant);
  1771. }),
  1772. .confirmText = tr::lng_box_remove(),
  1773. }));
  1774. }
  1775. void ParticipantsBoxController::unkickParticipant(not_null<UserData*> user) {
  1776. _editBox = nullptr;
  1777. if (const auto row = delegate()->peerListFindRow(user->id.value)) {
  1778. delegate()->peerListRemoveRow(row);
  1779. refreshRows();
  1780. }
  1781. const auto show = delegate()->peerListUiShow();
  1782. _peer->session().api().chatParticipants().add(show, _peer, { 1, user });
  1783. }
  1784. void ParticipantsBoxController::kickParticipantSure(
  1785. not_null<PeerData*> participant) {
  1786. _editBox = nullptr;
  1787. const auto restrictedRights = _additional.restrictedRights(participant);
  1788. const auto currentRights = restrictedRights
  1789. ? *restrictedRights
  1790. : ChatRestrictionsInfo();
  1791. if (const auto row = delegate()->peerListFindRow(participant->id.value)) {
  1792. delegate()->peerListRemoveRow(row);
  1793. refreshRows();
  1794. }
  1795. auto &session = _peer->session();
  1796. if (const auto chat = _peer->asChat()) {
  1797. session.api().chatParticipants().kick(chat, participant);
  1798. } else if (const auto channel = _peer->asChannel()) {
  1799. session.api().chatParticipants().kick(
  1800. channel,
  1801. participant,
  1802. currentRights);
  1803. }
  1804. }
  1805. void ParticipantsBoxController::removeAdmin(not_null<UserData*> user) {
  1806. _editBox = showBox(
  1807. Ui::MakeConfirmBox({
  1808. .text = tr::lng_profile_sure_remove_admin(
  1809. tr::now,
  1810. lt_user,
  1811. user->firstName),
  1812. .confirmed = crl::guard(this, [=] { removeAdminSure(user); }),
  1813. .confirmText = tr::lng_box_remove(),
  1814. }));
  1815. }
  1816. void ParticipantsBoxController::removeAdminSure(not_null<UserData*> user) {
  1817. _editBox = nullptr;
  1818. if (const auto chat = _peer->asChat()) {
  1819. const auto show = delegate()->peerListUiShow();
  1820. SaveChatAdmin(show, chat, user, false, crl::guard(this, [=] {
  1821. editAdminDone(
  1822. user,
  1823. ChatAdminRightsInfo(),
  1824. QString());
  1825. }), nullptr);
  1826. } else if (const auto channel = _peer->asChannel()) {
  1827. const auto adminRights = _additional.adminRights(user);
  1828. if (!adminRights) {
  1829. return;
  1830. }
  1831. RemoveAdmin(channel, user, *adminRights, crl::guard(this, [=] {
  1832. editAdminDone(
  1833. user,
  1834. ChatAdminRightsInfo(),
  1835. QString());
  1836. }), nullptr);
  1837. }
  1838. }
  1839. void ParticipantsBoxController::removeKickedWithRow(
  1840. not_null<PeerData*> participant) {
  1841. if (const auto row = delegate()->peerListFindRow(participant->id.value)) {
  1842. removeKicked(row, participant);
  1843. } else {
  1844. removeKicked(participant);
  1845. }
  1846. }
  1847. void ParticipantsBoxController::removeKicked(
  1848. not_null<PeerData*> participant) {
  1849. if (const auto channel = _peer->asChannel()) {
  1850. channel->session().api().chatParticipants().unblock(
  1851. channel,
  1852. participant);
  1853. }
  1854. }
  1855. void ParticipantsBoxController::removeKicked(
  1856. not_null<PeerListRow*> row,
  1857. not_null<PeerData*> participant) {
  1858. delegate()->peerListRemoveRow(row);
  1859. if (_role != Role::Kicked
  1860. && !delegate()->peerListFullRowsCount()) {
  1861. setDescriptionText(tr::lng_blocked_list_not_found(tr::now));
  1862. }
  1863. refreshRows();
  1864. removeKicked(participant);
  1865. }
  1866. bool ParticipantsBoxController::appendRow(not_null<PeerData*> participant) {
  1867. if (delegate()->peerListFindRow(participant->id.value)) {
  1868. recomputeTypeFor(participant);
  1869. return false;
  1870. } else if (auto row = createRow(participant)) {
  1871. const auto raw = row.get();
  1872. delegate()->peerListAppendRow(std::move(row));
  1873. if (_stories) {
  1874. _stories->process(raw);
  1875. }
  1876. if (_role != Role::Kicked) {
  1877. setDescriptionText(QString());
  1878. }
  1879. return true;
  1880. }
  1881. return false;
  1882. }
  1883. bool ParticipantsBoxController::prependRow(not_null<PeerData*> participant) {
  1884. if (const auto row = delegate()->peerListFindRow(participant->id.value)) {
  1885. recomputeTypeFor(participant);
  1886. refreshCustomStatus(row);
  1887. if (_role == Role::Admins) {
  1888. // Perhaps we've added a new admin from search.
  1889. delegate()->peerListPrependRowFromSearchResult(row);
  1890. if (_stories) {
  1891. _stories->process(row);
  1892. }
  1893. }
  1894. return false;
  1895. } else if (auto row = createRow(participant)) {
  1896. const auto raw = row.get();
  1897. delegate()->peerListPrependRow(std::move(row));
  1898. if (_stories) {
  1899. _stories->process(raw);
  1900. }
  1901. if (_role != Role::Kicked) {
  1902. setDescriptionText(QString());
  1903. }
  1904. return true;
  1905. }
  1906. return false;
  1907. }
  1908. bool ParticipantsBoxController::removeRow(not_null<PeerData*> participant) {
  1909. if (auto row = delegate()->peerListFindRow(participant->id.value)) {
  1910. if (_role == Role::Admins) {
  1911. // Perhaps we are removing an admin from search results.
  1912. row->setCustomStatus(tr::lng_channel_admin_status_not_admin(tr::now));
  1913. delegate()->peerListConvertRowToSearchResult(row);
  1914. } else {
  1915. delegate()->peerListRemoveRow(row);
  1916. }
  1917. if (_role != Role::Kicked
  1918. && !delegate()->peerListFullRowsCount()) {
  1919. setDescriptionText(tr::lng_blocked_list_not_found(tr::now));
  1920. }
  1921. return true;
  1922. }
  1923. return false;
  1924. }
  1925. std::unique_ptr<PeerListRow> ParticipantsBoxController::createRow(
  1926. not_null<PeerData*> participant) const {
  1927. const auto user = participant->asUser();
  1928. if (_role == Role::Profile) {
  1929. Assert(user != nullptr);
  1930. return std::make_unique<Row>(user, computeType(user));
  1931. }
  1932. const auto chat = _peer->asChat();
  1933. const auto channel = _peer->asChannel();
  1934. auto row = std::make_unique<PeerListRowWithLink>(participant);
  1935. refreshCustomStatus(row.get());
  1936. if (_role == Role::Admins
  1937. && user
  1938. && !_additional.isCreator(user)
  1939. && _additional.adminRights(user).has_value()
  1940. && _additional.canEditAdmin(user)) {
  1941. row->setActionLink(tr::lng_profile_kick(tr::now));
  1942. } else if (_role == Role::Kicked || _role == Role::Restricted) {
  1943. if (_additional.canRestrictParticipant(participant)) {
  1944. row->setActionLink(tr::lng_profile_delete_removed(tr::now));
  1945. }
  1946. } else if (_role == Role::Members) {
  1947. Assert(user != nullptr);
  1948. if ((chat ? chat->canBanMembers() : channel->canBanMembers())
  1949. && !_additional.isCreator(user)
  1950. && (!_additional.adminRights(user)
  1951. || _additional.canEditAdmin(user))) {
  1952. row->setActionLink(tr::lng_profile_kick(tr::now));
  1953. }
  1954. if (_role == Role::Members && user->isBot()) {
  1955. auto seesAllMessages = (user->botInfo->readsAllHistory || _additional.adminRights(user).has_value());
  1956. row->setCustomStatus(seesAllMessages
  1957. ? tr::lng_status_bot_reads_all(tr::now)
  1958. : tr::lng_status_bot_not_reads_all(tr::now));
  1959. }
  1960. }
  1961. return row;
  1962. }
  1963. auto ParticipantsBoxController::computeType(
  1964. not_null<PeerData*> participant) const -> Type {
  1965. const auto user = participant->asUser();
  1966. auto result = Type();
  1967. result.rights = (user && _additional.isCreator(user))
  1968. ? Rights::Creator
  1969. : (user && _additional.adminRights(user).has_value())
  1970. ? Rights::Admin
  1971. : Rights::Normal;
  1972. result.adminRank = user ? _additional.adminRank(user) : QString();
  1973. return result;
  1974. }
  1975. void ParticipantsBoxController::recomputeTypeFor(
  1976. not_null<PeerData*> participant) {
  1977. if (_role != Role::Profile) {
  1978. return;
  1979. }
  1980. const auto row = delegate()->peerListFindRow(participant->id.value);
  1981. if (row) {
  1982. static_cast<Row*>(row)->setType(computeType(participant));
  1983. }
  1984. }
  1985. void ParticipantsBoxController::refreshCustomStatus(
  1986. not_null<PeerListRow*> row) const {
  1987. const auto participant = row->peer();
  1988. const auto user = participant->asUser();
  1989. if (_role == Role::Admins) {
  1990. Assert(user != nullptr);
  1991. if (const auto by = _additional.adminPromotedBy(user)) {
  1992. row->setCustomStatus(tr::lng_channel_admin_status_promoted_by(
  1993. tr::now,
  1994. lt_user,
  1995. by->name()));
  1996. } else {
  1997. if (_additional.isCreator(user)) {
  1998. row->setCustomStatus(
  1999. tr::lng_channel_admin_status_creator(tr::now));
  2000. } else {
  2001. row->setCustomStatus(
  2002. tr::lng_channel_admin_status_not_admin(tr::now));
  2003. }
  2004. }
  2005. } else if (_role == Role::Kicked || _role == Role::Restricted) {
  2006. const auto by = _additional.restrictedBy(participant);
  2007. row->setCustomStatus((_role == Role::Kicked
  2008. ? tr::lng_channel_banned_status_removed_by
  2009. : tr::lng_channel_banned_status_restricted_by)(
  2010. tr::now,
  2011. lt_user,
  2012. by ? by->name() : "Unknown"));
  2013. }
  2014. }
  2015. void ParticipantsBoxController::subscribeToMigration() {
  2016. const auto chat = _peer->asChat();
  2017. if (!chat) {
  2018. return;
  2019. }
  2020. SubscribeToMigration(
  2021. chat,
  2022. lifetime(),
  2023. [=](not_null<ChannelData*> channel) { migrate(chat, channel); });
  2024. }
  2025. void ParticipantsBoxController::migrate(
  2026. not_null<ChatData*> chat,
  2027. not_null<ChannelData*> channel) {
  2028. _peer = channel;
  2029. _additional.migrate(chat, channel);
  2030. subscribeToCreatorChange(channel);
  2031. }
  2032. void ParticipantsBoxController::subscribeToCreatorChange(
  2033. not_null<ChannelData*> channel) {
  2034. const auto isCreator = channel->amCreator();
  2035. channel->flagsValue(
  2036. ) | rpl::filter([](const ChannelData::Flags::Change &change) {
  2037. return (change.diff & ChannelDataFlag::Creator);
  2038. }) | rpl::filter([=] {
  2039. return (isCreator != channel->amCreator());
  2040. }) | rpl::start_with_next([=] {
  2041. if (channel->isBroadcast()) {
  2042. fullListRefresh();
  2043. return;
  2044. }
  2045. const auto weak = base::make_weak(this);
  2046. const auto api = &channel->session().api();
  2047. api->request(MTPchannels_GetParticipants(
  2048. channel->inputChannel,
  2049. MTP_channelParticipantsRecent(),
  2050. MTP_int(0), // offset
  2051. MTP_int(channel->session().serverConfig().chatSizeMax),
  2052. MTP_long(0) // hash
  2053. )).done([=](const MTPchannels_ChannelParticipants &result) {
  2054. if (channel->amCreator()) {
  2055. channel->mgInfo->creator = channel->session().user().get();
  2056. }
  2057. channel->mgInfo->lastAdmins.clear();
  2058. channel->mgInfo->lastRestricted.clear();
  2059. channel->mgInfo->lastParticipants.clear();
  2060. result.match([&](const MTPDchannels_channelParticipants &data) {
  2061. Api::ChatParticipants::ParseRecent(channel, data);
  2062. }, [](const MTPDchannels_channelParticipantsNotModified &) {
  2063. });
  2064. if (weak) {
  2065. fullListRefresh();
  2066. }
  2067. }).send();
  2068. }, lifetime());
  2069. }
  2070. void ParticipantsBoxController::fullListRefresh() {
  2071. _additional = ParticipantsAdditionalData(_peer, _role);
  2072. while (const auto count = delegate()->peerListFullRowsCount()) {
  2073. delegate()->peerListRemoveRow(
  2074. delegate()->peerListRowAt(count - 1));
  2075. }
  2076. loadMoreRows();
  2077. refreshRows();
  2078. }
  2079. void ParticipantsBoxController::refreshRows() {
  2080. _fullCountValue = delegate()->peerListFullRowsCount();
  2081. delegate()->peerListRefreshRows();
  2082. }
  2083. ParticipantsBoxSearchController::ParticipantsBoxSearchController(
  2084. not_null<ChannelData*> channel,
  2085. Role role,
  2086. not_null<ParticipantsAdditionalData*> additional)
  2087. : _channel(channel)
  2088. , _role(role)
  2089. , _additional(additional)
  2090. , _api(&_channel->session().mtp()) {
  2091. _timer.setCallback([=] { searchOnServer(); });
  2092. }
  2093. void ParticipantsBoxSearchController::searchQuery(const QString &query) {
  2094. if (_query != query) {
  2095. _query = query;
  2096. _offset = 0;
  2097. _requestId = 0;
  2098. _allLoaded = false;
  2099. if (!_query.isEmpty() && !searchInCache()) {
  2100. _timer.callOnce(AutoSearchTimeout);
  2101. } else {
  2102. _timer.cancel();
  2103. }
  2104. }
  2105. }
  2106. auto ParticipantsBoxSearchController::saveState() const
  2107. -> std::unique_ptr<SavedStateBase> {
  2108. auto result = std::make_unique<SavedState>();
  2109. result->query = _query;
  2110. result->offset = _offset;
  2111. result->allLoaded = _allLoaded;
  2112. result->wasLoading = (_requestId != 0);
  2113. return result;
  2114. }
  2115. void ParticipantsBoxSearchController::restoreState(
  2116. std::unique_ptr<SavedStateBase> state) {
  2117. if (auto my = dynamic_cast<SavedState*>(state.get())) {
  2118. if (auto requestId = base::take(_requestId)) {
  2119. _api.request(requestId).cancel();
  2120. }
  2121. _cache.clear();
  2122. _queries.clear();
  2123. _allLoaded = my->allLoaded;
  2124. _offset = my->offset;
  2125. _query = my->query;
  2126. _timer.cancel();
  2127. _requestId = 0;
  2128. if (my->wasLoading) {
  2129. searchOnServer();
  2130. }
  2131. }
  2132. }
  2133. void ParticipantsBoxSearchController::searchOnServer() {
  2134. Expects(!_query.isEmpty());
  2135. loadMoreRows();
  2136. }
  2137. bool ParticipantsBoxSearchController::isLoading() {
  2138. return _timer.isActive() || _requestId;
  2139. }
  2140. bool ParticipantsBoxSearchController::searchInCache() {
  2141. const auto i = _cache.find(_query);
  2142. if (i != _cache.cend()) {
  2143. _requestId = 0;
  2144. searchDone(
  2145. _requestId,
  2146. i->second.result,
  2147. i->second.requestedCount);
  2148. return true;
  2149. }
  2150. return false;
  2151. }
  2152. bool ParticipantsBoxSearchController::loadMoreRows() {
  2153. if (_query.isEmpty()) {
  2154. return false;
  2155. }
  2156. if (_allLoaded || isLoading()) {
  2157. return true;
  2158. }
  2159. auto filter = [&] {
  2160. switch (_role) {
  2161. case Role::Admins: // Search for members, appoint as admin on found.
  2162. case Role::Profile:
  2163. case Role::Members:
  2164. return MTP_channelParticipantsSearch(MTP_string(_query));
  2165. case Role::Restricted:
  2166. return MTP_channelParticipantsBanned(MTP_string(_query));
  2167. case Role::Kicked:
  2168. return MTP_channelParticipantsKicked(MTP_string(_query));
  2169. }
  2170. Unexpected("Role in ParticipantsBoxSearchController.");
  2171. }();
  2172. // For search we request a lot of rows from the first query.
  2173. // (because we've waited for search request by timer already,
  2174. // so we don't expect it to be fast, but we want to fill cache).
  2175. const auto perPage = kParticipantsPerPage;
  2176. const auto participantsHash = uint64(0);
  2177. _requestId = _api.request(MTPchannels_GetParticipants(
  2178. _channel->inputChannel,
  2179. filter,
  2180. MTP_int(_offset),
  2181. MTP_int(perPage),
  2182. MTP_long(participantsHash)
  2183. )).done([=](
  2184. const MTPchannels_ChannelParticipants &result,
  2185. mtpRequestId requestId) {
  2186. searchDone(requestId, result, perPage);
  2187. }).fail([=](const MTP::Error &error, mtpRequestId requestId) {
  2188. if (_requestId == requestId) {
  2189. _requestId = 0;
  2190. _allLoaded = true;
  2191. delegate()->peerListSearchRefreshRows();
  2192. }
  2193. }).send();
  2194. auto entry = Query();
  2195. entry.text = _query;
  2196. entry.offset = _offset;
  2197. _queries.emplace(_requestId, entry);
  2198. return true;
  2199. }
  2200. void ParticipantsBoxSearchController::searchDone(
  2201. mtpRequestId requestId,
  2202. const MTPchannels_ChannelParticipants &result,
  2203. int requestedCount) {
  2204. auto query = _query;
  2205. if (requestId) {
  2206. const auto addToCache = [&](auto&&...) {
  2207. auto it = _queries.find(requestId);
  2208. if (it != _queries.cend()) {
  2209. query = it->second.text;
  2210. if (it->second.offset == 0) {
  2211. auto &entry = _cache[query];
  2212. entry.result = result;
  2213. entry.requestedCount = requestedCount;
  2214. }
  2215. _queries.erase(it);
  2216. }
  2217. };
  2218. result.match([&](const MTPDchannels_channelParticipants &data) {
  2219. Api::ChatParticipants::Parse(_channel, data);
  2220. addToCache();
  2221. }, [&](const MTPDchannels_channelParticipantsNotModified &) {
  2222. LOG(("API Error: "
  2223. "channels.channelParticipantsNotModified received!"));
  2224. });
  2225. }
  2226. if (_requestId != requestId) {
  2227. return;
  2228. }
  2229. _requestId = 0;
  2230. result.match([&](const MTPDchannels_channelParticipants &data) {
  2231. const auto &list = data.vparticipants().v;
  2232. if (list.size() < requestedCount) {
  2233. // We want cache to have full information about a query with
  2234. // small results count (that we don't need the second request).
  2235. // So we don't wait for empty list unlike the non-search case.
  2236. _allLoaded = true;
  2237. }
  2238. const auto overrideRole = (_role == Role::Admins)
  2239. ? Role::Members
  2240. : _role;
  2241. for (const auto &data : list) {
  2242. const auto user = _additional->applyParticipant(
  2243. Api::ChatParticipant(data, _channel),
  2244. overrideRole);
  2245. if (user) {
  2246. delegate()->peerListSearchAddRow(user);
  2247. }
  2248. }
  2249. _offset += list.size();
  2250. }, [&](const MTPDchannels_channelParticipantsNotModified &) {
  2251. _allLoaded = true;
  2252. });
  2253. delegate()->peerListSearchRefreshRows();
  2254. }