export_output_html.cpp 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510
  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 "export/output/export_output_html.h"
  8. #include "countries/countries_instance.h"
  9. #include "export/output/export_output_result.h"
  10. #include "export/data/export_data_types.h"
  11. #include "core/utils.h"
  12. #include "ui/text/format_values.h"
  13. #include <QtCore/QSize>
  14. #include <QtCore/QFile>
  15. #include <QtCore/QDateTime>
  16. namespace Export {
  17. namespace Output {
  18. namespace {
  19. constexpr auto kMessagesInFile = 1000;
  20. constexpr auto kPersonalUserpicSize = 90;
  21. constexpr auto kEntryUserpicSize = 48;
  22. constexpr auto kServiceMessagePhotoSize = 60;
  23. constexpr auto kHistoryUserpicSize = 42;
  24. constexpr auto kSavedMessagesColorIndex = uint8(3);
  25. constexpr auto kJoinWithinSeconds = 900;
  26. constexpr auto kPhotoMaxWidth = 520;
  27. constexpr auto kPhotoMaxHeight = 520;
  28. constexpr auto kPhotoMinWidth = 80;
  29. constexpr auto kPhotoMinHeight = 80;
  30. constexpr auto kStickerMaxWidth = 384;
  31. constexpr auto kStickerMaxHeight = 384;
  32. constexpr auto kStickerMinWidth = 80;
  33. constexpr auto kStickerMinHeight = 80;
  34. constexpr auto kStoryThumbWidth = 45;
  35. constexpr auto kStoryThumbHeight = 80;
  36. constexpr auto kChatsPriority = 0;
  37. constexpr auto kContactsPriority = 2;
  38. constexpr auto kFrequentContactsPriority = 3;
  39. constexpr auto kUserpicsPriority = 4;
  40. constexpr auto kStoriesPriority = 5;
  41. constexpr auto kSessionsPriority = 6;
  42. constexpr auto kWebSessionsPriority = 7;
  43. constexpr auto kOtherPriority = 8;
  44. const auto kLineBreak = QByteArrayLiteral("<br>");
  45. using Context = details::HtmlContext;
  46. using UserpicData = details::UserpicData;
  47. using StoryData = details::StoryData;
  48. using PeersMap = details::PeersMap;
  49. using MediaData = details::MediaData;
  50. bool IsGlobalLink(const QString &link) {
  51. return link.startsWith(u"http://"_q, Qt::CaseInsensitive)
  52. || link.startsWith(u"https://"_q, Qt::CaseInsensitive);
  53. }
  54. QByteArray NoFileDescription(Data::File::SkipReason reason) {
  55. using SkipReason = Data::File::SkipReason;
  56. switch (reason) {
  57. case SkipReason::Unavailable:
  58. return "Unavailable, please try again later.";
  59. case SkipReason::FileSize:
  60. return "Exceeds maximum size, "
  61. "change data exporting settings to download.";
  62. case SkipReason::FileType:
  63. return "Not included, "
  64. "change data exporting settings to download.";
  65. case SkipReason::None:
  66. return "";
  67. }
  68. Unexpected("Skip reason in NoFileDescription.");
  69. }
  70. auto CalculateThumbSize(
  71. int maxWidth,
  72. int maxHeight,
  73. int minWidth,
  74. int minHeight,
  75. bool expandForRetina = false) {
  76. return [=](QSize largeSize) {
  77. const auto multiplier = (expandForRetina ? 2 : 1);
  78. const auto checkWidth = largeSize.width() * multiplier;
  79. const auto checkHeight = largeSize.height() * multiplier;
  80. const auto smallSize = (checkWidth > maxWidth
  81. || checkHeight > maxHeight)
  82. ? largeSize.scaled(
  83. maxWidth,
  84. maxHeight,
  85. Qt::KeepAspectRatio)
  86. : largeSize;
  87. const auto retinaSize = QSize(
  88. smallSize.width() & ~0x01,
  89. smallSize.height() & ~0x01);
  90. return (retinaSize.width() < kPhotoMinWidth
  91. || retinaSize.height() < kPhotoMinHeight)
  92. ? QSize()
  93. : retinaSize;
  94. };
  95. }
  96. QByteArray SerializeString(const QByteArray &value) {
  97. const auto size = value.size();
  98. const auto begin = value.data();
  99. const auto end = begin + size;
  100. auto result = QByteArray();
  101. result.reserve(size * 6);
  102. for (auto p = begin; p != end; ++p) {
  103. const auto ch = *p;
  104. if (ch == '\n') {
  105. result.append("<br>", 4);
  106. } else if (ch == '"') {
  107. result.append("&quot;", 6);
  108. } else if (ch == '&') {
  109. result.append("&amp;", 5);
  110. } else if (ch == '\'') {
  111. result.append("&apos;", 6);
  112. } else if (ch == '<') {
  113. result.append("&lt;", 4);
  114. } else if (ch == '>') {
  115. result.append("&gt;", 4);
  116. } else if (ch >= 0 && ch < 32) {
  117. result.append("&#x", 3).append('0' + (ch >> 4));
  118. const auto left = (ch & 0x0F);
  119. if (left >= 10) {
  120. result.append('A' + (left - 10));
  121. } else {
  122. result.append('0' + left);
  123. }
  124. result.append(';');
  125. } else if (ch == char(0xE2)
  126. && (p + 2 < end)
  127. && *(p + 1) == char(0x80)) {
  128. if (*(p + 2) == char(0xA8)) { // Line separator.
  129. result.append("<br>", 4);
  130. } else if (*(p + 2) == char(0xA9)) { // Paragraph separator.
  131. result.append("<br>", 4);
  132. } else {
  133. result.append(ch);
  134. }
  135. } else {
  136. result.append(ch);
  137. }
  138. }
  139. return result;
  140. }
  141. QByteArray SerializeList(const std::vector<QByteArray> &values) {
  142. const auto count = values.size();
  143. if (count == 1) {
  144. return values[0];
  145. } else if (count > 1) {
  146. auto result = values[0];
  147. for (auto i = 1; i != count - 1; ++i) {
  148. result += ", " + values[i];
  149. }
  150. return result + " and " + values[count - 1];
  151. }
  152. return QByteArray();
  153. }
  154. QByteArray MakeLinks(const QByteArray &value) {
  155. const auto domain = QByteArray("https://telegram.org/");
  156. auto result = QByteArray();
  157. auto offset = 0;
  158. while (true) {
  159. const auto start = value.indexOf(domain, offset);
  160. if (start < 0) {
  161. break;
  162. }
  163. auto end = start + domain.size();
  164. for (; end != value.size(); ++end) {
  165. const auto ch = value[end];
  166. if ((ch < 'a' || ch > 'z')
  167. && (ch < 'A' || ch > 'Z')
  168. && (ch < '0' || ch > '9')
  169. && (ch != '-')
  170. && (ch != '_')
  171. && (ch != '/')) {
  172. break;
  173. }
  174. }
  175. if (start > offset) {
  176. const auto link = value.mid(start, end - start);
  177. result.append(value.mid(offset, start - offset));
  178. result.append("<a href=\"").append(link).append("\">");
  179. result.append(link);
  180. result.append("</a>");
  181. offset = end;
  182. }
  183. }
  184. if (result.isEmpty()) {
  185. return value;
  186. }
  187. if (offset < value.size()) {
  188. result.append(value.mid(offset));
  189. }
  190. return result;
  191. }
  192. QByteArray JoinList(
  193. const QByteArray &separator,
  194. const std::vector<QByteArray> &list) {
  195. if (list.empty()) {
  196. return QByteArray();
  197. } else if (list.size() == 1) {
  198. return list[0];
  199. }
  200. auto size = (list.size() - 1) * separator.size();
  201. for (const auto &value : list) {
  202. size += value.size();
  203. }
  204. auto result = QByteArray();
  205. result.reserve(size);
  206. auto counter = 0;
  207. while (true) {
  208. result.append(list[counter]);
  209. if (++counter == list.size()) {
  210. break;
  211. } else {
  212. result.append(separator);
  213. }
  214. }
  215. return result;
  216. }
  217. QByteArray FormatCustomEmoji(
  218. const Data::Utf8String &custom_emoji,
  219. const QByteArray &text,
  220. const QString &relativeLinkBase) {
  221. return (custom_emoji.isEmpty()
  222. ? "<a href=\"\" onclick=\"return ShowNotLoadedEmoji();\">"
  223. : (custom_emoji == Data::TextPart::UnavailableEmoji())
  224. ? "<a href=\"\" onclick=\"return ShowNotAvailableEmoji();\">"
  225. : ("<a href = \""
  226. + (relativeLinkBase + custom_emoji).toUtf8()
  227. + "\">"))
  228. + text
  229. + "</a>";
  230. }
  231. QByteArray FormatText(
  232. const std::vector<Data::TextPart> &data,
  233. const QString &internalLinksDomain,
  234. const QString &relativeLinkBase) {
  235. return JoinList(QByteArray(), ranges::views::all(
  236. data
  237. ) | ranges::views::transform([&](const Data::TextPart &part) {
  238. const auto text = SerializeString(part.text);
  239. using Type = Data::TextPart::Type;
  240. switch (part.type) {
  241. case Type::Text: return text;
  242. case Type::Unknown: return text;
  243. case Type::Mention:
  244. return "<a href=\""
  245. + internalLinksDomain.toUtf8()
  246. + text.mid(1)
  247. + "\">" + text + "</a>";
  248. case Type::Hashtag: return "<a href=\"\" "
  249. "onclick=\"return ShowHashtag("
  250. + SerializeString('"' + text.mid(1) + '"')
  251. + ")\">" + text + "</a>";
  252. case Type::BotCommand: return "<a href=\"\" "
  253. "onclick=\"return ShowBotCommand("
  254. + SerializeString('"' + text.mid(1) + '"')
  255. + ")\">" + text + "</a>";
  256. case Type::Url: return "<a href=\""
  257. + text
  258. + "\">" + text + "</a>";
  259. case Type::Email: return "<a href=\"mailto:"
  260. + text
  261. + "\">" + text + "</a>";
  262. case Type::Bold: return "<strong>" + text + "</strong>";
  263. case Type::Italic: return "<em>" + text + "</em>";
  264. case Type::Code: return "<code>" + text + "</code>";
  265. case Type::Pre: return "<pre>" + text + "</pre>";
  266. case Type::TextUrl: return "<a href=\""
  267. + SerializeString(part.additional)
  268. + "\">" + text + "</a>";
  269. case Type::MentionName: return "<a href=\"\" "
  270. "onclick=\"return ShowMentionName()\">" + text + "</a>";
  271. case Type::Phone: return "<a href=\"tel:"
  272. + text
  273. + "\">" + text + "</a>";
  274. case Type::Cashtag: return "<a href=\"\" "
  275. "onclick=\"return ShowCashtag("
  276. + SerializeString('"' + text.mid(1) + '"')
  277. + ")\">" + text + "</a>";
  278. case Type::Underline: return "<u>" + text + "</u>";
  279. case Type::Strike: return "<s>" + text + "</s>";
  280. case Type::Blockquote:
  281. return "<blockquote>" + text + "</blockquote>";
  282. case Type::BankCard:
  283. return text;
  284. case Type::Spoiler: return "<span class=\"spoiler hidden\" "
  285. "onclick=\"ShowSpoiler(this)\">"
  286. "<span aria-hidden=\"true\">"
  287. + text + "</span></span>";
  288. case Type::CustomEmoji:
  289. return FormatCustomEmoji(part.additional, text, relativeLinkBase);
  290. }
  291. Unexpected("Type in text entities serialization.");
  292. }) | ranges::to_vector);
  293. }
  294. Data::Utf8String FormatUsername(const Data::Utf8String &username) {
  295. return username.isEmpty() ? username : ('@' + username);
  296. }
  297. bool DisplayDate(TimeId date, TimeId previousDate) {
  298. if (!previousDate) {
  299. return true;
  300. }
  301. return QDateTime::fromSecsSinceEpoch(date).date()
  302. != QDateTime::fromSecsSinceEpoch(previousDate).date();
  303. }
  304. QByteArray FormatDateText(TimeId date) {
  305. const auto parsed = QDateTime::fromSecsSinceEpoch(date).date();
  306. const auto month = [](int index) {
  307. switch (index) {
  308. case 1: return "January";
  309. case 2: return "February";
  310. case 3: return "March";
  311. case 4: return "April";
  312. case 5: return "May";
  313. case 6: return "June";
  314. case 7: return "July";
  315. case 8: return "August";
  316. case 9: return "September";
  317. case 10: return "October";
  318. case 11: return "November";
  319. case 12: return "December";
  320. }
  321. return "Unknown";
  322. };
  323. return Data::NumberToString(parsed.day())
  324. + ' '
  325. + month(parsed.month())
  326. + ' '
  327. + Data::NumberToString(parsed.year());
  328. }
  329. QByteArray FormatTimeText(TimeId date) {
  330. const auto parsed = QDateTime::fromSecsSinceEpoch(date).time();
  331. return Data::NumberToString(parsed.hour(), 2)
  332. + ':'
  333. + Data::NumberToString(parsed.minute(), 2);
  334. }
  335. } // namespace
  336. namespace details {
  337. struct UserpicData {
  338. uint8 colorIndex = 0;
  339. int pixelSize = 0;
  340. QString imageLink;
  341. QString largeLink;
  342. QByteArray firstName;
  343. QByteArray lastName;
  344. QByteArray tooltip;
  345. };
  346. struct StoryData {
  347. QString imageLink;
  348. QString largeLink;
  349. };
  350. class PeersMap {
  351. public:
  352. using Peer = Data::Peer;
  353. using User = Data::User;
  354. using Chat = Data::Chat;
  355. PeersMap(const std::map<PeerId, Peer> &data);
  356. const Peer &peer(PeerId peerId) const;
  357. const User &user(UserId userId) const;
  358. QByteArray wrapPeerName(PeerId peerId) const;
  359. QByteArray wrapUserName(UserId userId) const;
  360. QByteArray wrapUserNames(const std::vector<UserId> &data) const;
  361. private:
  362. const std::map<PeerId, Data::Peer> &_data;
  363. };
  364. struct MediaData {
  365. QByteArray title;
  366. QByteArray description;
  367. QByteArray status;
  368. QByteArray classes;
  369. QString thumb;
  370. QString link;
  371. };
  372. PeersMap::PeersMap(const std::map<PeerId, Peer> &data) : _data(data) {
  373. }
  374. auto PeersMap::peer(PeerId peerId) const -> const Peer & {
  375. if (const auto i = _data.find(peerId); i != end(_data)) {
  376. return i->second;
  377. }
  378. static auto empty = Peer{ User() };
  379. return empty;
  380. }
  381. auto PeersMap::user(UserId userId) const -> const User & {
  382. if (const auto result = peer(peerFromUser(userId)).user()) {
  383. return *result;
  384. }
  385. static auto empty = User();
  386. return empty;
  387. }
  388. QByteArray PeersMap::wrapPeerName(PeerId peerId) const {
  389. const auto result = peer(peerId).name();
  390. return result.isEmpty()
  391. ? QByteArray("Deleted")
  392. : SerializeString(result);
  393. }
  394. QByteArray PeersMap::wrapUserName(UserId userId) const {
  395. const auto result = user(userId).name();
  396. return result.isEmpty()
  397. ? QByteArray("Deleted Account")
  398. : SerializeString(result);
  399. }
  400. QByteArray PeersMap::wrapUserNames(const std::vector<UserId> &data) const {
  401. auto list = std::vector<QByteArray>();
  402. for (const auto &userId : data) {
  403. list.push_back(wrapUserName(userId));
  404. }
  405. return SerializeList(list);
  406. }
  407. QByteArray HtmlContext::pushTag(
  408. const QByteArray &tag,
  409. std::map<QByteArray, QByteArray> &&attributes) {
  410. auto data = Tag();
  411. data.name = tag;
  412. auto empty = false;
  413. auto inner = QByteArray();
  414. for (const auto &[name, value] : attributes) {
  415. if (name == "inline") {
  416. data.block = false;
  417. } else if (name == "empty") {
  418. empty = true;
  419. } else {
  420. inner.append(' ').append(name);
  421. inner.append("=\"").append(SerializeString(value)).append("\"");
  422. }
  423. }
  424. auto result = (data.block ? ("\n" + indent()) : QByteArray())
  425. + "<" + data.name + inner + (empty ? "/" : "") + ">"
  426. + (data.block ? "\n" : "");
  427. if (!empty) {
  428. _tags.push_back(data);
  429. }
  430. return result;
  431. }
  432. QByteArray HtmlContext::popTag() {
  433. Expects(!_tags.empty());
  434. const auto data = _tags.back();
  435. _tags.pop_back();
  436. return (data.block ? ("\n" + indent()) : QByteArray())
  437. + "</" + data.name + ">"
  438. + (data.block ? "\n" : "");
  439. }
  440. QByteArray HtmlContext::indent() const {
  441. return QByteArray(_tags.size(), ' ');
  442. }
  443. bool HtmlContext::empty() const {
  444. return _tags.empty();
  445. }
  446. } // namespace details
  447. struct HtmlWriter::MessageInfo {
  448. enum class Type {
  449. Service,
  450. Default,
  451. };
  452. int id = 0;
  453. Type type = Type::Service;
  454. PeerId fromId = 0;
  455. UserId viaBotId = 0;
  456. TimeId date = 0;
  457. PeerId forwardedFromId = 0;
  458. QString forwardedFromName;
  459. bool forwarded = false;
  460. bool showForwardedAsOriginal = false;
  461. TimeId forwardedDate = 0;
  462. };
  463. class HtmlWriter::Wrap {
  464. public:
  465. Wrap(const QString &path, const QString &base, Stats *stats);
  466. [[nodiscard]] bool empty() const;
  467. [[nodiscard]] QByteArray pushTag(
  468. const QByteArray &tag,
  469. std::map<QByteArray, QByteArray> &&attributes = {});
  470. [[nodiscard]] QByteArray popTag();
  471. [[nodiscard]] QByteArray indent() const;
  472. [[nodiscard]] QByteArray pushDiv(
  473. const QByteArray &className,
  474. const QByteArray &style = {});
  475. [[nodiscard]] QByteArray pushUserpic(const UserpicData &userpic);
  476. [[nodiscard]] QByteArray pushListEntry(
  477. const UserpicData &userpic,
  478. const QByteArray &name,
  479. const QByteArray &details,
  480. const QByteArray &info,
  481. const QString &link = QString());
  482. [[nodiscard]] QByteArray pushStoriesListEntry(
  483. const StoryData &story,
  484. const QByteArray &name,
  485. const QByteArrayList &details,
  486. const QByteArray &info,
  487. const std::vector<Data::TextPart> &caption,
  488. const QString &internalLinksDomain,
  489. const QString &link = QString());
  490. [[nodiscard]] QByteArray pushSessionListEntry(
  491. int apiId,
  492. const QByteArray &name,
  493. const QByteArray &subname,
  494. std::initializer_list<QByteArray> details,
  495. const QByteArray &info = QByteArray());
  496. [[nodiscard]] QByteArray pushHeader(
  497. const QByteArray &header,
  498. const QString &path = QString());
  499. [[nodiscard]] QByteArray pushSection(
  500. const QByteArray &label,
  501. const QByteArray &type,
  502. int count,
  503. const QString &path);
  504. [[nodiscard]] QByteArray pushAbout(
  505. const QByteArray &text,
  506. bool withDivider = false);
  507. [[nodiscard]] QByteArray pushServiceMessage(
  508. int messageId,
  509. const Data::DialogInfo &dialog,
  510. const QString &basePath,
  511. const QByteArray &text,
  512. const Data::Photo *photo = nullptr);
  513. [[nodiscard]] std::pair<MessageInfo, QByteArray> pushMessage(
  514. const Data::Message &message,
  515. const MessageInfo *previous,
  516. const Data::DialogInfo &dialog,
  517. const QString &basePath,
  518. const PeersMap &peers,
  519. const QString &internalLinksDomain,
  520. Fn<QByteArray(int messageId, QByteArray text)> wrapMessageLink);
  521. [[nodiscard]] Result writeBlock(const QByteArray &block);
  522. [[nodiscard]] Result close();
  523. [[nodiscard]] QString relativePath(const QString &path) const;
  524. [[nodiscard]] QString relativePath(const Data::File &file) const;
  525. ~Wrap();
  526. private:
  527. [[nodiscard]] QByteArray composeStart();
  528. [[nodiscard]] QByteArray pushGenericListEntry(
  529. const QString &link,
  530. const UserpicData &userpic,
  531. const QByteArray &name,
  532. const QByteArray &subname,
  533. std::initializer_list<QByteArray> details,
  534. const QByteArray &info);
  535. [[nodiscard]] bool messageNeedsWrap(
  536. const Data::Message &message,
  537. const MessageInfo *previous) const;
  538. [[nodiscard]] bool forwardedNeedsWrap(
  539. const Data::Message &message,
  540. const MessageInfo *previous) const;
  541. [[nodiscard]] MediaData prepareMediaData(
  542. const Data::Message &message,
  543. const QString &basePath,
  544. const PeersMap &peers,
  545. const QString &internalLinksDomain) const;
  546. [[nodiscard]] QByteArray pushMedia(
  547. const Data::Message &message,
  548. const QString &basePath,
  549. const PeersMap &peers,
  550. const QString &internalLinksDomain,
  551. Fn<QByteArray(int messageId, QByteArray text)> wrapMessageLink);
  552. [[nodiscard]] QByteArray pushGenericMedia(const MediaData &data);
  553. [[nodiscard]] QByteArray pushStickerMedia(
  554. const Data::Document &data,
  555. const QString &basePath);
  556. [[nodiscard]] QByteArray pushAnimatedMedia(
  557. const Data::Document &data,
  558. const QString &basePath);
  559. [[nodiscard]] QByteArray pushVideoFileMedia(
  560. const Data::Document &data,
  561. const QString &basePath);
  562. [[nodiscard]] QByteArray pushPhotoMedia(
  563. const Data::Photo &data,
  564. const QString &basePath);
  565. [[nodiscard]] QByteArray pushPoll(const Data::Poll &data);
  566. [[nodiscard]] QByteArray pushGiveaway(
  567. const PeersMap &peers,
  568. const Data::GiveawayStart &data);
  569. [[nodiscard]] QByteArray pushGiveaway(
  570. const PeersMap &peers,
  571. const Data::GiveawayResults &data,
  572. Fn<QByteArray(int messageId, QByteArray text)> wrapMessageLink);
  573. File _file;
  574. QByteArray _composedStart;
  575. bool _closed = false;
  576. QByteArray _base;
  577. Context _context;
  578. };
  579. struct HtmlWriter::SavedSection {
  580. int priority = 0;
  581. QByteArray label;
  582. QByteArray type;
  583. int count = 0;
  584. QString path;
  585. };
  586. void FillUserpicNames(UserpicData &data, const Data::Peer &peer) {
  587. if (peer.user()) {
  588. data.firstName = peer.user()->info.firstName;
  589. data.lastName = peer.user()->info.lastName;
  590. } else if (peer.chat()) {
  591. data.firstName = peer.name();
  592. }
  593. }
  594. void FillUserpicNames(UserpicData &data, const QByteArray &full) {
  595. const auto names = full.split(' ');
  596. data.firstName = names[0];
  597. for (auto i = 1; i != names.size(); ++i) {
  598. if (names[i].isEmpty()) {
  599. continue;
  600. }
  601. if (!data.lastName.isEmpty()) {
  602. data.lastName.append(' ');
  603. }
  604. data.lastName.append(names[i]);
  605. }
  606. }
  607. QByteArray ComposeName(const UserpicData &data, const QByteArray &empty) {
  608. return ((data.firstName.isEmpty() && data.lastName.isEmpty())
  609. ? empty
  610. : (data.firstName + ' ' + data.lastName));
  611. }
  612. QString WriteUserpicThumb(
  613. const QString &basePath,
  614. const QString &largePath,
  615. const UserpicData &userpic,
  616. const QString &postfix = "_thumb") {
  617. return Data::WriteImageThumb(
  618. basePath,
  619. largePath,
  620. userpic.pixelSize * 2,
  621. userpic.pixelSize * 2,
  622. postfix);
  623. }
  624. HtmlWriter::Wrap::Wrap(
  625. const QString &path,
  626. const QString &base,
  627. Stats *stats)
  628. : _file(path, stats) {
  629. Expects(base.endsWith('/'));
  630. Expects(path.startsWith(base));
  631. const auto left = path.mid(base.size());
  632. const auto nesting = ranges::count(left, '/');
  633. _base = QString("../").repeated(nesting).toUtf8();
  634. _composedStart = composeStart();
  635. }
  636. bool HtmlWriter::Wrap::empty() const {
  637. return _file.empty();
  638. }
  639. QByteArray HtmlWriter::Wrap::pushTag(
  640. const QByteArray &tag,
  641. std::map<QByteArray, QByteArray> &&attributes) {
  642. return _context.pushTag(tag, std::move(attributes));
  643. }
  644. QByteArray HtmlWriter::Wrap::popTag() {
  645. return _context.popTag();
  646. }
  647. QByteArray HtmlWriter::Wrap::indent() const {
  648. return _context.indent();
  649. }
  650. QByteArray HtmlWriter::Wrap::pushDiv(
  651. const QByteArray &className,
  652. const QByteArray &style) {
  653. return style.isEmpty()
  654. ? _context.pushTag("div", { { "class", className } })
  655. : _context.pushTag("div", {
  656. { "class", className },
  657. { "style", style }
  658. });
  659. }
  660. QByteArray HtmlWriter::Wrap::pushUserpic(const UserpicData &userpic) {
  661. const auto size = Data::NumberToString(userpic.pixelSize) + "px";
  662. auto result = QByteArray();
  663. if (!userpic.largeLink.isEmpty()) {
  664. result.append(pushTag("a", {
  665. { "class", "userpic_link" },
  666. { "href", relativePath(userpic.largeLink).toUtf8() }
  667. }));
  668. }
  669. const auto sizeStyle = "width: " + size + "; height: " + size;
  670. if (!userpic.imageLink.isEmpty()) {
  671. result.append(pushTag("img", {
  672. { "class", "userpic" },
  673. { "style", sizeStyle },
  674. { "src", relativePath(userpic.imageLink).toUtf8() },
  675. { "empty", "" }
  676. }));
  677. } else {
  678. result.append(pushTag("div", {
  679. {
  680. "class",
  681. "userpic userpic"
  682. + Data::NumberToString(userpic.colorIndex + 1)
  683. },
  684. { "style", sizeStyle }
  685. }));
  686. if (userpic.tooltip.isEmpty()) {
  687. result.append(pushDiv(
  688. "initials",
  689. "line-height: " + size));
  690. } else {
  691. result.append(pushTag("div", {
  692. { "class", "initials" },
  693. { "style", "line-height: " + size },
  694. { "title", userpic.tooltip },
  695. }));
  696. }
  697. auto character = [](const QByteArray &from) {
  698. const auto utf = QString::fromUtf8(from).trimmed();
  699. return utf.isEmpty()
  700. ? QByteArray()
  701. : SerializeString(utf.mid(0, 1).toUtf8());
  702. };
  703. result.append(character(userpic.firstName));
  704. result.append(character(userpic.lastName));
  705. result.append(popTag());
  706. result.append(popTag());
  707. }
  708. if (!userpic.largeLink.isEmpty()) {
  709. result.append(popTag());
  710. }
  711. return result;
  712. }
  713. QByteArray HtmlWriter::Wrap::pushListEntry(
  714. const UserpicData &userpic,
  715. const QByteArray &name,
  716. const QByteArray &details,
  717. const QByteArray &info,
  718. const QString &link) {
  719. return pushGenericListEntry(
  720. link,
  721. userpic,
  722. name,
  723. {},
  724. { details },
  725. info);
  726. }
  727. QByteArray HtmlWriter::Wrap::pushStoriesListEntry(
  728. const StoryData &story,
  729. const QByteArray &name,
  730. const QByteArrayList &details,
  731. const QByteArray &info,
  732. const std::vector<Data::TextPart> &caption,
  733. const QString &internalLinksDomain,
  734. const QString &link) {
  735. auto result = pushDiv("entry clearfix");
  736. if (!link.isEmpty()) {
  737. result.append(pushTag("a", {
  738. { "class", "pull_left userpic_wrap" },
  739. { "href", relativePath(link).toUtf8() + "#allow_back" },
  740. }));
  741. } else {
  742. result.append(pushDiv("pull_left userpic_wrap"));
  743. }
  744. if (!story.imageLink.isEmpty()) {
  745. const auto sizeStyle = "width: "
  746. + Data::NumberToString(kStoryThumbWidth)
  747. + "px; height: "
  748. + Data::NumberToString(kStoryThumbHeight)
  749. + "px";
  750. result.append(pushTag("img", {
  751. { "class", "story" },
  752. { "style", sizeStyle },
  753. { "src", relativePath(story.imageLink).toUtf8() },
  754. { "empty", "" }
  755. }));
  756. }
  757. result.append(popTag());
  758. result.append(pushDiv("body"));
  759. if (!info.isEmpty()) {
  760. result.append(pushDiv("pull_right info details"));
  761. result.append(SerializeString(info));
  762. result.append(popTag());
  763. }
  764. if (!name.isEmpty()) {
  765. if (!link.isEmpty()) {
  766. result.append(pushTag("a", {
  767. { "class", "block_link expanded" },
  768. { "href", relativePath(link).toUtf8() + "#allow_back" },
  769. }));
  770. }
  771. result.append(pushDiv("name bold"));
  772. result.append(SerializeString(name));
  773. result.append(popTag());
  774. if (!link.isEmpty()) {
  775. result.append(popTag());
  776. }
  777. }
  778. const auto text = caption.empty()
  779. ? QByteArray()
  780. : FormatText(caption, internalLinksDomain, _base);
  781. if (!text.isEmpty()) {
  782. result.append(pushDiv("text"));
  783. result.append(text);
  784. result.append(popTag());
  785. }
  786. for (const auto &detail : details) {
  787. result.append(pushDiv("details_entry details"));
  788. result.append(SerializeString(detail));
  789. result.append(popTag());
  790. }
  791. result.append(popTag());
  792. result.append(popTag());
  793. return result;
  794. }
  795. QByteArray HtmlWriter::Wrap::pushSessionListEntry(
  796. int apiId,
  797. const QByteArray &name,
  798. const QByteArray &subname,
  799. std::initializer_list<QByteArray> details,
  800. const QByteArray &info) {
  801. const auto link = QString();
  802. auto userpic = UserpicData{
  803. Data::ApplicationColorIndex(apiId),
  804. kEntryUserpicSize
  805. };
  806. userpic.firstName = name;
  807. return pushGenericListEntry(
  808. link,
  809. userpic,
  810. name,
  811. subname,
  812. details,
  813. info);
  814. }
  815. QByteArray HtmlWriter::Wrap::pushGenericListEntry(
  816. const QString &link,
  817. const UserpicData &userpic,
  818. const QByteArray &name,
  819. const QByteArray &subname,
  820. std::initializer_list<QByteArray> details,
  821. const QByteArray &info) {
  822. auto result = link.isEmpty()
  823. ? pushDiv("entry clearfix")
  824. : pushTag("a", {
  825. { "class", "entry block_link clearfix" },
  826. { "href", relativePath(link).toUtf8() + "#allow_back" },
  827. });
  828. result.append(pushDiv("pull_left userpic_wrap"));
  829. result.append(pushUserpic(userpic));
  830. result.append(popTag());
  831. result.append(pushDiv("body"));
  832. if (!info.isEmpty()) {
  833. result.append(pushDiv("pull_right info details"));
  834. result.append(SerializeString(info));
  835. result.append(popTag());
  836. }
  837. if (!name.isEmpty()) {
  838. result.append(pushDiv("name bold"));
  839. result.append(SerializeString(name));
  840. result.append(popTag());
  841. }
  842. if (!subname.isEmpty()) {
  843. result.append(pushDiv("subname bold"));
  844. result.append(SerializeString(subname));
  845. result.append(popTag());
  846. }
  847. for (const auto &detail : details) {
  848. result.append(pushDiv("details_entry details"));
  849. result.append(SerializeString(detail));
  850. result.append(popTag());
  851. }
  852. result.append(popTag());
  853. result.append(popTag());
  854. return result;
  855. }
  856. Result HtmlWriter::Wrap::writeBlock(const QByteArray &block) {
  857. Expects(!_closed);
  858. const auto result = [&] {
  859. if (block.isEmpty()) {
  860. return _file.writeBlock(block);
  861. } else if (_file.empty()) {
  862. return _file.writeBlock(_composedStart + block);
  863. }
  864. return _file.writeBlock(block);
  865. }();
  866. if (!result) {
  867. _closed = true;
  868. }
  869. return result;
  870. }
  871. QByteArray HtmlWriter::Wrap::pushHeader(
  872. const QByteArray &header,
  873. const QString &path) {
  874. auto result = pushDiv("page_header");
  875. result.append(path.isEmpty()
  876. ? pushDiv("content")
  877. : pushTag("a", {
  878. { "class", "content block_link" },
  879. { "href", relativePath(path).toUtf8() },
  880. { "onclick", "return GoBack(this)"},
  881. }));
  882. result.append(pushDiv("text bold"));
  883. result.append(SerializeString(header));
  884. result.append(popTag());
  885. result.append(popTag());
  886. result.append(popTag());
  887. return result;
  888. }
  889. QByteArray HtmlWriter::Wrap::pushSection(
  890. const QByteArray &header,
  891. const QByteArray &type,
  892. int count,
  893. const QString &link) {
  894. auto result = pushTag("a", {
  895. { "class", "section block_link " + type },
  896. { "href", link.toUtf8() + "#allow_back" },
  897. });
  898. result.append(pushDiv("counter details"));
  899. result.append(Data::NumberToString(count));
  900. result.append(popTag());
  901. result.append(pushDiv("label bold"));
  902. result.append(SerializeString(header));
  903. result.append(popTag());
  904. result.append(popTag());
  905. return result;
  906. }
  907. QByteArray HtmlWriter::Wrap::pushAbout(
  908. const QByteArray &text,
  909. bool withDivider) {
  910. auto result = pushDiv(withDivider
  911. ? "page_about details with_divider"
  912. : "page_about details");
  913. result.append(MakeLinks(SerializeString(text)));
  914. result.append(popTag());
  915. return result;
  916. }
  917. QByteArray HtmlWriter::Wrap::pushServiceMessage(
  918. int messageId,
  919. const Data::DialogInfo &dialog,
  920. const QString &basePath,
  921. const QByteArray &serialized,
  922. const Data::Photo *photo) {
  923. auto result = pushTag("div", {
  924. { "class", "message service" },
  925. { "id", "message" + Data::NumberToString(messageId) }
  926. });
  927. result.append(pushDiv("body details"));
  928. result.append(serialized);
  929. result.append(popTag());
  930. if (photo) {
  931. auto userpic = UserpicData();
  932. userpic.colorIndex = dialog.colorIndex;
  933. userpic.firstName = dialog.name;
  934. userpic.lastName = dialog.lastName;
  935. userpic.pixelSize = kServiceMessagePhotoSize;
  936. userpic.largeLink = photo->image.file.relativePath;
  937. userpic.imageLink = WriteUserpicThumb(
  938. basePath,
  939. userpic.largeLink,
  940. userpic);
  941. result.append(pushDiv("userpic_wrap"));
  942. result.append(pushUserpic(userpic));
  943. result.append(popTag());
  944. }
  945. result.append(popTag());
  946. return result;
  947. }
  948. auto HtmlWriter::Wrap::pushMessage(
  949. const Data::Message &message,
  950. const MessageInfo *previous,
  951. const Data::DialogInfo &dialog,
  952. const QString &basePath,
  953. const PeersMap &peers,
  954. const QString &internalLinksDomain,
  955. Fn<QByteArray(int messageId, QByteArray text)> wrapMessageLink
  956. ) -> std::pair<MessageInfo, QByteArray> {
  957. using namespace Data;
  958. auto info = MessageInfo();
  959. info.id = message.id;
  960. info.fromId = message.fromId;
  961. info.viaBotId = message.viaBotId;
  962. info.date = message.date;
  963. info.forwardedFromId = message.forwardedFromId;
  964. info.forwardedFromName = message.forwardedFromName;
  965. info.forwardedDate = message.forwardedDate;
  966. info.forwarded = message.forwarded;
  967. info.showForwardedAsOriginal = message.showForwardedAsOriginal;
  968. if (v::is<UnsupportedMedia>(message.media.content)) {
  969. return { info, pushServiceMessage(
  970. message.id,
  971. dialog,
  972. basePath,
  973. "This message is not supported by this version "
  974. "of Telegram Desktop. Please update the application.") };
  975. }
  976. const auto wrapReplyToLink = [&](const QByteArray &text) {
  977. return wrapMessageLink(message.replyToMsgId, text);
  978. };
  979. using DialogType = Data::DialogInfo::Type;
  980. const auto isChannel = (dialog.type == DialogType::PrivateChannel)
  981. || (dialog.type == DialogType::PublicChannel);
  982. const auto serviceFrom = peers.wrapPeerName(message.fromId);
  983. const auto serviceText = v::match(message.action.content, [&](
  984. const ActionChatCreate &data) {
  985. return serviceFrom
  986. + " created group &laquo;"
  987. + SerializeString(data.title)
  988. + "&raquo;"
  989. + (data.userIds.empty()
  990. ? QByteArray()
  991. : " with members " + peers.wrapUserNames(data.userIds));
  992. }, [&](const ActionChatEditTitle &data) {
  993. return isChannel
  994. ? ("Channel title changed to &laquo;"
  995. + SerializeString(data.title)
  996. + "&raquo;")
  997. : (serviceFrom
  998. + " changed group title to &laquo;"
  999. + SerializeString(data.title)
  1000. + "&raquo;");
  1001. }, [&](const ActionChatEditPhoto &data) {
  1002. return isChannel
  1003. ? QByteArray("Channel photo changed")
  1004. : (serviceFrom + " changed group photo");
  1005. }, [&](const ActionChatDeletePhoto &data) {
  1006. return isChannel
  1007. ? QByteArray("Channel photo removed")
  1008. : (serviceFrom + " removed group photo");
  1009. }, [&](const ActionChatAddUser &data) {
  1010. return serviceFrom
  1011. + " invited "
  1012. + peers.wrapUserNames(data.userIds);
  1013. }, [&](const ActionChatDeleteUser &data) {
  1014. return serviceFrom
  1015. + " removed "
  1016. + peers.wrapUserName(data.userId);
  1017. }, [&](const ActionChatJoinedByLink &data) {
  1018. return serviceFrom
  1019. + " joined group by link from "
  1020. + peers.wrapUserName(data.inviterId);
  1021. }, [&](const ActionChannelCreate &data) {
  1022. return "Channel &laquo;"
  1023. + SerializeString(data.title)
  1024. + "&raquo; created";
  1025. }, [&](const ActionChatMigrateTo &data) {
  1026. return serviceFrom
  1027. + " converted this group to a supergroup";
  1028. }, [&](const ActionChannelMigrateFrom &data) {
  1029. return serviceFrom
  1030. + " converted a basic group to this supergroup "
  1031. + "&laquo;" + SerializeString(data.title) + "&raquo;";
  1032. }, [&](const ActionPinMessage &data) {
  1033. return serviceFrom
  1034. + " pinned "
  1035. + wrapReplyToLink("this message");
  1036. }, [&](const ActionHistoryClear &data) {
  1037. return QByteArray("History cleared");
  1038. }, [&](const ActionGameScore &data) {
  1039. return serviceFrom
  1040. + " scored "
  1041. + NumberToString(data.score)
  1042. + " in "
  1043. + wrapReplyToLink("this game");
  1044. }, [&](const ActionPaymentSent &data) {
  1045. const auto amount = FormatMoneyAmount(data.amount, data.currency);
  1046. if (data.recurringUsed) {
  1047. return "You were charged " + amount + " via recurring payment";
  1048. }
  1049. auto result = "You have successfully transferred "
  1050. + amount
  1051. + " for "
  1052. + wrapReplyToLink("this invoice");
  1053. if (data.recurringInit) {
  1054. result += " and allowed future recurring payments";
  1055. }
  1056. return result;
  1057. }, [&](const ActionPhoneCall &data) {
  1058. return QByteArray();
  1059. }, [&](const ActionScreenshotTaken &data) {
  1060. return serviceFrom + " took a screenshot";
  1061. }, [&](const ActionCustomAction &data) {
  1062. return data.message;
  1063. }, [&](const ActionBotAllowed &data) {
  1064. return data.attachMenu
  1065. ? "You allowed this bot to message you "
  1066. "when you added it in the attachment menu."_q
  1067. : data.fromRequest
  1068. ? "You allowed this bot to message you in his web-app."_q
  1069. : data.app.isEmpty()
  1070. ? ("You allowed this bot to message you when you opened "
  1071. + SerializeString(data.app))
  1072. : ("You allowed this bot to message you when you logged in on "
  1073. + SerializeString(data.domain));
  1074. }, [&](const ActionSecureValuesSent &data) {
  1075. auto list = std::vector<QByteArray>();
  1076. for (const auto type : data.types) {
  1077. list.push_back([&] {
  1078. using Type = ActionSecureValuesSent::Type;
  1079. switch (type) {
  1080. case Type::PersonalDetails: return "Personal details";
  1081. case Type::Passport: return "Passport";
  1082. case Type::DriverLicense: return "Driver license";
  1083. case Type::IdentityCard: return "Identity card";
  1084. case Type::InternalPassport: return "Internal passport";
  1085. case Type::Address: return "Address information";
  1086. case Type::UtilityBill: return "Utility bill";
  1087. case Type::BankStatement: return "Bank statement";
  1088. case Type::RentalAgreement: return "Rental agreement";
  1089. case Type::PassportRegistration:
  1090. return "Passport registration";
  1091. case Type::TemporaryRegistration:
  1092. return "Temporary registration";
  1093. case Type::Phone: return "Phone number";
  1094. case Type::Email: return "Email";
  1095. }
  1096. return "";
  1097. }());
  1098. }
  1099. return "You have sent the following documents: "
  1100. + SerializeList(list);
  1101. }, [&](const ActionContactSignUp &data) {
  1102. return serviceFrom + " joined Telegram";
  1103. }, [&](const ActionGeoProximityReached &data) {
  1104. const auto fromName = peers.wrapPeerName(data.fromId);
  1105. const auto toName = peers.wrapPeerName(data.toId);
  1106. const auto distance = [&]() -> QString {
  1107. if (data.distance >= 1000) {
  1108. const auto km = (10 * (data.distance / 10)) / 1000.;
  1109. return QString::number(km) + " km";
  1110. } else if (data.distance == 1) {
  1111. return "1 meter";
  1112. } else {
  1113. return QString::number(data.distance) + " meters";
  1114. }
  1115. }().toUtf8();
  1116. if (data.fromSelf) {
  1117. return "You are now within " + distance + " from " + toName;
  1118. } else if (data.toSelf) {
  1119. return fromName + " is now within " + distance + " from you";
  1120. } else {
  1121. return fromName
  1122. + " is now within "
  1123. + distance
  1124. + " from "
  1125. + toName;
  1126. }
  1127. }, [&](const ActionPhoneNumberRequest &data) {
  1128. return serviceFrom + " requested your phone number";
  1129. }, [&](const ActionGroupCall &data) {
  1130. const auto durationText = (data.duration
  1131. ? (" (" + QString::number(data.duration) + " seconds)")
  1132. : QString()).toUtf8();
  1133. return isChannel
  1134. ? ("Voice chat" + durationText)
  1135. : (serviceFrom + " started voice chat" + durationText);
  1136. }, [&](const ActionInviteToGroupCall &data) {
  1137. return serviceFrom
  1138. + " invited "
  1139. + peers.wrapUserNames(data.userIds)
  1140. + " to the voice chat";
  1141. }, [&](const ActionSetMessagesTTL &data) {
  1142. const auto periodText = (data.period == 7 * 86400)
  1143. ? "7 days"
  1144. : (data.period == 86400)
  1145. ? "24 hours"
  1146. : QByteArray();
  1147. return isChannel
  1148. ? (data.period
  1149. ? "New messages will auto-delete in " + periodText
  1150. : "New messages will not auto-delete")
  1151. : (data.period
  1152. ? (serviceFrom
  1153. + " has set messages to auto-delete in " + periodText)
  1154. : (serviceFrom
  1155. + " has set messages not to auto-delete"));
  1156. }, [&](const ActionGroupCallScheduled &data) {
  1157. const auto dateText = FormatDateTime(data.date);
  1158. return isChannel
  1159. ? ("Voice chat scheduled for " + dateText)
  1160. : (serviceFrom + " scheduled a voice chat for " + dateText);
  1161. }, [&](const ActionSetChatTheme &data) {
  1162. if (data.emoji.isEmpty()) {
  1163. return isChannel
  1164. ? "Channel theme was disabled"
  1165. : (serviceFrom + " disabled chat theme");
  1166. }
  1167. return isChannel
  1168. ? ("Channel theme was changed to " + data.emoji).toUtf8()
  1169. : (serviceFrom + " changed chat theme to " + data.emoji).toUtf8();
  1170. }, [&](const ActionChatJoinedByRequest &data) {
  1171. return serviceFrom
  1172. + " joined group by request";
  1173. }, [&](const ActionWebViewDataSent &data) {
  1174. return "You have just successfully transferred data from the &laquo;"
  1175. + SerializeString(data.text)
  1176. + "&raquo; button to the bot";
  1177. }, [&](const ActionGiftPremium &data) {
  1178. if (!data.months || data.cost.isEmpty()) {
  1179. return serviceFrom + " sent you a gift.";
  1180. }
  1181. return serviceFrom
  1182. + " sent you a gift for "
  1183. + data.cost
  1184. + ": Telegram Premium for "
  1185. + QString::number(data.months).toUtf8()
  1186. + " months.";
  1187. }, [&](const ActionTopicCreate &data) {
  1188. return serviceFrom
  1189. + " created topic &laquo;"
  1190. + SerializeString(data.title)
  1191. + "&raquo;";
  1192. }, [&](const ActionTopicEdit &data) {
  1193. auto parts = QList<QByteArray>();
  1194. if (!data.title.isEmpty()) {
  1195. parts.push_back("title to &laquo;"
  1196. + SerializeString(data.title)
  1197. + "&raquo;");
  1198. }
  1199. if (data.iconEmojiId) {
  1200. parts.push_back("icon to &laquo;"
  1201. + QString::number(*data.iconEmojiId).toUtf8()
  1202. + "&raquo;");
  1203. }
  1204. return serviceFrom + " changed topic " + parts.join(',');
  1205. }, [&](const ActionSuggestProfilePhoto &data) {
  1206. return serviceFrom + " suggests to use this photo";
  1207. }, [&](const ActionRequestedPeer &data) {
  1208. return "requested: "_q/* + data.peerId*/;
  1209. }, [&](const ActionSetChatWallPaper &data) {
  1210. return serviceFrom
  1211. + (data.same
  1212. ? (" set "
  1213. + wrapReplyToLink("the same background")
  1214. + " for this chat")
  1215. : " set a new background for this chat");
  1216. }, [&](const ActionGiftCode &data) {
  1217. return data.unclaimed
  1218. ? ("This is an unclaimed Telegram Premium for "
  1219. + NumberToString(data.months)
  1220. + (data.months > 1 ? " months" : "month")
  1221. + " prize in a giveaway organized by a channel.")
  1222. : data.viaGiveaway
  1223. ? ("You won a Telegram Premium for "
  1224. + NumberToString(data.months)
  1225. + (data.months > 1 ? " months" : "month")
  1226. + " prize in a giveaway organized by a channel.")
  1227. : ("You've received a Telegram Premium for "
  1228. + NumberToString(data.months)
  1229. + (data.months > 1 ? " months" : "month")
  1230. + " gift from a channel.");
  1231. }, [&](const ActionGiveawayLaunch &data) {
  1232. return serviceFrom + " just started a giveaway "
  1233. "of Telegram Premium subscriptions to its followers.";
  1234. }, [&](const ActionGiveawayResults &data) {
  1235. return !data.winners
  1236. ? "No winners of the giveaway could be selected."
  1237. : (data.credits && data.unclaimed)
  1238. ? "Some winners of the giveaway were randomly selected by "
  1239. "Telegram and received their prize."
  1240. : (!data.credits && data.unclaimed)
  1241. ? "Some winners of the giveaway were randomly selected by "
  1242. "Telegram and received private messages with giftcodes."
  1243. : (data.credits && !data.unclaimed)
  1244. ? NumberToString(data.winners) + " of the giveaway was randomly "
  1245. "selected by Telegram and received their prize."
  1246. : NumberToString(data.winners) + " of the giveaway was randomly "
  1247. "selected by Telegram and received private messages with "
  1248. "giftcodes.";
  1249. }, [&](const ActionBoostApply &data) {
  1250. return serviceFrom
  1251. + " boosted the group "
  1252. + QByteArray::number(data.boosts)
  1253. + (data.boosts > 1 ? " times" : " time");
  1254. }, [&](const ActionPaymentRefunded &data) {
  1255. const auto amount = FormatMoneyAmount(data.amount, data.currency);
  1256. auto result = peers.wrapPeerName(data.peerId)
  1257. + " refunded back "
  1258. + amount;
  1259. return result;
  1260. }, [&](const ActionGiftStars &data) {
  1261. if (!data.credits || data.cost.isEmpty()) {
  1262. return serviceFrom + " sent you a gift.";
  1263. }
  1264. return serviceFrom
  1265. + " sent you a gift for "
  1266. + data.cost
  1267. + ": "
  1268. + QString::number(data.credits).toUtf8()
  1269. + " Telegram Stars.";
  1270. }, [&](const ActionPrizeStars &data) {
  1271. return "You won a prize in a giveaway organized by "
  1272. + peers.wrapPeerName(data.peerId)
  1273. + ".\n Your prize is "
  1274. + QString::number(data.amount).toUtf8()
  1275. + " Telegram Stars.";
  1276. }, [&](const ActionStarGift &data) {
  1277. return serviceFrom
  1278. + " sent you a gift of "
  1279. + QByteArray::number(data.stars)
  1280. + " Telegram Stars.";
  1281. }, [](v::null_t) { return QByteArray(); });
  1282. if (!serviceText.isEmpty()) {
  1283. const auto &content = message.action.content;
  1284. const auto photo = v::is<ActionChatEditPhoto>(content)
  1285. ? &v::get<ActionChatEditPhoto>(content).photo
  1286. : v::is<ActionSuggestProfilePhoto>(content)
  1287. ? &v::get<ActionSuggestProfilePhoto>(content).photo
  1288. : nullptr;
  1289. return { info, pushServiceMessage(
  1290. message.id,
  1291. dialog,
  1292. basePath,
  1293. serviceText,
  1294. photo) };
  1295. }
  1296. info.type = MessageInfo::Type::Default;
  1297. const auto wrap = messageNeedsWrap(message, previous);
  1298. const auto fromPeerId = message.fromId;
  1299. const auto showForwardedInfo = message.forwarded
  1300. && !message.showForwardedAsOriginal;
  1301. auto forwardedUserpic = UserpicData();
  1302. if (message.forwarded) {
  1303. forwardedUserpic.colorIndex = message.forwardedFromId
  1304. ? PeerColorIndex(message.forwardedFromId)
  1305. : PeerColorIndex(message.id);
  1306. forwardedUserpic.pixelSize = kHistoryUserpicSize;
  1307. if (message.forwardedFromId) {
  1308. FillUserpicNames(
  1309. forwardedUserpic,
  1310. peers.peer(message.forwardedFromId));
  1311. } else {
  1312. FillUserpicNames(forwardedUserpic, message.forwardedFromName);
  1313. }
  1314. }
  1315. auto userpic = UserpicData();
  1316. if (message.showForwardedAsOriginal) {
  1317. userpic = forwardedUserpic;
  1318. } else {
  1319. userpic.colorIndex = PeerColorIndex(fromPeerId);
  1320. userpic.pixelSize = kHistoryUserpicSize;
  1321. FillUserpicNames(userpic, peers.peer(fromPeerId));
  1322. }
  1323. const auto via = [&] {
  1324. if (message.viaBotId) {
  1325. const auto &user = peers.user(message.viaBotId);
  1326. if (!user.username.isEmpty()) {
  1327. return SerializeString(user.username);
  1328. }
  1329. }
  1330. return QByteArray();
  1331. }();
  1332. const auto className = wrap
  1333. ? "message default clearfix"
  1334. : "message default clearfix joined";
  1335. auto block = pushTag("div", {
  1336. { "class", className },
  1337. { "id", "message" + NumberToString(message.id) }
  1338. });
  1339. if (wrap) {
  1340. block.append(pushDiv("pull_left userpic_wrap"));
  1341. block.append(pushUserpic(userpic));
  1342. block.append(popTag());
  1343. }
  1344. block.append(pushDiv("body"));
  1345. block.append(pushTag("div", {
  1346. { "class", "pull_right date details" },
  1347. { "title", FormatDateTime(message.date, true) },
  1348. }));
  1349. block.append(FormatTimeText(message.date));
  1350. block.append(popTag());
  1351. if (wrap) {
  1352. block.append(pushDiv("from_name"));
  1353. block.append(SerializeString(
  1354. ComposeName(userpic, "Deleted Account")));
  1355. if (!via.isEmpty()
  1356. && (!message.forwarded || message.showForwardedAsOriginal)) {
  1357. block.append(" via @" + via);
  1358. }
  1359. block.append(popTag());
  1360. }
  1361. if (showForwardedInfo) {
  1362. const auto forwardedWrap = forwardedNeedsWrap(message, previous);
  1363. if (forwardedWrap) {
  1364. block.append(pushDiv("pull_left forwarded userpic_wrap"));
  1365. block.append(pushUserpic(forwardedUserpic));
  1366. block.append(popTag());
  1367. }
  1368. block.append(pushDiv("forwarded body"));
  1369. if (forwardedWrap) {
  1370. block.append(pushDiv("from_name"));
  1371. block.append(SerializeString(
  1372. ComposeName(forwardedUserpic, "Deleted Account")));
  1373. if (!via.isEmpty()) {
  1374. block.append(" via @" + via);
  1375. }
  1376. block.append(pushTag("span", {
  1377. { "class", "date details" },
  1378. { "title", FormatDateTime(message.forwardedDate, true) },
  1379. { "inline", "" }
  1380. }));
  1381. block.append(' ' + FormatDateTime(message.forwardedDate));
  1382. block.append(popTag());
  1383. block.append(popTag());
  1384. }
  1385. }
  1386. if (message.replyToMsgId) {
  1387. block.append(pushDiv("reply_to details"));
  1388. if (message.replyToPeerId) {
  1389. block.append("In reply to a message in another chat");
  1390. } else {
  1391. block.append("In reply to ");
  1392. block.append(wrapReplyToLink("this message"));
  1393. }
  1394. block.append(popTag());
  1395. }
  1396. block.append(
  1397. pushMedia(
  1398. message,
  1399. basePath,
  1400. peers,
  1401. internalLinksDomain,
  1402. wrapMessageLink));
  1403. const auto text = FormatText(message.text, internalLinksDomain, _base);
  1404. if (!text.isEmpty()) {
  1405. block.append(pushDiv("text"));
  1406. block.append(text);
  1407. block.append(popTag());
  1408. }
  1409. if (!message.inlineButtonRows.empty()) {
  1410. using Type = HistoryMessageMarkupButton::Type;
  1411. const auto endline = u" | "_q;
  1412. block.append(pushTag("table", { { "class", "bot_buttons_table" } }));
  1413. block.append(pushTag("tbody"));
  1414. for (const auto &row : message.inlineButtonRows) {
  1415. block.append(pushTag("tr"));
  1416. block.append(pushTag("td", { { "class", "bot_button_row" } }));
  1417. for (const auto &button : row) {
  1418. using Attribute = std::pair<QByteArray, QByteArray>;
  1419. const auto content = (!button.data.isEmpty()
  1420. ? (u"Data: "_q + button.data + endline)
  1421. : QString())
  1422. + (!button.forwardText.isEmpty()
  1423. ? (u"Forward text: "_q + button.forwardText + endline)
  1424. : QString())
  1425. + (u"Type: "_q
  1426. + HistoryMessageMarkupButton::TypeToString(button));
  1427. const auto link = (button.type == Type::Url)
  1428. ? button.data
  1429. : QByteArray();
  1430. const auto onclick = (button.type != Type::Url)
  1431. ? ("return ShowTextCopied('" + content + "');").toUtf8()
  1432. : QByteArray();
  1433. block.append(pushTag("div", { { "class", "bot_button" } }));
  1434. block.append(pushTag("a", {
  1435. link.isEmpty() ? Attribute() : Attribute{ "href", link },
  1436. onclick.isEmpty()
  1437. ? Attribute()
  1438. : Attribute{ "onclick", onclick },
  1439. }));
  1440. block.append(pushTag("div"));
  1441. block.append(button.text.toUtf8());
  1442. block.append(popTag());
  1443. block.append(popTag());
  1444. block.append(popTag());
  1445. if (&button != &row.back()) {
  1446. block.append(pushTag("div", {
  1447. { "class", "bot_button_column_separator" }
  1448. }));
  1449. block.append(popTag());
  1450. }
  1451. }
  1452. block.append(popTag());
  1453. block.append(popTag());
  1454. }
  1455. block.append(popTag());
  1456. block.append(popTag());
  1457. }
  1458. if (!message.signature.isEmpty()) {
  1459. block.append(pushDiv("signature details"));
  1460. block.append(SerializeString(message.signature));
  1461. block.append(popTag());
  1462. }
  1463. if (showForwardedInfo) {
  1464. block.append(popTag());
  1465. }
  1466. if (!message.reactions.empty()) {
  1467. block.append(pushDiv("reactions"));
  1468. for (const auto &reaction : message.reactions) {
  1469. auto reactionClass = QByteArray("reaction");
  1470. for (const auto &recent : reaction.recent) {
  1471. const auto peer = peers.peer(recent.peerId);
  1472. if (peer.user() && peer.user()->isSelf) {
  1473. reactionClass += " active";
  1474. break;
  1475. }
  1476. }
  1477. if (reaction.type == Reaction::Type::Paid) {
  1478. reactionClass += " paid";
  1479. }
  1480. block.append(pushTag("div", {
  1481. { "class", reactionClass },
  1482. }));
  1483. block.append(pushTag("div", {
  1484. { "class", "emoji" },
  1485. }));
  1486. switch (reaction.type) {
  1487. case Reaction::Type::Emoji:
  1488. block.append(SerializeString(reaction.emoji.toUtf8()));
  1489. break;
  1490. case Reaction::Type::CustomEmoji:
  1491. block.append(FormatCustomEmoji(
  1492. reaction.documentId,
  1493. "\U0001F44B",
  1494. _base));
  1495. break;
  1496. case Reaction::Type::Paid:
  1497. block.append(SerializeString("\u2B50"));
  1498. break;
  1499. }
  1500. block.append(popTag());
  1501. if (!reaction.recent.empty()) {
  1502. block.append(pushTag("div", {
  1503. { "class", "userpics" },
  1504. }));
  1505. for (const auto &recent : reaction.recent) {
  1506. const auto peer = peers.peer(recent.peerId);
  1507. block.append(pushUserpic(UserpicData({
  1508. .colorIndex = peer.colorIndex(),
  1509. .pixelSize = 20,
  1510. .firstName = peer.user()
  1511. ? peer.user()->info.firstName
  1512. : peer.name(),
  1513. .lastName = peer.user()
  1514. ? peer.user()->info.lastName
  1515. : "",
  1516. .tooltip = peer.name(),
  1517. })));
  1518. }
  1519. block.append(popTag());
  1520. }
  1521. if (reaction.recent.empty()
  1522. || (reaction.count > reaction.recent.size())) {
  1523. block.append(pushTag("div", {
  1524. { "class", "count" },
  1525. }));
  1526. block.append(NumberToString(reaction.count));
  1527. block.append(popTag());
  1528. }
  1529. block.append(popTag());
  1530. }
  1531. block.append(popTag());
  1532. }
  1533. block.append(popTag());
  1534. block.append(popTag());
  1535. return { info, block };
  1536. }
  1537. bool HtmlWriter::Wrap::messageNeedsWrap(
  1538. const Data::Message &message,
  1539. const MessageInfo *previous) const {
  1540. if (!previous) {
  1541. return true;
  1542. } else if (previous->type != MessageInfo::Type::Default) {
  1543. return true;
  1544. } else if (!message.fromId || previous->fromId != message.fromId) {
  1545. return true;
  1546. } else if (message.viaBotId != previous->viaBotId) {
  1547. return true;
  1548. } else if (QDateTime::fromSecsSinceEpoch(previous->date).date()
  1549. != QDateTime::fromSecsSinceEpoch(message.date).date()) {
  1550. return true;
  1551. } else if (message.forwarded != previous->forwarded
  1552. || message.showForwardedAsOriginal != previous->showForwardedAsOriginal
  1553. || message.forwardedFromId != previous->forwardedFromId
  1554. || message.forwardedFromName != previous->forwardedFromName) {
  1555. return true;
  1556. } else if (std::abs(message.date - previous->date)
  1557. > ((message.forwardedFromId || !message.forwardedFromName.isEmpty())
  1558. ? 1
  1559. : kJoinWithinSeconds)) {
  1560. return true;
  1561. }
  1562. return false;
  1563. }
  1564. QByteArray HtmlWriter::Wrap::pushMedia(
  1565. const Data::Message &message,
  1566. const QString &basePath,
  1567. const PeersMap &peers,
  1568. const QString &internalLinksDomain,
  1569. Fn<QByteArray(int messageId, QByteArray text)> wrapMessageLink) {
  1570. const auto data = prepareMediaData(
  1571. message,
  1572. basePath,
  1573. peers,
  1574. internalLinksDomain);
  1575. if (!data.classes.isEmpty()) {
  1576. return pushGenericMedia(data);
  1577. }
  1578. using namespace Data;
  1579. const auto &content = message.media.content;
  1580. if (const auto document = std::get_if<Document>(&content)) {
  1581. Assert(!message.media.ttl);
  1582. if (document->isSticker) {
  1583. return pushStickerMedia(*document, basePath);
  1584. } else if (document->isAnimated) {
  1585. return pushAnimatedMedia(*document, basePath);
  1586. } else if (document->isVideoFile) {
  1587. return pushVideoFileMedia(*document, basePath);
  1588. }
  1589. Unexpected("Non generic document in HtmlWriter::Wrap::pushMedia.");
  1590. } else if (const auto photo = std::get_if<Photo>(&content)) {
  1591. Assert(!message.media.ttl);
  1592. return pushPhotoMedia(*photo, basePath);
  1593. } else if (const auto poll = std::get_if<Poll>(&content)) {
  1594. return pushPoll(*poll);
  1595. } else if (const auto giveaway = std::get_if<GiveawayStart>(&content)) {
  1596. return pushGiveaway(peers, *giveaway);
  1597. } else if (const auto giveaway = std::get_if<GiveawayResults>(&content)) {
  1598. return pushGiveaway(peers, *giveaway, wrapMessageLink);
  1599. }
  1600. Assert(v::is_null(content));
  1601. return QByteArray();
  1602. }
  1603. QByteArray HtmlWriter::Wrap::pushGenericMedia(const MediaData &data) {
  1604. auto result = pushDiv("media_wrap clearfix");
  1605. if (data.link.isEmpty()) {
  1606. result.append(pushDiv("media clearfix pull_left " + data.classes));
  1607. } else {
  1608. result.append(pushTag("a", {
  1609. {
  1610. "class",
  1611. "media clearfix pull_left block_link " + data.classes
  1612. },
  1613. {
  1614. "href",
  1615. (IsGlobalLink(data.link)
  1616. ? data.link.toUtf8()
  1617. : relativePath(data.link).toUtf8())
  1618. }
  1619. }));
  1620. }
  1621. if (data.thumb.isEmpty()) {
  1622. result.append(pushDiv("fill pull_left"));
  1623. result.append(popTag());
  1624. } else {
  1625. result.append(pushTag("img", {
  1626. { "class", "thumb pull_left" },
  1627. { "src", relativePath(data.thumb).toUtf8() },
  1628. { "empty", "" }
  1629. }));
  1630. }
  1631. result.append(pushDiv("body"));
  1632. if (!data.title.isEmpty()) {
  1633. result.append(pushDiv("title bold"));
  1634. result.append(SerializeString(data.title));
  1635. result.append(popTag());
  1636. }
  1637. if (!data.description.isEmpty()) {
  1638. result.append(pushDiv("description"));
  1639. result.append(SerializeString(data.description));
  1640. result.append(popTag());
  1641. }
  1642. if (!data.status.isEmpty()) {
  1643. result.append(pushDiv("status details"));
  1644. result.append(SerializeString(data.status));
  1645. result.append(popTag());
  1646. }
  1647. result.append(popTag());
  1648. result.append(popTag());
  1649. result.append(popTag());
  1650. return result;
  1651. }
  1652. QByteArray HtmlWriter::Wrap::pushStickerMedia(
  1653. const Data::Document &data,
  1654. const QString &basePath) {
  1655. using namespace Data;
  1656. const auto &[thumb, size] = WriteImageThumb(
  1657. basePath,
  1658. data.file.relativePath,
  1659. CalculateThumbSize(
  1660. kStickerMaxWidth,
  1661. kStickerMaxHeight,
  1662. kStickerMinWidth,
  1663. kStickerMinHeight),
  1664. "PNG",
  1665. -1);
  1666. if (thumb.isEmpty()) {
  1667. auto generic = MediaData();
  1668. generic.title = "Sticker";
  1669. generic.status = data.stickerEmoji;
  1670. if (data.file.relativePath.isEmpty()) {
  1671. if (!generic.status.isEmpty()) {
  1672. generic.status += ", ";
  1673. }
  1674. generic.status += FormatFileSize(data.file.size);
  1675. } else {
  1676. generic.link = data.file.relativePath;
  1677. }
  1678. generic.description = NoFileDescription(data.file.skipReason);
  1679. generic.classes = "media_photo";
  1680. return pushGenericMedia(generic);
  1681. }
  1682. auto result = pushDiv("media_wrap clearfix");
  1683. result.append(pushTag("a", {
  1684. { "class", "sticker_wrap clearfix pull_left" },
  1685. {
  1686. "href",
  1687. relativePath(data.file.relativePath).toUtf8()
  1688. }
  1689. }));
  1690. const auto sizeStyle = "width: "
  1691. + NumberToString(size.width() / 2)
  1692. + "px; height: "
  1693. + NumberToString(size.height() / 2)
  1694. + "px";
  1695. result.append(pushTag("img", {
  1696. { "class", "sticker" },
  1697. { "style", sizeStyle },
  1698. { "src", relativePath(thumb).toUtf8() },
  1699. { "empty", "" }
  1700. }));
  1701. result.append(popTag());
  1702. result.append(popTag());
  1703. return result;
  1704. }
  1705. QByteArray HtmlWriter::Wrap::pushAnimatedMedia(
  1706. const Data::Document &data,
  1707. const QString &basePath) {
  1708. using namespace Data;
  1709. auto size = QSize(data.width, data.height);
  1710. auto thumbSize = CalculateThumbSize(
  1711. kPhotoMaxWidth,
  1712. kPhotoMaxHeight,
  1713. kPhotoMinWidth,
  1714. kPhotoMinHeight,
  1715. true)(size);
  1716. if (data.thumb.file.relativePath.isEmpty()
  1717. || data.file.relativePath.isEmpty()
  1718. || !thumbSize.width()
  1719. || !thumbSize.height()) {
  1720. auto generic = MediaData();
  1721. generic.title = "Animation";
  1722. generic.status = FormatFileSize(data.file.size);
  1723. generic.link = data.file.relativePath;
  1724. generic.description = NoFileDescription(data.file.skipReason);
  1725. generic.classes = "media_video";
  1726. return pushGenericMedia(generic);
  1727. }
  1728. auto result = pushDiv("media_wrap clearfix");
  1729. result.append(pushTag("a", {
  1730. { "class", "animated_wrap clearfix pull_left" },
  1731. {
  1732. "href",
  1733. relativePath(data.file.relativePath).toUtf8()
  1734. }
  1735. }));
  1736. result.append(pushDiv("video_play_bg"));
  1737. result.append(pushDiv("gif_play"));
  1738. result.append("GIF");
  1739. result.append(popTag());
  1740. result.append(popTag());
  1741. const auto sizeStyle = "width: "
  1742. + NumberToString(thumbSize.width() / 2)
  1743. + "px; height: "
  1744. + NumberToString(thumbSize.height() / 2)
  1745. + "px";
  1746. result.append(pushTag("img", {
  1747. { "class", "animated" },
  1748. { "style", sizeStyle },
  1749. { "src", relativePath(data.thumb.file.relativePath).toUtf8() },
  1750. { "empty", "" }
  1751. }));
  1752. result.append(popTag());
  1753. result.append(popTag());
  1754. return result;
  1755. }
  1756. QByteArray HtmlWriter::Wrap::pushVideoFileMedia(
  1757. const Data::Document &data,
  1758. const QString &basePath) {
  1759. using namespace Data;
  1760. auto size = QSize(data.width, data.height);
  1761. auto thumbSize = CalculateThumbSize(
  1762. kPhotoMaxWidth,
  1763. kPhotoMaxHeight,
  1764. kPhotoMinWidth,
  1765. kPhotoMinHeight,
  1766. true)(size);
  1767. if (data.thumb.file.relativePath.isEmpty()
  1768. || data.file.relativePath.isEmpty()
  1769. || !thumbSize.width()
  1770. || !thumbSize.height()) {
  1771. auto generic = MediaData();
  1772. generic.title = "Video file";
  1773. generic.status = FormatDuration(data.duration);
  1774. if (data.file.relativePath.isEmpty()) {
  1775. generic.status += ", " + FormatFileSize(data.file.size);
  1776. } else {
  1777. generic.link = data.file.relativePath;
  1778. }
  1779. generic.description = NoFileDescription(data.file.skipReason);
  1780. generic.classes = "media_video";
  1781. return pushGenericMedia(generic);
  1782. }
  1783. auto result = pushDiv("media_wrap clearfix");
  1784. result.append(pushTag("a", {
  1785. { "class", "video_file_wrap clearfix pull_left" },
  1786. {
  1787. "href",
  1788. relativePath(data.file.relativePath).toUtf8()
  1789. }
  1790. }));
  1791. result.append(pushDiv("video_play_bg"));
  1792. result.append(pushDiv("video_play"));
  1793. result.append(popTag());
  1794. result.append(popTag());
  1795. result.append(pushDiv("video_duration"));
  1796. result.append(FormatDuration(data.duration));
  1797. result.append(popTag());
  1798. const auto sizeStyle = "width: "
  1799. + NumberToString(thumbSize.width() / 2)
  1800. + "px; height: "
  1801. + NumberToString(thumbSize.height() / 2)
  1802. + "px";
  1803. result.append(pushTag("img", {
  1804. { "class", "video_file" },
  1805. { "style", sizeStyle },
  1806. { "src", relativePath(data.thumb.file.relativePath).toUtf8() },
  1807. { "empty", "" }
  1808. }));
  1809. result.append(popTag());
  1810. result.append(popTag());
  1811. return result;
  1812. }
  1813. QByteArray HtmlWriter::Wrap::pushPhotoMedia(
  1814. const Data::Photo &data,
  1815. const QString &basePath) {
  1816. using namespace Data;
  1817. const auto &[thumb, size] = WriteImageThumb(
  1818. basePath,
  1819. data.image.file.relativePath,
  1820. CalculateThumbSize(
  1821. kPhotoMaxWidth,
  1822. kPhotoMaxHeight,
  1823. kPhotoMinWidth,
  1824. kPhotoMinHeight));
  1825. if (thumb.isEmpty()) {
  1826. auto generic = MediaData();
  1827. generic.title = "Photo";
  1828. generic.status = Ui::FormatImageSizeText(
  1829. QSize(data.image.width, data.image.height)).toUtf8();
  1830. if (data.image.file.relativePath.isEmpty()) {
  1831. generic.status += ", " + FormatFileSize(data.image.file.size);
  1832. } else {
  1833. generic.link = data.image.file.relativePath;
  1834. }
  1835. generic.description = NoFileDescription(data.image.file.skipReason);
  1836. generic.classes = "media_photo";
  1837. return pushGenericMedia(generic);
  1838. }
  1839. auto result = pushDiv("media_wrap clearfix");
  1840. result.append(pushTag("a", {
  1841. { "class", "photo_wrap clearfix pull_left" },
  1842. {
  1843. "href",
  1844. relativePath(data.image.file.relativePath).toUtf8()
  1845. }
  1846. }));
  1847. const auto sizeStyle = "width: "
  1848. + NumberToString(size.width() / 2)
  1849. + "px; height: "
  1850. + NumberToString(size.height() / 2)
  1851. + "px";
  1852. result.append(pushTag("img", {
  1853. { "class", "photo" },
  1854. { "style", sizeStyle },
  1855. { "src", relativePath(thumb).toUtf8() },
  1856. { "empty", "" }
  1857. }));
  1858. result.append(popTag());
  1859. result.append(popTag());
  1860. return result;
  1861. }
  1862. QByteArray HtmlWriter::Wrap::pushPoll(const Data::Poll &data) {
  1863. using namespace Data;
  1864. auto result = pushDiv("media_wrap clearfix");
  1865. result.append(pushDiv("media_poll"));
  1866. result.append(pushDiv("question bold"));
  1867. result.append(SerializeString(data.question));
  1868. result.append(popTag());
  1869. result.append(pushDiv("details"));
  1870. if (data.closed) {
  1871. result.append(SerializeString("Final results"));
  1872. } else {
  1873. result.append(SerializeString("Anonymous poll"));
  1874. }
  1875. result.append(popTag());
  1876. const auto votes = [](int count) {
  1877. if (count > 1) {
  1878. return NumberToString(count) + " votes";
  1879. } else if (count > 0) {
  1880. return NumberToString(count) + " vote";
  1881. }
  1882. return QByteArray("No votes");
  1883. };
  1884. const auto details = [&](const Poll::Answer &answer) {
  1885. if (!answer.votes) {
  1886. return QByteArray("");
  1887. } else if (!answer.my) {
  1888. return " <span class=\"details\">"
  1889. + votes(answer.votes)
  1890. + "</span>";
  1891. }
  1892. return " <span class=\"details\">"
  1893. + votes(answer.votes)
  1894. + ", chosen vote</span>";
  1895. };
  1896. for (const auto &answer : data.answers) {
  1897. result.append(pushDiv("answer"));
  1898. result.append("- " + SerializeString(answer.text) + details(answer));
  1899. result.append(popTag());
  1900. }
  1901. result.append(pushDiv("total details "));
  1902. result.append(votes(data.totalVotes));
  1903. result.append(popTag());
  1904. result.append(popTag());
  1905. result.append(popTag());
  1906. return result;
  1907. }
  1908. QByteArray HtmlWriter::Wrap::pushGiveaway(
  1909. const PeersMap &peers,
  1910. const Data::GiveawayStart &data) {
  1911. auto result = pushDiv("media_wrap clearfix");
  1912. result.append(pushDiv("media_giveaway"));
  1913. result.append(pushDiv("section_title bold"));
  1914. result.append((data.quantity > 1)
  1915. ? SerializeString("Giveaway Prizes")
  1916. : SerializeString("Giveaway Prize"));
  1917. result.append(popTag());
  1918. {
  1919. result.append(pushDiv("section_body"));
  1920. result.append("<b>"
  1921. + Data::NumberToString(data.quantity)
  1922. + "</b> "
  1923. + SerializeString(data.additionalPrize.toUtf8()));
  1924. result.append(popTag());
  1925. result.append(pushDiv("section_title bold"));
  1926. result.append(SerializeString("with"));
  1927. result.append(popTag());
  1928. };
  1929. result.append(pushDiv("section_body"));
  1930. if (data.credits > 0) {
  1931. result.append("<b>"
  1932. + Data::NumberToString(data.credits)
  1933. + (SerializeString(data.credits == 1 ? (" Star") : (" Stars")))
  1934. + "</b> " + SerializeString("will be distributed ")
  1935. + ((data.quantity == 1)
  1936. ? SerializeString("to ")
  1937. + "<b>"
  1938. + Data::NumberToString(data.quantity)
  1939. + "</b> " + SerializeString("winner.")
  1940. : SerializeString("among ")
  1941. + "<b>"
  1942. + Data::NumberToString(data.quantity)
  1943. + "</b> " + SerializeString("winners.")));
  1944. } else {
  1945. result.append("<b>"
  1946. + Data::NumberToString(data.quantity)
  1947. + "</b> "
  1948. + SerializeString((data.quantity > 1)
  1949. ? "Telegram Premium Subscriptions"
  1950. : "Telegram Premium Subscription")
  1951. + " for <b>" + Data::NumberToString(data.months) + "</b> "
  1952. + (data.months > 1 ? "months." : "month."));
  1953. }
  1954. result.append(popTag());
  1955. result.append(pushDiv("section_title bold"));
  1956. result.append(SerializeString("Participants"));
  1957. result.append(popTag());
  1958. result.append(pushDiv("section_body"));
  1959. auto channels = QByteArrayList();
  1960. auto anyChannel = false;
  1961. auto anyGroup = false;
  1962. for (const auto &channel : data.channels) {
  1963. if (const auto chat = peers.peer(channel).chat()) {
  1964. if (chat->isBroadcast) {
  1965. anyChannel = true;
  1966. } else if (chat->isSupergroup) {
  1967. anyGroup = true;
  1968. }
  1969. }
  1970. channels.append("<b>" + peers.wrapPeerName(channel) + "</b>");
  1971. }
  1972. const auto participants = [&] {
  1973. if (data.all && !anyGroup && anyChannel && channels.size() == 1) {
  1974. return "All subscribers of the channel:";
  1975. }
  1976. if (data.all && !anyGroup && anyChannel && channels.size() > 1) {
  1977. return "All subscribers of the channels:";
  1978. }
  1979. if (data.all && anyGroup && !anyChannel && channels.size() == 1) {
  1980. return "All members of the group:";
  1981. }
  1982. if (data.all && anyGroup && !anyChannel && channels.size() > 1) {
  1983. return "All members of the groups:";
  1984. }
  1985. if (data.all && anyGroup && anyChannel && channels.size() == 1) {
  1986. return "All members of the group:";
  1987. }
  1988. if (data.all && anyGroup && anyChannel && channels.size() > 1) {
  1989. return "All members of the groups and channels:";
  1990. }
  1991. if (!data.all && !anyGroup && anyChannel && channels.size() == 1) {
  1992. return "All users who joined the channel below after this date:";
  1993. }
  1994. if (!data.all && !anyGroup && anyChannel && channels.size() > 1) {
  1995. return "All users who joined the channels below after this date:";
  1996. }
  1997. if (!data.all && anyGroup && !anyChannel && channels.size() == 1) {
  1998. return "All users who joined the group below after this date:";
  1999. }
  2000. if (!data.all && anyGroup && !anyChannel && channels.size() > 1) {
  2001. return "All users who joined the groups below after this date:";
  2002. }
  2003. if (!data.all && anyGroup && anyChannel && channels.size() == 1) {
  2004. return "All users who joined the group below after this date:";
  2005. }
  2006. if (!data.all && anyGroup && anyChannel && channels.size() > 1) {
  2007. return "All users who joined the groups and channels below "
  2008. "after this date:";
  2009. }
  2010. return "";
  2011. }();
  2012. result.append(SerializeString(participants)) + channels.join(", ");
  2013. result.append(popTag());
  2014. {
  2015. const auto &instance = Countries::Instance();
  2016. auto countries = QStringList();
  2017. for (const auto &country : data.countries) {
  2018. const auto name = instance.countryNameByISO2(country);
  2019. const auto flag = instance.flagEmojiByISO2(country);
  2020. countries.push_back(flag + QChar(0xA0) + name);
  2021. }
  2022. if (const auto count = countries.size()) {
  2023. auto united = countries.front();
  2024. for (auto i = 1; i != count; ++i) {
  2025. united = ((i + 1 == count)
  2026. ? u"%1 and %2"_q
  2027. : u"%1, %2"_q).arg(united, countries[i]);
  2028. }
  2029. result.append(pushDiv("section_body"));
  2030. result.append(
  2031. SerializeString((u"from %1"_q).arg(united).toUtf8()));
  2032. result.append(popTag());
  2033. }
  2034. }
  2035. result.append(pushDiv("section_title bold"));
  2036. result.append(SerializeString("Winners Selection Date"));
  2037. result.append(popTag());
  2038. result.append(pushDiv("section_body"));
  2039. result.append(Data::FormatDateTime(data.untilDate));
  2040. result.append(popTag());
  2041. result.append(popTag());
  2042. result.append(popTag());
  2043. return result;
  2044. }
  2045. QByteArray HtmlWriter::Wrap::pushGiveaway(
  2046. const PeersMap &peers,
  2047. const Data::GiveawayResults &data,
  2048. Fn<QByteArray(int messageId, QByteArray text)> wrapMessageLink) {
  2049. auto result = pushDiv("media_wrap clearfix");
  2050. result.append(pushDiv("media_giveaway"));
  2051. result.append(pushDiv("section_title bold"));
  2052. result.append((data.winnersCount > 1)
  2053. ? SerializeString("Winners Selected!")
  2054. : SerializeString("Winner Selected!"));
  2055. result.append(popTag());
  2056. result.append(pushDiv("section_body"));
  2057. result.append(
  2058. "<b>" + Data::NumberToString(data.winnersCount) + "</b> "
  2059. + SerializeString((data.winnersCount > 1) ? "winners" : "winner")
  2060. + " of the "
  2061. + wrapMessageLink(data.launchId, "Giveaway")
  2062. + " was randomly selected by Telegram.");
  2063. result.append(popTag());
  2064. result.append(pushDiv("section_title bold"));
  2065. result.append((data.winnersCount > 1)
  2066. ? SerializeString("Winners")
  2067. : SerializeString("Winner"));
  2068. result.append(popTag());
  2069. result.append(pushDiv("section_body"));
  2070. auto winners = QByteArrayList();
  2071. for (const auto &winner : data.winners) {
  2072. winners.append("<b>" + peers.wrapPeerName(winner) + "</b>");
  2073. }
  2074. const auto andMore = [&, size = data.winners.size()] {
  2075. if (data.winnersCount > size) {
  2076. return SerializeString(" and ")
  2077. + Data::NumberToString(data.winnersCount - size)
  2078. + SerializeString(" more!");
  2079. }
  2080. return QByteArray();
  2081. }();
  2082. result.append(winners.join(", ") + andMore);
  2083. result.append(popTag());
  2084. result.append(pushDiv("section_body"));
  2085. const auto prize = [&, singleStar = (data.credits == 1)] {
  2086. if (data.credits && data.winnersCount == 1) {
  2087. return SerializeString("The winner received ")
  2088. + "<b>"
  2089. + Data::NumberToString(data.credits)
  2090. + "</b>"
  2091. + SerializeString(singleStar ? " Star." : " Stars.");
  2092. } else if (data.credits && data.winnersCount > 1) {
  2093. return SerializeString("All winners received ")
  2094. + "<b>"
  2095. + Data::NumberToString(data.credits)
  2096. + "</b>"
  2097. + SerializeString(singleStar
  2098. ? " Star in total."
  2099. : " Stars in total.");
  2100. } else if (data.unclaimedCount) {
  2101. return SerializeString("Some winners couldn't be selected.");
  2102. } else if (data.winnersCount == 1) {
  2103. return SerializeString(
  2104. "The winner received their gift link in a private message.");
  2105. } else if (data.winnersCount > 1) {
  2106. return SerializeString(
  2107. "All winners received gift links in private messages.");
  2108. }
  2109. return QByteArray();
  2110. }();
  2111. result.append(prize);
  2112. result.append(popTag());
  2113. result.append(popTag());
  2114. result.append(popTag());
  2115. return result;
  2116. }
  2117. MediaData HtmlWriter::Wrap::prepareMediaData(
  2118. const Data::Message &message,
  2119. const QString &basePath,
  2120. const PeersMap &peers,
  2121. const QString &internalLinksDomain) const {
  2122. using namespace Data;
  2123. auto result = MediaData();
  2124. const auto &action = message.action;
  2125. if (const auto call = std::get_if<ActionPhoneCall>(&action.content)) {
  2126. result.classes = "media_call";
  2127. result.title = peers.peer(message.out
  2128. ? message.peerId
  2129. : message.selfId).name();
  2130. result.status = [&] {
  2131. using Reason = ActionPhoneCall::DiscardReason;
  2132. const auto reason = call->discardReason;
  2133. if (message.out) {
  2134. return reason == Reason::Missed ? "Cancelled" : "Outgoing";
  2135. } else if (reason == Reason::Missed) {
  2136. return "Missed";
  2137. } else if (reason == Reason::Busy) {
  2138. return "Declined";
  2139. }
  2140. return "Incoming";
  2141. }();
  2142. if (call->duration > 0) {
  2143. result.classes += " success";
  2144. result.status += " ("
  2145. + NumberToString(call->duration)
  2146. + " seconds)";
  2147. }
  2148. return result;
  2149. }
  2150. v::match(message.media.content, [&](const Photo &data) {
  2151. if (message.media.ttl) {
  2152. result.title = "Self-destructing photo";
  2153. result.status = data.id
  2154. ? "Please view it on your mobile"
  2155. : "Expired";
  2156. result.classes = "media_photo";
  2157. return;
  2158. }
  2159. // At least try to pushPhotoMedia.
  2160. }, [&](const Document &data) {
  2161. if (message.media.ttl) {
  2162. result.title = "Self-destructing video";
  2163. result.status = data.id
  2164. ? "Please view it on your mobile"
  2165. : "Expired";
  2166. result.classes = "media_video";
  2167. return;
  2168. }
  2169. const auto hasFile = !data.file.relativePath.isEmpty();
  2170. result.link = data.file.relativePath;
  2171. result.description = NoFileDescription(data.file.skipReason);
  2172. if (data.isSticker) {
  2173. // At least try to pushStickerMedia.
  2174. } else if (data.isVideoMessage) {
  2175. result.title = "Video message";
  2176. result.status = FormatDuration(data.duration);
  2177. if (!hasFile) {
  2178. result.status += ", " + FormatFileSize(data.file.size);
  2179. }
  2180. result.thumb = data.thumb.file.relativePath;
  2181. result.classes = "media_video";
  2182. } else if (data.isVoiceMessage) {
  2183. result.title = "Voice message";
  2184. result.status = FormatDuration(data.duration);
  2185. if (!hasFile) {
  2186. result.status += ", " + FormatFileSize(data.file.size);
  2187. }
  2188. result.classes = "media_voice_message";
  2189. } else if (data.isAnimated) {
  2190. // At least try to pushAnimatedMedia.
  2191. } else if (data.isVideoFile) {
  2192. // At least try to pushVideoFileMedia.
  2193. } else if (data.isAudioFile) {
  2194. result.title = (data.songPerformer.isEmpty()
  2195. || data.songTitle.isEmpty())
  2196. ? QByteArray("Audio file")
  2197. : data.songPerformer + " \xe2\x80\x93 " + data.songTitle;
  2198. result.status = FormatDuration(data.duration);
  2199. if (!hasFile) {
  2200. result.status += ", " + FormatFileSize(data.file.size);
  2201. }
  2202. result.classes = "media_audio_file";
  2203. } else {
  2204. result.title = data.name.isEmpty()
  2205. ? QByteArray("File")
  2206. : data.name;
  2207. result.status = FormatFileSize(data.file.size);
  2208. result.classes = "media_file";
  2209. }
  2210. }, [&](const SharedContact &data) {
  2211. result.title = data.info.firstName + ' ' + data.info.lastName;
  2212. result.classes = "media_contact";
  2213. result.status = FormatPhoneNumber(data.info.phoneNumber);
  2214. if (!data.vcard.content.isEmpty()) {
  2215. result.status += " - vCard";
  2216. result.link = data.vcard.relativePath;
  2217. }
  2218. }, [&](const GeoPoint &data) {
  2219. if (message.media.ttl) {
  2220. result.classes = "media_live_location";
  2221. result.title = "Live location";
  2222. result.status = "";
  2223. } else {
  2224. result.classes = "media_location";
  2225. result.title = "Location";
  2226. }
  2227. if (data.valid) {
  2228. const auto latitude = NumberToString(data.latitude);
  2229. const auto longitude = NumberToString(data.longitude);
  2230. const auto coords = latitude + ',' + longitude;
  2231. result.status = latitude + ", " + longitude;
  2232. result.link = "https://maps.google.com/maps?q="
  2233. + coords
  2234. + "&ll="
  2235. + coords
  2236. + "&z=16";
  2237. }
  2238. }, [&](const Venue &data) {
  2239. result.classes = "media_venue";
  2240. result.title = data.title;
  2241. result.description = data.address;
  2242. if (data.point.valid) {
  2243. const auto latitude = NumberToString(data.point.latitude);
  2244. const auto longitude = NumberToString(data.point.longitude);
  2245. const auto coords = latitude + ',' + longitude;
  2246. result.link = "https://maps.google.com/maps?q="
  2247. + coords
  2248. + "&ll="
  2249. + coords
  2250. + "&z=16";
  2251. }
  2252. }, [&](const Game &data) {
  2253. result.classes = "media_game";
  2254. result.title = data.title;
  2255. result.description = data.description;
  2256. if (data.botId != 0 && !data.shortName.isEmpty()) {
  2257. const auto bot = peers.user(data.botId);
  2258. if (bot.isBot && !bot.username.isEmpty()) {
  2259. const auto link = internalLinksDomain.toUtf8()
  2260. + bot.username
  2261. + "?game="
  2262. + data.shortName;
  2263. result.link = link;
  2264. result.status = link;
  2265. }
  2266. }
  2267. }, [&](const Invoice &data) {
  2268. result.classes = "media_invoice";
  2269. result.title = data.title;
  2270. result.description = data.description;
  2271. result.status = Data::FormatMoneyAmount(data.amount, data.currency);
  2272. }, [](const Poll &data) {
  2273. }, [](const GiveawayStart &data) {
  2274. }, [](const GiveawayResults &data) {
  2275. }, [&](const PaidMedia &data) {
  2276. result.classes = "media_invoice";
  2277. result.status = Data::FormatMoneyAmount(data.stars, "XTR");
  2278. }, [](const UnsupportedMedia &data) {
  2279. Unexpected("Unsupported message.");
  2280. }, [](v::null_t) {});
  2281. return result;
  2282. }
  2283. bool HtmlWriter::Wrap::forwardedNeedsWrap(
  2284. const Data::Message &message,
  2285. const MessageInfo *previous) const {
  2286. Expects(message.forwarded);
  2287. if (messageNeedsWrap(message, previous)) {
  2288. return true;
  2289. } else if (!message.forwardedFromId
  2290. || message.forwardedFromId != previous->forwardedFromId) {
  2291. return true;
  2292. } else if (!peerIsUser(message.forwardedFromId)) {
  2293. return true;
  2294. } else if (abs(message.forwardedDate - previous->forwardedDate)
  2295. > kJoinWithinSeconds) {
  2296. return true;
  2297. }
  2298. return false;
  2299. }
  2300. Result HtmlWriter::Wrap::close() {
  2301. if (!std::exchange(_closed, true) && !_file.empty()) {
  2302. auto block = QByteArray();
  2303. while (!_context.empty()) {
  2304. block.append(_context.popTag());
  2305. }
  2306. return _file.writeBlock(block);
  2307. }
  2308. return Result::Success();
  2309. }
  2310. QString HtmlWriter::Wrap::relativePath(const QString &path) const {
  2311. return _base + path;
  2312. }
  2313. QString HtmlWriter::Wrap::relativePath(const Data::File &file) const {
  2314. return relativePath(file.relativePath);
  2315. }
  2316. QByteArray HtmlWriter::Wrap::composeStart() {
  2317. auto result = "<!DOCTYPE html>" + _context.pushTag("html");
  2318. result.append(pushTag("head"));
  2319. result.append(pushTag("meta", {
  2320. { "charset", "utf-8" },
  2321. { "empty", "" }
  2322. }));
  2323. result.append(pushTag("title", { { "inline", "" } }));
  2324. result.append("Exported Data");
  2325. result.append(popTag());
  2326. result.append(_context.pushTag("meta", {
  2327. { "name", "viewport" },
  2328. { "content", "width=device-width, initial-scale=1.0" },
  2329. { "empty", "" }
  2330. }));
  2331. result.append(_context.pushTag("link", {
  2332. { "href", _base + "css/style.css" },
  2333. { "rel", "stylesheet" },
  2334. { "empty", "" }
  2335. }));
  2336. result.append(_context.pushTag("script", {
  2337. { "src", _base + "js/script.js" },
  2338. { "type", "text/javascript" },
  2339. }));
  2340. result.append(_context.popTag());
  2341. result.append(popTag());
  2342. result.append(pushTag("body", {
  2343. { "onload", "CheckLocation();" }
  2344. }));
  2345. result.append(pushDiv("page_wrap"));
  2346. return result;
  2347. }
  2348. HtmlWriter::Wrap::~Wrap() {
  2349. (void)close();
  2350. }
  2351. HtmlWriter::HtmlWriter() = default;
  2352. Result HtmlWriter::start(
  2353. const Settings &settings,
  2354. const Environment &environment,
  2355. Stats *stats) {
  2356. Expects(settings.path.endsWith('/'));
  2357. _settings = base::duplicate(settings);
  2358. _environment = environment;
  2359. _stats = stats;
  2360. //const auto result = copyFile(
  2361. // ":/export/css/bootstrap.min.css",
  2362. // "css/bootstrap.min.css");
  2363. //if (!result) {
  2364. // return result;
  2365. //}
  2366. const auto copy = [&](const QString &filename) {
  2367. return copyFile(":/export/" + filename, filename);
  2368. };
  2369. const auto files = {
  2370. "css/style.css",
  2371. "images/back.png",
  2372. "images/media_call.png",
  2373. "images/media_contact.png",
  2374. "images/media_file.png",
  2375. "images/media_game.png",
  2376. "images/media_location.png",
  2377. "images/media_music.png",
  2378. "images/media_photo.png",
  2379. "images/media_shop.png",
  2380. "images/media_video.png",
  2381. "images/media_voice.png",
  2382. "images/section_calls.png",
  2383. "images/section_chats.png",
  2384. "images/section_contacts.png",
  2385. "images/section_frequent.png",
  2386. "images/section_other.png",
  2387. "images/section_photos.png",
  2388. "images/section_sessions.png",
  2389. "images/section_stories.png",
  2390. "images/section_web.png",
  2391. "js/script.js",
  2392. };
  2393. for (const auto path : files) {
  2394. const auto name = QString(path);
  2395. if (const auto result = copy(name); !result) {
  2396. return result;
  2397. } else if (const auto png = name.indexOf(".png"); png > 0) {
  2398. const auto x2 = name.mid(0, png) + "@2x.png";
  2399. if (const auto result = copy(x2); !result) {
  2400. return result;
  2401. }
  2402. }
  2403. }
  2404. if (_settings.onlySinglePeer()) {
  2405. return Result::Success();
  2406. }
  2407. _summary = fileWithRelativePath(mainFileRelativePath());
  2408. auto block = _summary->pushHeader("Exported Data");
  2409. block.append(_summary->pushDiv("page_body"));
  2410. return _summary->writeBlock(block);
  2411. }
  2412. Result HtmlWriter::writePersonal(const Data::PersonalInfo &data) {
  2413. Expects(_summary != nullptr);
  2414. _selfColorIndex = data.user.info.colorIndex;
  2415. if (_settings.types & Settings::Type::Userpics) {
  2416. _delayedPersonalInfo = std::make_unique<Data::PersonalInfo>(data);
  2417. return Result::Success();
  2418. }
  2419. return writeDefaultPersonal(data);
  2420. }
  2421. Result HtmlWriter::writeDefaultPersonal(const Data::PersonalInfo &data) {
  2422. return writePreparedPersonal(data, QString());
  2423. }
  2424. Result HtmlWriter::writeDelayedPersonal(const QString &userpicPath) {
  2425. if (!_delayedPersonalInfo) {
  2426. return Result::Success();
  2427. }
  2428. const auto result = writePreparedPersonal(
  2429. *base::take(_delayedPersonalInfo),
  2430. userpicPath);
  2431. if (!result) {
  2432. return result;
  2433. }
  2434. if (_userpicsCount) {
  2435. pushUserpicsSection();
  2436. }
  2437. return Result::Success();
  2438. }
  2439. Result HtmlWriter::writePreparedPersonal(
  2440. const Data::PersonalInfo &data,
  2441. const QString &userpicPath) {
  2442. Expects(_summary != nullptr);
  2443. const auto &info = data.user.info;
  2444. auto userpic = UserpicData{ _selfColorIndex, kPersonalUserpicSize };
  2445. userpic.largeLink = userpicPath.isEmpty()
  2446. ? QString()
  2447. : userpicsFilePath();
  2448. userpic.imageLink = WriteUserpicThumb(
  2449. _settings.path,
  2450. userpicPath,
  2451. userpic,
  2452. "_info");
  2453. userpic.firstName = info.firstName;
  2454. userpic.lastName = info.lastName;
  2455. auto block = _summary->pushDiv("personal_info clearfix");
  2456. block.append(_summary->pushDiv("pull_right userpic_wrap"));
  2457. block.append(_summary->pushUserpic(userpic));
  2458. block.append(_summary->popTag());
  2459. const auto pushRows = [&](
  2460. QByteArray name,
  2461. std::vector<std::pair<QByteArray, QByteArray>> &&values) {
  2462. block.append(_summary->pushDiv("rows " + name));
  2463. for (const auto &[key, value] : values) {
  2464. if (value.isEmpty()) {
  2465. continue;
  2466. }
  2467. block.append(_summary->pushDiv("row"));
  2468. block.append(_summary->pushDiv("label details"));
  2469. block.append(SerializeString(key));
  2470. block.append(_summary->popTag());
  2471. block.append(_summary->pushDiv("value bold"));
  2472. block.append(SerializeString(value));
  2473. block.append(_summary->popTag());
  2474. block.append(_summary->popTag());
  2475. }
  2476. block.append(_summary->popTag());
  2477. };
  2478. pushRows("names", {
  2479. { "First name", info.firstName },
  2480. { "Last name", info.lastName },
  2481. });
  2482. pushRows("info", {
  2483. { "Phone number", Data::FormatPhoneNumber(info.phoneNumber) },
  2484. { "Username", FormatUsername(data.user.username) },
  2485. });
  2486. pushRows("bio", { { "Bio", data.bio } });
  2487. block.append(_summary->popTag());
  2488. _summaryNeedDivider = true;
  2489. return _summary->writeBlock(block);
  2490. }
  2491. Result HtmlWriter::writeUserpicsStart(const Data::UserpicsInfo &data) {
  2492. Expects(_summary != nullptr);
  2493. Expects(_userpics == nullptr);
  2494. _userpicsCount = data.count;
  2495. if (!_userpicsCount) {
  2496. return Result::Success();
  2497. }
  2498. _userpics = fileWithRelativePath(userpicsFilePath());
  2499. auto block = _userpics->pushHeader(
  2500. "Profile pictures",
  2501. mainFileRelativePath());
  2502. block.append(_userpics->pushDiv("page_body list_page"));
  2503. block.append(_userpics->pushDiv("entry_list"));
  2504. if (const auto result = _userpics->writeBlock(block); !result) {
  2505. return result;
  2506. }
  2507. if (!_delayedPersonalInfo) {
  2508. pushUserpicsSection();
  2509. }
  2510. return Result::Success();
  2511. }
  2512. Result HtmlWriter::writeUserpicsSlice(const Data::UserpicsSlice &data) {
  2513. Expects(_userpics != nullptr);
  2514. Expects(!data.list.empty());
  2515. const auto firstPath = data.list.front().image.file.relativePath;
  2516. if (const auto result = writeDelayedPersonal(firstPath); !result) {
  2517. return result;
  2518. }
  2519. auto block = QByteArray();
  2520. for (const auto &userpic : data.list) {
  2521. auto data = UserpicData{ _selfColorIndex, kEntryUserpicSize };
  2522. using SkipReason = Data::File::SkipReason;
  2523. const auto &file = userpic.image.file;
  2524. Assert(!file.relativePath.isEmpty()
  2525. || file.skipReason != SkipReason::None);
  2526. const auto status = [&]() -> Data::Utf8String {
  2527. switch (file.skipReason) {
  2528. case SkipReason::Unavailable:
  2529. return "(Photo unavailable, please try again later)";
  2530. case SkipReason::FileSize:
  2531. return "(Photo exceeds maximum size. "
  2532. "Change data exporting settings to download.)";
  2533. case SkipReason::FileType:
  2534. return "(Photo not included. "
  2535. "Change data exporting settings to download.)";
  2536. case SkipReason::None: return Data::FormatFileSize(file.size);
  2537. }
  2538. Unexpected("Skip reason while writing photo path.");
  2539. }();
  2540. const auto &path = userpic.image.file.relativePath;
  2541. data.imageLink = WriteUserpicThumb(_settings.path, path, data);
  2542. data.firstName = path.toUtf8();
  2543. block.append(_userpics->pushListEntry(
  2544. data,
  2545. (path.isEmpty() ? QString("Photo unavailable") : path).toUtf8(),
  2546. status,
  2547. (userpic.date > 0
  2548. ? Data::FormatDateTime(userpic.date)
  2549. : QByteArray()),
  2550. path));
  2551. }
  2552. return _userpics->writeBlock(block);
  2553. }
  2554. Result HtmlWriter::writeUserpicsEnd() {
  2555. if (const auto result = writeDelayedPersonal(QString()); !result) {
  2556. return result;
  2557. } else if (_userpics) {
  2558. return base::take(_userpics)->close();
  2559. }
  2560. return Result::Success();
  2561. }
  2562. QString HtmlWriter::userpicsFilePath() const {
  2563. return "lists/profile_pictures.html";
  2564. }
  2565. void HtmlWriter::pushUserpicsSection() {
  2566. pushSection(
  2567. kUserpicsPriority,
  2568. "Profile pictures",
  2569. "photos",
  2570. _userpicsCount,
  2571. userpicsFilePath());
  2572. }
  2573. Result HtmlWriter::writeStoriesStart(const Data::StoriesInfo &data) {
  2574. Expects(_summary != nullptr);
  2575. Expects(_stories == nullptr);
  2576. _storiesCount = data.count;
  2577. if (!_storiesCount) {
  2578. return Result::Success();
  2579. }
  2580. _stories = fileWithRelativePath(storiesFilePath());
  2581. auto block = _stories->pushHeader(
  2582. "Stories archive",
  2583. mainFileRelativePath());
  2584. block.append(_stories->pushDiv("page_body list_page"));
  2585. block.append(_stories->pushDiv("entry_list"));
  2586. if (const auto result = _stories->writeBlock(block); !result) {
  2587. return result;
  2588. }
  2589. return Result::Success();
  2590. }
  2591. Result HtmlWriter::writeStoriesSlice(const Data::StoriesSlice &data) {
  2592. Expects(_stories != nullptr);
  2593. _storiesCount -= data.skipped;
  2594. if (data.list.empty()) {
  2595. return Result::Success();
  2596. }
  2597. auto block = QByteArray();
  2598. for (const auto &story : data.list) {
  2599. auto data = StoryData{};
  2600. using SkipReason = Data::File::SkipReason;
  2601. const auto &file = story.file();
  2602. Assert(!file.relativePath.isEmpty()
  2603. || file.skipReason != SkipReason::None);
  2604. auto status = QByteArrayList();
  2605. if (story.pinned) {
  2606. status.append("Saved to Profile");
  2607. }
  2608. if (story.expires > 0) {
  2609. status.append("Expiring: " + Data::FormatDateTime(story.expires));
  2610. }
  2611. status.append([&]() -> Data::Utf8String {
  2612. switch (file.skipReason) {
  2613. case SkipReason::Unavailable:
  2614. return "(Story unavailable, please try again later)";
  2615. case SkipReason::FileSize:
  2616. return "(Story exceeds maximum size. "
  2617. "Change data exporting settings to download.)";
  2618. case SkipReason::FileType:
  2619. return "(Story not included. "
  2620. "Change data exporting settings to download.)";
  2621. case SkipReason::None: return Data::FormatFileSize(file.size);
  2622. }
  2623. Unexpected("Skip reason while writing story path.");
  2624. }());
  2625. const auto &path = story.file().relativePath;
  2626. const auto &image = story.thumb().file.relativePath.isEmpty()
  2627. ? story.file().relativePath
  2628. : story.thumb().file.relativePath;
  2629. data.imageLink = Data::WriteImageThumb(
  2630. _settings.path,
  2631. image,
  2632. kStoryThumbWidth * 2,
  2633. kStoryThumbHeight * 2);
  2634. const auto info = (story.date > 0)
  2635. ? Data::FormatDateTime(story.date)
  2636. : QByteArray();
  2637. block.append(_stories->pushStoriesListEntry(
  2638. data,
  2639. (path.isEmpty() ? QString("Story unavailable") : path).toUtf8(),
  2640. status,
  2641. info,
  2642. story.caption,
  2643. _environment.internalLinksDomain,
  2644. path));
  2645. }
  2646. return _stories->writeBlock(block);
  2647. }
  2648. Result HtmlWriter::writeStoriesEnd() {
  2649. pushStoriesSection();
  2650. if (_stories) {
  2651. return base::take(_stories)->close();
  2652. }
  2653. return Result::Success();
  2654. }
  2655. QString HtmlWriter::storiesFilePath() const {
  2656. return "lists/stories.html";
  2657. }
  2658. void HtmlWriter::pushStoriesSection() {
  2659. pushSection(
  2660. kStoriesPriority,
  2661. "Stories archive",
  2662. "stories",
  2663. _storiesCount,
  2664. storiesFilePath());
  2665. }
  2666. Result HtmlWriter::writeContactsList(const Data::ContactsList &data) {
  2667. Expects(_summary != nullptr);
  2668. if (const auto result = writeSavedContacts(data); !result) {
  2669. return result;
  2670. } else if (const auto result = writeFrequentContacts(data); !result) {
  2671. return result;
  2672. }
  2673. return Result::Success();
  2674. }
  2675. Result HtmlWriter::writeSavedContacts(const Data::ContactsList &data) {
  2676. if (data.list.empty()) {
  2677. return Result::Success();
  2678. }
  2679. const auto filename = "lists/contacts.html";
  2680. const auto file = fileWithRelativePath(filename);
  2681. auto block = file->pushHeader(
  2682. "Contacts",
  2683. mainFileRelativePath());
  2684. block.append(file->pushDiv("page_body list_page"));
  2685. block.append(file->pushAbout(_environment.aboutContacts));
  2686. block.append(file->pushDiv("entry_list"));
  2687. for (const auto index : Data::SortedContactsIndices(data)) {
  2688. const auto &contact = data.list[index];
  2689. auto userpic = UserpicData{
  2690. Data::ContactColorIndex(contact),
  2691. kEntryUserpicSize
  2692. };
  2693. userpic.firstName = contact.firstName;
  2694. userpic.lastName = contact.lastName;
  2695. if (contact.userId) {
  2696. const auto raw = contact.userId.bare & PeerId::kChatTypeMask;
  2697. userpic.tooltip = (u"ID: "_q + QString::number(raw)).toUtf8();
  2698. }
  2699. block.append(file->pushListEntry(
  2700. userpic,
  2701. ComposeName(userpic, "Deleted Account"),
  2702. Data::FormatPhoneNumber(contact.phoneNumber),
  2703. Data::FormatDateTime(contact.date)));
  2704. }
  2705. if (const auto result = file->writeBlock(block); !result) {
  2706. return result;
  2707. } else if (const auto closed = file->close(); !closed) {
  2708. return closed;
  2709. }
  2710. pushSection(
  2711. kContactsPriority,
  2712. "Contacts",
  2713. "contacts",
  2714. data.list.size(),
  2715. filename);
  2716. return Result::Success();
  2717. }
  2718. Result HtmlWriter::writeFrequentContacts(const Data::ContactsList &data) {
  2719. const auto size = data.correspondents.size()
  2720. + data.inlineBots.size()
  2721. + data.phoneCalls.size();
  2722. if (!size) {
  2723. return Result::Success();
  2724. }
  2725. const auto filename = "lists/frequent.html";
  2726. const auto file = fileWithRelativePath(filename);
  2727. auto block = file->pushHeader(
  2728. "Frequent contacts",
  2729. mainFileRelativePath());
  2730. block.append(file->pushDiv("page_body list_page"));
  2731. block.append(file->pushAbout(_environment.aboutFrequent));
  2732. block.append(file->pushDiv("entry_list"));
  2733. const auto writeList = [&](
  2734. const std::vector<Data::TopPeer> &peers,
  2735. Data::Utf8String category) {
  2736. for (const auto &top : peers) {
  2737. const auto name = [&]() -> Data::Utf8String {
  2738. if (top.peer.chat()) {
  2739. return top.peer.name();
  2740. } else if (top.peer.user()->isSelf) {
  2741. return "Saved messages";
  2742. } else {
  2743. return top.peer.user()->info.firstName;
  2744. }
  2745. }();
  2746. const auto lastName = [&]() -> Data::Utf8String {
  2747. if (top.peer.user() && !top.peer.user()->isSelf) {
  2748. return top.peer.user()->info.lastName;
  2749. }
  2750. return {};
  2751. }();
  2752. auto userpic = UserpicData{
  2753. Data::PeerColorIndex(top.peer.id()),
  2754. kEntryUserpicSize
  2755. };
  2756. userpic.firstName = name;
  2757. userpic.lastName = lastName;
  2758. block.append(file->pushListEntry(
  2759. userpic,
  2760. ComposeName(userpic, "Deleted Account"),
  2761. "Rating: " + Data::NumberToString(top.rating),
  2762. category));
  2763. }
  2764. };
  2765. writeList(data.correspondents, "people");
  2766. writeList(data.inlineBots, "inline bots");
  2767. writeList(data.phoneCalls, "calls");
  2768. if (const auto result = file->writeBlock(block); !result) {
  2769. return result;
  2770. } else if (const auto closed = file->close(); !closed) {
  2771. return closed;
  2772. }
  2773. pushSection(
  2774. kFrequentContactsPriority,
  2775. "Frequent contacts",
  2776. "frequent",
  2777. size,
  2778. filename);
  2779. return Result::Success();
  2780. }
  2781. Result HtmlWriter::writeSessionsList(const Data::SessionsList &data) {
  2782. Expects(_summary != nullptr);
  2783. if (const auto result = writeSessions(data); !result) {
  2784. return result;
  2785. } else if (const auto result = writeWebSessions(data); !result) {
  2786. return result;
  2787. }
  2788. return Result::Success();
  2789. }
  2790. Result HtmlWriter::writeSessions(const Data::SessionsList &data) {
  2791. Expects(_summary != nullptr);
  2792. if (data.list.empty()) {
  2793. return Result::Success();
  2794. }
  2795. const auto filename = "lists/sessions.html";
  2796. const auto file = fileWithRelativePath(filename);
  2797. auto block = file->pushHeader(
  2798. "Sessions",
  2799. mainFileRelativePath());
  2800. block.append(file->pushDiv("page_body list_page"));
  2801. block.append(file->pushAbout(_environment.aboutSessions));
  2802. block.append(file->pushDiv("entry_list"));
  2803. for (const auto &session : data.list) {
  2804. block.append(file->pushSessionListEntry(
  2805. session.applicationId,
  2806. ((session.applicationName.isEmpty()
  2807. ? Data::Utf8String("Unknown")
  2808. : session.applicationName)
  2809. + ' '
  2810. + session.applicationVersion),
  2811. (session.deviceModel
  2812. + ", "
  2813. + session.platform
  2814. + ' '
  2815. + session.systemVersion),
  2816. {
  2817. (session.ip
  2818. + " \xE2\x80\x93 "
  2819. + session.region
  2820. + ((session.region.isEmpty() || session.country.isEmpty())
  2821. ? QByteArray()
  2822. : QByteArray(", "))
  2823. + session.country),
  2824. "Last active: " + Data::FormatDateTime(session.lastActive),
  2825. "Created: " + Data::FormatDateTime(session.created)
  2826. }));
  2827. }
  2828. if (const auto result = file->writeBlock(block); !result) {
  2829. return result;
  2830. } else if (const auto closed = file->close(); !closed) {
  2831. return closed;
  2832. }
  2833. pushSection(
  2834. kSessionsPriority,
  2835. "Sessions",
  2836. "sessions",
  2837. data.list.size(),
  2838. filename);
  2839. return Result::Success();
  2840. }
  2841. Result HtmlWriter::writeWebSessions(const Data::SessionsList &data) {
  2842. Expects(_summary != nullptr);
  2843. if (data.webList.empty()) {
  2844. return Result::Success();
  2845. }
  2846. const auto filename = "lists/web_sessions.html";
  2847. const auto file = fileWithRelativePath(filename);
  2848. auto block = file->pushHeader(
  2849. "Web sessions",
  2850. mainFileRelativePath());
  2851. block.append(file->pushDiv("page_body list_page"));
  2852. block.append(file->pushAbout(_environment.aboutWebSessions));
  2853. block.append(file->pushDiv("entry_list"));
  2854. for (const auto &session : data.webList) {
  2855. block.append(file->pushSessionListEntry(
  2856. Data::DomainApplicationId(session.domain),
  2857. (session.domain.isEmpty()
  2858. ? Data::Utf8String("Unknown")
  2859. : session.domain),
  2860. session.platform + ", " + session.browser,
  2861. {
  2862. session.ip + " \xE2\x80\x93 " + session.region,
  2863. "Last active: " + Data::FormatDateTime(session.lastActive),
  2864. "Created: " + Data::FormatDateTime(session.created)
  2865. },
  2866. (session.botUsername.isEmpty()
  2867. ? QByteArray()
  2868. : ('@' + session.botUsername))));
  2869. }
  2870. if (const auto result = file->writeBlock(block); !result) {
  2871. return result;
  2872. } else if (const auto closed = file->close(); !closed) {
  2873. return closed;
  2874. }
  2875. pushSection(
  2876. kWebSessionsPriority,
  2877. "Web sessions",
  2878. "web",
  2879. data.webList.size(),
  2880. filename);
  2881. return Result::Success();
  2882. }
  2883. Result HtmlWriter::writeOtherData(const Data::File &data) {
  2884. Expects(_summary != nullptr);
  2885. pushSection(
  2886. kOtherPriority,
  2887. "Other data",
  2888. "other",
  2889. 1,
  2890. data.relativePath);
  2891. return Result::Success();
  2892. }
  2893. Result HtmlWriter::writeDialogsStart(const Data::DialogsInfo &data) {
  2894. Expects(_chats == nullptr);
  2895. if (data.chats.empty() && data.left.empty()) {
  2896. return Result::Success();
  2897. } else if (_settings.onlySinglePeer()) {
  2898. return Result::Success();
  2899. }
  2900. _dialogsRelativePath = "lists/chats.html";
  2901. _chats = fileWithRelativePath(_dialogsRelativePath);
  2902. auto block = _chats->pushHeader(
  2903. "Chats",
  2904. mainFileRelativePath());
  2905. block.append(_chats->pushDiv("page_body list_page"));
  2906. if (const auto result = _chats->writeBlock(block); !result) {
  2907. return result;
  2908. }
  2909. pushSection(
  2910. kChatsPriority,
  2911. "Chats",
  2912. "chats",
  2913. data.chats.size() + data.left.size(),
  2914. "lists/chats.html");
  2915. return writeSections();
  2916. }
  2917. Result HtmlWriter::writeDialogStart(const Data::DialogInfo &data) {
  2918. Expects(_chat == nullptr);
  2919. _chat = fileWithRelativePath(data.relativePath + messagesFile(0));
  2920. _chatFileEmpty = true;
  2921. _messagesCount = 0;
  2922. _dateMessageId = 0;
  2923. _lastMessageInfo = nullptr;
  2924. _lastMessageIdsPerFile.clear();
  2925. _dialog = data;
  2926. return Result::Success();
  2927. }
  2928. Result HtmlWriter::writeDialogSlice(const Data::MessagesSlice &data) {
  2929. Expects(_chat != nullptr);
  2930. Expects(!data.list.empty());
  2931. const auto messageLinkWrapper = [&](int messageId, QByteArray text) {
  2932. return wrapMessageLink(messageId, text);
  2933. };
  2934. auto oldIndex = (_messagesCount > 0)
  2935. ? ((_messagesCount - 1) / kMessagesInFile)
  2936. : 0;
  2937. auto previous = _lastMessageInfo.get();
  2938. auto saved = std::optional<MessageInfo>();
  2939. auto block = QByteArray();
  2940. for (const auto &message : data.list) {
  2941. if (Data::SkipMessageByDate(message, _settings)) {
  2942. continue;
  2943. }
  2944. const auto newIndex = (_messagesCount / kMessagesInFile);
  2945. if (oldIndex != newIndex) {
  2946. if (const auto result = _chat->writeBlock(block); !result) {
  2947. return result;
  2948. } else if (const auto next = switchToNextChatFile(newIndex)) {
  2949. Assert(saved.has_value() || _lastMessageInfo != nullptr);
  2950. _lastMessageIdsPerFile.push_back(saved
  2951. ? saved->id
  2952. : _lastMessageInfo->id);
  2953. block = QByteArray();
  2954. _lastMessageInfo = nullptr;
  2955. previous = nullptr;
  2956. saved = std::nullopt;
  2957. oldIndex = newIndex;
  2958. } else {
  2959. return next;
  2960. }
  2961. }
  2962. if (_chatFileEmpty) {
  2963. if (const auto result = writeDialogOpening(oldIndex); !result) {
  2964. return result;
  2965. }
  2966. _chatFileEmpty = false;
  2967. }
  2968. const auto date = message.date;
  2969. if (DisplayDate(date, previous ? previous->date : 0)) {
  2970. block.append(_chat->pushServiceMessage(
  2971. --_dateMessageId,
  2972. _dialog,
  2973. _settings.path,
  2974. FormatDateText(date)));
  2975. }
  2976. const auto &[info, content] = _chat->pushMessage(
  2977. message,
  2978. previous,
  2979. _dialog,
  2980. _settings.path,
  2981. data.peers,
  2982. _environment.internalLinksDomain,
  2983. messageLinkWrapper);
  2984. block.append(content);
  2985. ++_messagesCount;
  2986. saved = info;
  2987. previous = &*saved;
  2988. }
  2989. if (saved) {
  2990. _lastMessageInfo = std::make_unique<MessageInfo>(*saved);
  2991. }
  2992. return block.isEmpty() ? Result::Success() : _chat->writeBlock(block);
  2993. }
  2994. Result HtmlWriter::writeEmptySinglePeer() {
  2995. Expects(_chat != nullptr);
  2996. if (!_settings.onlySinglePeer() || _messagesCount != 0) {
  2997. return Result::Success();
  2998. }
  2999. Assert(_chatFileEmpty);
  3000. if (const auto result = writeDialogOpening(0); !result) {
  3001. return result;
  3002. }
  3003. return _chat->writeBlock(_chat->pushServiceMessage(
  3004. --_dateMessageId,
  3005. _dialog,
  3006. _settings.path,
  3007. "No exported messages"));
  3008. }
  3009. Result HtmlWriter::writeDialogEnd() {
  3010. Expects(_settings.onlySinglePeer() || _chats != nullptr);
  3011. Expects(_chat != nullptr);
  3012. if (const auto result = writeEmptySinglePeer(); !result) {
  3013. return result;
  3014. }
  3015. if (const auto closed = base::take(_chat)->close(); !closed) {
  3016. return closed;
  3017. } else if (_settings.onlySinglePeer()) {
  3018. return Result::Success();
  3019. }
  3020. using Type = Data::DialogInfo::Type;
  3021. const auto TypeString = [](Type type) {
  3022. switch (type) {
  3023. case Type::Unknown: return "unknown";
  3024. case Type::Self:
  3025. case Type::Replies:
  3026. case Type::VerifyCodes:
  3027. case Type::Personal: return "private";
  3028. case Type::Bot: return "bot";
  3029. case Type::PrivateGroup:
  3030. case Type::PrivateSupergroup:
  3031. case Type::PublicSupergroup: return "group";
  3032. case Type::PrivateChannel:
  3033. case Type::PublicChannel: return "channel";
  3034. }
  3035. Unexpected("Dialog type in TypeString.");
  3036. };
  3037. const auto DeletedString = [](Type type) {
  3038. switch (type) {
  3039. case Type::Unknown:
  3040. case Type::Self:
  3041. case Type::Replies:
  3042. case Type::VerifyCodes:
  3043. case Type::Personal:
  3044. case Type::Bot: return "Deleted Account";
  3045. case Type::PrivateGroup:
  3046. case Type::PrivateSupergroup:
  3047. case Type::PublicSupergroup: return "Deleted Group";
  3048. case Type::PrivateChannel:
  3049. case Type::PublicChannel: return "Deleted Channel";
  3050. }
  3051. Unexpected("Dialog type in TypeString.");
  3052. };
  3053. const auto NameString = [](
  3054. const Data::DialogInfo &dialog) -> QByteArray {
  3055. if (dialog.type == Type::Self) {
  3056. return "Saved messages";
  3057. } else if (dialog.type == Type::Replies) {
  3058. return "Replies";
  3059. } else if (dialog.type == Type::VerifyCodes) {
  3060. return "Verification Codes";
  3061. }
  3062. return dialog.name;
  3063. };
  3064. const auto LastNameString = [](
  3065. const Data::DialogInfo &dialog) -> QByteArray {
  3066. if (dialog.type != Type::Personal && dialog.type != Type::Bot) {
  3067. return {};
  3068. }
  3069. return dialog.lastName;
  3070. };
  3071. const auto CountString = [](int count, bool outgoing) -> QByteArray {
  3072. if (count == 1) {
  3073. return outgoing ? "1 outgoing message" : "1 message";
  3074. } else if (!count) {
  3075. return outgoing ? "No outgoing messages" : "No messages";
  3076. }
  3077. return Data::NumberToString(count)
  3078. + (outgoing ? " outgoing messages" : " messages");
  3079. };
  3080. auto userpic = UserpicData{
  3081. ((_dialog.type == Type::Self
  3082. || _dialog.type == Type::Replies
  3083. || _dialog.type == Type::VerifyCodes)
  3084. ? kSavedMessagesColorIndex
  3085. : Data::PeerColorIndex(_dialog.peerId)),
  3086. kEntryUserpicSize
  3087. };
  3088. userpic.firstName = NameString(_dialog);
  3089. userpic.lastName = LastNameString(_dialog);
  3090. const auto result = validateDialogsMode(_dialog.isLeftChannel);
  3091. if (!result) {
  3092. return result;
  3093. }
  3094. return _chats->writeBlock(_chats->pushListEntry(
  3095. userpic,
  3096. ComposeName(userpic, DeletedString(_dialog.type)),
  3097. CountString(_messagesCount, _dialog.onlyMyMessages),
  3098. TypeString(_dialog.type),
  3099. (_messagesCount > 0
  3100. ? (_dialog.relativePath + "messages.html")
  3101. : QString())));
  3102. }
  3103. Result HtmlWriter::validateDialogsMode(bool isLeftChannel) {
  3104. const auto mode = isLeftChannel
  3105. ? DialogsMode::Left
  3106. : DialogsMode::Chats;
  3107. if (_dialogsMode == mode) {
  3108. return Result::Success();
  3109. } else if (_dialogsMode != DialogsMode::None) {
  3110. const auto result = _chats->writeBlock(_chats->popTag());
  3111. if (!result) {
  3112. return result;
  3113. }
  3114. }
  3115. _dialogsMode = mode;
  3116. auto block = _chats->pushAbout(isLeftChannel
  3117. ? _environment.aboutLeftChats
  3118. : _environment.aboutChats);
  3119. block.append(_chats->pushDiv("entry_list"));
  3120. return _chats->writeBlock(block);
  3121. }
  3122. Result HtmlWriter::writeDialogsEnd() {
  3123. if (_chats) {
  3124. return base::take(_chats)->close();
  3125. }
  3126. return Result::Success();
  3127. }
  3128. Result HtmlWriter::writeDialogOpening(int index) {
  3129. const auto name = (_dialog.name.isEmpty()
  3130. && _dialog.lastName.isEmpty())
  3131. ? QByteArray("Deleted Account")
  3132. : (_dialog.name + ' ' + _dialog.lastName);
  3133. auto block = _chat->pushHeader(
  3134. name,
  3135. _settings.onlySinglePeer() ? QString() : _dialogsRelativePath);
  3136. block.append(_chat->pushDiv("page_body chat_page"));
  3137. block.append(_chat->pushDiv("history"));
  3138. if (index > 0) {
  3139. const auto previousPath = messagesFile(index - 1);
  3140. block.append(_chat->pushTag("a", {
  3141. { "class", "pagination block_link" },
  3142. { "href", previousPath.toUtf8() }
  3143. }));
  3144. block.append("Previous messages");
  3145. block.append(_chat->popTag());
  3146. }
  3147. return _chat->writeBlock(block);
  3148. }
  3149. void HtmlWriter::pushSection(
  3150. int priority,
  3151. const QByteArray &label,
  3152. const QByteArray &type,
  3153. int count,
  3154. const QString &path) {
  3155. _savedSections.push_back({
  3156. priority,
  3157. label,
  3158. type,
  3159. count,
  3160. path
  3161. });
  3162. }
  3163. Result HtmlWriter::writeSections() {
  3164. Expects(_summary != nullptr);
  3165. if (_savedSections.empty()) {
  3166. return Result::Success();
  3167. } else if (!_haveSections) {
  3168. auto block = _summary->pushDiv(
  3169. _summaryNeedDivider ? "sections with_divider" : "sections");
  3170. if (const auto result = _summary->writeBlock(block); !result) {
  3171. return result;
  3172. }
  3173. _haveSections = true;
  3174. _summaryNeedDivider = false;
  3175. }
  3176. auto block = QByteArray();
  3177. ranges::sort(_savedSections, std::less<>(), [](const SavedSection &data) {
  3178. return data.priority;
  3179. });
  3180. for (const auto &section : base::take(_savedSections)) {
  3181. block.append(_summary->pushSection(
  3182. section.label,
  3183. section.type,
  3184. section.count,
  3185. _summary->relativePath(section.path)));
  3186. }
  3187. return _summary->writeBlock(block);
  3188. }
  3189. QByteArray HtmlWriter::wrapMessageLink(int messageId, QByteArray text) {
  3190. const auto it = ranges::find_if(_lastMessageIdsPerFile, [&](int maxMessageId) {
  3191. return messageId <= maxMessageId;
  3192. });
  3193. if (it == end(_lastMessageIdsPerFile)) {
  3194. return "<a href=\"#go_to_message"
  3195. + Data::NumberToString(messageId)
  3196. + "\" onclick=\"return GoToMessage("
  3197. + Data::NumberToString(messageId)
  3198. + ")\">"
  3199. + text + "</a>";
  3200. } else {
  3201. const auto index = it - begin(_lastMessageIdsPerFile);
  3202. return "<a href=\"" + messagesFile(index).toUtf8()
  3203. + "#go_to_message"
  3204. + Data::NumberToString(messageId)
  3205. + "\">"
  3206. + text + "</a>";
  3207. }
  3208. }
  3209. Result HtmlWriter::switchToNextChatFile(int index) {
  3210. Expects(_chat != nullptr);
  3211. const auto nextPath = messagesFile(index);
  3212. auto next = _chat->pushTag("a", {
  3213. { "class", "pagination block_link" },
  3214. { "href", nextPath.toUtf8() }
  3215. });
  3216. next.append("Next messages");
  3217. next.append(_chat->popTag());
  3218. if (const auto result = _chat->writeBlock(next); !result) {
  3219. return result;
  3220. } else if (const auto end = _chat->close(); !end) {
  3221. return end;
  3222. }
  3223. _chat = fileWithRelativePath(_dialog.relativePath + nextPath);
  3224. _chatFileEmpty = true;
  3225. return Result::Success();
  3226. }
  3227. Result HtmlWriter::finish() {
  3228. Expects(_settings.onlySinglePeer() || _summary != nullptr);
  3229. if (_settings.onlySinglePeer()) {
  3230. return Result::Success();
  3231. }
  3232. if (const auto result = writeSections(); !result) {
  3233. return result;
  3234. }
  3235. auto block = QByteArray();
  3236. if (_haveSections) {
  3237. block.append(_summary->popTag());
  3238. _summaryNeedDivider = true;
  3239. _haveSections = false;
  3240. }
  3241. block.append(_summary->pushAbout(
  3242. _environment.aboutTelegram,
  3243. _summaryNeedDivider));
  3244. if (const auto result = _summary->writeBlock(block); !result) {
  3245. return result;
  3246. }
  3247. return _summary->close();
  3248. }
  3249. Result HtmlWriter::copyFile(
  3250. const QString &source,
  3251. const QString &relativePath) const {
  3252. return File::Copy(
  3253. source,
  3254. pathWithRelativePath(relativePath),
  3255. _stats);
  3256. }
  3257. QString HtmlWriter::mainFilePath() {
  3258. return pathWithRelativePath(_settings.onlySinglePeer()
  3259. ? messagesFile(0)
  3260. : mainFileRelativePath());
  3261. }
  3262. QString HtmlWriter::mainFileRelativePath() const {
  3263. return "export_results.html";
  3264. }
  3265. QString HtmlWriter::pathWithRelativePath(const QString &path) const {
  3266. return _settings.path + path;
  3267. }
  3268. QString HtmlWriter::messagesFile(int index) const {
  3269. return "messages"
  3270. + (index > 0 ? QString::number(index + 1) : QString())
  3271. + ".html";
  3272. }
  3273. std::unique_ptr<HtmlWriter::Wrap> HtmlWriter::fileWithRelativePath(
  3274. const QString &path) const {
  3275. return std::make_unique<Wrap>(
  3276. pathWithRelativePath(path),
  3277. _settings.path,
  3278. _stats);
  3279. }
  3280. HtmlWriter::~HtmlWriter() = default;
  3281. } // namespace Output
  3282. } // namespace Export