passport_form_controller.cpp 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765
  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 "passport/passport_form_controller.h"
  8. #include "passport/passport_encryption.h"
  9. #include "passport/passport_panel_controller.h"
  10. #include "passport/passport_panel_edit_document.h"
  11. #include "ui/boxes/confirm_box.h"
  12. #include "boxes/passcode_box.h"
  13. #include "lang/lang_keys.h"
  14. #include "lang/lang_hardcoded.h"
  15. #include "base/random.h"
  16. #include "base/qthelp_url.h"
  17. #include "base/unixtime.h"
  18. #include "base/call_delayed.h"
  19. #include "data/data_session.h"
  20. #include "data/data_user.h"
  21. #include "mainwindow.h"
  22. #include "window/window_session_controller.h"
  23. #include "core/click_handler_types.h"
  24. #include "ui/toast/toast.h"
  25. #include "ui/widgets/sent_code_field.h"
  26. #include "main/main_session.h"
  27. #include "storage/localimageloader.h"
  28. #include "storage/localstorage.h"
  29. #include "storage/file_upload.h"
  30. #include "storage/file_download_mtproto.h"
  31. #include <QtCore/QJsonDocument>
  32. #include <QtCore/QJsonArray>
  33. #include <QtCore/QJsonObject>
  34. namespace Passport {
  35. namespace {
  36. constexpr auto kDocumentScansLimit = 20;
  37. constexpr auto kTranslationScansLimit = 20;
  38. constexpr auto kShortPollTimeout = crl::time(3000);
  39. constexpr auto kRememberCredentialsDelay = crl::time(1800 * 1000);
  40. bool ForwardServiceErrorRequired(const QString &error) {
  41. return (error == u"BOT_INVALID"_q)
  42. || (error == u"PUBLIC_KEY_REQUIRED"_q)
  43. || (error == u"PUBLIC_KEY_INVALID"_q)
  44. || (error == u"SCOPE_EMPTY"_q)
  45. || (error == u"PAYLOAD_EMPTY"_q);
  46. }
  47. bool SaveErrorRequiresRestart(const QString &error) {
  48. return (error == u"PASSWORD_REQUIRED"_q)
  49. || (error == u"SECURE_SECRET_REQUIRED"_q)
  50. || (error == u"SECURE_SECRET_INVALID"_q);
  51. }
  52. bool AcceptErrorRequiresRestart(const QString &error) {
  53. return (error == u"PASSWORD_REQUIRED"_q)
  54. || (error == u"SECURE_SECRET_REQUIRED"_q)
  55. || (error == u"SECURE_VALUE_EMPTY"_q)
  56. || (error == u"SECURE_VALUE_HASH_INVALID"_q);
  57. }
  58. std::map<QString, QString> GetTexts(const ValueMap &map) {
  59. auto result = std::map<QString, QString>();
  60. for (const auto &[key, value] : map.fields) {
  61. result[key] = value.text;
  62. }
  63. return result;
  64. }
  65. QImage ReadImage(bytes::const_span buffer) {
  66. return Images::Read({
  67. .content = QByteArray::fromRawData(
  68. reinterpret_cast<const char*>(buffer.data()),
  69. buffer.size()),
  70. .forceOpaque = true,
  71. }).image;
  72. }
  73. Value::Type ConvertType(const MTPSecureValueType &type) {
  74. using Type = Value::Type;
  75. switch (type.type()) {
  76. case mtpc_secureValueTypePersonalDetails:
  77. return Type::PersonalDetails;
  78. case mtpc_secureValueTypePassport:
  79. return Type::Passport;
  80. case mtpc_secureValueTypeDriverLicense:
  81. return Type::DriverLicense;
  82. case mtpc_secureValueTypeIdentityCard:
  83. return Type::IdentityCard;
  84. case mtpc_secureValueTypeInternalPassport:
  85. return Type::InternalPassport;
  86. case mtpc_secureValueTypeAddress:
  87. return Type::Address;
  88. case mtpc_secureValueTypeUtilityBill:
  89. return Type::UtilityBill;
  90. case mtpc_secureValueTypeBankStatement:
  91. return Type::BankStatement;
  92. case mtpc_secureValueTypeRentalAgreement:
  93. return Type::RentalAgreement;
  94. case mtpc_secureValueTypePassportRegistration:
  95. return Type::PassportRegistration;
  96. case mtpc_secureValueTypeTemporaryRegistration:
  97. return Type::TemporaryRegistration;
  98. case mtpc_secureValueTypePhone:
  99. return Type::Phone;
  100. case mtpc_secureValueTypeEmail:
  101. return Type::Email;
  102. }
  103. Unexpected("Type in secureValueType type.");
  104. };
  105. MTPSecureValueType ConvertType(Value::Type type) {
  106. using Type = Value::Type;
  107. switch (type) {
  108. case Type::PersonalDetails:
  109. return MTP_secureValueTypePersonalDetails();
  110. case Type::Passport:
  111. return MTP_secureValueTypePassport();
  112. case Type::DriverLicense:
  113. return MTP_secureValueTypeDriverLicense();
  114. case Type::IdentityCard:
  115. return MTP_secureValueTypeIdentityCard();
  116. case Type::InternalPassport:
  117. return MTP_secureValueTypeInternalPassport();
  118. case Type::Address:
  119. return MTP_secureValueTypeAddress();
  120. case Type::UtilityBill:
  121. return MTP_secureValueTypeUtilityBill();
  122. case Type::BankStatement:
  123. return MTP_secureValueTypeBankStatement();
  124. case Type::RentalAgreement:
  125. return MTP_secureValueTypeRentalAgreement();
  126. case Type::PassportRegistration:
  127. return MTP_secureValueTypePassportRegistration();
  128. case Type::TemporaryRegistration:
  129. return MTP_secureValueTypeTemporaryRegistration();
  130. case Type::Phone:
  131. return MTP_secureValueTypePhone();
  132. case Type::Email:
  133. return MTP_secureValueTypeEmail();
  134. }
  135. Unexpected("Type in FormController::submit.");
  136. }
  137. void CollectToRequestedRow(
  138. RequestedRow &row,
  139. const MTPSecureRequiredType &data) {
  140. data.match([&](const MTPDsecureRequiredType &data) {
  141. row.values.emplace_back(ConvertType(data.vtype()));
  142. auto &value = row.values.back();
  143. value.selfieRequired = data.is_selfie_required();
  144. value.translationRequired = data.is_translation_required();
  145. value.nativeNames = data.is_native_names();
  146. }, [&](const MTPDsecureRequiredTypeOneOf &data) {
  147. row.values.reserve(row.values.size() + data.vtypes().v.size());
  148. for (const auto &one : data.vtypes().v) {
  149. CollectToRequestedRow(row, one);
  150. }
  151. });
  152. }
  153. void ApplyDataChanges(ValueData &data, ValueMap &&changes) {
  154. data.parsedInEdit = data.parsed;
  155. for (auto &[key, value] : changes.fields) {
  156. data.parsedInEdit.fields[key] = std::move(value);
  157. }
  158. }
  159. RequestedRow CollectRequestedRow(const MTPSecureRequiredType &data) {
  160. auto result = RequestedRow();
  161. CollectToRequestedRow(result, data);
  162. return result;
  163. }
  164. QJsonObject GetJSONFromMap(
  165. const std::map<QString, bytes::const_span> &map) {
  166. auto result = QJsonObject();
  167. for (const auto &[key, value] : map) {
  168. const auto raw = QByteArray::fromRawData(
  169. reinterpret_cast<const char*>(value.data()),
  170. value.size());
  171. result.insert(key, QString::fromUtf8(raw.toBase64()));
  172. }
  173. return result;
  174. }
  175. QJsonObject GetJSONFromFile(const File &file) {
  176. return GetJSONFromMap({
  177. { "file_hash", file.hash },
  178. { "secret", file.secret }
  179. });
  180. }
  181. FormRequest PreprocessRequest(const FormRequest &request) {
  182. auto result = request;
  183. result.publicKey.replace("\r\n", "\n");
  184. return result;
  185. }
  186. QString ValueCredentialsKey(Value::Type type) {
  187. using Type = Value::Type;
  188. switch (type) {
  189. case Type::PersonalDetails: return "personal_details";
  190. case Type::Passport: return "passport";
  191. case Type::DriverLicense: return "driver_license";
  192. case Type::IdentityCard: return "identity_card";
  193. case Type::InternalPassport: return "internal_passport";
  194. case Type::Address: return "address";
  195. case Type::UtilityBill: return "utility_bill";
  196. case Type::BankStatement: return "bank_statement";
  197. case Type::RentalAgreement: return "rental_agreement";
  198. case Type::PassportRegistration: return "passport_registration";
  199. case Type::TemporaryRegistration: return "temporary_registration";
  200. case Type::Phone:
  201. case Type::Email: return QString();
  202. }
  203. Unexpected("Type in ValueCredentialsKey.");
  204. }
  205. QString SpecialScanCredentialsKey(FileType type) {
  206. switch (type) {
  207. case FileType::FrontSide: return "front_side";
  208. case FileType::ReverseSide: return "reverse_side";
  209. case FileType::Selfie: return "selfie";
  210. }
  211. Unexpected("Type in SpecialScanCredentialsKey.");
  212. }
  213. QString ValidateUrl(const QString &url) {
  214. const auto result = qthelp::validate_url(url);
  215. return (result.startsWith("http://", Qt::CaseInsensitive)
  216. || result.startsWith("https://", Qt::CaseInsensitive))
  217. ? result
  218. : QString();
  219. }
  220. auto ParseConfig(const QByteArray &json) {
  221. auto languagesByCountryCode = std::map<QString, QString>();
  222. auto error = QJsonParseError{ 0, QJsonParseError::NoError };
  223. const auto document = QJsonDocument::fromJson(json, &error);
  224. if (error.error != QJsonParseError::NoError) {
  225. LOG(("API Error: Failed to parse passport config, error: %1."
  226. ).arg(error.errorString()));
  227. return languagesByCountryCode;
  228. } else if (!document.isObject()) {
  229. LOG(("API Error: Not an object received in passport config."));
  230. return languagesByCountryCode;
  231. }
  232. const auto object = document.object();
  233. for (auto i = object.constBegin(); i != object.constEnd(); ++i) {
  234. const auto countryCode = i.key();
  235. const auto language = i.value();
  236. if (!language.isString()) {
  237. LOG(("API Error: Not a string in passport config item."));
  238. continue;
  239. }
  240. languagesByCountryCode.emplace(
  241. countryCode,
  242. language.toString());
  243. }
  244. return languagesByCountryCode;
  245. }
  246. } // namespace
  247. QString NonceNameByScope(const QString &scope) {
  248. return (scope.startsWith('{') && scope.endsWith('}'))
  249. ? u"nonce"_q
  250. : u"payload"_q;
  251. }
  252. bool ValueChanged(not_null<const Value*> value, const ValueMap &data) {
  253. const auto FileChanged = [](const EditFile &file) {
  254. if (file.uploadData) {
  255. return !file.deleted;
  256. }
  257. return file.deleted;
  258. };
  259. for (const auto &scan : value->filesInEdit(FileType::Scan)) {
  260. if (FileChanged(scan)) {
  261. return true;
  262. }
  263. }
  264. for (const auto &scan : value->filesInEdit(FileType::Translation)) {
  265. if (FileChanged(scan)) {
  266. return true;
  267. }
  268. }
  269. for (const auto &[type, scan] : value->specialScansInEdit) {
  270. if (FileChanged(scan)) {
  271. return true;
  272. }
  273. }
  274. const auto &existing = value->data.parsed.fields;
  275. for (const auto &[key, value] : data.fields) {
  276. const auto i = existing.find(key);
  277. if (i != existing.end()) {
  278. if (i->second.text != value.text) {
  279. return true;
  280. }
  281. } else if (!value.text.isEmpty()) {
  282. return true;
  283. }
  284. }
  285. return false;
  286. }
  287. FormRequest::FormRequest(
  288. UserId botId,
  289. const QString &scope,
  290. const QString &callbackUrl,
  291. const QString &publicKey,
  292. const QString &nonce)
  293. : botId(botId)
  294. , scope(scope)
  295. , callbackUrl(ValidateUrl(callbackUrl))
  296. , publicKey(publicKey)
  297. , nonce(nonce) {
  298. }
  299. EditFile::EditFile(
  300. not_null<Main::Session*> session,
  301. not_null<const Value*> value,
  302. FileType type,
  303. const File &fields,
  304. std::unique_ptr<UploadScanData> &&uploadData)
  305. : value(value)
  306. , type(type)
  307. , fields(std::move(fields))
  308. , uploadData(session, std::move(uploadData))
  309. , guard(std::make_shared<bool>(true)) {
  310. }
  311. UploadScanDataPointer::UploadScanDataPointer(
  312. not_null<Main::Session*> session,
  313. std::unique_ptr<UploadScanData> &&value)
  314. : _session(session)
  315. , _value(std::move(value)) {
  316. }
  317. UploadScanDataPointer::UploadScanDataPointer(
  318. UploadScanDataPointer &&other) = default;
  319. UploadScanDataPointer &UploadScanDataPointer::operator=(
  320. UploadScanDataPointer &&other) = default;
  321. UploadScanDataPointer::~UploadScanDataPointer() {
  322. if (const auto value = _value.get()) {
  323. if (const auto fullId = value->fullId) {
  324. _session->uploader().cancel(fullId);
  325. }
  326. }
  327. }
  328. UploadScanData *UploadScanDataPointer::get() const {
  329. return _value.get();
  330. }
  331. UploadScanDataPointer::operator UploadScanData*() const {
  332. return _value.get();
  333. }
  334. UploadScanDataPointer::operator bool() const {
  335. return _value.get();
  336. }
  337. UploadScanData *UploadScanDataPointer::operator->() const {
  338. return _value.get();
  339. }
  340. RequestedValue::RequestedValue(Value::Type type) : type(type) {
  341. }
  342. Value::Value(Type type) : type(type) {
  343. }
  344. bool Value::requiresScan(FileType type) const {
  345. if (type == FileType::Scan) {
  346. return (this->type == Type::UtilityBill)
  347. || (this->type == Type::BankStatement)
  348. || (this->type == Type::RentalAgreement)
  349. || (this->type == Type::PassportRegistration)
  350. || (this->type == Type::TemporaryRegistration);
  351. } else if (type == FileType::Translation) {
  352. return translationRequired;
  353. } else {
  354. return requiresSpecialScan(type);
  355. }
  356. }
  357. bool Value::requiresSpecialScan(FileType type) const {
  358. switch (type) {
  359. case FileType::FrontSide:
  360. return (this->type == Type::Passport)
  361. || (this->type == Type::DriverLicense)
  362. || (this->type == Type::IdentityCard)
  363. || (this->type == Type::InternalPassport);
  364. case FileType::ReverseSide:
  365. return (this->type == Type::DriverLicense)
  366. || (this->type == Type::IdentityCard);
  367. case FileType::Selfie:
  368. return selfieRequired;
  369. }
  370. Unexpected("Special scan type in requiresSpecialScan.");
  371. }
  372. void Value::fillDataFrom(Value &&other) {
  373. const auto savedSelfieRequired = selfieRequired;
  374. const auto savedTranslationRequired = translationRequired;
  375. const auto savedNativeNames = nativeNames;
  376. const auto savedEditScreens = editScreens;
  377. *this = std::move(other);
  378. selfieRequired = savedSelfieRequired;
  379. translationRequired = savedTranslationRequired;
  380. nativeNames = savedNativeNames;
  381. editScreens = savedEditScreens;
  382. }
  383. bool Value::scansAreFilled() const {
  384. return (whatNotFilled() == 0);
  385. }
  386. int Value::whatNotFilled() const {
  387. const auto noRequiredSpecialScan = [&](FileType type) {
  388. return requiresSpecialScan(type)
  389. && (specialScans.find(type) == end(specialScans));
  390. };
  391. if (requiresScan(FileType::Scan) && _scans.empty()) {
  392. return kNothingFilled;
  393. } else if (noRequiredSpecialScan(FileType::FrontSide)) {
  394. return kNothingFilled;
  395. }
  396. auto result = 0;
  397. if (requiresScan(FileType::Translation) && _translations.empty()) {
  398. result |= kNoTranslationFilled;
  399. }
  400. if (noRequiredSpecialScan(FileType::ReverseSide)
  401. || noRequiredSpecialScan(FileType::Selfie)) {
  402. result |= kNoSelfieFilled;
  403. }
  404. return result;
  405. }
  406. void Value::saveInEdit(not_null<Main::Session*> session) {
  407. const auto saveList = [&](FileType type) {
  408. filesInEdit(type) = ranges::views::all(
  409. files(type)
  410. ) | ranges::views::transform([=](const File &file) {
  411. return EditFile(session, this, type, file, nullptr);
  412. }) | ranges::to_vector;
  413. };
  414. saveList(FileType::Scan);
  415. saveList(FileType::Translation);
  416. specialScansInEdit.clear();
  417. for (const auto &[type, scan] : specialScans) {
  418. specialScansInEdit.emplace(type, EditFile(
  419. session,
  420. this,
  421. type,
  422. scan,
  423. nullptr));
  424. }
  425. data.parsedInEdit = data.parsed;
  426. }
  427. void Value::clearEditData() {
  428. filesInEdit(FileType::Scan).clear();
  429. filesInEdit(FileType::Translation).clear();
  430. specialScansInEdit.clear();
  431. data.encryptedSecretInEdit.clear();
  432. data.hashInEdit.clear();
  433. data.parsedInEdit = ValueMap();
  434. }
  435. bool Value::uploadingScan() const {
  436. const auto uploading = [](const EditFile &file) {
  437. return file.uploadData
  438. && file.uploadData->fullId
  439. && !file.deleted;
  440. };
  441. const auto uploadingInList = [&](FileType type) {
  442. const auto &list = filesInEdit(type);
  443. return ranges::any_of(list, uploading);
  444. };
  445. if (uploadingInList(FileType::Scan)
  446. || uploadingInList(FileType::Translation)) {
  447. return true;
  448. }
  449. if (ranges::any_of(specialScansInEdit, [&](const auto &pair) {
  450. return uploading(pair.second);
  451. })) {
  452. return true;
  453. }
  454. return false;
  455. }
  456. bool Value::saving() const {
  457. return (saveRequestId != 0)
  458. || (verification.requestId != 0)
  459. || (verification.codeLength != 0)
  460. || uploadingScan();
  461. }
  462. std::vector<File> &Value::files(FileType type) {
  463. switch (type) {
  464. case FileType::Scan: return _scans;
  465. case FileType::Translation: return _translations;
  466. }
  467. Unexpected("Type in Value::files().");
  468. }
  469. const std::vector<File> &Value::files(FileType type) const {
  470. switch (type) {
  471. case FileType::Scan: return _scans;
  472. case FileType::Translation: return _translations;
  473. }
  474. Unexpected("Type in Value::files() const.");
  475. }
  476. QString &Value::fileMissingError(FileType type) {
  477. switch (type) {
  478. case FileType::Scan: return _scanMissingError;
  479. case FileType::Translation: return _translationMissingError;
  480. }
  481. Unexpected("Type in Value::fileMissingError().");
  482. }
  483. const QString &Value::fileMissingError(FileType type) const {
  484. switch (type) {
  485. case FileType::Scan: return _scanMissingError;
  486. case FileType::Translation: return _translationMissingError;
  487. }
  488. Unexpected("Type in Value::fileMissingError() const.");
  489. }
  490. std::vector<EditFile> &Value::filesInEdit(FileType type) {
  491. switch (type) {
  492. case FileType::Scan: return _scansInEdit;
  493. case FileType::Translation: return _translationsInEdit;
  494. }
  495. Unexpected("Type in Value::filesInEdit().");
  496. }
  497. const std::vector<EditFile> &Value::filesInEdit(FileType type) const {
  498. switch (type) {
  499. case FileType::Scan: return _scansInEdit;
  500. case FileType::Translation: return _translationsInEdit;
  501. }
  502. Unexpected("Type in Value::filesInEdit() const.");
  503. }
  504. EditFile &Value::fileInEdit(FileType type, std::optional<int> fileIndex) {
  505. switch (type) {
  506. case FileType::Scan:
  507. case FileType::Translation: {
  508. auto &list = filesInEdit(type);
  509. Assert(fileIndex.has_value());
  510. Assert(*fileIndex >= 0 && *fileIndex < list.size());
  511. return list[*fileIndex];
  512. } break;
  513. }
  514. const auto i = specialScansInEdit.find(type);
  515. Assert(!fileIndex.has_value());
  516. Assert(i != end(specialScansInEdit));
  517. return i->second;
  518. }
  519. const EditFile &Value::fileInEdit(
  520. FileType type,
  521. std::optional<int> fileIndex) const {
  522. switch (type) {
  523. case FileType::Scan:
  524. case FileType::Translation: {
  525. auto &list = filesInEdit(type);
  526. Assert(fileIndex.has_value());
  527. Assert(*fileIndex >= 0 && *fileIndex < list.size());
  528. return list[*fileIndex];
  529. } break;
  530. }
  531. const auto i = specialScansInEdit.find(type);
  532. Assert(!fileIndex.has_value());
  533. Assert(i != end(specialScansInEdit));
  534. return i->second;
  535. }
  536. std::vector<EditFile> Value::takeAllFilesInEdit() {
  537. auto result = base::take(filesInEdit(FileType::Scan));
  538. auto &translation = filesInEdit(FileType::Translation);
  539. auto &special = specialScansInEdit;
  540. result.reserve(result.size() + translation.size() + special.size());
  541. for (auto &scan : base::take(translation)) {
  542. result.push_back(std::move(scan));
  543. }
  544. for (auto &[type, scan] : base::take(special)) {
  545. result.push_back(std::move(scan));
  546. }
  547. return result;
  548. }
  549. FormController::FormController(
  550. not_null<Window::SessionController*> controller,
  551. const FormRequest &request)
  552. : _controller(controller)
  553. , _api(&_controller->session().mtp())
  554. , _request(PreprocessRequest(request))
  555. , _shortPollTimer([=] { reloadPassword(); })
  556. , _view(std::make_unique<PanelController>(this)) {
  557. }
  558. Main::Session &FormController::session() const {
  559. return _controller->session();
  560. }
  561. void FormController::show() {
  562. requestForm();
  563. requestPassword();
  564. }
  565. UserData *FormController::bot() const {
  566. return _bot;
  567. }
  568. QString FormController::privacyPolicyUrl() const {
  569. return _form.privacyPolicyUrl;
  570. }
  571. bytes::vector FormController::passwordHashForAuth(
  572. bytes::const_span password) const {
  573. return Core::ComputeCloudPasswordHash(_password.request.algo, password);
  574. }
  575. auto FormController::prepareFinalData() -> FinalData {
  576. auto errors = std::vector<not_null<const Value*>>();
  577. auto hashes = QVector<MTPSecureValueHash>();
  578. auto secureData = QJsonObject();
  579. const auto addValueToJSON = [&](
  580. const QString &key,
  581. not_null<const Value*> value) {
  582. auto object = QJsonObject();
  583. if (!value->data.parsed.fields.empty()) {
  584. object.insert("data", GetJSONFromMap({
  585. { "data_hash", value->data.hash },
  586. { "secret", value->data.secret }
  587. }));
  588. }
  589. const auto addList = [&](
  590. const QString &key,
  591. const std::vector<File> &list) {
  592. if (!list.empty()) {
  593. auto files = QJsonArray();
  594. for (const auto &scan : list) {
  595. files.append(GetJSONFromFile(scan));
  596. }
  597. object.insert(key, files);
  598. }
  599. };
  600. addList("files", value->files(FileType::Scan));
  601. if (value->translationRequired) {
  602. addList("translation", value->files(FileType::Translation));
  603. }
  604. for (const auto &[type, scan] : value->specialScans) {
  605. if (value->requiresSpecialScan(type)) {
  606. object.insert(
  607. SpecialScanCredentialsKey(type),
  608. GetJSONFromFile(scan));
  609. }
  610. }
  611. secureData.insert(key, object);
  612. };
  613. const auto addValue = [&](not_null<const Value*> value) {
  614. hashes.push_back(MTP_secureValueHash(
  615. ConvertType(value->type),
  616. MTP_bytes(value->submitHash)));
  617. const auto key = ValueCredentialsKey(value->type);
  618. if (!key.isEmpty()) {
  619. addValueToJSON(key, value);
  620. }
  621. };
  622. const auto scopes = ComputeScopes(_form);
  623. for (const auto &scope : scopes) {
  624. const auto row = ComputeScopeRow(scope);
  625. if (row.ready.isEmpty() || !row.error.isEmpty()) {
  626. errors.push_back(scope.details
  627. ? scope.details
  628. : scope.documents[0].get());
  629. continue;
  630. }
  631. if (scope.details) {
  632. addValue(scope.details);
  633. }
  634. if (!scope.documents.empty()) {
  635. for (const auto &document : scope.documents) {
  636. if (document->scansAreFilled()) {
  637. addValue(document);
  638. break;
  639. }
  640. }
  641. }
  642. }
  643. auto json = QJsonObject();
  644. if (errors.empty()) {
  645. json.insert("secure_data", secureData);
  646. json.insert(NonceNameByScope(_request.scope), _request.nonce);
  647. }
  648. return {
  649. hashes,
  650. QJsonDocument(json).toJson(QJsonDocument::Compact),
  651. errors
  652. };
  653. }
  654. std::vector<not_null<const Value*>> FormController::submitGetErrors() {
  655. if (_submitRequestId || _submitSuccess|| _cancelled) {
  656. return {};
  657. }
  658. const auto prepared = prepareFinalData();
  659. if (!prepared.errors.empty()) {
  660. return prepared.errors;
  661. }
  662. const auto credentialsEncryptedData = EncryptData(
  663. bytes::make_span(prepared.credentials));
  664. const auto credentialsEncryptedSecret = EncryptCredentialsSecret(
  665. credentialsEncryptedData.secret,
  666. bytes::make_span(_request.publicKey.toUtf8()));
  667. _submitRequestId = _api.request(MTPaccount_AcceptAuthorization(
  668. MTP_long(_request.botId.bare),
  669. MTP_string(_request.scope),
  670. MTP_string(_request.publicKey),
  671. MTP_vector<MTPSecureValueHash>(prepared.hashes),
  672. MTP_secureCredentialsEncrypted(
  673. MTP_bytes(credentialsEncryptedData.bytes),
  674. MTP_bytes(credentialsEncryptedData.hash),
  675. MTP_bytes(credentialsEncryptedSecret))
  676. )).done([=] {
  677. _submitRequestId = 0;
  678. _submitSuccess = true;
  679. _view->showToast(tr::lng_passport_success(tr::now));
  680. base::call_delayed(
  681. (st::defaultToast.durationFadeIn
  682. + Ui::Toast::kDefaultDuration
  683. + st::defaultToast.durationFadeOut),
  684. this,
  685. [=] { cancel(); });
  686. }).fail([=](const MTP::Error &error) {
  687. _submitRequestId = 0;
  688. if (handleAppUpdateError(error.type())) {
  689. } else if (AcceptErrorRequiresRestart(error.type())) {
  690. suggestRestart();
  691. } else {
  692. _view->show(Ui::MakeInformBox(
  693. Lang::Hard::SecureAcceptError() + "\n" + error.type()));
  694. }
  695. }).send();
  696. return {};
  697. }
  698. void FormController::checkPasswordHash(
  699. mtpRequestId &guard,
  700. bytes::vector hash,
  701. PasswordCheckCallback callback) {
  702. _passwordCheckHash = std::move(hash);
  703. _passwordCheckCallback = std::move(callback);
  704. if (_password.request.id) {
  705. passwordChecked();
  706. } else {
  707. requestPasswordData(guard);
  708. }
  709. }
  710. void FormController::passwordChecked() {
  711. if (!_password.request || !_password.request.id) {
  712. return passwordServerError();
  713. }
  714. const auto check = Core::ComputeCloudPasswordCheck(
  715. _password.request,
  716. _passwordCheckHash);
  717. if (!check) {
  718. return passwordServerError();
  719. }
  720. _password.request.id = 0;
  721. _passwordCheckCallback(check);
  722. }
  723. void FormController::requestPasswordData(mtpRequestId &guard) {
  724. if (!_passwordCheckCallback) {
  725. return passwordServerError();
  726. }
  727. _api.request(base::take(guard)).cancel();
  728. guard = _api.request(
  729. MTPaccount_GetPassword()
  730. ).done([=, &guard](const MTPaccount_Password &result) {
  731. guard = 0;
  732. result.match([&](const MTPDaccount_password &data) {
  733. _password.request = Core::ParseCloudPasswordCheckRequest(data);
  734. passwordChecked();
  735. });
  736. }).send();
  737. }
  738. void FormController::submitPassword(const QByteArray &password) {
  739. Expects(!!_password.request);
  740. const auto submitSaved = !base::take(_savedPasswordValue).isEmpty();
  741. if (_passwordCheckRequestId) {
  742. return;
  743. } else if (password.isEmpty()) {
  744. _passwordError.fire(QString());
  745. return;
  746. }
  747. const auto callback = [=](const Core::CloudPasswordResult &check) {
  748. submitPassword(check, password, submitSaved);
  749. };
  750. checkPasswordHash(
  751. _passwordCheckRequestId,
  752. passwordHashForAuth(bytes::make_span(password)),
  753. callback);
  754. }
  755. void FormController::submitPassword(
  756. const Core::CloudPasswordResult &check,
  757. const QByteArray &password,
  758. bool submitSaved) {
  759. _passwordCheckRequestId = _api.request(MTPaccount_GetPasswordSettings(
  760. check.result
  761. )).handleFloodErrors(
  762. ).done([=](const MTPaccount_PasswordSettings &result) {
  763. Expects(result.type() == mtpc_account_passwordSettings);
  764. _passwordCheckRequestId = 0;
  765. _savedPasswordValue = QByteArray();
  766. const auto &data = result.c_account_passwordSettings();
  767. _password.confirmedEmail = qs(data.vemail().value_or_empty());
  768. if (const auto wrapped = data.vsecure_settings()) {
  769. const auto &settings = wrapped->c_secureSecretSettings();
  770. const auto algo = Core::ParseSecureSecretAlgo(
  771. settings.vsecure_algo());
  772. if (v::is_null(algo)) {
  773. _view->showUpdateAppBox();
  774. return;
  775. }
  776. const auto hashForSecret = Core::ComputeSecureSecretHash(
  777. algo,
  778. bytes::make_span(password));
  779. validateSecureSecret(
  780. bytes::make_span(settings.vsecure_secret().v),
  781. hashForSecret,
  782. bytes::make_span(password),
  783. settings.vsecure_secret_id().v);
  784. if (!_secret.empty()) {
  785. auto saved = SavedCredentials();
  786. saved.hashForAuth = base::take(_passwordCheckHash);
  787. saved.hashForSecret = hashForSecret;
  788. saved.secretId = _secretId;
  789. session().data().rememberPassportCredentials(
  790. std::move(saved),
  791. kRememberCredentialsDelay);
  792. }
  793. } else {
  794. validateSecureSecret(
  795. bytes::const_span(), // secure_secret
  796. bytes::const_span(), // hash for secret
  797. bytes::make_span(password),
  798. 0); // secure_secret_id
  799. }
  800. }).fail([=](const MTP::Error &error) {
  801. _passwordCheckRequestId = 0;
  802. if (error.type() == u"SRP_ID_INVALID"_q) {
  803. handleSrpIdInvalid(_passwordCheckRequestId);
  804. } else if (submitSaved) {
  805. // Force reload and show form.
  806. _password = PasswordSettings();
  807. reloadPassword();
  808. } else if (MTP::IsFloodError(error)) {
  809. _passwordError.fire(tr::lng_flood_error(tr::now));
  810. } else if (error.type() == u"PASSWORD_HASH_INVALID"_q
  811. || error.type() == u"SRP_PASSWORD_CHANGED"_q) {
  812. _passwordError.fire(tr::lng_passport_password_wrong(tr::now));
  813. } else {
  814. _passwordError.fire_copy(error.type());
  815. }
  816. }).send();
  817. }
  818. bool FormController::handleSrpIdInvalid(mtpRequestId &guard) {
  819. const auto now = crl::now();
  820. if (_lastSrpIdInvalidTime > 0
  821. && now - _lastSrpIdInvalidTime < Core::kHandleSrpIdInvalidTimeout) {
  822. _password.request.id = 0;
  823. _passwordError.fire(Lang::Hard::ServerError());
  824. return false;
  825. } else {
  826. _lastSrpIdInvalidTime = now;
  827. requestPasswordData(guard);
  828. return true;
  829. }
  830. }
  831. void FormController::passwordServerError() {
  832. _view->showCriticalError(Lang::Hard::ServerError());
  833. }
  834. void FormController::checkSavedPasswordSettings(
  835. const SavedCredentials &credentials) {
  836. const auto callback = [=](const Core::CloudPasswordResult &check) {
  837. checkSavedPasswordSettings(check, credentials);
  838. };
  839. checkPasswordHash(
  840. _passwordCheckRequestId,
  841. credentials.hashForAuth,
  842. callback);
  843. }
  844. void FormController::checkSavedPasswordSettings(
  845. const Core::CloudPasswordResult &check,
  846. const SavedCredentials &credentials) {
  847. _passwordCheckRequestId = _api.request(MTPaccount_GetPasswordSettings(
  848. check.result
  849. )).done([=](const MTPaccount_PasswordSettings &result) {
  850. Expects(result.type() == mtpc_account_passwordSettings);
  851. _passwordCheckRequestId = 0;
  852. const auto &data = result.c_account_passwordSettings();
  853. if (const auto wrapped = data.vsecure_settings()) {
  854. const auto &settings = wrapped->c_secureSecretSettings();
  855. const auto algo = Core::ParseSecureSecretAlgo(
  856. settings.vsecure_algo());
  857. if (v::is_null(algo)) {
  858. _view->showUpdateAppBox();
  859. return;
  860. } else if (!settings.vsecure_secret().v.isEmpty()
  861. && settings.vsecure_secret_id().v == credentials.secretId) {
  862. _password.confirmedEmail = qs(data.vemail().value_or_empty());
  863. validateSecureSecret(
  864. bytes::make_span(settings.vsecure_secret().v),
  865. credentials.hashForSecret,
  866. {},
  867. settings.vsecure_secret_id().v);
  868. }
  869. }
  870. if (_secret.empty()) {
  871. session().data().forgetPassportCredentials();
  872. showForm();
  873. }
  874. }).fail([=](const MTP::Error &error) {
  875. _passwordCheckRequestId = 0;
  876. if (error.type() != u"SRP_ID_INVALID"_q
  877. || !handleSrpIdInvalid(_passwordCheckRequestId)) {
  878. } else {
  879. session().data().forgetPassportCredentials();
  880. showForm();
  881. }
  882. }).send();
  883. }
  884. void FormController::recoverPassword() {
  885. if (!_password.hasRecovery) {
  886. _view->show(Ui::MakeInformBox(tr::lng_signin_no_email_forgot()));
  887. return;
  888. } else if (_recoverRequestId) {
  889. return;
  890. }
  891. _recoverRequestId = _api.request(MTPauth_RequestPasswordRecovery(
  892. )).done([=](const MTPauth_PasswordRecovery &result) {
  893. Expects(result.type() == mtpc_auth_passwordRecovery);
  894. _recoverRequestId = 0;
  895. const auto &data = result.c_auth_passwordRecovery();
  896. const auto pattern = qs(data.vemail_pattern());
  897. auto fields = PasscodeBox::CloudFields{
  898. .mtp = PasscodeBox::CloudFields::Mtp {
  899. .newAlgo = _password.newAlgo,
  900. .newSecureSecretAlgo = _password.newSecureAlgo,
  901. },
  902. .hasRecovery = _password.hasRecovery,
  903. .pendingResetDate = _password.pendingResetDate,
  904. };
  905. // MSVC x64 (non-LTO) Release build fails with a linker error:
  906. // - unresolved external variant::variant(variant const &)
  907. // It looks like a MSVC bug and this works like a workaround.
  908. const auto force = fields.mtp.newSecureSecretAlgo;
  909. const auto box = _view->show(Box<RecoverBox>(
  910. &_controller->session().mtp(),
  911. &_controller->session(),
  912. pattern,
  913. fields));
  914. box->newPasswordSet(
  915. ) | rpl::start_with_next([=](const QByteArray &password) {
  916. if (password.isEmpty()) {
  917. reloadPassword();
  918. } else {
  919. reloadAndSubmitPassword(password);
  920. }
  921. }, box->lifetime());
  922. box->recoveryExpired(
  923. ) | rpl::start_with_next([=] {
  924. box->closeBox();
  925. }, box->lifetime());
  926. }).fail([=](const MTP::Error &error) {
  927. _recoverRequestId = 0;
  928. _view->show(Ui::MakeInformBox(Lang::Hard::ServerError()
  929. + '\n'
  930. + error.type()));
  931. }).send();
  932. }
  933. void FormController::reloadPassword() {
  934. requestPassword();
  935. }
  936. void FormController::reloadAndSubmitPassword(const QByteArray &password) {
  937. _savedPasswordValue = password;
  938. requestPassword();
  939. }
  940. void FormController::cancelPassword() {
  941. if (_passwordRequestId) {
  942. return;
  943. }
  944. _passwordRequestId = _api.request(MTPaccount_CancelPasswordEmail(
  945. )).done([=] {
  946. _passwordRequestId = 0;
  947. reloadPassword();
  948. }).fail([=] {
  949. _passwordRequestId = 0;
  950. reloadPassword();
  951. }).send();
  952. }
  953. void FormController::validateSecureSecret(
  954. bytes::const_span encryptedSecret,
  955. bytes::const_span passwordHashForSecret,
  956. bytes::const_span passwordBytes,
  957. uint64 serverSecretId) {
  958. Expects(!passwordBytes.empty() || !passwordHashForSecret.empty());
  959. if (!passwordHashForSecret.empty() && !encryptedSecret.empty()) {
  960. _secret = DecryptSecureSecret(
  961. encryptedSecret,
  962. passwordHashForSecret);
  963. if (_secret.empty()) {
  964. _secretId = 0;
  965. LOG(("API Error: Failed to decrypt secure secret."));
  966. if (!passwordBytes.empty()) {
  967. suggestReset(bytes::make_vector(passwordBytes));
  968. }
  969. return;
  970. } else if (CountSecureSecretId(_secret) != serverSecretId) {
  971. _secret.clear();
  972. _secretId = 0;
  973. LOG(("API Error: Wrong secure secret id."));
  974. if (!passwordBytes.empty()) {
  975. suggestReset(bytes::make_vector(passwordBytes));
  976. }
  977. return;
  978. } else {
  979. _secretId = serverSecretId;
  980. decryptValues();
  981. }
  982. }
  983. if (_secret.empty()) {
  984. generateSecret(passwordBytes);
  985. }
  986. _secretReady.fire({});
  987. }
  988. void FormController::suggestReset(bytes::vector password) {
  989. for (auto &[type, value] : _form.values) {
  990. // if (!value.data.original.isEmpty()) {
  991. resetValue(value);
  992. // }
  993. }
  994. _view->suggestReset([=] {
  995. const auto callback = [=](const Core::CloudPasswordResult &check) {
  996. resetSecret(check, password);
  997. };
  998. checkPasswordHash(
  999. _saveSecretRequestId,
  1000. passwordHashForAuth(bytes::make_span(password)),
  1001. callback);
  1002. _secretReady.fire({});
  1003. });
  1004. }
  1005. void FormController::resetSecret(
  1006. const Core::CloudPasswordResult &check,
  1007. const bytes::vector &password) {
  1008. using Flag = MTPDaccount_passwordInputSettings::Flag;
  1009. _saveSecretRequestId = _api.request(MTPaccount_UpdatePasswordSettings(
  1010. check.result,
  1011. MTP_account_passwordInputSettings(
  1012. MTP_flags(Flag::f_new_secure_settings),
  1013. MTPPasswordKdfAlgo(), // new_algo
  1014. MTPbytes(), // new_password_hash
  1015. MTPstring(), // hint
  1016. MTPstring(), // email
  1017. MTP_secureSecretSettings(
  1018. MTP_securePasswordKdfAlgoUnknown(), // secure_algo
  1019. MTP_bytes(), // secure_secret
  1020. MTP_long(0))) // secure_secret_id
  1021. )).done([=] {
  1022. _saveSecretRequestId = 0;
  1023. generateSecret(password);
  1024. }).fail([=](const MTP::Error &error) {
  1025. _saveSecretRequestId = 0;
  1026. if (error.type() != u"SRP_ID_INVALID"_q
  1027. || !handleSrpIdInvalid(_saveSecretRequestId)) {
  1028. formFail(error.type());
  1029. }
  1030. }).send();
  1031. }
  1032. void FormController::decryptValues() {
  1033. Expects(!_secret.empty());
  1034. for (auto &[type, value] : _form.values) {
  1035. decryptValue(value);
  1036. }
  1037. fillErrors();
  1038. fillNativeFromFallback();
  1039. }
  1040. void FormController::fillErrors() {
  1041. const auto find = [&](const MTPSecureValueType &type) -> Value* {
  1042. const auto i = _form.values.find(ConvertType(type));
  1043. if (i != end(_form.values)) {
  1044. return &i->second;
  1045. }
  1046. LOG(("API Error: Value not found for error type."));
  1047. return nullptr;
  1048. };
  1049. const auto scan = [&](
  1050. Value &value,
  1051. FileType type,
  1052. bytes::const_span hash) -> File* {
  1053. auto &list = value.files(type);
  1054. const auto i = ranges::find_if(list, [&](const File &scan) {
  1055. return !bytes::compare(hash, scan.hash);
  1056. });
  1057. if (i != end(list)) {
  1058. return &*i;
  1059. }
  1060. LOG(("API Error: File not found for error value."));
  1061. return nullptr;
  1062. };
  1063. const auto setSpecialScanError = [&](FileType type, auto &&data) {
  1064. if (const auto value = find(data.vtype())) {
  1065. if (value->requiresSpecialScan(type)) {
  1066. const auto i = value->specialScans.find(type);
  1067. if (i != value->specialScans.end()) {
  1068. i->second.error = qs(data.vtext());
  1069. } else {
  1070. LOG(("API Error: "
  1071. "Special scan %1 not found for error value."
  1072. ).arg(int(type)));
  1073. }
  1074. }
  1075. }
  1076. };
  1077. for (const auto &error : std::as_const(_form.pendingErrors)) {
  1078. error.match([&](const MTPDsecureValueError &data) {
  1079. if (const auto value = find(data.vtype())) {
  1080. if (CanHaveErrors(value->type)) {
  1081. value->error = qs(data.vtext());
  1082. }
  1083. }
  1084. }, [&](const MTPDsecureValueErrorData &data) {
  1085. if (const auto value = find(data.vtype())) {
  1086. const auto key = qs(data.vfield());
  1087. if (CanHaveErrors(value->type)
  1088. && !SkipFieldCheck(value, key)) {
  1089. value->data.parsed.fields[key].error = qs(data.vtext());
  1090. }
  1091. }
  1092. }, [&](const MTPDsecureValueErrorFile &data) {
  1093. const auto hash = bytes::make_span(data.vfile_hash().v);
  1094. if (const auto value = find(data.vtype())) {
  1095. if (const auto file = scan(*value, FileType::Scan, hash)) {
  1096. if (value->requiresScan(FileType::Scan)) {
  1097. file->error = qs(data.vtext());
  1098. }
  1099. }
  1100. }
  1101. }, [&](const MTPDsecureValueErrorFiles &data) {
  1102. if (const auto value = find(data.vtype())) {
  1103. if (value->requiresScan(FileType::Scan)) {
  1104. value->fileMissingError(FileType::Scan)
  1105. = qs(data.vtext());
  1106. }
  1107. }
  1108. }, [&](const MTPDsecureValueErrorTranslationFile &data) {
  1109. const auto hash = bytes::make_span(data.vfile_hash().v);
  1110. if (const auto value = find(data.vtype())) {
  1111. const auto file = scan(*value, FileType::Translation, hash);
  1112. if (file && value->requiresScan(FileType::Translation)) {
  1113. file->error = qs(data.vtext());
  1114. }
  1115. }
  1116. }, [&](const MTPDsecureValueErrorTranslationFiles &data) {
  1117. if (const auto value = find(data.vtype())) {
  1118. if (value->requiresScan(FileType::Translation)) {
  1119. value->fileMissingError(FileType::Translation)
  1120. = qs(data.vtext());
  1121. }
  1122. }
  1123. }, [&](const MTPDsecureValueErrorFrontSide &data) {
  1124. setSpecialScanError(FileType::FrontSide, data);
  1125. }, [&](const MTPDsecureValueErrorReverseSide &data) {
  1126. setSpecialScanError(FileType::ReverseSide, data);
  1127. }, [&](const MTPDsecureValueErrorSelfie &data) {
  1128. setSpecialScanError(FileType::Selfie, data);
  1129. });
  1130. }
  1131. }
  1132. rpl::producer<EditDocumentCountry> FormController::preferredLanguage(
  1133. const QString &countryCode) {
  1134. const auto findLang = [=] {
  1135. if (countryCode.isEmpty()) {
  1136. return QString();
  1137. }
  1138. auto &langs = _passportConfig.languagesByCountryCode;
  1139. const auto i = langs.find(countryCode);
  1140. return (i == end(langs)) ? QString() : i->second;
  1141. };
  1142. return [=](auto consumer) {
  1143. const auto hash = _passportConfig.hash;
  1144. if (hash) {
  1145. consumer.put_next({ countryCode, findLang() });
  1146. consumer.put_done();
  1147. return rpl::lifetime() ;
  1148. }
  1149. _api.request(MTPhelp_GetPassportConfig(
  1150. MTP_int(hash)
  1151. )).done([=](const MTPhelp_PassportConfig &result) {
  1152. result.match([&](const MTPDhelp_passportConfig &data) {
  1153. _passportConfig.hash = data.vhash().v;
  1154. _passportConfig.languagesByCountryCode = ParseConfig(
  1155. data.vcountries_langs().c_dataJSON().vdata().v);
  1156. }, [](const MTPDhelp_passportConfigNotModified &data) {
  1157. });
  1158. consumer.put_next({ countryCode, findLang() });
  1159. consumer.put_done();
  1160. }).fail([=] {
  1161. consumer.put_next({ countryCode, QString() });
  1162. consumer.put_done();
  1163. }).send();
  1164. return rpl::lifetime();
  1165. };
  1166. }
  1167. void FormController::fillNativeFromFallback() {
  1168. // Check if additional values (*_name_native) were requested.
  1169. const auto i = _form.values.find(Value::Type::PersonalDetails);
  1170. if (i == end(_form.values) || !i->second.nativeNames) {
  1171. return;
  1172. }
  1173. auto values = i->second.data.parsed;
  1174. // Check if additional values should be copied from fallback values.
  1175. const auto scheme = GetDocumentScheme(
  1176. Scope::Type::PersonalDetails,
  1177. std::nullopt,
  1178. true,
  1179. [=](const QString &code) { return preferredLanguage(code); });
  1180. const auto dependencyIt = values.fields.find(
  1181. scheme.additionalDependencyKey);
  1182. const auto dependency = (dependencyIt == end(values.fields))
  1183. ? QString()
  1184. : dependencyIt->second.text;
  1185. // Copy additional values from fallback if they're not filled yet.
  1186. using Scheme = EditDocumentScheme;
  1187. scheme.preferredLanguage(
  1188. dependency
  1189. ) | rpl::map(
  1190. scheme.additionalShown
  1191. ) | rpl::take(
  1192. 1
  1193. ) | rpl::start_with_next([=](Scheme::AdditionalVisibility v) {
  1194. if (v != Scheme::AdditionalVisibility::OnlyIfError) {
  1195. return;
  1196. }
  1197. auto values = i->second.data.parsed;
  1198. auto changed = false;
  1199. for (const auto &row : scheme.rows) {
  1200. if (row.valueClass == Scheme::ValueClass::Additional) {
  1201. const auto nativeIt = values.fields.find(row.key);
  1202. const auto native = (nativeIt == end(values.fields))
  1203. ? QString()
  1204. : nativeIt->second.text;
  1205. if (!native.isEmpty()
  1206. || (nativeIt != end(values.fields)
  1207. && !nativeIt->second.error.isEmpty())) {
  1208. return;
  1209. }
  1210. const auto latinIt = values.fields.find(
  1211. row.additionalFallbackKey);
  1212. const auto latin = (latinIt == end(values.fields))
  1213. ? QString()
  1214. : latinIt->second.text;
  1215. if (row.error(latin).has_value()) {
  1216. return;
  1217. } else if (native != latin) {
  1218. values.fields[row.key].text = latin;
  1219. changed = true;
  1220. }
  1221. }
  1222. }
  1223. if (changed) {
  1224. startValueEdit(&i->second);
  1225. saveValueEdit(&i->second, std::move(values));
  1226. }
  1227. }, _lifetime);
  1228. }
  1229. void FormController::decryptValue(Value &value) const {
  1230. Expects(!_secret.empty());
  1231. if (!validateValueSecrets(value)) {
  1232. resetValue(value);
  1233. return;
  1234. }
  1235. if (!value.data.original.isEmpty()) {
  1236. const auto decrypted = DecryptData(
  1237. bytes::make_span(value.data.original),
  1238. value.data.hash,
  1239. value.data.secret);
  1240. if (decrypted.empty()) {
  1241. LOG(("API Error: Could not decrypt value fields."));
  1242. resetValue(value);
  1243. return;
  1244. }
  1245. const auto fields = DeserializeData(decrypted);
  1246. value.data.parsed.fields.clear();
  1247. for (const auto &[key, text] : fields) {
  1248. value.data.parsed.fields[key] = { text };
  1249. }
  1250. }
  1251. }
  1252. bool FormController::validateValueSecrets(Value &value) const {
  1253. if (!value.data.original.isEmpty()) {
  1254. value.data.secret = DecryptValueSecret(
  1255. value.data.encryptedSecret,
  1256. _secret,
  1257. value.data.hash);
  1258. if (value.data.secret.empty()) {
  1259. LOG(("API Error: Could not decrypt data secret."));
  1260. return false;
  1261. }
  1262. }
  1263. const auto validateFileSecret = [&](File &file) {
  1264. file.secret = DecryptValueSecret(
  1265. file.encryptedSecret,
  1266. _secret,
  1267. file.hash);
  1268. if (file.secret.empty()) {
  1269. LOG(("API Error: Could not decrypt file secret."));
  1270. return false;
  1271. }
  1272. return true;
  1273. };
  1274. for (auto &scan : value.files(FileType::Scan)) {
  1275. if (!validateFileSecret(scan)) {
  1276. return false;
  1277. }
  1278. }
  1279. for (auto &scan : value.files(FileType::Translation)) {
  1280. if (!validateFileSecret(scan)) {
  1281. return false;
  1282. }
  1283. }
  1284. for (auto &[type, scan] : value.specialScans) {
  1285. if (!validateFileSecret(scan)) {
  1286. return false;
  1287. }
  1288. }
  1289. return true;
  1290. }
  1291. void FormController::resetValue(Value &value) const {
  1292. value.fillDataFrom(Value(value.type));
  1293. }
  1294. rpl::producer<QString> FormController::passwordError() const {
  1295. return _passwordError.events();
  1296. }
  1297. const PasswordSettings &FormController::passwordSettings() const {
  1298. return _password;
  1299. }
  1300. void FormController::uploadScan(
  1301. not_null<const Value*> value,
  1302. FileType type,
  1303. QByteArray &&content) {
  1304. if (!canAddScan(value, type)) {
  1305. _view->showToast(tr::lng_passport_scans_limit_reached(tr::now));
  1306. return;
  1307. }
  1308. const auto nonconst = findValue(value);
  1309. const auto fileIndex = [&]() -> std::optional<int> {
  1310. auto scanInEdit = EditFile(
  1311. &session(),
  1312. nonconst,
  1313. type,
  1314. File(),
  1315. nullptr);
  1316. if (type == FileType::Scan || type == FileType::Translation) {
  1317. auto &list = nonconst->filesInEdit(type);
  1318. list.push_back(std::move(scanInEdit));
  1319. return list.size() - 1;
  1320. }
  1321. auto i = nonconst->specialScansInEdit.find(type);
  1322. if (i != nonconst->specialScansInEdit.end()) {
  1323. i->second = std::move(scanInEdit);
  1324. } else {
  1325. i = nonconst->specialScansInEdit.emplace(
  1326. type,
  1327. std::move(scanInEdit)).first;
  1328. }
  1329. return std::nullopt;
  1330. }();
  1331. auto &scan = nonconst->fileInEdit(type, fileIndex);
  1332. encryptFile(scan, std::move(content), [=](UploadScanData &&result) {
  1333. uploadEncryptedFile(
  1334. nonconst->fileInEdit(type, fileIndex),
  1335. std::move(result));
  1336. });
  1337. }
  1338. void FormController::deleteScan(
  1339. not_null<const Value*> value,
  1340. FileType type,
  1341. std::optional<int> fileIndex) {
  1342. scanDeleteRestore(value, type, fileIndex, true);
  1343. }
  1344. void FormController::restoreScan(
  1345. not_null<const Value*> value,
  1346. FileType type,
  1347. std::optional<int> fileIndex) {
  1348. scanDeleteRestore(value, type, fileIndex, false);
  1349. }
  1350. void FormController::prepareFile(
  1351. EditFile &file,
  1352. const QByteArray &content) {
  1353. const auto fileId = base::RandomValue<uint64>();
  1354. file.fields.size = content.size();
  1355. file.fields.id = fileId;
  1356. file.fields.dcId = _controller->session().mainDcId();
  1357. file.fields.secret = GenerateSecretBytes();
  1358. file.fields.date = base::unixtime::now();
  1359. file.fields.image = ReadImage(bytes::make_span(content));
  1360. file.fields.downloadStatus.set(LoadStatus::Status::Done);
  1361. _scanUpdated.fire(&file);
  1362. }
  1363. void FormController::encryptFile(
  1364. EditFile &file,
  1365. QByteArray &&content,
  1366. Fn<void(UploadScanData &&result)> callback) {
  1367. prepareFile(file, content);
  1368. const auto weak = std::weak_ptr<bool>(file.guard);
  1369. crl::async([
  1370. =,
  1371. fileId = file.fields.id,
  1372. bytes = std::move(content),
  1373. fileSecret = file.fields.secret
  1374. ] {
  1375. auto data = EncryptData(
  1376. bytes::make_span(bytes),
  1377. fileSecret);
  1378. auto result = UploadScanData();
  1379. result.fileId = fileId;
  1380. result.hash = std::move(data.hash);
  1381. result.bytes = std::move(data.bytes);
  1382. result.md5checksum.resize(32);
  1383. hashMd5Hex(
  1384. result.bytes.data(),
  1385. result.bytes.size(),
  1386. result.md5checksum.data());
  1387. crl::on_main([=, encrypted = std::move(result)]() mutable {
  1388. if (weak.lock()) {
  1389. callback(std::move(encrypted));
  1390. }
  1391. });
  1392. });
  1393. }
  1394. void FormController::scanDeleteRestore(
  1395. not_null<const Value*> value,
  1396. FileType type,
  1397. std::optional<int> fileIndex,
  1398. bool deleted) {
  1399. const auto nonconst = findValue(value);
  1400. auto &scan = nonconst->fileInEdit(type, fileIndex);
  1401. if (scan.deleted && !deleted) {
  1402. if (!canAddScan(value, type)) {
  1403. _view->showToast(tr::lng_passport_scans_limit_reached(tr::now));
  1404. return;
  1405. }
  1406. }
  1407. scan.deleted = deleted;
  1408. _scanUpdated.fire(&scan);
  1409. }
  1410. bool FormController::canAddScan(
  1411. not_null<const Value*> value,
  1412. FileType type) const {
  1413. const auto limit = (type == FileType::Scan)
  1414. ? kDocumentScansLimit
  1415. : (type == FileType::Translation)
  1416. ? kTranslationScansLimit
  1417. : -1;
  1418. if (limit < 0) {
  1419. return true;
  1420. }
  1421. const auto scansCount = ranges::count_if(
  1422. value->filesInEdit(type),
  1423. [](const EditFile &scan) { return !scan.deleted; });
  1424. return (scansCount < limit);
  1425. }
  1426. void FormController::subscribeToUploader() {
  1427. if (_uploaderSubscriptions) {
  1428. return;
  1429. }
  1430. using namespace Storage;
  1431. session().uploader().secureReady(
  1432. ) | rpl::start_with_next([=](const UploadSecureDone &data) {
  1433. scanUploadDone(data);
  1434. }, _uploaderSubscriptions);
  1435. session().uploader().secureProgress(
  1436. ) | rpl::start_with_next([=](const UploadSecureProgress &data) {
  1437. scanUploadProgress(data);
  1438. }, _uploaderSubscriptions);
  1439. session().uploader().secureFailed(
  1440. ) | rpl::start_with_next([=](const FullMsgId &fullId) {
  1441. scanUploadFail(fullId);
  1442. }, _uploaderSubscriptions);
  1443. }
  1444. void FormController::uploadEncryptedFile(
  1445. EditFile &file,
  1446. UploadScanData &&data) {
  1447. subscribeToUploader();
  1448. file.uploadData = UploadScanDataPointer(
  1449. &session(),
  1450. std::make_unique<UploadScanData>(std::move(data)));
  1451. auto prepared = MakePreparedFile({
  1452. .id = file.uploadData->fileId,
  1453. .type = SendMediaType::Secure,
  1454. });
  1455. prepared->content = QByteArray::fromRawData(
  1456. reinterpret_cast<char*>(file.uploadData->bytes.data()),
  1457. file.uploadData->bytes.size());
  1458. prepared->setFileData(prepared->content);
  1459. prepared->filemd5 = file.uploadData->md5checksum;
  1460. file.uploadData->fullId = FullMsgId(
  1461. session().userPeerId(),
  1462. session().data().nextLocalMessageId());
  1463. file.uploadData->status.set(LoadStatus::Status::InProgress, 0);
  1464. session().uploader().upload(
  1465. file.uploadData->fullId,
  1466. std::move(prepared));
  1467. }
  1468. void FormController::scanUploadDone(const Storage::UploadSecureDone &data) {
  1469. if (const auto file = findEditFile(data.fullId)) {
  1470. Assert(file->uploadData != nullptr);
  1471. Assert(file->uploadData->fileId == data.fileId);
  1472. file->uploadData->partsCount = data.partsCount;
  1473. file->fields.hash = std::move(file->uploadData->hash);
  1474. file->fields.encryptedSecret = EncryptValueSecret(
  1475. file->fields.secret,
  1476. _secret,
  1477. file->fields.hash);
  1478. file->uploadData->fullId = FullMsgId();
  1479. file->uploadData->status.set(LoadStatus::Status::Done);
  1480. _scanUpdated.fire(file);
  1481. }
  1482. }
  1483. void FormController::scanUploadProgress(
  1484. const Storage::UploadSecureProgress &data) {
  1485. if (const auto file = findEditFile(data.fullId)) {
  1486. Assert(file->uploadData != nullptr);
  1487. file->uploadData->status.set(
  1488. LoadStatus::Status::InProgress,
  1489. data.offset);
  1490. _scanUpdated.fire(file);
  1491. }
  1492. }
  1493. void FormController::scanUploadFail(const FullMsgId &fullId) {
  1494. if (const auto file = findEditFile(fullId)) {
  1495. Assert(file->uploadData != nullptr);
  1496. file->uploadData->status.set(LoadStatus::Status::Failed);
  1497. _scanUpdated.fire(file);
  1498. }
  1499. }
  1500. rpl::producer<> FormController::secretReadyEvents() const {
  1501. return _secretReady.events();
  1502. }
  1503. QString FormController::defaultEmail() const {
  1504. return _password.confirmedEmail;
  1505. }
  1506. QString FormController::defaultPhoneNumber() const {
  1507. return session().user()->phone();
  1508. }
  1509. auto FormController::scanUpdated() const
  1510. -> rpl::producer<not_null<const EditFile*>> {
  1511. return _scanUpdated.events();
  1512. }
  1513. auto FormController::valueSaveFinished() const
  1514. -> rpl::producer<not_null<const Value*>> {
  1515. return _valueSaveFinished.events();
  1516. }
  1517. auto FormController::verificationNeeded() const
  1518. -> rpl::producer<not_null<const Value*>> {
  1519. return _verificationNeeded.events();
  1520. }
  1521. auto FormController::verificationUpdate() const
  1522. -> rpl::producer<not_null<const Value*>> {
  1523. return _verificationUpdate.events();
  1524. }
  1525. void FormController::verify(
  1526. not_null<const Value*> value,
  1527. const QString &code) {
  1528. if (value->verification.requestId) {
  1529. return;
  1530. }
  1531. const auto nonconst = findValue(value);
  1532. const auto prepared = code.trimmed();
  1533. Assert(nonconst->verification.codeLength != 0);
  1534. verificationError(nonconst, QString());
  1535. if (nonconst->verification.codeLength > 0
  1536. && nonconst->verification.codeLength != prepared.size()) {
  1537. verificationError(nonconst, tr::lng_signin_wrong_code(tr::now));
  1538. return;
  1539. } else if (prepared.isEmpty()) {
  1540. verificationError(nonconst, tr::lng_signin_wrong_code(tr::now));
  1541. return;
  1542. }
  1543. nonconst->verification.requestId = [&] {
  1544. switch (nonconst->type) {
  1545. case Value::Type::Phone:
  1546. return _api.request(MTPaccount_VerifyPhone(
  1547. MTP_string(getPhoneFromValue(nonconst)),
  1548. MTP_string(nonconst->verification.phoneCodeHash),
  1549. MTP_string(prepared)
  1550. )).done([=](const MTPBool &result) {
  1551. savePlainTextValue(nonconst);
  1552. clearValueVerification(nonconst);
  1553. }).fail([=](const MTP::Error &error) {
  1554. nonconst->verification.requestId = 0;
  1555. if (error.type() == u"PHONE_CODE_INVALID"_q) {
  1556. verificationError(
  1557. nonconst,
  1558. tr::lng_signin_wrong_code(tr::now));
  1559. } else {
  1560. verificationError(nonconst, error.type());
  1561. }
  1562. }).send();
  1563. case Value::Type::Email:
  1564. return _api.request(MTPaccount_VerifyEmail(
  1565. MTP_emailVerifyPurposePassport(),
  1566. MTP_emailVerificationCode(MTP_string(prepared))
  1567. )).done([=](const MTPaccount_EmailVerified &result) {
  1568. savePlainTextValue(nonconst);
  1569. clearValueVerification(nonconst);
  1570. }).fail([=](const MTP::Error &error) {
  1571. nonconst->verification.requestId = 0;
  1572. if (error.type() == u"CODE_INVALID"_q) {
  1573. verificationError(
  1574. nonconst,
  1575. tr::lng_signin_wrong_code(tr::now));
  1576. } else {
  1577. verificationError(nonconst, error.type());
  1578. }
  1579. }).send();
  1580. }
  1581. Unexpected("Type in FormController::verify().");
  1582. }();
  1583. }
  1584. void FormController::verificationError(
  1585. not_null<Value*> value,
  1586. const QString &text) {
  1587. value->verification.error = text;
  1588. _verificationUpdate.fire_copy(value);
  1589. }
  1590. const Form &FormController::form() const {
  1591. return _form;
  1592. }
  1593. not_null<Value*> FormController::findValue(not_null<const Value*> value) {
  1594. const auto i = _form.values.find(value->type);
  1595. Assert(i != end(_form.values));
  1596. const auto result = &i->second;
  1597. Ensures(result == value);
  1598. return result;
  1599. }
  1600. void FormController::startValueEdit(not_null<const Value*> value) {
  1601. const auto nonconst = findValue(value);
  1602. ++nonconst->editScreens;
  1603. if (nonconst->saving()) {
  1604. return;
  1605. }
  1606. for (auto &scan : nonconst->files(FileType::Scan)) {
  1607. loadFile(scan);
  1608. }
  1609. if (nonconst->translationRequired) {
  1610. for (auto &scan : nonconst->files(FileType::Translation)) {
  1611. loadFile(scan);
  1612. }
  1613. }
  1614. for (auto &[type, scan] : nonconst->specialScans) {
  1615. if (nonconst->requiresSpecialScan(type)) {
  1616. loadFile(scan);
  1617. }
  1618. }
  1619. nonconst->saveInEdit(&session());
  1620. }
  1621. void FormController::loadFile(File &file) {
  1622. if (!file.image.isNull()) {
  1623. file.downloadStatus.set(LoadStatus::Status::Done);
  1624. return;
  1625. }
  1626. const auto key = FileKey{ file.id };
  1627. const auto i = _fileLoaders.find(key);
  1628. if (i != _fileLoaders.end()) {
  1629. return;
  1630. }
  1631. file.downloadStatus.set(LoadStatus::Status::InProgress, 0);
  1632. const auto &[j, ok] = _fileLoaders.emplace(
  1633. key,
  1634. std::make_unique<mtpFileLoader>(
  1635. &_controller->session(),
  1636. StorageFileLocation(
  1637. file.dcId,
  1638. session().userId(),
  1639. MTP_inputSecureFileLocation(
  1640. MTP_long(file.id),
  1641. MTP_long(file.accessHash))),
  1642. Data::FileOrigin(),
  1643. SecureFileLocation,
  1644. QString(),
  1645. file.size,
  1646. file.size,
  1647. LoadToCacheAsWell,
  1648. LoadFromCloudOrLocal,
  1649. false,
  1650. Data::kImageCacheTag));
  1651. const auto loader = j->second.get();
  1652. loader->updates(
  1653. ) | rpl::start_with_next_error_done([=] {
  1654. fileLoadProgress(key, loader->currentOffset());
  1655. }, [=](FileLoader::Error error) {
  1656. fileLoadFail(key);
  1657. }, [=] {
  1658. fileLoadDone(key, loader->bytes());
  1659. }, loader->lifetime());
  1660. loader->start();
  1661. }
  1662. void FormController::fileLoadDone(FileKey key, const QByteArray &bytes) {
  1663. if (const auto &[value, file] = findFile(key); file != nullptr) {
  1664. const auto decrypted = DecryptData(
  1665. bytes::make_span(bytes),
  1666. file->hash,
  1667. file->secret);
  1668. if (decrypted.empty()) {
  1669. fileLoadFail(key);
  1670. return;
  1671. }
  1672. file->downloadStatus.set(LoadStatus::Status::Done);
  1673. file->image = ReadImage(gsl::make_span(decrypted));
  1674. if (const auto fileInEdit = findEditFile(key)) {
  1675. fileInEdit->fields.image = file->image;
  1676. fileInEdit->fields.downloadStatus = file->downloadStatus;
  1677. _scanUpdated.fire(fileInEdit);
  1678. }
  1679. }
  1680. }
  1681. void FormController::fileLoadProgress(FileKey key, int offset) {
  1682. if (const auto &[value, file] = findFile(key); file != nullptr) {
  1683. file->downloadStatus.set(LoadStatus::Status::InProgress, offset);
  1684. if (const auto fileInEdit = findEditFile(key)) {
  1685. fileInEdit->fields.downloadStatus = file->downloadStatus;
  1686. _scanUpdated.fire(fileInEdit);
  1687. }
  1688. }
  1689. }
  1690. void FormController::fileLoadFail(FileKey key) {
  1691. if (const auto &[value, file] = findFile(key); file != nullptr) {
  1692. file->downloadStatus.set(LoadStatus::Status::Failed);
  1693. if (const auto fileInEdit = findEditFile(key)) {
  1694. fileInEdit->fields.downloadStatus = file->downloadStatus;
  1695. _scanUpdated.fire(fileInEdit);
  1696. }
  1697. }
  1698. }
  1699. void FormController::cancelValueEdit(not_null<const Value*> value) {
  1700. Expects(value->editScreens > 0);
  1701. const auto nonconst = findValue(value);
  1702. --nonconst->editScreens;
  1703. clearValueEdit(nonconst);
  1704. }
  1705. void FormController::valueEditFailed(not_null<Value*> value) {
  1706. Expects(!value->saving());
  1707. if (value->editScreens == 0) {
  1708. clearValueEdit(value);
  1709. }
  1710. }
  1711. void FormController::clearValueEdit(not_null<Value*> value) {
  1712. if (value->saving()) {
  1713. return;
  1714. }
  1715. value->clearEditData();
  1716. }
  1717. void FormController::cancelValueVerification(not_null<const Value*> value) {
  1718. const auto nonconst = findValue(value);
  1719. clearValueVerification(nonconst);
  1720. if (!nonconst->saving()) {
  1721. valueEditFailed(nonconst);
  1722. }
  1723. }
  1724. void FormController::clearValueVerification(not_null<Value*> value) {
  1725. const auto was = (value->verification.codeLength != 0);
  1726. if (const auto requestId = base::take(value->verification.requestId)) {
  1727. _api.request(requestId).cancel();
  1728. }
  1729. value->verification = Verification();
  1730. if (was) {
  1731. _verificationUpdate.fire_copy(value);
  1732. }
  1733. }
  1734. bool FormController::isEncryptedValue(Value::Type type) const {
  1735. return (type != Value::Type::Phone && type != Value::Type::Email);
  1736. }
  1737. void FormController::saveValueEdit(
  1738. not_null<const Value*> value,
  1739. ValueMap &&data) {
  1740. if (value->saving() || _submitRequestId) {
  1741. return;
  1742. }
  1743. // If we didn't change anything, we don't send save request
  1744. // and we don't reset value->error/[scan|translation]MissingError.
  1745. // Otherwise we reset them after save by re-parsing the value.
  1746. const auto nonconst = findValue(value);
  1747. if (!ValueChanged(nonconst, data)) {
  1748. nonconst->saveRequestId = -1;
  1749. crl::on_main(this, [=] {
  1750. nonconst->clearEditData();
  1751. nonconst->saveRequestId = 0;
  1752. _valueSaveFinished.fire_copy(nonconst);
  1753. });
  1754. return;
  1755. }
  1756. ApplyDataChanges(nonconst->data, std::move(data));
  1757. if (isEncryptedValue(nonconst->type)) {
  1758. saveEncryptedValue(nonconst);
  1759. } else {
  1760. savePlainTextValue(nonconst);
  1761. }
  1762. }
  1763. void FormController::deleteValueEdit(not_null<const Value*> value) {
  1764. if (value->saving() || _submitRequestId) {
  1765. return;
  1766. }
  1767. const auto nonconst = findValue(value);
  1768. nonconst->saveRequestId = _api.request(MTPaccount_DeleteSecureValue(
  1769. MTP_vector<MTPSecureValueType>(1, ConvertType(nonconst->type))
  1770. )).done([=] {
  1771. resetValue(*nonconst);
  1772. _valueSaveFinished.fire_copy(value);
  1773. }).fail([=](const MTP::Error &error) {
  1774. nonconst->saveRequestId = 0;
  1775. valueSaveShowError(nonconst, error);
  1776. }).send();
  1777. }
  1778. void FormController::saveEncryptedValue(not_null<Value*> value) {
  1779. Expects(isEncryptedValue(value->type));
  1780. if (_secret.empty()) {
  1781. _secretCallbacks.push_back([=] {
  1782. saveEncryptedValue(value);
  1783. });
  1784. return;
  1785. }
  1786. const auto wrapFile = [](const EditFile &file) {
  1787. if (const auto uploadData = file.uploadData.get()) {
  1788. return MTP_inputSecureFileUploaded(
  1789. MTP_long(file.fields.id),
  1790. MTP_int(uploadData->partsCount),
  1791. MTP_bytes(uploadData->md5checksum),
  1792. MTP_bytes(file.fields.hash),
  1793. MTP_bytes(file.fields.encryptedSecret));
  1794. }
  1795. return MTP_inputSecureFile(
  1796. MTP_long(file.fields.id),
  1797. MTP_long(file.fields.accessHash));
  1798. };
  1799. const auto wrapList = [&](not_null<const Value*> value, FileType type) {
  1800. const auto &list = value->filesInEdit(type);
  1801. auto result = QVector<MTPInputSecureFile>();
  1802. result.reserve(list.size());
  1803. for (const auto &scan : value->filesInEdit(type)) {
  1804. if (scan.deleted) {
  1805. continue;
  1806. }
  1807. result.push_back(wrapFile(scan));
  1808. }
  1809. return result;
  1810. };
  1811. const auto files = wrapList(value, FileType::Scan);
  1812. const auto translations = wrapList(value, FileType::Translation);
  1813. if (value->data.secret.empty()) {
  1814. value->data.secret = GenerateSecretBytes();
  1815. }
  1816. const auto encryptedData = EncryptData(
  1817. SerializeData(GetTexts(value->data.parsedInEdit)),
  1818. value->data.secret);
  1819. value->data.hashInEdit = encryptedData.hash;
  1820. value->data.encryptedSecretInEdit = EncryptValueSecret(
  1821. value->data.secret,
  1822. _secret,
  1823. value->data.hashInEdit);
  1824. const auto hasSpecialFile = [&](FileType type) {
  1825. const auto i = value->specialScansInEdit.find(type);
  1826. return (i != end(value->specialScansInEdit) && !i->second.deleted);
  1827. };
  1828. const auto specialFile = [&](FileType type) {
  1829. const auto i = value->specialScansInEdit.find(type);
  1830. return (i != end(value->specialScansInEdit) && !i->second.deleted)
  1831. ? wrapFile(i->second)
  1832. : MTPInputSecureFile();
  1833. };
  1834. const auto frontSide = specialFile(FileType::FrontSide);
  1835. const auto reverseSide = specialFile(FileType::ReverseSide);
  1836. const auto selfie = specialFile(FileType::Selfie);
  1837. const auto type = ConvertType(value->type);
  1838. const auto flags = (value->data.parsedInEdit.fields.empty()
  1839. ? MTPDinputSecureValue::Flag(0)
  1840. : MTPDinputSecureValue::Flag::f_data)
  1841. | (hasSpecialFile(FileType::FrontSide)
  1842. ? MTPDinputSecureValue::Flag::f_front_side
  1843. : MTPDinputSecureValue::Flag(0))
  1844. | (hasSpecialFile(FileType::ReverseSide)
  1845. ? MTPDinputSecureValue::Flag::f_reverse_side
  1846. : MTPDinputSecureValue::Flag(0))
  1847. | (hasSpecialFile(FileType::Selfie)
  1848. ? MTPDinputSecureValue::Flag::f_selfie
  1849. : MTPDinputSecureValue::Flag(0))
  1850. | (translations.empty()
  1851. ? MTPDinputSecureValue::Flag(0)
  1852. : MTPDinputSecureValue::Flag::f_translation)
  1853. | (files.empty()
  1854. ? MTPDinputSecureValue::Flag(0)
  1855. : MTPDinputSecureValue::Flag::f_files);
  1856. Assert(flags != MTPDinputSecureValue::Flags(0));
  1857. sendSaveRequest(value, MTP_inputSecureValue(
  1858. MTP_flags(flags),
  1859. type,
  1860. MTP_secureData(
  1861. MTP_bytes(encryptedData.bytes),
  1862. MTP_bytes(value->data.hashInEdit),
  1863. MTP_bytes(value->data.encryptedSecretInEdit)),
  1864. frontSide,
  1865. reverseSide,
  1866. selfie,
  1867. MTP_vector<MTPInputSecureFile>(translations),
  1868. MTP_vector<MTPInputSecureFile>(files),
  1869. MTPSecurePlainData()));
  1870. }
  1871. void FormController::savePlainTextValue(not_null<Value*> value) {
  1872. Expects(!isEncryptedValue(value->type));
  1873. const auto text = getPlainTextFromValue(value);
  1874. const auto type = [&] {
  1875. switch (value->type) {
  1876. case Value::Type::Phone: return MTP_secureValueTypePhone();
  1877. case Value::Type::Email: return MTP_secureValueTypeEmail();
  1878. }
  1879. Unexpected("Value type in savePlainTextValue().");
  1880. }();
  1881. const auto plain = [&] {
  1882. switch (value->type) {
  1883. case Value::Type::Phone: return MTP_securePlainPhone;
  1884. case Value::Type::Email: return MTP_securePlainEmail;
  1885. }
  1886. Unexpected("Value type in savePlainTextValue().");
  1887. }();
  1888. sendSaveRequest(value, MTP_inputSecureValue(
  1889. MTP_flags(MTPDinputSecureValue::Flag::f_plain_data),
  1890. type,
  1891. MTPSecureData(),
  1892. MTPInputSecureFile(),
  1893. MTPInputSecureFile(),
  1894. MTPInputSecureFile(),
  1895. MTPVector<MTPInputSecureFile>(),
  1896. MTPVector<MTPInputSecureFile>(),
  1897. plain(MTP_string(text))));
  1898. }
  1899. void FormController::sendSaveRequest(
  1900. not_null<Value*> value,
  1901. const MTPInputSecureValue &data) {
  1902. Expects(value->saveRequestId == 0);
  1903. value->saveRequestId = _api.request(MTPaccount_SaveSecureValue(
  1904. data,
  1905. MTP_long(_secretId)
  1906. )).done([=](const MTPSecureValue &result) {
  1907. auto scansInEdit = value->takeAllFilesInEdit();
  1908. auto refreshed = parseValue(result, scansInEdit);
  1909. decryptValue(refreshed);
  1910. value->fillDataFrom(std::move(refreshed));
  1911. _valueSaveFinished.fire_copy(value);
  1912. }).fail([=](const MTP::Error &error) {
  1913. value->saveRequestId = 0;
  1914. const auto code = error.type();
  1915. if (handleAppUpdateError(code)) {
  1916. } else if (code == u"PHONE_VERIFICATION_NEEDED"_q) {
  1917. if (value->type == Value::Type::Phone) {
  1918. startPhoneVerification(value);
  1919. return;
  1920. }
  1921. } else if (code == u"PHONE_NUMBER_INVALID"_q) {
  1922. if (value->type == Value::Type::Phone) {
  1923. value->data.parsedInEdit.fields["value"].error
  1924. = tr::lng_bad_phone(tr::now);
  1925. valueSaveFailed(value);
  1926. return;
  1927. }
  1928. } else if (code == u"EMAIL_VERIFICATION_NEEDED"_q) {
  1929. if (value->type == Value::Type::Email) {
  1930. startEmailVerification(value);
  1931. return;
  1932. }
  1933. } else if (code == u"EMAIL_INVALID"_q) {
  1934. if (value->type == Value::Type::Email) {
  1935. value->data.parsedInEdit.fields["value"].error
  1936. = tr::lng_cloud_password_bad_email(tr::now);
  1937. valueSaveFailed(value);
  1938. return;
  1939. }
  1940. }
  1941. if (SaveErrorRequiresRestart(code)) {
  1942. suggestRestart();
  1943. } else {
  1944. valueSaveShowError(value, error);
  1945. }
  1946. }).send();
  1947. }
  1948. QString FormController::getPhoneFromValue(
  1949. not_null<const Value*> value) const {
  1950. Expects(value->type == Value::Type::Phone);
  1951. return getPlainTextFromValue(value);
  1952. }
  1953. QString FormController::getEmailFromValue(
  1954. not_null<const Value*> value) const {
  1955. Expects(value->type == Value::Type::Email);
  1956. return getPlainTextFromValue(value);
  1957. }
  1958. QString FormController::getPlainTextFromValue(
  1959. not_null<const Value*> value) const {
  1960. Expects(value->type == Value::Type::Phone
  1961. || value->type == Value::Type::Email);
  1962. const auto i = value->data.parsedInEdit.fields.find("value");
  1963. Assert(i != end(value->data.parsedInEdit.fields));
  1964. return i->second.text;
  1965. }
  1966. void FormController::startPhoneVerification(not_null<Value*> value) {
  1967. value->verification.requestId = _api.request(MTPaccount_SendVerifyPhoneCode(
  1968. MTP_string(getPhoneFromValue(value)),
  1969. MTP_codeSettings(
  1970. MTP_flags(0),
  1971. MTPVector<MTPbytes>(),
  1972. MTPstring(),
  1973. MTPBool())
  1974. )).done([=](const MTPauth_SentCode &result) {
  1975. result.match([&](const MTPDauth_sentCode &data) {
  1976. const auto next = data.vnext_type();
  1977. const auto timeout = data.vtimeout();
  1978. value->verification.requestId = 0;
  1979. value->verification.phoneCodeHash = qs(data.vphone_code_hash());
  1980. value->verification.fragmentUrl = QString();
  1981. const auto bad = [](const char *type) {
  1982. LOG(("API Error: Should not be '%1' "
  1983. "in FormController::startPhoneVerification.").arg(type));
  1984. };
  1985. data.vtype().match([&](const MTPDauth_sentCodeTypeApp &) {
  1986. LOG(("API Error: sentCodeTypeApp not expected "
  1987. "in FormController::startPhoneVerification."));
  1988. }, [&](const MTPDauth_sentCodeTypeCall &data) {
  1989. value->verification.codeLength = (data.vlength().v > 0)
  1990. ? data.vlength().v
  1991. : -1;
  1992. value->verification.call = std::make_unique<Ui::SentCodeCall>(
  1993. [=] { requestPhoneCall(value); },
  1994. [=] { _verificationUpdate.fire_copy(value); });
  1995. value->verification.call->setStatus(
  1996. { Ui::SentCodeCall::State::Called, 0 });
  1997. if (next) {
  1998. LOG(("API Error: next_type is not supported for calls."));
  1999. }
  2000. }, [&](const MTPDauth_sentCodeTypeSms &data) {
  2001. value->verification.codeLength = (data.vlength().v > 0)
  2002. ? data.vlength().v
  2003. : -1;
  2004. if (next && next->type() == mtpc_auth_codeTypeCall) {
  2005. value->verification.call = std::make_unique<Ui::SentCodeCall>(
  2006. [=] { requestPhoneCall(value); },
  2007. [=] { _verificationUpdate.fire_copy(value); });
  2008. value->verification.call->setStatus({
  2009. Ui::SentCodeCall::State::Waiting,
  2010. timeout.value_or(60),
  2011. });
  2012. }
  2013. }, [&](const MTPDauth_sentCodeTypeFragmentSms &data) {
  2014. value->verification.codeLength = data.vlength().v;
  2015. value->verification.fragmentUrl = qs(data.vurl());
  2016. value->verification.call = nullptr;
  2017. }, [&](const MTPDauth_sentCodeTypeFlashCall &) {
  2018. bad("FlashCall");
  2019. }, [&](const MTPDauth_sentCodeTypeMissedCall &) {
  2020. bad("MissedCall");
  2021. }, [&](const MTPDauth_sentCodeTypeFirebaseSms &) {
  2022. bad("FirebaseSms");
  2023. }, [&](const MTPDauth_sentCodeTypeEmailCode &) {
  2024. bad("EmailCode");
  2025. }, [&](const MTPDauth_sentCodeTypeSmsWord &) {
  2026. bad("SmsWord");
  2027. }, [&](const MTPDauth_sentCodeTypeSmsPhrase &) {
  2028. bad("SmsPhrase");
  2029. }, [&](const MTPDauth_sentCodeTypeSetUpEmailRequired &) {
  2030. bad("SetUpEmailRequired");
  2031. });
  2032. _verificationNeeded.fire_copy(value);
  2033. }, [](const MTPDauth_sentCodeSuccess &) {
  2034. LOG(("API Error: Unexpected auth.sentCodeSuccess "
  2035. "(FormController::startPhoneVerification)."));
  2036. });
  2037. }).fail([=](const MTP::Error &error) {
  2038. value->verification.requestId = 0;
  2039. valueSaveShowError(value, error);
  2040. }).send();
  2041. }
  2042. void FormController::startEmailVerification(not_null<Value*> value) {
  2043. value->verification.requestId = _api.request(
  2044. MTPaccount_SendVerifyEmailCode(
  2045. MTP_emailVerifyPurposePassport(),
  2046. MTP_string(getEmailFromValue(value)))
  2047. ).done([=](const MTPaccount_SentEmailCode &result) {
  2048. Expects(result.type() == mtpc_account_sentEmailCode);
  2049. value->verification.requestId = 0;
  2050. const auto &data = result.c_account_sentEmailCode();
  2051. value->verification.codeLength = (data.vlength().v > 0)
  2052. ? data.vlength().v
  2053. : -1;
  2054. _verificationNeeded.fire_copy(value);
  2055. }).fail([=](const MTP::Error &error) {
  2056. valueSaveShowError(value, error);
  2057. }).send();
  2058. }
  2059. void FormController::requestPhoneCall(not_null<Value*> value) {
  2060. Expects(value->verification.call != nullptr);
  2061. value->verification.call->setStatus(
  2062. { Ui::SentCodeCall::State::Calling, 0 });
  2063. _api.request(MTPauth_ResendCode(
  2064. MTP_flags(0),
  2065. MTP_string(getPhoneFromValue(value)),
  2066. MTP_string(value->verification.phoneCodeHash),
  2067. MTPstring() // reason
  2068. )).done([=] {
  2069. value->verification.call->callDone();
  2070. }).send();
  2071. }
  2072. void FormController::valueSaveShowError(
  2073. not_null<Value*> value,
  2074. const MTP::Error &error) {
  2075. _view->show(Ui::MakeInformBox(
  2076. Lang::Hard::SecureSaveError() + "\n" + error.type()));
  2077. valueSaveFailed(value);
  2078. }
  2079. void FormController::valueSaveFailed(not_null<Value*> value) {
  2080. valueEditFailed(value);
  2081. _valueSaveFinished.fire_copy(value);
  2082. }
  2083. void FormController::generateSecret(bytes::const_span password) {
  2084. Expects(!password.empty());
  2085. if (_saveSecretRequestId) {
  2086. return;
  2087. }
  2088. auto secret = GenerateSecretBytes();
  2089. auto saved = SavedCredentials();
  2090. saved.hashForAuth = _passwordCheckHash;
  2091. saved.hashForSecret = Core::ComputeSecureSecretHash(
  2092. _password.newSecureAlgo,
  2093. password);
  2094. saved.secretId = CountSecureSecretId(secret);
  2095. const auto callback = [=](const Core::CloudPasswordResult &check) {
  2096. saveSecret(check, saved, secret);
  2097. };
  2098. checkPasswordHash(_saveSecretRequestId, saved.hashForAuth, callback);
  2099. }
  2100. void FormController::saveSecret(
  2101. const Core::CloudPasswordResult &check,
  2102. const SavedCredentials &saved,
  2103. const bytes::vector &secret) {
  2104. const auto encryptedSecret = EncryptSecureSecret(
  2105. secret,
  2106. saved.hashForSecret);
  2107. using Flag = MTPDaccount_passwordInputSettings::Flag;
  2108. _saveSecretRequestId = _api.request(MTPaccount_UpdatePasswordSettings(
  2109. check.result,
  2110. MTP_account_passwordInputSettings(
  2111. MTP_flags(Flag::f_new_secure_settings),
  2112. MTPPasswordKdfAlgo(), // new_algo
  2113. MTPbytes(), // new_password_hash
  2114. MTPstring(), // hint
  2115. MTPstring(), // email
  2116. MTP_secureSecretSettings(
  2117. Core::PrepareSecureSecretAlgo(_password.newSecureAlgo),
  2118. MTP_bytes(encryptedSecret),
  2119. MTP_long(saved.secretId)))
  2120. )).done([=] {
  2121. session().data().rememberPassportCredentials(
  2122. std::move(saved),
  2123. kRememberCredentialsDelay);
  2124. _saveSecretRequestId = 0;
  2125. _secret = secret;
  2126. _secretId = saved.secretId;
  2127. //_password.salt = newPasswordSaltFull;
  2128. for (const auto &callback : base::take(_secretCallbacks)) {
  2129. callback();
  2130. }
  2131. }).fail([=](const MTP::Error &error) {
  2132. _saveSecretRequestId = 0;
  2133. if (error.type() != u"SRP_ID_INVALID"_q
  2134. || !handleSrpIdInvalid(_saveSecretRequestId)) {
  2135. suggestRestart();
  2136. }
  2137. }).send();
  2138. }
  2139. void FormController::suggestRestart() {
  2140. _suggestingRestart = true;
  2141. _view->show(Ui::MakeConfirmBox({
  2142. .text = tr::lng_passport_restart_sure(),
  2143. .confirmed = [=] { _controller->showPassportForm(_request); },
  2144. .cancelled = [=] { cancel(); },
  2145. .confirmText = tr::lng_passport_restart(),
  2146. }));
  2147. }
  2148. void FormController::requestForm() {
  2149. if (_request.nonce.isEmpty()) {
  2150. _formRequestId = -1;
  2151. formFail(NonceNameByScope(_request.scope).toUpper() + "_EMPTY");
  2152. return;
  2153. }
  2154. _formRequestId = _api.request(MTPaccount_GetAuthorizationForm(
  2155. MTP_long(_request.botId.bare),
  2156. MTP_string(_request.scope),
  2157. MTP_string(_request.publicKey)
  2158. )).done([=](const MTPaccount_AuthorizationForm &result) {
  2159. _formRequestId = 0;
  2160. formDone(result);
  2161. }).fail([=](const MTP::Error &error) {
  2162. formFail(error.type());
  2163. }).send();
  2164. }
  2165. auto FormController::parseFiles(
  2166. const QVector<MTPSecureFile> &data,
  2167. const std::vector<EditFile> &editData) const
  2168. -> std::vector<File> {
  2169. auto result = std::vector<File>();
  2170. result.reserve(data.size());
  2171. for (const auto &file : data) {
  2172. if (auto normal = parseFile(file, editData)) {
  2173. result.push_back(std::move(*normal));
  2174. }
  2175. }
  2176. return result;
  2177. }
  2178. auto FormController::parseFile(
  2179. const MTPSecureFile &data,
  2180. const std::vector<EditFile> &editData) const
  2181. -> std::optional<File> {
  2182. switch (data.type()) {
  2183. case mtpc_secureFileEmpty:
  2184. return std::nullopt;
  2185. case mtpc_secureFile: {
  2186. const auto &fields = data.c_secureFile();
  2187. auto result = File();
  2188. result.id = fields.vid().v;
  2189. result.accessHash = fields.vaccess_hash().v;
  2190. result.size = fields.vsize().v;
  2191. result.date = fields.vdate().v;
  2192. result.dcId = fields.vdc_id().v;
  2193. result.hash = bytes::make_vector(fields.vfile_hash().v);
  2194. result.encryptedSecret = bytes::make_vector(fields.vsecret().v);
  2195. fillDownloadedFile(result, editData);
  2196. return result;
  2197. } break;
  2198. }
  2199. Unexpected("Type in FormController::parseFile.");
  2200. }
  2201. void FormController::fillDownloadedFile(
  2202. File &destination,
  2203. const std::vector<EditFile> &source) const {
  2204. const auto i = ranges::find(
  2205. source,
  2206. destination.hash,
  2207. [](const EditFile &file) { return file.fields.hash; });
  2208. if (i == source.end()) {
  2209. return;
  2210. }
  2211. destination.image = i->fields.image;
  2212. destination.downloadStatus = i->fields.downloadStatus;
  2213. if (!i->uploadData) {
  2214. return;
  2215. }
  2216. const auto &bytes = i->uploadData->bytes;
  2217. if (bytes.size() > Storage::kMaxFileInMemory) {
  2218. return;
  2219. }
  2220. session().data().cache().put(
  2221. Data::DocumentCacheKey(destination.dcId, destination.id),
  2222. Storage::Cache::Database::TaggedValue(
  2223. QByteArray(
  2224. reinterpret_cast<const char*>(bytes.data()),
  2225. bytes.size()),
  2226. Data::kImageCacheTag));
  2227. }
  2228. auto FormController::parseValue(
  2229. const MTPSecureValue &value,
  2230. const std::vector<EditFile> &editData) const -> Value {
  2231. Expects(value.type() == mtpc_secureValue);
  2232. const auto &data = value.c_secureValue();
  2233. const auto type = ConvertType(data.vtype());
  2234. auto result = Value(type);
  2235. result.submitHash = bytes::make_vector(data.vhash().v);
  2236. if (const auto secureData = data.vdata()) {
  2237. secureData->match([&](const MTPDsecureData &data) {
  2238. result.data.original = data.vdata().v;
  2239. result.data.hash = bytes::make_vector(data.vdata_hash().v);
  2240. result.data.encryptedSecret = bytes::make_vector(data.vsecret().v);
  2241. });
  2242. }
  2243. if (const auto files = data.vfiles()) {
  2244. result.files(FileType::Scan) = parseFiles(files->v, editData);
  2245. }
  2246. if (const auto translation = data.vtranslation()) {
  2247. result.files(FileType::Translation) = parseFiles(
  2248. translation->v,
  2249. editData);
  2250. }
  2251. const auto parseSpecialScan = [&](
  2252. FileType type,
  2253. const MTPSecureFile &file) {
  2254. if (auto parsed = parseFile(file, editData)) {
  2255. result.specialScans.emplace(type, std::move(*parsed));
  2256. }
  2257. };
  2258. if (const auto side = data.vfront_side()) {
  2259. parseSpecialScan(FileType::FrontSide, *side);
  2260. }
  2261. if (const auto side = data.vreverse_side()) {
  2262. parseSpecialScan(FileType::ReverseSide, *side);
  2263. }
  2264. if (const auto selfie = data.vselfie()) {
  2265. parseSpecialScan(FileType::Selfie, *selfie);
  2266. }
  2267. if (const auto plain = data.vplain_data()) {
  2268. plain->match([&](const MTPDsecurePlainPhone &data) {
  2269. result.data.parsed.fields["value"].text = qs(data.vphone());
  2270. }, [&](const MTPDsecurePlainEmail &data) {
  2271. result.data.parsed.fields["value"].text = qs(data.vemail());
  2272. });
  2273. }
  2274. return result;
  2275. }
  2276. template <typename Condition>
  2277. EditFile *FormController::findEditFileByCondition(Condition &&condition) {
  2278. for (auto &pair : _form.values) {
  2279. auto &value = pair.second;
  2280. const auto foundInList = [&](FileType type) -> EditFile* {
  2281. for (auto &scan : value.filesInEdit(type)) {
  2282. if (condition(scan)) {
  2283. return &scan;
  2284. }
  2285. }
  2286. return nullptr;
  2287. };
  2288. if (const auto result = foundInList(FileType::Scan)) {
  2289. return result;
  2290. } else if (const auto other = foundInList(FileType::Translation)) {
  2291. return other;
  2292. }
  2293. for (auto &[special, scan] : value.specialScansInEdit) {
  2294. if (condition(scan)) {
  2295. return &scan;
  2296. }
  2297. }
  2298. }
  2299. return nullptr;
  2300. }
  2301. EditFile *FormController::findEditFile(const FullMsgId &fullId) {
  2302. return findEditFileByCondition([&](const EditFile &file) {
  2303. return (file.uploadData && file.uploadData->fullId == fullId);
  2304. });
  2305. }
  2306. EditFile *FormController::findEditFile(const FileKey &key) {
  2307. return findEditFileByCondition([&](const EditFile &file) {
  2308. return (file.fields.id == key.id);
  2309. });
  2310. }
  2311. auto FormController::findFile(const FileKey &key)
  2312. -> std::pair<Value*, File*> {
  2313. const auto found = [&](const File &file) {
  2314. return (file.id == key.id);
  2315. };
  2316. for (auto &pair : _form.values) {
  2317. auto &value = pair.second;
  2318. const auto foundInList = [&](FileType type) -> File* {
  2319. for (auto &scan : value.files(type)) {
  2320. if (found(scan)) {
  2321. return &scan;
  2322. }
  2323. }
  2324. return nullptr;
  2325. };
  2326. if (const auto result = foundInList(FileType::Scan)) {
  2327. return { &value, result };
  2328. } else if (const auto other = foundInList(FileType::Translation)) {
  2329. return { &value, other };
  2330. }
  2331. for (auto &[special, scan] : value.specialScans) {
  2332. if (found(scan)) {
  2333. return { &value, &scan };
  2334. }
  2335. }
  2336. }
  2337. return { nullptr, nullptr };
  2338. }
  2339. void FormController::formDone(const MTPaccount_AuthorizationForm &result) {
  2340. if (!parseForm(result)) {
  2341. _view->showCriticalError(tr::lng_passport_form_error(tr::now));
  2342. } else {
  2343. showForm();
  2344. }
  2345. }
  2346. bool FormController::parseForm(const MTPaccount_AuthorizationForm &result) {
  2347. Expects(result.type() == mtpc_account_authorizationForm);
  2348. const auto &data = result.c_account_authorizationForm();
  2349. session().data().processUsers(data.vusers());
  2350. for (const auto &value : data.vvalues().v) {
  2351. auto parsed = parseValue(value);
  2352. const auto type = parsed.type;
  2353. const auto alreadyIt = _form.values.find(type);
  2354. if (alreadyIt != _form.values.end()) {
  2355. LOG(("API Error: Two values for type %1 in authorization form"
  2356. "%1").arg(int(type)));
  2357. return false;
  2358. }
  2359. _form.values.emplace(type, std::move(parsed));
  2360. }
  2361. if (const auto url = data.vprivacy_policy_url()) {
  2362. _form.privacyPolicyUrl = qs(*url);
  2363. }
  2364. for (const auto &required : data.vrequired_types().v) {
  2365. const auto row = CollectRequestedRow(required);
  2366. for (const auto &requested : row.values) {
  2367. const auto type = requested.type;
  2368. const auto &[i, ok] = _form.values.emplace(type, Value(type));
  2369. auto &value = i->second;
  2370. value.translationRequired = requested.translationRequired;
  2371. value.selfieRequired = requested.selfieRequired;
  2372. value.nativeNames = requested.nativeNames;
  2373. }
  2374. _form.request.push_back(row.values
  2375. | ranges::views::transform([](const RequestedValue &value) {
  2376. return value.type;
  2377. }) | ranges::to_vector);
  2378. }
  2379. if (!ValidateForm(_form)) {
  2380. return false;
  2381. }
  2382. _bot = session().data().userLoaded(_request.botId);
  2383. _form.pendingErrors = data.verrors().v;
  2384. return true;
  2385. }
  2386. void FormController::formFail(const QString &error) {
  2387. _savedPasswordValue = QByteArray();
  2388. _serviceErrorText = error;
  2389. if (!handleAppUpdateError(error)) {
  2390. _view->showCriticalError(
  2391. tr::lng_passport_form_error(tr::now) + "\n" + error);
  2392. }
  2393. }
  2394. bool FormController::handleAppUpdateError(const QString &error) {
  2395. if (error == u"APP_VERSION_OUTDATED"_q) {
  2396. _view->showUpdateAppBox();
  2397. return true;
  2398. }
  2399. return false;
  2400. }
  2401. void FormController::requestPassword() {
  2402. if (_passwordRequestId) {
  2403. return;
  2404. }
  2405. _passwordRequestId = _api.request(MTPaccount_GetPassword(
  2406. )).done([=](const MTPaccount_Password &result) {
  2407. _passwordRequestId = 0;
  2408. passwordDone(result);
  2409. }).fail([=](const MTP::Error &error) {
  2410. formFail(error.type());
  2411. }).send();
  2412. }
  2413. void FormController::passwordDone(const MTPaccount_Password &result) {
  2414. Expects(result.type() == mtpc_account_password);
  2415. const auto changed = applyPassword(result.c_account_password());
  2416. if (changed) {
  2417. showForm();
  2418. }
  2419. shortPollEmailConfirmation();
  2420. }
  2421. void FormController::shortPollEmailConfirmation() {
  2422. if (_password.unconfirmedPattern.isEmpty()) {
  2423. _shortPollTimer.cancel();
  2424. return;
  2425. }
  2426. _shortPollTimer.callOnce(kShortPollTimeout);
  2427. }
  2428. void FormController::showForm() {
  2429. if (_formRequestId || _passwordRequestId) {
  2430. return;
  2431. } else if (!_bot) {
  2432. formFail(Lang::Hard::NoAuthorizationBot());
  2433. return;
  2434. }
  2435. if (_password.unknownAlgo
  2436. || v::is_null(_password.newAlgo)
  2437. || v::is_null(_password.newSecureAlgo)) {
  2438. _view->showUpdateAppBox();
  2439. return;
  2440. } else if (_password.request) {
  2441. if (!_savedPasswordValue.isEmpty()) {
  2442. submitPassword(base::duplicate(_savedPasswordValue));
  2443. } else if (const auto saved = session().data().passportCredentials()) {
  2444. checkSavedPasswordSettings(*saved);
  2445. } else {
  2446. _view->showAskPassword();
  2447. }
  2448. } else {
  2449. _view->showNoPassword();
  2450. }
  2451. }
  2452. bool FormController::applyPassword(const MTPDaccount_password &result) {
  2453. auto settings = PasswordSettings();
  2454. settings.hint = qs(result.vhint().value_or_empty());
  2455. settings.hasRecovery = result.is_has_recovery();
  2456. settings.notEmptyPassport = result.is_has_secure_values();
  2457. settings.request = Core::ParseCloudPasswordCheckRequest(result);
  2458. settings.unknownAlgo = result.vcurrent_algo() && !settings.request;
  2459. settings.unconfirmedPattern = qs(
  2460. result.vemail_unconfirmed_pattern().value_or_empty());
  2461. settings.newAlgo = Core::ValidateNewCloudPasswordAlgo(
  2462. Core::ParseCloudPasswordAlgo(result.vnew_algo()));
  2463. settings.newSecureAlgo = Core::ValidateNewSecureSecretAlgo(
  2464. Core::ParseSecureSecretAlgo(result.vnew_secure_algo()));
  2465. settings.pendingResetDate = result.vpending_reset_date().value_or_empty();
  2466. base::RandomAddSeed(bytes::make_span(result.vsecure_random().v));
  2467. return applyPassword(std::move(settings));
  2468. }
  2469. bool FormController::applyPassword(PasswordSettings &&settings) {
  2470. if (_password != settings) {
  2471. _password = std::move(settings);
  2472. return true;
  2473. }
  2474. return false;
  2475. }
  2476. void FormController::cancel() {
  2477. if (!_submitSuccess && _serviceErrorText.isEmpty()) {
  2478. _view->show(Ui::MakeConfirmBox({
  2479. .text = tr::lng_passport_stop_sure(),
  2480. .confirmed = [=] { cancelSure(); },
  2481. .cancelled = [=](Fn<void()> close) { cancelAbort(); close(); },
  2482. .confirmText = tr::lng_passport_stop(),
  2483. }));
  2484. } else {
  2485. cancelSure();
  2486. }
  2487. }
  2488. void FormController::cancelAbort() {
  2489. if (_cancelled || _submitSuccess) {
  2490. return;
  2491. } else if (_suggestingRestart) {
  2492. suggestRestart();
  2493. }
  2494. }
  2495. void FormController::cancelSure() {
  2496. if (!_cancelled) {
  2497. _cancelled = true;
  2498. if (!_request.callbackUrl.isEmpty()
  2499. && (_serviceErrorText.isEmpty()
  2500. || ForwardServiceErrorRequired(_serviceErrorText))) {
  2501. const auto url = qthelp::url_append_query_or_hash(
  2502. _request.callbackUrl,
  2503. (_submitSuccess
  2504. ? "tg_passport=success"
  2505. : (_serviceErrorText.isEmpty()
  2506. ? "tg_passport=cancel"
  2507. : "tg_passport=error&error=" + _serviceErrorText)));
  2508. UrlClickHandler::Open(url);
  2509. }
  2510. const auto timeout = _view->closeGetDuration();
  2511. base::call_delayed(timeout, this, [=] {
  2512. _controller->clearPassportForm();
  2513. });
  2514. }
  2515. }
  2516. rpl::lifetime &FormController::lifetime() {
  2517. return _lifetime;
  2518. }
  2519. FormController::~FormController() = default;
  2520. } // namespace Passport