edit_peer_info_box.cpp 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732
  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_peer_info_box.h"
  8. #include "apiwrap.h"
  9. #include "api/api_credits.h"
  10. #include "api/api_peer_photo.h"
  11. #include "api/api_statistics.h"
  12. #include "api/api_user_names.h"
  13. #include "main/main_session.h"
  14. #include "ui/boxes/confirm_box.h"
  15. #include "base/event_filter.h"
  16. #include "boxes/peers/edit_participants_box.h"
  17. #include "boxes/peers/edit_peer_color_box.h"
  18. #include "boxes/peers/edit_peer_common.h"
  19. #include "boxes/peers/edit_peer_type_box.h"
  20. #include "boxes/peers/edit_peer_history_visibility_box.h"
  21. #include "boxes/peers/edit_peer_permissions_box.h"
  22. #include "boxes/peers/edit_peer_invite_links.h"
  23. #include "boxes/peers/edit_linked_chat_box.h"
  24. #include "boxes/peers/edit_peer_requests_box.h"
  25. #include "boxes/peers/edit_peer_reactions.h"
  26. #include "boxes/peers/replace_boost_box.h"
  27. #include "boxes/peers/verify_peers_box.h"
  28. #include "boxes/peer_list_controllers.h"
  29. #include "boxes/stickers_box.h"
  30. #include "boxes/username_box.h"
  31. #include "chat_helpers/emoji_suggestions_widget.h"
  32. #include "chat_helpers/tabbed_panel.h"
  33. #include "chat_helpers/tabbed_selector.h"
  34. #include "core/application.h"
  35. #include "core/core_settings.h"
  36. #include "data/components/credits.h"
  37. #include "data/data_channel.h"
  38. #include "data/data_chat.h"
  39. #include "data/data_peer.h"
  40. #include "data/data_session.h"
  41. #include "data/data_changes.h"
  42. #include "data/data_message_reactions.h"
  43. #include "data/data_peer_values.h"
  44. #include "data/data_premium_limits.h"
  45. #include "data/data_user.h"
  46. #include "history/admin_log/history_admin_log_section.h"
  47. #include "info/bot/earn/info_bot_earn_widget.h"
  48. #include "info/bot/starref/info_bot_starref_join_widget.h"
  49. #include "info/bot/starref/info_bot_starref_setup_widget.h"
  50. #include "info/channel_statistics/boosts/info_boosts_widget.h"
  51. #include "info/channel_statistics/earn/earn_format.h"
  52. #include "info/channel_statistics/earn/earn_icons.h"
  53. #include "info/channel_statistics/earn/info_channel_earn_widget.h"
  54. #include "info/profile/info_profile_values.h"
  55. #include "info/info_memento.h"
  56. #include "lang/lang_keys.h"
  57. #include "mtproto/sender.h"
  58. #include "main/main_app_config.h"
  59. #include "settings/settings_common.h"
  60. #include "ui/boxes/boost_box.h"
  61. #include "ui/controls/emoji_button.h"
  62. #include "ui/controls/userpic_button.h"
  63. #include "ui/effects/premium_graphics.h"
  64. #include "ui/new_badges.h"
  65. #include "ui/rect.h"
  66. #include "ui/rp_widget.h"
  67. #include "ui/vertical_list.h"
  68. #include "ui/toast/toast.h"
  69. #include "ui/text/text_utilities.h"
  70. #include "ui/widgets/checkbox.h"
  71. #include "ui/widgets/buttons.h"
  72. #include "ui/widgets/fields/input_field.h"
  73. #include "ui/widgets/labels.h"
  74. #include "ui/wrap/padding_wrap.h"
  75. #include "ui/wrap/slide_wrap.h"
  76. #include "ui/wrap/vertical_layout.h"
  77. #include "ui/ui_utility.h"
  78. #include "window/window_session_controller.h"
  79. #include "api/api_invite_links.h"
  80. #include "styles/style_chat_helpers.h"
  81. #include "styles/style_layers.h"
  82. #include "styles/style_menu_icons.h"
  83. #include "styles/style_settings.h"
  84. #include "styles/style_boxes.h"
  85. #include "styles/style_info.h"
  86. #include <QtSvg/QSvgRenderer>
  87. namespace {
  88. constexpr auto kBotManagerUsername = "BotFather"_cs;
  89. [[nodiscard]] auto ToPositiveNumberString() {
  90. return rpl::map([](int count) {
  91. return count ? QString::number(count) : QString();
  92. });
  93. }
  94. [[nodiscard]] int EnableForumMinMembers(not_null<PeerData*> peer) {
  95. return peer->session().appConfig().get<int>(
  96. u"forum_upgrade_participants_min"_q,
  97. 200);
  98. }
  99. void AddSkip(
  100. not_null<Ui::VerticalLayout*> container,
  101. int top = st::editPeerTopButtonsLayoutSkip,
  102. int bottom = st::editPeerTopButtonsLayoutSkipToBottom) {
  103. Ui::AddSkip(container, top);
  104. Ui::AddDivider(container);
  105. Ui::AddSkip(container, bottom);
  106. }
  107. void AddButtonWithCount(
  108. not_null<Ui::VerticalLayout*> parent,
  109. rpl::producer<QString> &&text,
  110. rpl::producer<QString> &&count,
  111. Fn<void()> callback,
  112. Settings::IconDescriptor &&descriptor) {
  113. parent->add(EditPeerInfoBox::CreateButton(
  114. parent,
  115. std::move(text),
  116. std::move(count),
  117. std::move(callback),
  118. st::manageGroupButton,
  119. std::move(descriptor)));
  120. }
  121. not_null<Ui::SettingsButton*> AddButtonWithText(
  122. not_null<Ui::VerticalLayout*> parent,
  123. rpl::producer<QString> &&text,
  124. rpl::producer<QString> &&label,
  125. Fn<void()> callback,
  126. Settings::IconDescriptor &&descriptor) {
  127. return parent->add(EditPeerInfoBox::CreateButton(
  128. parent,
  129. std::move(text),
  130. std::move(label),
  131. std::move(callback),
  132. st::manageGroupTopButtonWithText,
  133. std::move(descriptor)));
  134. }
  135. void AddButtonDelete(
  136. not_null<Ui::VerticalLayout*> parent,
  137. rpl::producer<QString> &&text,
  138. Fn<void()> callback) {
  139. parent->add(EditPeerInfoBox::CreateButton(
  140. parent,
  141. std::move(text),
  142. rpl::single(QString()),
  143. std::move(callback),
  144. st::manageDeleteGroupButton,
  145. {}));
  146. }
  147. void SaveDefaultRestrictions(
  148. not_null<PeerData*> peer,
  149. ChatRestrictions rights,
  150. Fn<void()> done) {
  151. const auto api = &peer->session().api();
  152. const auto key = Api::RequestKey("default_restrictions", peer->id);
  153. const auto requestId = api->request(
  154. MTPmessages_EditChatDefaultBannedRights(
  155. peer->input,
  156. MTP_chatBannedRights(
  157. MTP_flags(
  158. MTPDchatBannedRights::Flags::from_raw(uint32(rights))),
  159. MTP_int(0)))
  160. ).done([=](const MTPUpdates &result) {
  161. api->clearModifyRequest(key);
  162. api->applyUpdates(result);
  163. done();
  164. }).fail([=](const MTP::Error &error) {
  165. api->clearModifyRequest(key);
  166. if (error.type() != u"CHAT_NOT_MODIFIED"_q) {
  167. return;
  168. }
  169. if (const auto chat = peer->asChat()) {
  170. chat->setDefaultRestrictions(rights);
  171. } else if (const auto channel = peer->asChannel()) {
  172. channel->setDefaultRestrictions(rights);
  173. } else {
  174. Unexpected("Peer in ApiWrap::saveDefaultRestrictions.");
  175. }
  176. done();
  177. }).send();
  178. api->registerModifyRequest(key, requestId);
  179. }
  180. void SaveSlowmodeSeconds(
  181. not_null<ChannelData*> channel,
  182. int seconds,
  183. Fn<void()> done) {
  184. const auto api = &channel->session().api();
  185. const auto key = Api::RequestKey("slowmode_seconds", channel->id);
  186. const auto requestId = api->request(MTPchannels_ToggleSlowMode(
  187. channel->inputChannel,
  188. MTP_int(seconds)
  189. )).done([=](const MTPUpdates &result) {
  190. api->clearModifyRequest(key);
  191. api->applyUpdates(result);
  192. channel->setSlowmodeSeconds(seconds);
  193. done();
  194. }).fail([=](const MTP::Error &error) {
  195. api->clearModifyRequest(key);
  196. if (error.type() != u"CHAT_NOT_MODIFIED"_q) {
  197. return;
  198. }
  199. channel->setSlowmodeSeconds(seconds);
  200. done();
  201. }).send();
  202. api->registerModifyRequest(key, requestId);
  203. }
  204. void SaveStarsPerMessage(
  205. not_null<ChannelData*> channel,
  206. int starsPerMessage,
  207. Fn<void()> done) {
  208. const auto api = &channel->session().api();
  209. const auto key = Api::RequestKey("stars_per_message", channel->id);
  210. const auto requestId = api->request(MTPchannels_UpdatePaidMessagesPrice(
  211. channel->inputChannel,
  212. MTP_long(starsPerMessage)
  213. )).done([=](const MTPUpdates &result) {
  214. api->clearModifyRequest(key);
  215. api->applyUpdates(result);
  216. channel->setStarsPerMessage(starsPerMessage);
  217. done();
  218. }).fail([=](const MTP::Error &error) {
  219. api->clearModifyRequest(key);
  220. if (error.type() != u"CHAT_NOT_MODIFIED"_q) {
  221. return;
  222. }
  223. channel->setStarsPerMessage(starsPerMessage);
  224. done();
  225. }).send();
  226. api->registerModifyRequest(key, requestId);
  227. }
  228. void SaveBoostsUnrestrict(
  229. not_null<ChannelData*> channel,
  230. int boostsUnrestrict,
  231. Fn<void()> done) {
  232. const auto api = &channel->session().api();
  233. const auto key = Api::RequestKey("boosts_unrestrict", channel->id);
  234. const auto requestId = api->request(
  235. MTPchannels_SetBoostsToUnblockRestrictions(
  236. channel->inputChannel,
  237. MTP_int(boostsUnrestrict))
  238. ).done([=](const MTPUpdates &result) {
  239. api->clearModifyRequest(key);
  240. api->applyUpdates(result);
  241. channel->setBoostsUnrestrict(
  242. channel->boostsApplied(),
  243. boostsUnrestrict);
  244. done();
  245. }).fail([=](const MTP::Error &error) {
  246. api->clearModifyRequest(key);
  247. if (error.type() != u"CHAT_NOT_MODIFIED"_q) {
  248. return;
  249. }
  250. channel->setBoostsUnrestrict(
  251. channel->boostsApplied(),
  252. boostsUnrestrict);
  253. done();
  254. }).send();
  255. api->registerModifyRequest(key, requestId);
  256. }
  257. void ShowEditPermissions(
  258. not_null<Window::SessionNavigation*> navigation,
  259. not_null<PeerData*> peer) {
  260. auto createBox = [=](not_null<Ui::GenericBox*> box) {
  261. const auto saving = box->lifetime().make_state<int>(0);
  262. const auto save = [=](
  263. not_null<PeerData*> peer,
  264. EditPeerPermissionsBoxResult result) {
  265. Expects(result.slowmodeSeconds == 0 || peer->isChannel());
  266. const auto close = crl::guard(box, [=] { box->closeBox(); });
  267. SaveDefaultRestrictions(
  268. peer,
  269. result.rights,
  270. close);
  271. if (const auto channel = peer->asChannel()) {
  272. SaveSlowmodeSeconds(channel, result.slowmodeSeconds, close);
  273. SaveBoostsUnrestrict(
  274. channel,
  275. result.boostsUnrestrict,
  276. close);
  277. SaveStarsPerMessage(channel, result.starsPerMessage, close);
  278. }
  279. };
  280. auto done = [=](EditPeerPermissionsBoxResult result) {
  281. if (*saving) {
  282. return;
  283. }
  284. *saving = true;
  285. const auto saveFor = peer->migrateToOrMe();
  286. const auto chat = saveFor->asChat();
  287. if (!chat
  288. || (!result.slowmodeSeconds
  289. && !result.boostsUnrestrict
  290. && !result.starsPerMessage)) {
  291. save(saveFor, result);
  292. return;
  293. }
  294. const auto api = &peer->session().api();
  295. api->migrateChat(chat, [=](not_null<ChannelData*> channel) {
  296. save(channel, result);
  297. }, [=](const QString &) {
  298. *saving = false;
  299. });
  300. };
  301. ShowEditPeerPermissionsBox(box, navigation, peer, std::move(done));
  302. };
  303. navigation->parentController()->show(Box(std::move(createBox)));
  304. }
  305. class Controller : public base::has_weak_ptr {
  306. public:
  307. Controller(
  308. not_null<Window::SessionNavigation*> navigation,
  309. not_null<Ui::BoxContent*> box,
  310. not_null<PeerData*> peer);
  311. ~Controller();
  312. [[nodiscard]] object_ptr<Ui::VerticalLayout> createContent();
  313. void setFocus();
  314. private:
  315. struct Controls {
  316. Ui::InputField *title = nullptr;
  317. Ui::InputField *description = nullptr;
  318. Ui::UserpicButton *photo = nullptr;
  319. rpl::lifetime initialPhotoImageWaiting;
  320. Ui::VerticalLayout *buttonsLayout = nullptr;
  321. Ui::SettingsButton *forumToggle = nullptr;
  322. bool forumToggleLocked = false;
  323. bool levelRequested = false;
  324. Ui::SlideWrap<> *historyVisibilityWrap = nullptr;
  325. };
  326. struct Saving {
  327. std::optional<QString> username;
  328. std::optional<std::vector<QString>> usernamesOrder;
  329. std::optional<QString> title;
  330. std::optional<QString> description;
  331. std::optional<bool> hiddenPreHistory;
  332. std::optional<bool> forum;
  333. std::optional<bool> signatures;
  334. std::optional<bool> signatureProfiles;
  335. std::optional<bool> noForwards;
  336. std::optional<bool> joinToWrite;
  337. std::optional<bool> requestToJoin;
  338. std::optional<ChannelData*> linkedChat;
  339. };
  340. [[nodiscard]] object_ptr<Ui::RpWidget> createPhotoAndTitleEdit();
  341. [[nodiscard]] object_ptr<Ui::RpWidget> createTitleEdit();
  342. [[nodiscard]] object_ptr<Ui::RpWidget> createPhotoEdit();
  343. [[nodiscard]] object_ptr<Ui::RpWidget> createDescriptionEdit();
  344. [[nodiscard]] object_ptr<Ui::RpWidget> createManageGroupButtons();
  345. [[nodiscard]] object_ptr<Ui::RpWidget> createStickersEdit();
  346. [[nodiscard]] bool canEditInformation() const;
  347. [[nodiscard]] bool canEditReactions() const;
  348. void refreshHistoryVisibility();
  349. void refreshForumToggleLocked();
  350. void showEditPeerTypeBox(
  351. std::optional<rpl::producer<QString>> error = {});
  352. void showEditLinkedChatBox();
  353. void fillPrivacyTypeButton();
  354. void fillLinkedChatButton();
  355. //void fillInviteLinkButton();
  356. void fillForumButton();
  357. void fillColorIndexButton();
  358. void fillSignaturesButton();
  359. void fillHistoryVisibilityButton();
  360. void fillManageSection();
  361. void fillPendingRequestsButton();
  362. void fillBotUsernamesButton();
  363. void fillBotCurrencyButton();
  364. void fillBotCreditsButton();
  365. void fillBotAffiliateProgram();
  366. void fillBotEditIntroButton();
  367. void fillBotEditCommandsButton();
  368. void fillBotEditSettingsButton();
  369. void fillBotVerifyAccounts();
  370. void submitTitle();
  371. void submitDescription();
  372. void deleteWithConfirmation();
  373. void deleteChannel();
  374. void editReactions();
  375. [[nodiscard]] std::optional<Saving> validate() const;
  376. [[nodiscard]] bool validateUsernamesOrder(Saving &to) const;
  377. [[nodiscard]] bool validateUsername(Saving &to) const;
  378. [[nodiscard]] bool validateLinkedChat(Saving &to) const;
  379. [[nodiscard]] bool validateTitle(Saving &to) const;
  380. [[nodiscard]] bool validateDescription(Saving &to) const;
  381. [[nodiscard]] bool validateHistoryVisibility(Saving &to) const;
  382. [[nodiscard]] bool validateForum(Saving &to) const;
  383. [[nodiscard]] bool validateSignatures(Saving &to) const;
  384. [[nodiscard]] bool validateForwards(Saving &to) const;
  385. [[nodiscard]] bool validateJoinToWrite(Saving &to) const;
  386. [[nodiscard]] bool validateRequestToJoin(Saving &to) const;
  387. void save();
  388. void saveUsernamesOrder();
  389. void saveUsername();
  390. void saveLinkedChat();
  391. void saveTitle();
  392. void saveDescription();
  393. void saveHistoryVisibility();
  394. void saveForum();
  395. void saveSignatures();
  396. void saveForwards();
  397. void saveJoinToWrite();
  398. void saveRequestToJoin();
  399. void savePhoto();
  400. void pushSaveStage(FnMut<void()> &&lambda);
  401. void continueSave();
  402. void cancelSave();
  403. void toggleBotManager(const QString &command);
  404. void togglePreHistoryHidden(
  405. not_null<ChannelData*> channel,
  406. bool hidden,
  407. Fn<void()> done,
  408. Fn<void()> fail);
  409. void subscribeToMigration();
  410. void migrate(not_null<ChannelData*> channel);
  411. std::optional<ChannelData*> _linkedChatSavedValue;
  412. ChannelData *_linkedChatOriginalValue = nullptr;
  413. bool _channelHasLocationOriginalValue = false;
  414. std::optional<HistoryVisibility> _historyVisibilitySavedValue;
  415. std::optional<EditPeerTypeData> _typeDataSavedValue;
  416. std::optional<bool> _forumSavedValue;
  417. std::optional<bool> _signaturesSavedValue;
  418. std::optional<bool> _signatureProfilesSavedValue;
  419. const not_null<Window::SessionNavigation*> _navigation;
  420. const not_null<Ui::BoxContent*> _box;
  421. not_null<PeerData*> _peer;
  422. MTP::Sender _api;
  423. const bool _isGroup = false;
  424. const bool _isBot = false;
  425. base::unique_qptr<Ui::VerticalLayout> _wrap;
  426. Controls _controls;
  427. std::deque<FnMut<void()>> _saveStagesQueue;
  428. Saving _savingData;
  429. struct PrivacyAndForwards {
  430. Privacy privacy;
  431. bool noForwards = false;
  432. };
  433. const rpl::event_stream<PrivacyAndForwards> _privacyTypeUpdates;
  434. const rpl::event_stream<ChannelData*> _linkedChatUpdates;
  435. mtpRequestId _linkedChatsRequestId = 0;
  436. rpl::lifetime _lifetime;
  437. };
  438. Controller::Controller(
  439. not_null<Window::SessionNavigation*> navigation,
  440. not_null<Ui::BoxContent*> box,
  441. not_null<PeerData*> peer)
  442. : _navigation(navigation)
  443. , _box(box)
  444. , _peer(peer)
  445. , _api(&_peer->session().mtp())
  446. , _isGroup(_peer->isChat() || _peer->isMegagroup())
  447. , _isBot(_peer->isUser() && _peer->asUser()->botInfo) {
  448. _box->setTitle(_isBot
  449. ? tr::lng_edit_bot_title()
  450. : _isGroup
  451. ? tr::lng_edit_group()
  452. : tr::lng_edit_channel_title());
  453. _box->addButton(tr::lng_settings_save(), [=] {
  454. save();
  455. });
  456. _box->addButton(tr::lng_cancel(), [=] {
  457. _box->closeBox();
  458. });
  459. subscribeToMigration();
  460. _peer->updateFull();
  461. }
  462. Controller::~Controller() = default;
  463. void Controller::subscribeToMigration() {
  464. SubscribeToMigration(
  465. _peer,
  466. _lifetime,
  467. [=](not_null<ChannelData*> channel) { migrate(channel); });
  468. }
  469. void Controller::migrate(not_null<ChannelData*> channel) {
  470. _peer = channel;
  471. _peer->updateFull();
  472. }
  473. object_ptr<Ui::VerticalLayout> Controller::createContent() {
  474. auto result = object_ptr<Ui::VerticalLayout>(_box);
  475. _wrap.reset(result.data());
  476. _controls = Controls();
  477. _wrap->add(createPhotoAndTitleEdit());
  478. _wrap->add(createDescriptionEdit());
  479. _wrap->add(createManageGroupButtons());
  480. return result;
  481. }
  482. void Controller::setFocus() {
  483. if (_controls.title) {
  484. _controls.title->setFocusFast();
  485. }
  486. }
  487. object_ptr<Ui::RpWidget> Controller::createPhotoAndTitleEdit() {
  488. Expects(_wrap != nullptr);
  489. if (!canEditInformation()) {
  490. return nullptr;
  491. }
  492. auto result = object_ptr<Ui::RpWidget>(_wrap);
  493. const auto container = result.data();
  494. const auto photoWrap = Ui::AttachParentChild(
  495. container,
  496. createPhotoEdit());
  497. const auto titleEdit = Ui::AttachParentChild(
  498. container,
  499. createTitleEdit());
  500. photoWrap->heightValue(
  501. ) | rpl::start_with_next([container](int height) {
  502. container->resize(container->width(), height);
  503. }, photoWrap->lifetime());
  504. container->widthValue(
  505. ) | rpl::start_with_next([titleEdit](int width) {
  506. const auto left = st::editPeerPhotoMargins.left()
  507. + st::defaultUserpicButton.size.width();
  508. titleEdit->resizeToWidth(width - left);
  509. titleEdit->moveToLeft(left, 0, width);
  510. }, titleEdit->lifetime());
  511. return result;
  512. }
  513. object_ptr<Ui::RpWidget> Controller::createPhotoEdit() {
  514. Expects(_wrap != nullptr);
  515. using PhotoWrap = Ui::PaddingWrap<Ui::UserpicButton>;
  516. auto photoWrap = object_ptr<PhotoWrap>(
  517. _wrap,
  518. object_ptr<Ui::UserpicButton>(
  519. _wrap,
  520. _navigation->parentController(),
  521. _peer,
  522. Ui::UserpicButton::Role::ChangePhoto,
  523. Ui::UserpicButton::Source::PeerPhoto,
  524. st::defaultUserpicButton),
  525. st::editPeerPhotoMargins);
  526. _controls.photo = photoWrap->entity();
  527. _controls.photo->showCustomOnChosen();
  528. return photoWrap;
  529. }
  530. object_ptr<Ui::RpWidget> Controller::createTitleEdit() {
  531. Expects(_wrap != nullptr);
  532. auto result = object_ptr<Ui::PaddingWrap<Ui::InputField>>(
  533. _wrap,
  534. object_ptr<Ui::InputField>(
  535. _wrap,
  536. st::editPeerTitleField,
  537. (_isBot
  538. ? tr::lng_dlg_new_bot_name
  539. : _isGroup
  540. ? tr::lng_dlg_new_group_name
  541. : tr::lng_dlg_new_channel_name)(),
  542. _peer->name()),
  543. st::editPeerTitleMargins);
  544. result->entity()->setMaxLength(Ui::EditPeer::kMaxGroupChannelTitle);
  545. result->entity()->setInstantReplaces(Ui::InstantReplaces::Default());
  546. result->entity()->setInstantReplacesEnabled(
  547. Core::App().settings().replaceEmojiValue());
  548. Ui::Emoji::SuggestionsController::Init(
  549. _wrap->window(),
  550. result->entity(),
  551. &_peer->session());
  552. result->entity()->submits(
  553. ) | rpl::start_with_next([=] {
  554. submitTitle();
  555. }, result->entity()->lifetime());
  556. {
  557. const auto field = result->entity();
  558. const auto container = _box->getDelegate()->outerContainer();
  559. using Selector = ChatHelpers::TabbedSelector;
  560. using PanelPtr = base::unique_qptr<ChatHelpers::TabbedPanel>;
  561. const auto emojiPanelPtr = field->lifetime().make_state<PanelPtr>(
  562. base::make_unique_q<ChatHelpers::TabbedPanel>(
  563. container,
  564. ChatHelpers::TabbedPanelDescriptor{
  565. .ownedSelector = object_ptr<Selector>(
  566. nullptr,
  567. ChatHelpers::TabbedSelectorDescriptor{
  568. .show = _navigation->uiShow(),
  569. .st = st::defaultComposeControls.tabbed,
  570. .level = Window::GifPauseReason::Layer,
  571. .mode = Selector::Mode::PeerTitle,
  572. }),
  573. }));
  574. const auto emojiPanel = emojiPanelPtr->get();
  575. emojiPanel->setDesiredHeightValues(
  576. 1.,
  577. st::emojiPanMinHeight / 2,
  578. st::emojiPanMinHeight);
  579. emojiPanel->hide();
  580. emojiPanel->selector()->setCurrentPeer(_peer);
  581. emojiPanel->selector()->emojiChosen(
  582. ) | rpl::start_with_next([=](ChatHelpers::EmojiChosen data) {
  583. Ui::InsertEmojiAtCursor(field->textCursor(), data.emoji);
  584. field->setFocus();
  585. }, field->lifetime());
  586. emojiPanel->setDropDown(true);
  587. const auto emojiToggle = Ui::CreateChild<Ui::EmojiButton>(
  588. field,
  589. st::defaultComposeControls.files.emoji);
  590. emojiToggle->show();
  591. emojiToggle->installEventFilter(emojiPanel);
  592. emojiToggle->addClickHandler([=] { emojiPanel->toggleAnimated(); });
  593. const auto updateEmojiPanelGeometry = [=] {
  594. const auto parent = emojiPanel->parentWidget();
  595. const auto global = emojiToggle->mapToGlobal({ 0, 0 });
  596. const auto local = parent->mapFromGlobal(global);
  597. emojiPanel->moveTopRight(
  598. local.y() + emojiToggle->height(),
  599. local.x() + emojiToggle->width() * 3);
  600. };
  601. field->lifetime().make_state<base::unique_qptr<QObject>>([&] {
  602. return base::install_event_filter(container, [=](
  603. not_null<QEvent*> event) {
  604. const auto type = event->type();
  605. if (type == QEvent::Move || type == QEvent::Resize) {
  606. crl::on_main(field, [=] { updateEmojiPanelGeometry(); });
  607. }
  608. return base::EventFilterResult::Continue;
  609. });
  610. }());
  611. field->widthValue() | rpl::start_with_next([=](int width) {
  612. const auto &p = st::editPeerTitleEmojiPosition;
  613. emojiToggle->moveToRight(p.x(), p.y(), width);
  614. updateEmojiPanelGeometry();
  615. }, emojiToggle->lifetime());
  616. base::install_event_filter(emojiToggle, [=](not_null<QEvent*> event) {
  617. if (event->type() == QEvent::Enter) {
  618. updateEmojiPanelGeometry();
  619. }
  620. return base::EventFilterResult::Continue;
  621. });
  622. }
  623. _controls.title = result->entity();
  624. return result;
  625. }
  626. object_ptr<Ui::RpWidget> Controller::createDescriptionEdit() {
  627. Expects(_wrap != nullptr);
  628. if (!canEditInformation()) {
  629. return nullptr;
  630. }
  631. auto result = object_ptr<Ui::PaddingWrap<Ui::InputField>>(
  632. _wrap,
  633. object_ptr<Ui::InputField>(
  634. _wrap,
  635. st::editPeerDescription,
  636. Ui::InputField::Mode::MultiLine,
  637. tr::lng_create_group_description(),
  638. _peer->about()),
  639. st::editPeerDescriptionMargins);
  640. result->entity()->setMaxLength(Ui::EditPeer::kMaxChannelDescription);
  641. result->entity()->setInstantReplaces(Ui::InstantReplaces::Default());
  642. result->entity()->setInstantReplacesEnabled(
  643. Core::App().settings().replaceEmojiValue());
  644. result->entity()->setSubmitSettings(
  645. Core::App().settings().sendSubmitWay());
  646. Ui::Emoji::SuggestionsController::Init(
  647. _wrap->window(),
  648. result->entity(),
  649. &_peer->session());
  650. result->entity()->submits(
  651. ) | rpl::start_with_next([=] {
  652. submitDescription();
  653. }, result->entity()->lifetime());
  654. _controls.description = result->entity();
  655. return result;
  656. }
  657. object_ptr<Ui::RpWidget> Controller::createManageGroupButtons() {
  658. Expects(_wrap != nullptr);
  659. auto result = object_ptr<Ui::PaddingWrap<Ui::VerticalLayout>>(
  660. _wrap,
  661. object_ptr<Ui::VerticalLayout>(_wrap),
  662. st::editPeerBottomButtonsLayoutMargins);
  663. _controls.buttonsLayout = result->entity();
  664. fillManageSection();
  665. return result;
  666. }
  667. object_ptr<Ui::RpWidget> Controller::createStickersEdit() {
  668. Expects(_wrap != nullptr);
  669. const auto channel = _peer->asChannel();
  670. const auto bottomSkip = st::editPeerTopButtonsLayoutSkipCustomBottom;
  671. auto result = object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
  672. _wrap,
  673. object_ptr<Ui::VerticalLayout>(_wrap));
  674. const auto container = result->entity();
  675. Ui::AddSubsectionTitle(
  676. container,
  677. tr::lng_group_stickers(),
  678. { 0, st::defaultSubsectionTitlePadding.top() - bottomSkip, 0, 0 });
  679. AddButtonWithCount(
  680. container,
  681. tr::lng_group_stickers_add(),
  682. rpl::single(QString()), //Empty count.
  683. [=, controller = _navigation->parentController()] {
  684. const auto isEmoji = false;
  685. controller->show(
  686. Box<StickersBox>(controller->uiShow(), channel, isEmoji));
  687. },
  688. { &st::menuIconStickers });
  689. Ui::AddSkip(container, bottomSkip);
  690. Ui::AddDividerText(
  691. container,
  692. tr::lng_group_stickers_description());
  693. Ui::AddSkip(container, bottomSkip);
  694. return result;
  695. }
  696. bool Controller::canEditInformation() const {
  697. if (_isBot) {
  698. return _peer->asUser()->botInfo->canEditInformation;
  699. } else if (const auto channel = _peer->asChannel()) {
  700. return channel->canEditInformation();
  701. } else if (const auto chat = _peer->asChat()) {
  702. return chat->canEditInformation();
  703. }
  704. return false;
  705. }
  706. bool Controller::canEditReactions() const {
  707. if (const auto channel = _peer->asChannel()) {
  708. return channel->amCreator()
  709. || (channel->adminRights() & ChatAdminRight::ChangeInfo);
  710. } else if (const auto chat = _peer->asChat()) {
  711. return chat->amCreator()
  712. || (chat->adminRights() & ChatAdminRight::ChangeInfo);
  713. }
  714. return false;
  715. }
  716. void Controller::refreshHistoryVisibility() {
  717. if (!_controls.historyVisibilityWrap) {
  718. return;
  719. }
  720. const auto withUsername = _typeDataSavedValue
  721. && (_typeDataSavedValue->privacy == Privacy::HasUsername);
  722. _controls.historyVisibilityWrap->toggle(
  723. (!withUsername
  724. && !_channelHasLocationOriginalValue
  725. && (!_linkedChatSavedValue || !*_linkedChatSavedValue)
  726. && (!_forumSavedValue || !*_forumSavedValue)),
  727. anim::type::instant);
  728. }
  729. void Controller::showEditPeerTypeBox(
  730. std::optional<rpl::producer<QString>> error) {
  731. const auto boxCallback = crl::guard(this, [=](EditPeerTypeData data) {
  732. _privacyTypeUpdates.fire({ data.privacy, data.noForwards });
  733. _typeDataSavedValue = data;
  734. refreshHistoryVisibility();
  735. });
  736. _typeDataSavedValue->hasLinkedChat
  737. = (_linkedChatSavedValue.value_or(nullptr) != nullptr);
  738. const auto box = _navigation->parentController()->show(
  739. Box<EditPeerTypeBox>(
  740. _navigation,
  741. _peer,
  742. _channelHasLocationOriginalValue,
  743. boxCallback,
  744. _typeDataSavedValue,
  745. error));
  746. box->boxClosing(
  747. ) | rpl::start_with_next([peer = _peer] {
  748. peer->session().api().usernames().requestToCache(peer);
  749. }, box->lifetime());
  750. }
  751. void Controller::showEditLinkedChatBox() {
  752. Expects(_peer->isChannel());
  753. if (_forumSavedValue && *_forumSavedValue) {
  754. ShowForumForDiscussionError(_navigation);
  755. return;
  756. }
  757. const auto box = std::make_shared<QPointer<Ui::BoxContent>>();
  758. const auto channel = _peer->asChannel();
  759. const auto callback = [=](ChannelData *result) {
  760. if (*box) {
  761. (*box)->closeBox();
  762. }
  763. *_linkedChatSavedValue = result;
  764. _linkedChatUpdates.fire_copy(result);
  765. refreshHistoryVisibility();
  766. refreshForumToggleLocked();
  767. };
  768. const auto canEdit = channel->isBroadcast()
  769. ? channel->canEditInformation()
  770. : (channel->canPinMessages()
  771. && (channel->amCreator() || channel->adminRights() != 0)
  772. && (!channel->hiddenPreHistory()
  773. || channel->canEditPreHistoryHidden()));
  774. if (const auto chat = *_linkedChatSavedValue) {
  775. *box = _navigation->parentController()->show(EditLinkedChatBox(
  776. _navigation,
  777. channel,
  778. chat,
  779. canEdit,
  780. callback));
  781. return;
  782. } else if (!canEdit || _linkedChatsRequestId) {
  783. return;
  784. } else if (channel->isMegagroup()) {
  785. if (_forumSavedValue
  786. && *_forumSavedValue
  787. && _linkedChatOriginalValue) {
  788. ShowForumForDiscussionError(_navigation);
  789. } else {
  790. // Restore original linked channel.
  791. callback(_linkedChatOriginalValue);
  792. }
  793. return;
  794. }
  795. _linkedChatsRequestId = _api.request(
  796. MTPchannels_GetGroupsForDiscussion()
  797. ).done([=](const MTPmessages_Chats &result) {
  798. _linkedChatsRequestId = 0;
  799. const auto list = result.match([&](const auto &data) {
  800. return data.vchats().v;
  801. });
  802. auto chats = std::vector<not_null<PeerData*>>();
  803. chats.reserve(list.size());
  804. for (const auto &item : list) {
  805. chats.emplace_back(_peer->owner().processChat(item));
  806. }
  807. *box = _navigation->parentController()->show(EditLinkedChatBox(
  808. _navigation,
  809. channel,
  810. std::move(chats),
  811. callback));
  812. }).fail([=] {
  813. _linkedChatsRequestId = 0;
  814. }).send();
  815. }
  816. void Controller::fillPrivacyTypeButton() {
  817. Expects(_controls.buttonsLayout != nullptr);
  818. // Create Privacy Button.
  819. const auto hasLocation = _peer->isChannel()
  820. && _peer->asChannel()->hasLocation();
  821. _typeDataSavedValue = EditPeerTypeData{
  822. .privacy = ((_peer->isChannel()
  823. && _peer->asChannel()->hasUsername())
  824. ? Privacy::HasUsername
  825. : Privacy::NoUsername),
  826. .username = (_peer->isChannel()
  827. ? _peer->asChannel()->editableUsername()
  828. : QString()),
  829. .usernamesOrder = (_peer->isChannel()
  830. ? _peer->asChannel()->usernames()
  831. : std::vector<QString>()),
  832. .noForwards = !_peer->allowsForwarding(),
  833. .joinToWrite = (_peer->isMegagroup()
  834. && _peer->asChannel()->joinToWrite()),
  835. .requestToJoin = (_peer->isMegagroup()
  836. && _peer->asChannel()->requestToJoin()),
  837. };
  838. const auto isGroup = (_peer->isChat() || _peer->isMegagroup());
  839. AddButtonWithText(
  840. _controls.buttonsLayout,
  841. (hasLocation
  842. ? tr::lng_manage_peer_link_type
  843. : isGroup
  844. ? tr::lng_manage_peer_group_type
  845. : tr::lng_manage_peer_channel_type)(),
  846. _privacyTypeUpdates.events(
  847. ) | rpl::map([=](PrivacyAndForwards data) {
  848. const auto flag = data.privacy;
  849. if (flag == Privacy::HasUsername) {
  850. _peer->session().api().usernames().requestToCache(_peer);
  851. }
  852. return (flag == Privacy::HasUsername)
  853. ? (hasLocation
  854. ? tr::lng_manage_peer_link_permanent
  855. : isGroup
  856. ? tr::lng_manage_public_group_title
  857. : tr::lng_manage_public_peer_title)()
  858. : (hasLocation
  859. ? tr::lng_manage_peer_link_invite
  860. : ((!data.noForwards) && isGroup)
  861. ? tr::lng_manage_private_group_title
  862. : ((!data.noForwards) && !isGroup)
  863. ? tr::lng_manage_private_peer_title
  864. : isGroup
  865. ? tr::lng_manage_private_group_noforwards_title
  866. : tr::lng_manage_private_peer_noforwards_title)();
  867. }) | rpl::flatten_latest(),
  868. [=] { showEditPeerTypeBox(); },
  869. { &st::menuIconCustomize });
  870. _privacyTypeUpdates.fire_copy({
  871. _typeDataSavedValue->privacy,
  872. _typeDataSavedValue->noForwards,
  873. });
  874. }
  875. void Controller::fillLinkedChatButton() {
  876. Expects(_controls.buttonsLayout != nullptr);
  877. _linkedChatSavedValue = _linkedChatOriginalValue = _peer->isChannel()
  878. ? _peer->asChannel()->linkedChat()
  879. : nullptr;
  880. const auto isGroup = (_peer->isChat() || _peer->isMegagroup());
  881. auto text = !isGroup
  882. ? tr::lng_manage_discussion_group()
  883. : rpl::combine(
  884. tr::lng_manage_linked_channel(),
  885. tr::lng_manage_linked_channel_restore(),
  886. _linkedChatUpdates.events()
  887. ) | rpl::map([=](
  888. const QString &edit,
  889. const QString &restore,
  890. ChannelData *chat) {
  891. return chat ? edit : restore;
  892. });
  893. auto label = isGroup
  894. ? _linkedChatUpdates.events(
  895. ) | rpl::map([](ChannelData *chat) {
  896. return chat ? chat->name() : QString();
  897. }) | rpl::type_erased()
  898. : rpl::combine(
  899. tr::lng_manage_discussion_group_add(),
  900. _linkedChatUpdates.events()
  901. ) | rpl::map([=](const QString &add, ChannelData *chat) {
  902. return chat ? chat->name() : add;
  903. }) | rpl::type_erased();
  904. AddButtonWithText(
  905. _controls.buttonsLayout,
  906. std::move(text),
  907. std::move(label),
  908. [=] { showEditLinkedChatBox(); },
  909. { isGroup ? &st::menuIconChannel : &st::menuIconGroups });
  910. _linkedChatUpdates.fire_copy(*_linkedChatSavedValue);
  911. }
  912. //
  913. //void Controller::fillInviteLinkButton() {
  914. // Expects(_controls.buttonsLayout != nullptr);
  915. //
  916. // const auto buttonCallback = [=] {
  917. // Ui::show(Box<EditPeerTypeBox>(_peer), Ui::LayerOption::KeepOther);
  918. // };
  919. //
  920. // AddButtonWithText(
  921. // _controls.buttonsLayout,
  922. // tr::lng_profile_invite_link_section(),
  923. // rpl::single(QString()), //Empty text.
  924. // buttonCallback);
  925. //}
  926. void Controller::fillForumButton() {
  927. Expects(_controls.buttonsLayout != nullptr);
  928. const auto button = _controls.forumToggle = _controls.buttonsLayout->add(
  929. EditPeerInfoBox::CreateButton(
  930. _controls.buttonsLayout,
  931. tr::lng_forum_topics_switch(),
  932. rpl::single(QString()),
  933. [] {},
  934. st::manageGroupTopicsButton,
  935. { &st::menuIconTopics }));
  936. const auto unlocks = std::make_shared<rpl::event_stream<bool>>();
  937. button->toggleOn(
  938. rpl::single(_peer->isForum()) | rpl::then(unlocks->events())
  939. )->toggledValue(
  940. ) | rpl::start_with_next([=](bool toggled) {
  941. if (_controls.forumToggleLocked && toggled) {
  942. unlocks->fire(false);
  943. if (_linkedChatSavedValue && *_linkedChatSavedValue) {
  944. ShowForumForDiscussionError(_navigation);
  945. } else {
  946. _navigation->showToast(
  947. tr::lng_forum_topics_not_enough(
  948. tr::now,
  949. lt_count,
  950. EnableForumMinMembers(_peer),
  951. Ui::Text::RichLangValue));
  952. }
  953. } else {
  954. _forumSavedValue = toggled;
  955. if (toggled) {
  956. _savingData.hiddenPreHistory = false;
  957. }
  958. refreshHistoryVisibility();
  959. }
  960. }, _controls.buttonsLayout->lifetime());
  961. refreshForumToggleLocked();
  962. }
  963. void Controller::refreshForumToggleLocked() {
  964. if (!_controls.forumToggle) {
  965. return;
  966. }
  967. const auto limit = EnableForumMinMembers(_peer);
  968. const auto chat = _peer->asChat();
  969. const auto channel = _peer->asChannel();
  970. const auto notenough = !_peer->isForum()
  971. && ((chat ? chat->count : channel->membersCount()) < limit);
  972. const auto linked = _linkedChatSavedValue
  973. && *_linkedChatSavedValue;
  974. const auto locked = _controls.forumToggleLocked = notenough || linked;
  975. _controls.forumToggle->setToggleLocked(locked);
  976. }
  977. void Controller::fillColorIndexButton() {
  978. Expects(_controls.buttonsLayout != nullptr);
  979. const auto show = _navigation->uiShow();
  980. AddPeerColorButton(
  981. _controls.buttonsLayout,
  982. _navigation->uiShow(),
  983. _peer,
  984. st::managePeerColorsButton);
  985. }
  986. void Controller::fillSignaturesButton() {
  987. Expects(_controls.buttonsLayout != nullptr);
  988. const auto channel = _peer->asChannel();
  989. if (!channel) {
  990. return;
  991. }
  992. const auto signs = AddButtonWithText(
  993. _controls.buttonsLayout,
  994. tr::lng_edit_sign_messages(),
  995. rpl::single(QString()),
  996. [] {},
  997. { &st::menuIconSigned }
  998. )->toggleOn(rpl::single(channel->addsSignature()));
  999. const auto profiles = _controls.buttonsLayout->add(
  1000. object_ptr<Ui::SlideWrap<Ui::SettingsButton>>(
  1001. _controls.buttonsLayout,
  1002. EditPeerInfoBox::CreateButton(
  1003. _controls.buttonsLayout,
  1004. tr::lng_edit_sign_profiles(),
  1005. rpl::single(QString()),
  1006. [] {},
  1007. st::manageGroupTopButtonWithText,
  1008. { &st::menuIconProfile })));
  1009. profiles->toggleOn(signs->toggledValue());
  1010. profiles->finishAnimating();
  1011. profiles->entity()->toggleOn(rpl::single(
  1012. channel->addsSignature() && channel->signatureProfiles()
  1013. ))->toggledValue(
  1014. ) | rpl::start_with_next([=](bool toggled) {
  1015. _signatureProfilesSavedValue = toggled;
  1016. }, profiles->entity()->lifetime());
  1017. signs->toggledValue(
  1018. ) | rpl::start_with_next([=](bool toggled) {
  1019. _signaturesSavedValue = toggled;
  1020. if (!toggled) {
  1021. _signatureProfilesSavedValue = false;
  1022. }
  1023. }, _controls.buttonsLayout->lifetime());
  1024. Ui::AddSkip(_controls.buttonsLayout);
  1025. Ui::AddDividerText(
  1026. _controls.buttonsLayout,
  1027. rpl::conditional(
  1028. signs->toggledValue(),
  1029. tr::lng_edit_sign_profiles_about(Ui::Text::WithEntities),
  1030. tr::lng_edit_sign_messages_about(Ui::Text::WithEntities)));
  1031. Ui::AddSkip(_controls.buttonsLayout);
  1032. }
  1033. void Controller::fillHistoryVisibilityButton() {
  1034. Expects(_controls.buttonsLayout != nullptr);
  1035. const auto wrapLayout = _controls.buttonsLayout->add(
  1036. object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
  1037. _controls.buttonsLayout,
  1038. object_ptr<Ui::VerticalLayout>(_controls.buttonsLayout),
  1039. st::boxOptionListPadding)); // Empty margins.
  1040. _controls.historyVisibilityWrap = wrapLayout;
  1041. const auto channel = _peer->asChannel();
  1042. const auto container = wrapLayout->entity();
  1043. _historyVisibilitySavedValue = (!channel || channel->hiddenPreHistory())
  1044. ? HistoryVisibility::Hidden
  1045. : HistoryVisibility::Visible;
  1046. _channelHasLocationOriginalValue = channel && channel->hasLocation();
  1047. const auto updateHistoryVisibility
  1048. = std::make_shared<rpl::event_stream<HistoryVisibility>>();
  1049. const auto boxCallback = crl::guard(this, [=](HistoryVisibility checked) {
  1050. updateHistoryVisibility->fire(std::move(checked));
  1051. _historyVisibilitySavedValue = checked;
  1052. });
  1053. const auto buttonCallback = [=] {
  1054. _peer->updateFull();
  1055. const auto canEdit = [&] {
  1056. if (const auto chat = _peer->asChat()) {
  1057. return chat->canEditPreHistoryHidden();
  1058. } else if (const auto channel = _peer->asChannel()) {
  1059. return channel->canEditPreHistoryHidden();
  1060. }
  1061. Unexpected("User in HistoryVisibilityEdit.");
  1062. }();
  1063. if (!canEdit) {
  1064. return;
  1065. }
  1066. _navigation->parentController()->show(Box(
  1067. EditPeerHistoryVisibilityBox,
  1068. _peer->isChat(),
  1069. boxCallback,
  1070. *_historyVisibilitySavedValue));
  1071. };
  1072. AddButtonWithText(
  1073. container,
  1074. tr::lng_manage_history_visibility_title(),
  1075. updateHistoryVisibility->events(
  1076. ) | rpl::map([](HistoryVisibility flag) {
  1077. return (HistoryVisibility::Visible == flag
  1078. ? tr::lng_manage_history_visibility_shown
  1079. : tr::lng_manage_history_visibility_hidden)();
  1080. }) | rpl::flatten_latest(),
  1081. buttonCallback,
  1082. { &st::menuIconChatBubble });
  1083. updateHistoryVisibility->fire_copy(*_historyVisibilitySavedValue);
  1084. refreshHistoryVisibility();
  1085. }
  1086. void Controller::fillManageSection() {
  1087. Expects(_controls.buttonsLayout != nullptr);
  1088. if (_isBot) {
  1089. const auto &container = _controls.buttonsLayout;
  1090. ::AddSkip(container, 0);
  1091. fillBotUsernamesButton();
  1092. fillBotCurrencyButton();
  1093. fillBotCreditsButton();
  1094. fillBotAffiliateProgram();
  1095. fillBotEditIntroButton();
  1096. fillBotEditCommandsButton();
  1097. fillBotEditSettingsButton();
  1098. Ui::AddSkip(
  1099. container,
  1100. st::editPeerTopButtonsLayoutSkipCustomBottom);
  1101. container->add(object_ptr<Ui::DividerLabel>(
  1102. container,
  1103. object_ptr<Ui::FlatLabel>(
  1104. container,
  1105. tr::lng_manage_peer_bot_about(
  1106. lt_bot,
  1107. rpl::single(Ui::Text::Link(
  1108. '@' + kBotManagerUsername.utf16(),
  1109. _peer->session().createInternalLinkFull(
  1110. kBotManagerUsername.utf16()))),
  1111. Ui::Text::RichLangValue),
  1112. st::boxDividerLabel),
  1113. st::defaultBoxDividerLabelPadding));
  1114. fillBotVerifyAccounts();
  1115. return;
  1116. }
  1117. const auto chat = _peer->asChat();
  1118. const auto channel = _peer->asChannel();
  1119. const auto isChannel = (!chat);
  1120. if (!chat && !channel) {
  1121. return;
  1122. }
  1123. const auto canEditType = isChannel
  1124. ? channel->amCreator()
  1125. : chat->amCreator();
  1126. const auto canEditSignatures = isChannel
  1127. && channel->canEditSignatures()
  1128. && !channel->isMegagroup();
  1129. const auto canEditPreHistoryHidden = isChannel
  1130. ? channel->canEditPreHistoryHidden()
  1131. : chat->canEditPreHistoryHidden();
  1132. const auto canEditForum = isChannel
  1133. ? (channel->isMegagroup() && channel->amCreator())
  1134. : chat->amCreator();
  1135. const auto canEditPermissions = isChannel
  1136. ? channel->canEditPermissions()
  1137. : chat->canEditPermissions();
  1138. const auto canEditInviteLinks = isChannel
  1139. ? channel->canHaveInviteLink()
  1140. : chat->canHaveInviteLink();
  1141. const auto canViewAdmins = isChannel
  1142. ? channel->canViewAdmins()
  1143. : chat->amIn();
  1144. const auto canViewMembers = isChannel
  1145. ? channel->canViewMembers()
  1146. : chat->amIn();
  1147. const auto canViewKicked = isChannel
  1148. && (channel->isMegagroup()
  1149. ? (channel->isBroadcast() || channel->isGigagroup())
  1150. : true);
  1151. const auto hasRecentActions = isChannel
  1152. && (channel->hasAdminRights() || channel->amCreator());
  1153. const auto hasStarRef = Info::BotStarRef::Join::Allowed(_peer)
  1154. && isChannel
  1155. && channel->canPostMessages();
  1156. const auto canEditStickers = isChannel && channel->canEditStickers();
  1157. const auto canDeleteChannel = isChannel && channel->canDelete();
  1158. const auto canEditColorIndex = isChannel && channel->canEditEmoji();
  1159. const auto canViewOrEditLinkedChat = isChannel
  1160. && (channel->linkedChat()
  1161. || (channel->isBroadcast() && channel->canEditInformation()));
  1162. ::AddSkip(_controls.buttonsLayout, 0);
  1163. if (canEditType) {
  1164. fillPrivacyTypeButton();
  1165. //} else if (canEditInviteLinks) {
  1166. // fillInviteLinkButton();
  1167. }
  1168. if (canViewOrEditLinkedChat) {
  1169. fillLinkedChatButton();
  1170. }
  1171. if (canEditPreHistoryHidden) {
  1172. fillHistoryVisibilityButton();
  1173. }
  1174. if (canEditForum) {
  1175. fillForumButton();
  1176. }
  1177. if (canEditColorIndex) {
  1178. fillColorIndexButton();
  1179. }
  1180. if (canEditSignatures) {
  1181. fillSignaturesButton();
  1182. } else if (canEditPreHistoryHidden
  1183. || canEditForum
  1184. || canEditColorIndex
  1185. //|| canEditInviteLinks
  1186. || canViewOrEditLinkedChat
  1187. || canEditType) {
  1188. ::AddSkip(_controls.buttonsLayout);
  1189. }
  1190. if (canEditReactions()) {
  1191. auto allowedReactions = Info::Profile::MigratedOrMeValue(
  1192. _peer
  1193. ) | rpl::map([=](not_null<PeerData*> peer) {
  1194. return peer->session().changes().peerFlagsValue(
  1195. peer,
  1196. Data::PeerUpdate::Flag::Reactions
  1197. ) | rpl::map([=] {
  1198. return Data::PeerAllowedReactions(peer);
  1199. });
  1200. }) | rpl::flatten_latest();
  1201. auto label = std::move(
  1202. allowedReactions
  1203. ) | rpl::map([=](const Data::AllowedReactions &allowed) {
  1204. const auto some = int(allowed.some.size());
  1205. return (allowed.type != Data::AllowedReactionsType::Some)
  1206. ? tr::lng_manage_peer_reactions_on(tr::now)
  1207. : some
  1208. ? QString::number(some)
  1209. : tr::lng_manage_peer_reactions_off(tr::now);
  1210. });
  1211. AddButtonWithCount(
  1212. _controls.buttonsLayout,
  1213. tr::lng_manage_peer_reactions(),
  1214. std::move(label),
  1215. [=] { editReactions(); },
  1216. { &st::menuIconGroupReactions });
  1217. }
  1218. if (canEditPermissions) {
  1219. AddButtonWithCount(
  1220. _controls.buttonsLayout,
  1221. tr::lng_manage_peer_permissions(),
  1222. Info::Profile::MigratedOrMeValue(
  1223. _peer
  1224. ) | rpl::map([=](not_null<PeerData*> peer) {
  1225. return Info::Profile::RestrictionsCountValue(
  1226. peer
  1227. ) | rpl::map([=](int count) {
  1228. return QString::number(count)
  1229. + QString("/")
  1230. + QString::number(int(Data::ListOfRestrictions(
  1231. { .isForum = peer->isForum() }).size()));
  1232. });
  1233. }) | rpl::flatten_latest(),
  1234. [=] { ShowEditPermissions(_navigation, _peer); },
  1235. { &st::menuIconPermissions });
  1236. }
  1237. if (canEditInviteLinks) {
  1238. auto count = Info::Profile::MigratedOrMeValue(
  1239. _peer
  1240. ) | rpl::map([=](not_null<PeerData*> peer) {
  1241. peer->session().api().inviteLinks().requestMyLinks(peer);
  1242. return peer->session().changes().peerUpdates(
  1243. peer,
  1244. Data::PeerUpdate::Flag::InviteLinks
  1245. ) | rpl::map([=] {
  1246. return peer->session().api().inviteLinks().myLinks(
  1247. peer).count;
  1248. });
  1249. }) | rpl::flatten_latest(
  1250. ) | rpl::start_spawning(_controls.buttonsLayout->lifetime());
  1251. const auto wrap = _controls.buttonsLayout->add(
  1252. object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
  1253. _controls.buttonsLayout,
  1254. object_ptr<Ui::VerticalLayout>(
  1255. _controls.buttonsLayout)));
  1256. AddButtonWithCount(
  1257. wrap->entity(),
  1258. tr::lng_manage_peer_invite_links(),
  1259. rpl::duplicate(count) | ToPositiveNumberString(),
  1260. [=] {
  1261. _navigation->parentController()->show(Box(
  1262. ManageInviteLinksBox,
  1263. _peer,
  1264. _peer->session().user(),
  1265. 0,
  1266. 0));
  1267. },
  1268. { &st::menuIconLinks });
  1269. wrap->toggle(true, anim::type::instant);
  1270. }
  1271. if (canViewAdmins) {
  1272. AddButtonWithCount(
  1273. _controls.buttonsLayout,
  1274. tr::lng_manage_peer_administrators(),
  1275. Info::Profile::MigratedOrMeValue(
  1276. _peer
  1277. ) | rpl::map(
  1278. Info::Profile::AdminsCountValue
  1279. ) | rpl::flatten_latest(
  1280. ) | ToPositiveNumberString(),
  1281. [=] {
  1282. ParticipantsBoxController::Start(
  1283. _navigation,
  1284. _peer,
  1285. ParticipantsBoxController::Role::Admins);
  1286. },
  1287. { &st::menuIconAdmin });
  1288. }
  1289. if (canViewMembers) {
  1290. AddButtonWithCount(
  1291. _controls.buttonsLayout,
  1292. (_isGroup
  1293. ? tr::lng_manage_peer_members()
  1294. : tr::lng_manage_peer_subscribers()),
  1295. Info::Profile::MigratedOrMeValue(
  1296. _peer
  1297. ) | rpl::map(
  1298. Info::Profile::MembersCountValue
  1299. ) | rpl::flatten_latest(
  1300. ) | ToPositiveNumberString(),
  1301. [=] {
  1302. ParticipantsBoxController::Start(
  1303. _navigation,
  1304. _peer,
  1305. ParticipantsBoxController::Role::Members);
  1306. },
  1307. { &st::menuIconGroups });
  1308. }
  1309. fillPendingRequestsButton();
  1310. if (canViewKicked) {
  1311. AddButtonWithCount(
  1312. _controls.buttonsLayout,
  1313. tr::lng_manage_peer_removed_users(),
  1314. Info::Profile::KickedCountValue(channel)
  1315. | ToPositiveNumberString(),
  1316. [=] {
  1317. ParticipantsBoxController::Start(
  1318. _navigation,
  1319. _peer,
  1320. ParticipantsBoxController::Role::Kicked);
  1321. },
  1322. { &st::menuIconRemove });
  1323. }
  1324. if (hasRecentActions) {
  1325. auto callback = [=] {
  1326. _navigation->showSection(
  1327. std::make_shared<AdminLog::SectionMemento>(channel));
  1328. };
  1329. AddButtonWithCount(
  1330. _controls.buttonsLayout,
  1331. tr::lng_manage_peer_recent_actions(),
  1332. rpl::single(QString()), // Empty count.
  1333. std::move(callback),
  1334. { &st::menuIconGroupLog });
  1335. }
  1336. if (hasStarRef) {
  1337. auto callback = [=] {
  1338. _navigation->showSection(Info::BotStarRef::Join::Make(_peer));
  1339. };
  1340. AddButtonWithCount(
  1341. _controls.buttonsLayout,
  1342. tr::lng_manage_peer_star_ref(),
  1343. rpl::single(QString()), // Empty count.
  1344. std::move(callback),
  1345. { .icon = &st::menuIconStarRefShare, .newBadge = true });
  1346. }
  1347. if (canEditStickers || canDeleteChannel) {
  1348. ::AddSkip(_controls.buttonsLayout);
  1349. }
  1350. if (canEditStickers) {
  1351. _controls.buttonsLayout->add(createStickersEdit());
  1352. }
  1353. if (canDeleteChannel) {
  1354. AddButtonDelete(
  1355. _controls.buttonsLayout,
  1356. (_isGroup
  1357. ? tr::lng_profile_delete_group
  1358. : tr::lng_profile_delete_channel)(),
  1359. [=]{ deleteWithConfirmation(); }
  1360. );
  1361. }
  1362. if (canEditStickers || canDeleteChannel) {
  1363. ::AddSkip(_controls.buttonsLayout);
  1364. }
  1365. }
  1366. void Controller::editReactions() {
  1367. const auto done = [=](const Data::AllowedReactions &chosen) {
  1368. SaveAllowedReactions(_peer, chosen);
  1369. };
  1370. if (!_peer->isBroadcast()) {
  1371. _navigation->uiShow()->show(Box(
  1372. EditAllowedReactionsBox,
  1373. EditAllowedReactionsArgs{
  1374. .navigation = _navigation,
  1375. .isGroup = true,
  1376. .list = _navigation->session().data().reactions().list(
  1377. Data::Reactions::Type::Active),
  1378. .allowed = Data::PeerAllowedReactions(_peer),
  1379. .save = done,
  1380. }));
  1381. return;
  1382. }
  1383. if (_controls.levelRequested) {
  1384. return;
  1385. }
  1386. _controls.levelRequested = true;
  1387. _api.request(MTPpremium_GetBoostsStatus(
  1388. _peer->input
  1389. )).done([=](const MTPpremium_BoostsStatus &result) {
  1390. _controls.levelRequested = false;
  1391. if (const auto channel = _peer->asChannel()) {
  1392. channel->updateLevelHint(result.data().vlevel().v);
  1393. }
  1394. const auto link = qs(result.data().vboost_url());
  1395. const auto weak = base::make_weak(_navigation->parentController());
  1396. auto counters = ParseBoostCounters(result);
  1397. counters.mine = 0; // Don't show current level as just-reached.
  1398. const auto askForBoosts = [=](int required) {
  1399. if (const auto strong = weak.get()) {
  1400. const auto openStatistics = [=, peer = _peer] {
  1401. strong->showSection(Info::Boosts::Make(peer));
  1402. };
  1403. strong->show(Box(Ui::AskBoostBox, Ui::AskBoostBoxData{
  1404. .link = link,
  1405. .boost = counters,
  1406. .reason = { Ui::AskBoostCustomReactions{ required } },
  1407. }, openStatistics, nullptr));
  1408. }
  1409. };
  1410. _navigation->uiShow()->show(Box(
  1411. EditAllowedReactionsBox,
  1412. EditAllowedReactionsArgs{
  1413. .navigation = _navigation,
  1414. .allowedCustomReactions = counters.level,
  1415. .customReactionsHardLimit = Data::PremiumLimits(
  1416. &_peer->session()).maxBoostLevel(),
  1417. .list = _navigation->session().data().reactions().list(
  1418. Data::Reactions::Type::Active),
  1419. .allowed = Data::PeerAllowedReactions(_peer),
  1420. .askForBoosts = askForBoosts,
  1421. .save = done,
  1422. }));
  1423. }).send();
  1424. }
  1425. void Controller::fillPendingRequestsButton() {
  1426. auto pendingRequestsCount = Info::Profile::MigratedOrMeValue(
  1427. _peer
  1428. ) | rpl::map(
  1429. Info::Profile::PendingRequestsCountValue
  1430. ) | rpl::flatten_latest(
  1431. ) | rpl::start_spawning(_controls.buttonsLayout->lifetime());
  1432. const auto wrap = _controls.buttonsLayout->add(
  1433. object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
  1434. _controls.buttonsLayout,
  1435. object_ptr<Ui::VerticalLayout>(
  1436. _controls.buttonsLayout)));
  1437. AddButtonWithCount(
  1438. wrap->entity(),
  1439. (_isGroup
  1440. ? tr::lng_manage_peer_requests()
  1441. : tr::lng_manage_peer_requests_channel()),
  1442. rpl::duplicate(pendingRequestsCount) | ToPositiveNumberString(),
  1443. [=] { RequestsBoxController::Start(_navigation, _peer); },
  1444. { &st::menuIconInvite });
  1445. std::move(
  1446. pendingRequestsCount
  1447. ) | rpl::start_with_next([=](int count) {
  1448. wrap->toggle(count > 0, anim::type::instant);
  1449. }, wrap->lifetime());
  1450. }
  1451. void Controller::fillBotUsernamesButton() {
  1452. Expects(_isBot);
  1453. const auto user = _peer->asUser();
  1454. auto localUsernames = rpl::single(
  1455. user->usernames()
  1456. ) | rpl::map([](const std::vector<QString> &usernames) {
  1457. return ranges::views::all(
  1458. usernames
  1459. ) | ranges::views::transform([](const QString &u) {
  1460. return Data::Username{ u };
  1461. }) | ranges::to_vector;
  1462. });
  1463. auto usernamesValue = std::move(
  1464. localUsernames
  1465. ) | rpl::then(
  1466. _peer->session().api().usernames().loadUsernames(_peer)
  1467. );
  1468. auto rightLabel = rpl::duplicate(
  1469. usernamesValue
  1470. ) | rpl::map([=](const Data::Usernames &usernames) {
  1471. if (usernames.size() <= 1) {
  1472. return user->session().createInternalLink(user->username());
  1473. } else {
  1474. const auto active = ranges::count_if(
  1475. usernames,
  1476. [](const Data::Username &u) { return u.active; });
  1477. return u"%1/%2"_q.arg(active).arg(usernames.size());
  1478. }
  1479. });
  1480. auto leftLabel = std::move(
  1481. usernamesValue
  1482. ) | rpl::map([=](const Data::Usernames &usernames) {
  1483. return (usernames.size() <= 1)
  1484. ? tr::lng_manage_peer_bot_public_link()
  1485. : tr::lng_manage_peer_bot_public_links();
  1486. }) | rpl::flatten_latest();
  1487. _controls.buttonsLayout->add(
  1488. object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
  1489. _controls.buttonsLayout,
  1490. object_ptr<Ui::VerticalLayout>(
  1491. _controls.buttonsLayout)));
  1492. AddButtonWithCount(
  1493. _controls.buttonsLayout,
  1494. std::move(leftLabel),
  1495. std::move(rightLabel),
  1496. [=] {
  1497. _navigation->uiShow()->showBox(Box(UsernamesBox, user));
  1498. },
  1499. { &st::menuIconLinks });
  1500. }
  1501. void Controller::fillBotCurrencyButton() {
  1502. Expects(_isBot);
  1503. struct State final {
  1504. rpl::variable<QString> balance;
  1505. };
  1506. auto &lifetime = _controls.buttonsLayout->lifetime();
  1507. const auto state = lifetime.make_state<State>();
  1508. const auto format = [=](uint64 balance) {
  1509. return Info::ChannelEarn::MajorPart(balance)
  1510. + Info::ChannelEarn::MinorPart(balance);
  1511. };
  1512. const auto was = _peer->session().credits().balanceCurrency(
  1513. _peer->id);
  1514. if (was) {
  1515. state->balance = format(was);
  1516. }
  1517. const auto wrap = _controls.buttonsLayout->add(
  1518. object_ptr<Ui::SlideWrap<Ui::SettingsButton>>(
  1519. _controls.buttonsLayout,
  1520. EditPeerInfoBox::CreateButton(
  1521. _controls.buttonsLayout,
  1522. tr::lng_manage_peer_bot_balance_currency(),
  1523. state->balance.value(),
  1524. [controller = _navigation->parentController(), peer = _peer] {
  1525. controller->showSection(Info::ChannelEarn::Make(peer));
  1526. },
  1527. st::manageGroupButton,
  1528. {})));
  1529. wrap->toggle(!state->balance.current().isEmpty(), anim::type::instant);
  1530. const auto button = wrap->entity();
  1531. {
  1532. const auto currencyLoad
  1533. = button->lifetime().make_state<Api::EarnStatistics>(_peer);
  1534. currencyLoad->request(
  1535. ) | rpl::start_with_error_done([=](const QString &error) {
  1536. }, [=] {
  1537. const auto balance = currencyLoad->data().currentBalance;
  1538. if (balance) {
  1539. wrap->toggle(true, anim::type::normal);
  1540. }
  1541. state->balance = format(balance);
  1542. }, button->lifetime());
  1543. }
  1544. {
  1545. const auto icon = Ui::CreateChild<Ui::RpWidget>(button);
  1546. icon->resize(st::menuIconLinks.size());
  1547. const auto image = Ui::Earn::MenuIconCurrency(icon->size());
  1548. icon->paintRequest() | rpl::start_with_next([=] {
  1549. auto p = QPainter(icon);
  1550. p.drawImage(0, 0, image);
  1551. }, icon->lifetime());
  1552. button->sizeValue(
  1553. ) | rpl::start_with_next([=](const QSize &size) {
  1554. icon->moveToLeft(
  1555. button->st().iconLeft,
  1556. (size.height() - icon->height()) / 2);
  1557. }, icon->lifetime());
  1558. }
  1559. }
  1560. void Controller::fillBotCreditsButton() {
  1561. Expects(_isBot);
  1562. struct State final {
  1563. rpl::variable<QString> balance;
  1564. };
  1565. auto &lifetime = _controls.buttonsLayout->lifetime();
  1566. const auto state = lifetime.make_state<State>();
  1567. if (const auto balance = _peer->session().credits().balance(_peer->id)) {
  1568. state->balance = Lang::FormatStarsAmountDecimal(balance);
  1569. }
  1570. const auto wrap = _controls.buttonsLayout->add(
  1571. object_ptr<Ui::SlideWrap<Ui::SettingsButton>>(
  1572. _controls.buttonsLayout,
  1573. EditPeerInfoBox::CreateButton(
  1574. _controls.buttonsLayout,
  1575. tr::lng_manage_peer_bot_balance_credits(),
  1576. state->balance.value(),
  1577. [controller = _navigation->parentController(), peer = _peer] {
  1578. controller->showSection(Info::BotEarn::Make(peer));
  1579. },
  1580. st::manageGroupButton,
  1581. {})));
  1582. wrap->toggle(!state->balance.current().isEmpty(), anim::type::instant);
  1583. const auto button = wrap->entity();
  1584. {
  1585. const auto api = button->lifetime().make_state<Api::CreditsStatus>(
  1586. _peer);
  1587. api->request({}, [=](Data::CreditsStatusSlice data) {
  1588. if (data.balance) {
  1589. wrap->toggle(true, anim::type::normal);
  1590. }
  1591. state->balance = Lang::FormatStarsAmountDecimal(data.balance);
  1592. });
  1593. }
  1594. {
  1595. const auto icon = Ui::CreateChild<Ui::RpWidget>(button);
  1596. const auto image = Ui::Earn::MenuIconCredits();
  1597. icon->resize(image.size() / style::DevicePixelRatio());
  1598. icon->paintRequest() | rpl::start_with_next([=] {
  1599. auto p = QPainter(icon);
  1600. p.drawImage(0, 0, image);
  1601. }, icon->lifetime());
  1602. button->sizeValue(
  1603. ) | rpl::start_with_next([=](const QSize &size) {
  1604. icon->moveToLeft(
  1605. button->st().iconLeft,
  1606. (size.height() - icon->height()) / 2);
  1607. }, icon->lifetime());
  1608. }
  1609. }
  1610. void Controller::fillBotAffiliateProgram() {
  1611. Expects(_isBot);
  1612. if (!Info::BotStarRef::Setup::Allowed(_peer)) {
  1613. return;
  1614. }
  1615. const auto user = _peer->asUser();
  1616. auto label = user->session().changes().peerFlagsValue(
  1617. user,
  1618. Data::PeerUpdate::Flag::StarRefProgram
  1619. ) | rpl::map([=] {
  1620. const auto commission = user->botInfo
  1621. ? user->botInfo->starRefProgram.commission
  1622. : 0;
  1623. return commission
  1624. ? Info::BotStarRef::FormatCommission(commission)
  1625. : tr::lng_manage_peer_bot_star_ref_off(tr::now);
  1626. });
  1627. AddButtonWithCount(
  1628. _controls.buttonsLayout,
  1629. tr::lng_manage_peer_bot_star_ref(),
  1630. std::move(label),
  1631. [controller = _navigation->parentController(), user] {
  1632. controller->showSection(Info::BotStarRef::Setup::Make(user));
  1633. },
  1634. { .icon = &st::menuIconSharing, .newBadge = true });
  1635. }
  1636. void Controller::fillBotEditIntroButton() {
  1637. Expects(_isBot);
  1638. const auto user = _peer->asUser();
  1639. AddButtonWithCount(
  1640. _controls.buttonsLayout,
  1641. tr::lng_manage_peer_bot_edit_intro(),
  1642. rpl::never<QString>(),
  1643. [=] { toggleBotManager(u"%1-intro"_q.arg(user->username())); },
  1644. { &st::menuIconEdit });
  1645. }
  1646. void Controller::fillBotEditCommandsButton() {
  1647. Expects(_isBot);
  1648. const auto user = _peer->asUser();
  1649. AddButtonWithCount(
  1650. _controls.buttonsLayout,
  1651. tr::lng_manage_peer_bot_edit_commands(),
  1652. rpl::never<QString>(),
  1653. [=] { toggleBotManager(u"%1-commands"_q.arg(user->username())); },
  1654. { &st::menuIconBotCommands });
  1655. }
  1656. void Controller::fillBotEditSettingsButton() {
  1657. Expects(_isBot);
  1658. const auto user = _peer->asUser();
  1659. AddButtonWithCount(
  1660. _controls.buttonsLayout,
  1661. tr::lng_manage_peer_bot_edit_settings(),
  1662. rpl::never<QString>(),
  1663. [=] { toggleBotManager(user->username()); },
  1664. { &st::menuIconSettings });
  1665. }
  1666. void Controller::fillBotVerifyAccounts() {
  1667. Expects(_isBot);
  1668. const auto user = _peer->asUser();
  1669. const auto wrap = _controls.buttonsLayout->add(
  1670. object_ptr<Ui::SlideWrap<Ui::VerticalLayout>>(
  1671. _controls.buttonsLayout,
  1672. object_ptr<Ui::VerticalLayout>(
  1673. _controls.buttonsLayout)));
  1674. wrap->toggleOn(rpl::single(
  1675. rpl::empty
  1676. ) | rpl::then(user->owner().botCommandsChanges(
  1677. ) | rpl::filter(
  1678. rpl::mappers::_1 == _peer
  1679. ) | rpl::to_empty) | rpl::map([=] {
  1680. const auto info = user->botInfo.get();
  1681. return info && info->verifierSettings;
  1682. }));
  1683. const auto inner = wrap->entity();
  1684. Ui::AddSkip(inner);
  1685. AddButtonWithCount(
  1686. inner,
  1687. tr::lng_manage_peer_bot_verify(),
  1688. rpl::never<QString>(),
  1689. [controller = _navigation->parentController(), user] {
  1690. controller->show(MakeVerifyPeersBox(controller, user));
  1691. },
  1692. { &st::menuIconFactcheck });
  1693. Ui::AddSkip(inner);
  1694. Ui::AddDivider(inner);
  1695. }
  1696. void Controller::submitTitle() {
  1697. Expects(_controls.title != nullptr);
  1698. if (_controls.title->getLastText().isEmpty()) {
  1699. _controls.title->showError();
  1700. _box->scrollToWidget(_controls.title);
  1701. } else if (_controls.description) {
  1702. _controls.description->setFocus();
  1703. _box->scrollToWidget(_controls.description);
  1704. }
  1705. }
  1706. void Controller::submitDescription() {
  1707. Expects(_controls.title != nullptr);
  1708. Expects(_controls.description != nullptr);
  1709. if (_controls.title->getLastText().isEmpty()) {
  1710. _controls.title->showError();
  1711. _box->scrollToWidget(_controls.title);
  1712. } else {
  1713. save();
  1714. }
  1715. }
  1716. std::optional<Controller::Saving> Controller::validate() const {
  1717. auto result = Saving();
  1718. if (validateUsernamesOrder(result)
  1719. && validateUsername(result)
  1720. && validateLinkedChat(result)
  1721. && validateTitle(result)
  1722. && validateDescription(result)
  1723. && validateHistoryVisibility(result)
  1724. && validateForum(result)
  1725. && validateSignatures(result)
  1726. && validateForwards(result)
  1727. && validateJoinToWrite(result)
  1728. && validateRequestToJoin(result)) {
  1729. return result;
  1730. }
  1731. return {};
  1732. }
  1733. bool Controller::validateUsernamesOrder(Saving &to) const {
  1734. if (!_typeDataSavedValue) {
  1735. return true;
  1736. } else if (_typeDataSavedValue->privacy != Privacy::HasUsername) {
  1737. to.usernamesOrder = std::vector<QString>();
  1738. return true;
  1739. }
  1740. to.usernamesOrder = _typeDataSavedValue->usernamesOrder;
  1741. return true;
  1742. }
  1743. bool Controller::validateUsername(Saving &to) const {
  1744. if (!_typeDataSavedValue) {
  1745. return true;
  1746. } else if (_typeDataSavedValue->privacy != Privacy::HasUsername) {
  1747. to.username = QString();
  1748. return true;
  1749. }
  1750. const auto username = _typeDataSavedValue->username;
  1751. if (username.isEmpty()) {
  1752. to.username = QString();
  1753. return true;
  1754. }
  1755. to.username = username;
  1756. return true;
  1757. }
  1758. bool Controller::validateLinkedChat(Saving &to) const {
  1759. if (!_linkedChatSavedValue) {
  1760. return true;
  1761. }
  1762. to.linkedChat = *_linkedChatSavedValue;
  1763. return true;
  1764. }
  1765. bool Controller::validateTitle(Saving &to) const {
  1766. if (!_controls.title) {
  1767. return true;
  1768. }
  1769. const auto title = _controls.title->getLastText().trimmed();
  1770. if (title.isEmpty()) {
  1771. _controls.title->showError();
  1772. _box->scrollToWidget(_controls.title);
  1773. return false;
  1774. }
  1775. to.title = title;
  1776. return true;
  1777. }
  1778. bool Controller::validateDescription(Saving &to) const {
  1779. if (!_controls.description) {
  1780. return true;
  1781. }
  1782. to.description = _controls.description->getLastText().trimmed();
  1783. return true;
  1784. }
  1785. bool Controller::validateHistoryVisibility(Saving &to) const {
  1786. if (!_controls.historyVisibilityWrap
  1787. || !_controls.historyVisibilityWrap->toggled()
  1788. || _channelHasLocationOriginalValue
  1789. || (_typeDataSavedValue
  1790. && _typeDataSavedValue->privacy == Privacy::HasUsername)) {
  1791. return true;
  1792. }
  1793. to.hiddenPreHistory
  1794. = (_historyVisibilitySavedValue == HistoryVisibility::Hidden);
  1795. return true;
  1796. }
  1797. bool Controller::validateForum(Saving &to) const {
  1798. if (!_forumSavedValue.has_value()) {
  1799. return true;
  1800. }
  1801. to.forum = _forumSavedValue;
  1802. return true;
  1803. }
  1804. bool Controller::validateSignatures(Saving &to) const {
  1805. Expects(_signaturesSavedValue.has_value()
  1806. == _signatureProfilesSavedValue.has_value());
  1807. if (!_signaturesSavedValue.has_value()) {
  1808. return true;
  1809. }
  1810. to.signatures = _signaturesSavedValue;
  1811. to.signatureProfiles = _signatureProfilesSavedValue;
  1812. return true;
  1813. }
  1814. bool Controller::validateForwards(Saving &to) const {
  1815. if (!_typeDataSavedValue) {
  1816. return true;
  1817. }
  1818. to.noForwards = _typeDataSavedValue->noForwards;
  1819. return true;
  1820. }
  1821. bool Controller::validateJoinToWrite(Saving &to) const {
  1822. if (!_typeDataSavedValue) {
  1823. return true;
  1824. }
  1825. to.joinToWrite = _typeDataSavedValue->joinToWrite;
  1826. return true;
  1827. }
  1828. bool Controller::validateRequestToJoin(Saving &to) const {
  1829. if (!_typeDataSavedValue) {
  1830. return true;
  1831. }
  1832. to.requestToJoin = _typeDataSavedValue->requestToJoin;
  1833. return true;
  1834. }
  1835. void Controller::save() {
  1836. Expects(_wrap != nullptr);
  1837. if (!_saveStagesQueue.empty()) {
  1838. return;
  1839. }
  1840. if (const auto saving = validate()) {
  1841. _savingData = *saving;
  1842. pushSaveStage([=] { saveUsernamesOrder(); });
  1843. pushSaveStage([=] { saveUsername(); });
  1844. pushSaveStage([=] { saveLinkedChat(); });
  1845. pushSaveStage([=] { saveTitle(); });
  1846. pushSaveStage([=] { saveDescription(); });
  1847. pushSaveStage([=] { saveHistoryVisibility(); });
  1848. pushSaveStage([=] { saveForum(); });
  1849. pushSaveStage([=] { saveSignatures(); });
  1850. pushSaveStage([=] { saveForwards(); });
  1851. pushSaveStage([=] { saveJoinToWrite(); });
  1852. pushSaveStage([=] { saveRequestToJoin(); });
  1853. pushSaveStage([=] { savePhoto(); });
  1854. continueSave();
  1855. }
  1856. }
  1857. void Controller::pushSaveStage(FnMut<void()> &&lambda) {
  1858. _saveStagesQueue.push_back(std::move(lambda));
  1859. }
  1860. void Controller::continueSave() {
  1861. if (!_saveStagesQueue.empty()) {
  1862. auto next = std::move(_saveStagesQueue.front());
  1863. _saveStagesQueue.pop_front();
  1864. next();
  1865. }
  1866. }
  1867. void Controller::cancelSave() {
  1868. _saveStagesQueue.clear();
  1869. }
  1870. void Controller::saveUsernamesOrder() {
  1871. const auto channel = _peer->asChannel();
  1872. if (!_savingData.usernamesOrder || !channel) {
  1873. return continueSave();
  1874. }
  1875. if (_savingData.usernamesOrder->empty()) {
  1876. _api.request(MTPchannels_DeactivateAllUsernames(
  1877. channel->inputChannel
  1878. )).done([=] {
  1879. channel->setUsernames(channel->editableUsername().isEmpty()
  1880. ? Data::Usernames()
  1881. : Data::Usernames{
  1882. { channel->editableUsername(), true, true }
  1883. });
  1884. continueSave();
  1885. }).send();
  1886. } else {
  1887. const auto lifetime = std::make_shared<rpl::lifetime>();
  1888. const auto newUsernames = (*_savingData.usernamesOrder);
  1889. _peer->session().api().usernames().reorder(
  1890. _peer,
  1891. newUsernames
  1892. ) | rpl::start_with_done([=] {
  1893. channel->setUsernames(ranges::views::all(
  1894. newUsernames
  1895. ) | ranges::views::transform([&](QString username) {
  1896. const auto editable
  1897. = (channel->editableUsername() == username);
  1898. return Data::Username{
  1899. .username = std::move(username),
  1900. .active = true,
  1901. .editable = editable,
  1902. };
  1903. }) | ranges::to_vector);
  1904. continueSave();
  1905. lifetime->destroy();
  1906. }, *lifetime);
  1907. }
  1908. }
  1909. void Controller::saveUsername() {
  1910. const auto channel = _peer->asChannel();
  1911. const auto username = (channel ? channel->editableUsername() : QString());
  1912. if (!_savingData.username || *_savingData.username == username) {
  1913. return continueSave();
  1914. } else if (!channel) {
  1915. const auto saveForChannel = [=](not_null<ChannelData*> channel) {
  1916. if (_peer->asChannel() == channel) {
  1917. saveUsername();
  1918. } else {
  1919. cancelSave();
  1920. }
  1921. };
  1922. _peer->session().api().migrateChat(
  1923. _peer->asChat(),
  1924. crl::guard(this, saveForChannel));
  1925. return;
  1926. }
  1927. const auto newUsername = (*_savingData.username);
  1928. _api.request(MTPchannels_UpdateUsername(
  1929. channel->inputChannel,
  1930. MTP_string(newUsername)
  1931. )).done([=] {
  1932. channel->setName(
  1933. TextUtilities::SingleLine(channel->name()),
  1934. newUsername);
  1935. continueSave();
  1936. }).fail([=](const MTP::Error &error) {
  1937. const auto &type = error.type();
  1938. if (type == u"USERNAME_NOT_MODIFIED"_q) {
  1939. channel->setName(
  1940. TextUtilities::SingleLine(channel->name()),
  1941. TextUtilities::SingleLine(*_savingData.username));
  1942. continueSave();
  1943. return;
  1944. }
  1945. // Very rare case.
  1946. showEditPeerTypeBox([&] {
  1947. if (type == u"USERNAME_INVALID"_q) {
  1948. return tr::lng_create_channel_link_invalid();
  1949. } else if (type == u"USERNAME_OCCUPIED"_q
  1950. || type == u"USERNAMES_UNAVAILABLE"_q) {
  1951. return tr::lng_create_channel_link_occupied();
  1952. }
  1953. return tr::lng_create_channel_link_invalid();
  1954. }());
  1955. cancelSave();
  1956. }).send();
  1957. }
  1958. void Controller::saveLinkedChat() {
  1959. const auto channel = _peer->asChannel();
  1960. if (!channel) {
  1961. return continueSave();
  1962. }
  1963. if (!_savingData.linkedChat
  1964. || *_savingData.linkedChat == channel->linkedChat()) {
  1965. return continueSave();
  1966. }
  1967. const auto chat = *_savingData.linkedChat;
  1968. if (channel->isBroadcast() && chat && chat->hiddenPreHistory()) {
  1969. togglePreHistoryHidden(
  1970. chat,
  1971. false,
  1972. [=] { saveLinkedChat(); },
  1973. [=] { cancelSave(); });
  1974. return;
  1975. }
  1976. const auto input = *_savingData.linkedChat
  1977. ? (*_savingData.linkedChat)->inputChannel
  1978. : MTP_inputChannelEmpty();
  1979. _api.request(MTPchannels_SetDiscussionGroup(
  1980. (channel->isBroadcast() ? channel->inputChannel : input),
  1981. (channel->isBroadcast() ? input : channel->inputChannel)
  1982. )).done([=] {
  1983. channel->setLinkedChat(*_savingData.linkedChat);
  1984. continueSave();
  1985. }).fail([=] {
  1986. cancelSave();
  1987. }).send();
  1988. }
  1989. void Controller::saveTitle() {
  1990. if (!_savingData.title || *_savingData.title == _peer->name()) {
  1991. return continueSave();
  1992. }
  1993. const auto onDone = [=](const MTPUpdates &result) {
  1994. _peer->session().api().applyUpdates(result);
  1995. continueSave();
  1996. };
  1997. const auto onFail = [=](const MTP::Error &error) {
  1998. const auto &type = error.type();
  1999. if (type == u"CHAT_NOT_MODIFIED"_q
  2000. || type == u"CHAT_TITLE_NOT_MODIFIED"_q) {
  2001. if (const auto channel = _peer->asChannel()) {
  2002. channel->setName(
  2003. *_savingData.title,
  2004. channel->editableUsername());
  2005. } else if (const auto chat = _peer->asChat()) {
  2006. chat->setName(*_savingData.title);
  2007. }
  2008. continueSave();
  2009. return;
  2010. }
  2011. _controls.title->showError();
  2012. if (type == u"NO_CHAT_TITLE"_q) {
  2013. _box->scrollToWidget(_controls.title);
  2014. }
  2015. cancelSave();
  2016. };
  2017. if (const auto channel = _peer->asChannel()) {
  2018. _api.request(MTPchannels_EditTitle(
  2019. channel->inputChannel,
  2020. MTP_string(*_savingData.title)
  2021. )).done(std::move(onDone)
  2022. ).fail(std::move(onFail)
  2023. ).send();
  2024. } else if (const auto chat = _peer->asChat()) {
  2025. _api.request(MTPmessages_EditChatTitle(
  2026. chat->inputChat,
  2027. MTP_string(*_savingData.title)
  2028. )).done(std::move(onDone)
  2029. ).fail(std::move(onFail)
  2030. ).send();
  2031. } else if (_isBot) {
  2032. _api.request(MTPbots_GetBotInfo(
  2033. MTP_flags(MTPbots_GetBotInfo::Flag::f_bot),
  2034. _peer->asUser()->inputUser,
  2035. MTPstring() // Lang code.
  2036. )).done([=](const MTPbots_BotInfo &result) {
  2037. const auto was = qs(result.data().vname());
  2038. const auto now = *_savingData.title;
  2039. if (was == now) {
  2040. return continueSave();
  2041. }
  2042. using Flag = MTPbots_SetBotInfo::Flag;
  2043. _api.request(MTPbots_SetBotInfo(
  2044. MTP_flags(Flag::f_bot | Flag::f_name),
  2045. _peer->asUser()->inputUser,
  2046. MTPstring(), // Lang code.
  2047. MTP_string(now), // Name.
  2048. MTPstring(), // About.
  2049. MTPstring() // Description.
  2050. )).done([=] {
  2051. continueSave();
  2052. }).fail(std::move(onFail)
  2053. ).send();
  2054. }).fail(std::move(onFail)
  2055. ).send();
  2056. } else {
  2057. continueSave();
  2058. }
  2059. }
  2060. void Controller::saveDescription() {
  2061. if (!_savingData.description
  2062. || *_savingData.description == _peer->about()) {
  2063. return continueSave();
  2064. }
  2065. const auto successCallback = [=] {
  2066. _peer->setAbout(*_savingData.description);
  2067. continueSave();
  2068. };
  2069. if (_isBot) {
  2070. _api.request(MTPbots_GetBotInfo(
  2071. MTP_flags(MTPbots_GetBotInfo::Flag::f_bot),
  2072. _peer->asUser()->inputUser,
  2073. MTPstring() // Lang code.
  2074. )).done([=](const MTPbots_BotInfo &result) {
  2075. const auto was = qs(result.data().vabout());
  2076. const auto now = *_savingData.description;
  2077. if (was == now) {
  2078. return continueSave();
  2079. }
  2080. using Flag = MTPbots_SetBotInfo::Flag;
  2081. _api.request(MTPbots_SetBotInfo(
  2082. MTP_flags(Flag::f_bot | Flag::f_about),
  2083. _peer->asUser()->inputUser,
  2084. MTPstring(), // Lang code.
  2085. MTPstring(), // Name.
  2086. MTP_string(now), // About.
  2087. MTPstring() // Description.
  2088. )).done([=] {
  2089. successCallback();
  2090. }).fail([=] {
  2091. _controls.description->showError();
  2092. cancelSave();
  2093. }).send();
  2094. }).fail([=] {
  2095. continueSave();
  2096. }).send();
  2097. return;
  2098. }
  2099. _api.request(MTPmessages_EditChatAbout(
  2100. _peer->input,
  2101. MTP_string(*_savingData.description)
  2102. )).done([=] {
  2103. successCallback();
  2104. }).fail([=](const MTP::Error &error) {
  2105. const auto &type = error.type();
  2106. if (type == u"CHAT_ABOUT_NOT_MODIFIED"_q) {
  2107. successCallback();
  2108. return;
  2109. }
  2110. _controls.description->showError();
  2111. cancelSave();
  2112. }).send();
  2113. }
  2114. void Controller::saveHistoryVisibility() {
  2115. const auto channel = _peer->asChannel();
  2116. const auto hidden = channel ? channel->hiddenPreHistory() : true;
  2117. if (!_savingData.hiddenPreHistory
  2118. || *_savingData.hiddenPreHistory == hidden) {
  2119. return continueSave();
  2120. } else if (!channel) {
  2121. const auto saveForChannel = [=](not_null<ChannelData*> channel) {
  2122. if (_peer->asChannel() == channel) {
  2123. saveHistoryVisibility();
  2124. } else {
  2125. cancelSave();
  2126. }
  2127. };
  2128. _peer->session().api().migrateChat(
  2129. _peer->asChat(),
  2130. crl::guard(this, saveForChannel));
  2131. return;
  2132. }
  2133. togglePreHistoryHidden(
  2134. channel,
  2135. *_savingData.hiddenPreHistory,
  2136. [=] { continueSave(); },
  2137. [=] { cancelSave(); });
  2138. }
  2139. void Controller::toggleBotManager(const QString &command) {
  2140. const auto controller = _navigation->parentController();
  2141. _api.request(MTPcontacts_ResolveUsername(
  2142. MTP_flags(0),
  2143. MTP_string(kBotManagerUsername.utf16()),
  2144. MTP_string()
  2145. )).done([=](const MTPcontacts_ResolvedPeer &result) {
  2146. _peer->owner().processUsers(result.data().vusers());
  2147. _peer->owner().processChats(result.data().vchats());
  2148. const auto botPeer = _peer->owner().peerLoaded(
  2149. peerFromMTP(result.data().vpeer()));
  2150. if (const auto bot = botPeer ? botPeer->asUser() : nullptr) {
  2151. const auto show = controller->uiShow();
  2152. _peer->session().api().sendBotStart(show, bot, bot, command);
  2153. controller->showPeerHistory(bot);
  2154. }
  2155. }).send();
  2156. }
  2157. void Controller::togglePreHistoryHidden(
  2158. not_null<ChannelData*> channel,
  2159. bool hidden,
  2160. Fn<void()> done,
  2161. Fn<void()> fail) {
  2162. const auto apply = [=] {
  2163. // Update in the result doesn't contain the
  2164. // channelFull:flags field which holds this value.
  2165. // So after saving we need to update it manually.
  2166. const auto flags = channel->flags();
  2167. const auto flag = ChannelDataFlag::PreHistoryHidden;
  2168. channel->setFlags(hidden ? (flags | flag) : (flags & ~flag));
  2169. done();
  2170. };
  2171. _api.request(MTPchannels_TogglePreHistoryHidden(
  2172. channel->inputChannel,
  2173. MTP_bool(hidden)
  2174. )).done([=](const MTPUpdates &result) {
  2175. channel->session().api().applyUpdates(result);
  2176. apply();
  2177. }).fail([=](const MTP::Error &error) {
  2178. if (error.type() == u"CHAT_NOT_MODIFIED"_q) {
  2179. apply();
  2180. } else {
  2181. fail();
  2182. }
  2183. }).send();
  2184. }
  2185. void Controller::saveForum() {
  2186. const auto channel = _peer->asChannel();
  2187. if (!_savingData.forum
  2188. || *_savingData.forum == _peer->isForum()) {
  2189. return continueSave();
  2190. } else if (!channel) {
  2191. const auto saveForChannel = [=](not_null<ChannelData*> channel) {
  2192. if (_peer->asChannel() == channel) {
  2193. saveForum();
  2194. } else {
  2195. cancelSave();
  2196. }
  2197. };
  2198. _peer->session().api().migrateChat(
  2199. _peer->asChat(),
  2200. crl::guard(this, saveForChannel));
  2201. return;
  2202. }
  2203. _api.request(MTPchannels_ToggleForum(
  2204. channel->inputChannel,
  2205. MTP_bool(*_savingData.forum)
  2206. )).done([=](const MTPUpdates &result) {
  2207. const auto weak = base::make_weak(this);
  2208. channel->session().api().applyUpdates(result);
  2209. if (weak) { // todo better to be able to save in closed already box.
  2210. continueSave();
  2211. }
  2212. }).fail([=](const MTP::Error &error) {
  2213. if (error.type() == u"CHAT_NOT_MODIFIED"_q) {
  2214. continueSave();
  2215. } else {
  2216. cancelSave();
  2217. }
  2218. }).send();
  2219. }
  2220. void Controller::saveSignatures() {
  2221. Expects(_savingData.signatures.has_value()
  2222. == _savingData.signatureProfiles.has_value());
  2223. const auto channel = _peer->asChannel();
  2224. if (!_savingData.signatures
  2225. || !channel
  2226. || ((*_savingData.signatures == channel->addsSignature())
  2227. && (*_savingData.signatureProfiles
  2228. == channel->signatureProfiles()))) {
  2229. return continueSave();
  2230. }
  2231. using Flag = MTPchannels_ToggleSignatures::Flag;
  2232. _api.request(MTPchannels_ToggleSignatures(
  2233. MTP_flags(Flag()
  2234. | (*_savingData.signatures
  2235. ? Flag::f_signatures_enabled
  2236. : Flag())
  2237. | (*_savingData.signatureProfiles
  2238. ? Flag::f_profiles_enabled
  2239. : Flag())),
  2240. channel->inputChannel
  2241. )).done([=](const MTPUpdates &result) {
  2242. channel->session().api().applyUpdates(result);
  2243. continueSave();
  2244. }).fail([=](const MTP::Error &error) {
  2245. if (error.type() == u"CHAT_NOT_MODIFIED"_q) {
  2246. continueSave();
  2247. } else {
  2248. cancelSave();
  2249. }
  2250. }).send();
  2251. }
  2252. void Controller::saveForwards() {
  2253. if (!_savingData.noForwards
  2254. || *_savingData.noForwards != _peer->allowsForwarding()) {
  2255. return continueSave();
  2256. }
  2257. _api.request(MTPmessages_ToggleNoForwards(
  2258. _peer->input,
  2259. MTP_bool(*_savingData.noForwards)
  2260. )).done([=](const MTPUpdates &result) {
  2261. _peer->session().api().applyUpdates(result);
  2262. continueSave();
  2263. }).fail([=](const MTP::Error &error) {
  2264. if (error.type() == u"CHAT_NOT_MODIFIED"_q) {
  2265. continueSave();
  2266. } else {
  2267. cancelSave();
  2268. }
  2269. }).send();
  2270. }
  2271. void Controller::saveJoinToWrite() {
  2272. const auto joinToWrite = _peer->isMegagroup()
  2273. && _peer->asChannel()->joinToWrite();
  2274. if (!_savingData.joinToWrite
  2275. || *_savingData.joinToWrite == joinToWrite) {
  2276. return continueSave();
  2277. }
  2278. _api.request(MTPchannels_ToggleJoinToSend(
  2279. _peer->asChannel()->inputChannel,
  2280. MTP_bool(*_savingData.joinToWrite)
  2281. )).done([=](const MTPUpdates &result) {
  2282. _peer->session().api().applyUpdates(result);
  2283. continueSave();
  2284. }).fail([=](const MTP::Error &error) {
  2285. if (error.type() == u"CHAT_NOT_MODIFIED"_q) {
  2286. continueSave();
  2287. } else {
  2288. cancelSave();
  2289. }
  2290. }).send();
  2291. }
  2292. void Controller::saveRequestToJoin() {
  2293. const auto requestToJoin = _peer->isMegagroup()
  2294. && _peer->asChannel()->requestToJoin();
  2295. if (!_savingData.requestToJoin
  2296. || *_savingData.requestToJoin == requestToJoin) {
  2297. return continueSave();
  2298. }
  2299. _api.request(MTPchannels_ToggleJoinRequest(
  2300. _peer->asChannel()->inputChannel,
  2301. MTP_bool(*_savingData.requestToJoin)
  2302. )).done([=](const MTPUpdates &result) {
  2303. _peer->session().api().applyUpdates(result);
  2304. continueSave();
  2305. }).fail([=](const MTP::Error &error) {
  2306. if (error.type() == u"CHAT_NOT_MODIFIED"_q) {
  2307. continueSave();
  2308. } else {
  2309. cancelSave();
  2310. }
  2311. }).send();
  2312. }
  2313. void Controller::savePhoto() {
  2314. auto image = _controls.photo
  2315. ? _controls.photo->takeResultImage()
  2316. : QImage();
  2317. if (!image.isNull()) {
  2318. _peer->session().api().peerPhoto().upload(
  2319. _peer,
  2320. { std::move(image) });
  2321. }
  2322. _box->closeBox();
  2323. }
  2324. void Controller::deleteWithConfirmation() {
  2325. const auto channel = _peer->asChannel();
  2326. Assert(channel != nullptr);
  2327. const auto text = (_isGroup
  2328. ? tr::lng_sure_delete_group
  2329. : tr::lng_sure_delete_channel)(tr::now);
  2330. const auto deleteCallback = crl::guard(this, [=] {
  2331. deleteChannel();
  2332. });
  2333. _navigation->parentController()->show(
  2334. Ui::MakeConfirmBox({
  2335. .text = text,
  2336. .confirmed = deleteCallback,
  2337. .confirmText = tr::lng_box_delete(),
  2338. .confirmStyle = &st::attentionBoxButton,
  2339. }));
  2340. }
  2341. void Controller::deleteChannel() {
  2342. Expects(_peer->isChannel());
  2343. const auto channel = _peer->asChannel();
  2344. const auto chat = channel->migrateFrom();
  2345. const auto session = &_peer->session();
  2346. _navigation->parentController()->hideLayer();
  2347. Core::App().closeChatFromWindows(channel);
  2348. if (chat) {
  2349. session->api().deleteConversation(chat, false);
  2350. }
  2351. session->api().request(MTPchannels_DeleteChannel(
  2352. channel->inputChannel
  2353. )).done([=](const MTPUpdates &result) {
  2354. session->api().applyUpdates(result);
  2355. //}).fail([=](const MTP::Error &error) {
  2356. // if (error.type() == u"CHANNEL_TOO_LARGE"_q) {
  2357. // Ui::show(Box<Ui::InformBox>(tr::lng_cant_delete_channel(tr::now)));
  2358. // }
  2359. }).send();
  2360. }
  2361. } // namespace
  2362. EditPeerInfoBox::EditPeerInfoBox(
  2363. QWidget*,
  2364. not_null<Window::SessionNavigation*> navigation,
  2365. not_null<PeerData*> peer)
  2366. : _navigation(navigation)
  2367. , _peer(peer->migrateToOrMe()) {
  2368. }
  2369. void EditPeerInfoBox::prepare() {
  2370. const auto controller = Ui::CreateChild<Controller>(
  2371. this,
  2372. _navigation,
  2373. this,
  2374. _peer);
  2375. _focusRequests.events(
  2376. ) | rpl::start_with_next(
  2377. [=] { controller->setFocus(); },
  2378. lifetime());
  2379. auto content = controller->createContent();
  2380. setDimensionsToContent(st::boxWideWidth, content);
  2381. setInnerWidget(object_ptr<Ui::OverrideMargins>(
  2382. this,
  2383. std::move(content)));
  2384. }
  2385. object_ptr<Ui::SettingsButton> EditPeerInfoBox::CreateButton(
  2386. not_null<QWidget*> parent,
  2387. rpl::producer<QString> &&text,
  2388. rpl::producer<QString> &&count,
  2389. Fn<void()> callback,
  2390. const style::SettingsCountButton &st,
  2391. Settings::IconDescriptor &&descriptor) {
  2392. auto result = object_ptr<Ui::SettingsButton>(
  2393. parent,
  2394. rpl::duplicate(text),
  2395. st.button);
  2396. const auto button = result.data();
  2397. button->addClickHandler(callback);
  2398. const auto badge = descriptor.newBadge
  2399. ? Ui::NewBadge::CreateNewBadge(
  2400. button,
  2401. tr::lng_premium_summary_new_badge()).get()
  2402. : nullptr;
  2403. if (descriptor) {
  2404. AddButtonIcon(
  2405. button,
  2406. st.button,
  2407. std::move(descriptor));
  2408. }
  2409. auto labelText = rpl::combine(
  2410. rpl::duplicate(text),
  2411. std::move(count),
  2412. button->widthValue()
  2413. ) | rpl::map([&st](const QString &text, const QString &count, int width) {
  2414. const auto available = width
  2415. - st.button.padding.left()
  2416. - (st.button.style.font->spacew * 2)
  2417. - st.button.style.font->width(text)
  2418. - st.labelPosition.x();
  2419. const auto required = st.label.style.font->width(count);
  2420. return (required > available)
  2421. ? st.label.style.font->elided(count, std::max(available, 0))
  2422. : count;
  2423. });
  2424. if (badge) {
  2425. rpl::combine(
  2426. std::move(text),
  2427. rpl::duplicate(labelText),
  2428. button->widthValue()
  2429. ) | rpl::start_with_next([=](
  2430. const QString &text,
  2431. const QString &label,
  2432. int width) {
  2433. const auto space = st.button.style.font->spacew;
  2434. const auto left = st.button.padding.left()
  2435. + st.button.style.font->width(text)
  2436. + space;
  2437. const auto right = st.labelPosition.x()
  2438. + st.label.style.font->width(label)
  2439. + (space * 2);
  2440. const auto available = width - left - right;
  2441. badge->setVisible(available >= badge->width());
  2442. if (!badge->isHidden()) {
  2443. const auto top = st.button.padding.top()
  2444. + st.button.style.font->ascent
  2445. - st::settingsPremiumNewBadge.style.font->ascent
  2446. - st::settingsPremiumNewBadgePadding.top();
  2447. badge->moveToLeft(left, top, width);
  2448. }
  2449. }, badge->lifetime());
  2450. }
  2451. const auto label = Ui::CreateChild<Ui::FlatLabel>(
  2452. button,
  2453. std::move(labelText),
  2454. st.label);
  2455. label->setAttribute(Qt::WA_TransparentForMouseEvents);
  2456. label->show();
  2457. rpl::combine(
  2458. button->widthValue(),
  2459. label->widthValue()
  2460. ) | rpl::start_with_next([=, &st](int outerWidth, int width) {
  2461. label->moveToRight(
  2462. st.labelPosition.x(),
  2463. st.labelPosition.y(),
  2464. outerWidth);
  2465. }, label->lifetime());
  2466. return result;
  2467. }
  2468. bool EditPeerInfoBox::Available(not_null<PeerData*> peer) {
  2469. if (const auto bot = peer->asUser()) {
  2470. return bot->botInfo && bot->botInfo->canEditInformation;
  2471. } else if (const auto chat = peer->asChat()) {
  2472. return false
  2473. || chat->canEditInformation()
  2474. || chat->canEditPermissions();
  2475. } else if (const auto channel = peer->asChannel()) {
  2476. // canViewMembers() is removed, because in supergroups you
  2477. // see them in profile and in channels only admins can see them.
  2478. // canViewAdmins() is removed, because in supergroups it is
  2479. // always true and in channels it is equal to canViewBanned().
  2480. return false
  2481. //|| channel->canViewMembers()
  2482. //|| channel->canViewAdmins()
  2483. || channel->canViewBanned()
  2484. || channel->canEditInformation()
  2485. || channel->canEditPermissions()
  2486. || channel->hasAdminRights()
  2487. || channel->amCreator();
  2488. } else {
  2489. return false;
  2490. }
  2491. }
  2492. void ShowEditChatPermissions(
  2493. not_null<Window::SessionNavigation*> navigation,
  2494. not_null<PeerData*> peer) {
  2495. ShowEditPermissions(navigation, peer);
  2496. }