webclient.ts 172 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398
  1. /**
  2. * This file is part of Threema Web.
  3. *
  4. * Threema Web is free software: you can redistribute it and/or modify it
  5. * under the terms of the GNU Affero General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or (at
  7. * your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Affero General Public License
  15. * along with Threema Web. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. /// <reference types="@saltyrtc/chunked-dc" />
  18. /// <reference types="@saltyrtc/task-webrtc" />
  19. /// <reference types="@saltyrtc/task-relayed-data" />
  20. import {StateService as UiStateService} from '@uirouter/angularjs';
  21. import {Logger} from 'ts-log';
  22. import * as msgpack from 'msgpack-lite';
  23. import {
  24. arraysAreEqual,
  25. base64ToU8a,
  26. bufferToUrl,
  27. copyDeepOrReference,
  28. hasFeature,
  29. hasValue,
  30. hexToU8a,
  31. msgpackVisualizer,
  32. randomString,
  33. stringToUtf8a,
  34. u8aToHex,
  35. } from '../helpers';
  36. import {
  37. isContactReceiver,
  38. isDistributionListReceiver,
  39. isGroupReceiver,
  40. isValidReceiverType,
  41. } from '../typeguards';
  42. import {BatteryStatusService} from './battery';
  43. import {BrowserService} from './browser';
  44. import {TrustedKeyStoreService} from './keystore';
  45. import {LogService} from './log';
  46. import {MessageService} from './message';
  47. import {MimeService} from './mime';
  48. import {NotificationService} from './notification';
  49. import {PeerConnectionHelper} from './peerconnection';
  50. import {PushService, PushSession} from './push';
  51. import {QrCodeService} from './qrcode';
  52. import {ReceiverService} from './receiver';
  53. import {StateService} from './state';
  54. import {ThemeService} from './theme';
  55. import {TimeoutService} from './timeout';
  56. import {TitleService} from './title';
  57. import {VersionService} from './version';
  58. import {PushError, TimeoutError} from '../exceptions';
  59. import {ConfidentialWireMessage} from '../helpers/confidential';
  60. import {UnboundedFlowControlledDataChannel} from '../helpers/data_channel';
  61. import {DeviceUnreachableController, PushRejectedDialogController} from '../partials/messenger';
  62. import {ChunkCache} from '../protocol/cache';
  63. import {SequenceNumber} from '../protocol/sequence_number';
  64. // Aliases
  65. import InitializationStep = threema.InitializationStep;
  66. import ContactReceiverFeature = threema.ContactReceiverFeature;
  67. import DisconnectReason = threema.DisconnectReason;
  68. import PushSessionConfig = threema.PushSessionConfig;
  69. /**
  70. * Payload of a connectionInfo message.
  71. */
  72. interface ConnectionInfo {
  73. id: ArrayBuffer;
  74. resume?: {
  75. id: ArrayBuffer;
  76. sequenceNumber: number;
  77. };
  78. }
  79. const fakeConnectionId = Uint8Array.from([
  80. 1, 2, 3, 4, 5, 6, 7, 8,
  81. 1, 2, 3, 4, 5, 6, 7, 8,
  82. 1, 2, 3, 4, 5, 6, 7, 8,
  83. 1, 2, 3, 4, 5, 6, 7, 8,
  84. ]);
  85. /**
  86. * This service handles everything related to the communication with the peer.
  87. */
  88. export class WebClientService {
  89. public static readonly MAX_CONNECT_ATTEMPTS = 3;
  90. private static DATA_CHANNEL_MAX_CHUNK_SIZE = 256 * 1024;
  91. private static RELAYED_DATA_CHUNK_SIZE = 64 * 1024;
  92. private static SEQUENCE_NUMBER_MIN = 0;
  93. private static SEQUENCE_NUMBER_MAX = (2 ** 32) - 1;
  94. private static CHUNK_CACHE_SIZE_MAX = 2 * 1024 * 1024;
  95. private static AVATAR_LOW_MAX_SIZE = 48;
  96. private static MAX_FILE_SIZE_WEBRTC_TASK_V0 = 15 * 1024 * 1024;
  97. private static CONNECTION_ID_NONCE = stringToUtf8a('connectionidconnectionid');
  98. private static TYPE_REQUEST = 'request';
  99. private static TYPE_RESPONSE = 'response';
  100. private static TYPE_UPDATE = 'update';
  101. private static TYPE_CREATE = 'create';
  102. private static TYPE_DELETE = 'delete';
  103. private static SUB_TYPE_RECEIVER = 'receiver';
  104. private static SUB_TYPE_RECEIVERS = 'receivers';
  105. private static SUB_TYPE_CONVERSATIONS = 'conversations';
  106. private static SUB_TYPE_CONVERSATION = 'conversation';
  107. private static SUB_TYPE_MESSAGE = 'message';
  108. private static SUB_TYPE_MESSAGES = 'messages';
  109. private static SUB_TYPE_TEXT_MESSAGE = 'textMessage';
  110. private static SUB_TYPE_FILE_MESSAGE = 'fileMessage';
  111. private static SUB_TYPE_AVATAR = 'avatar';
  112. private static SUB_TYPE_THUMBNAIL = 'thumbnail';
  113. private static SUB_TYPE_BLOB = 'blob';
  114. private static SUB_TYPE_TYPING = 'typing';
  115. private static SUB_TYPE_READ = 'read';
  116. private static SUB_TYPE_CLIENT_INFO = 'clientInfo';
  117. private static SUB_TYPE_KEY_PERSISTED = 'keyPersisted';
  118. private static SUB_TYPE_ACK = 'ack';
  119. private static SUB_TYPE_CONTACT_DETAIL = 'contactDetail';
  120. private static SUB_TYPE_CONTACT = 'contact';
  121. private static SUB_TYPE_GROUP = 'group';
  122. private static SUB_TYPE_DISTRIBUTION_LIST = 'distributionList';
  123. private static SUB_TYPE_ALERT = 'alert';
  124. private static SUB_TYPE_GROUP_SYNC = 'groupSync';
  125. private static SUB_TYPE_BATTERY_STATUS = 'batteryStatus';
  126. private static SUB_TYPE_CLEAN_RECEIVER_CONVERSATION = 'cleanReceiverConversation';
  127. private static SUB_TYPE_CONFIRM = 'confirm';
  128. private static SUB_TYPE_CONFIRM_ACTION = 'confirmAction'; // TODO: deprecated
  129. private static SUB_TYPE_PROFILE = 'profile';
  130. private static SUB_TYPE_CONNECTION_ACK = 'connectionAck';
  131. private static SUB_TYPE_CONNECTION_DISCONNECT = 'connectionDisconnect';
  132. private static SUB_TYPE_CONNECTION_INFO = 'connectionInfo';
  133. private static ARGUMENT_MODE = 'mode';
  134. private static ARGUMENT_MODE_NEW = 'new';
  135. private static ARGUMENT_MODE_MODIFIED = 'modified';
  136. private static ARGUMENT_MODE_REMOVED = 'removed';
  137. private static ARGUMENT_RECEIVER_TYPE = 'type';
  138. private static ARGUMENT_RECEIVER_ID = 'id';
  139. private static ARGUMENT_TEMPORARY_ID = 'temporaryId'; // TODO: deprecated
  140. private static ARGUMENT_REFERENCE_MSG_ID = 'refMsgId';
  141. private static ARGUMENT_AVATAR = 'avatar';
  142. private static ARGUMENT_AVATAR_HIGH_RESOLUTION = 'highResolution';
  143. private static ARGUMENT_NICKNAME = 'publicNickname';
  144. private static ARGUMENT_IS_TYPING = 'isTyping';
  145. private static ARGUMENT_MESSAGE_ID = 'messageId';
  146. private static ARGUMENT_HAS_MORE = 'more';
  147. private static ARGUMENT_MESSAGE_ACKNOWLEDGED = 'acknowledged';
  148. private static ARGUMENT_IDENTITY = 'identity';
  149. private static ARGUMENT_SUCCESS = 'success'; // TODO: deprecated
  150. private static ARGUMENT_SYSTEM_CONTACT = 'systemContact';
  151. private static ARGUMENT_NAME = 'name';
  152. private static ARGUMENT_MEMBERS = 'members';
  153. private static ARGUMENT_FIRST_NAME = 'firstName';
  154. private static ARGUMENT_LAST_NAME = 'lastName';
  155. private static ARGUMENT_DELETE_TYPE = 'deleteType';
  156. private static ARGUMENT_ERROR = 'error'; // TODO: deprecated
  157. private static ARGUMENT_MAX_SIZE = 'maxSize';
  158. private static ARGUMENT_USER_AGENT = 'userAgent';
  159. private static ARGUMENT_BROWSER_NAME = 'browserName';
  160. private static ARGUMENT_BROWSER_VERSION = 'browserVersion';
  161. private static DELETE_GROUP_TYPE_LEAVE = 'leave';
  162. private static DELETE_GROUP_TYPE_DELETE = 'delete';
  163. private static DATA_FIELD_BLOB_BLOB = 'blob';
  164. private static DATA_FIELD_BLOB_TYPE = 'type';
  165. private static DATA_FIELD_BLOB_NAME = 'name';
  166. private static DC_LABEL = 'THREEMA';
  167. // Angular services
  168. private $state: UiStateService;
  169. private $rootScope: any;
  170. private $q: ng.IQService;
  171. private $window: ng.IWindowService;
  172. private $translate: ng.translate.ITranslateService;
  173. private $filter: any;
  174. private $timeout: ng.ITimeoutService;
  175. private $mdDialog: ng.material.IDialogService;
  176. // Custom services
  177. private batteryStatusService: BatteryStatusService;
  178. private browserService: BrowserService;
  179. private logService: LogService;
  180. private messageService: MessageService;
  181. private mimeService: MimeService;
  182. private notificationService: NotificationService;
  183. private pushService: PushService;
  184. private qrCodeService: QrCodeService;
  185. private receiverService: ReceiverService;
  186. private themeService: ThemeService;
  187. private timeoutService: TimeoutService;
  188. private titleService: TitleService; // Don't remove, needs to be initialized to handle events
  189. private versionService: VersionService;
  190. // Logging
  191. private readonly log: Logger;
  192. private readonly arpLog: Logger;
  193. private readonly arpLogV: Logger;
  194. private readonly msgpackLog: Logger;
  195. // State handling
  196. private startupPromise: ng.IDeferred<{}> = null; // TODO: deferred type
  197. public startupDone: boolean = false;
  198. private handoverDone: boolean = false;
  199. private pendingInitializationStepRoutines: Set<threema.InitializationStepRoutine> = new Set();
  200. private initialized: Set<threema.InitializationStep> = new Set();
  201. private stateService: StateService;
  202. // Session connection
  203. private saltyRtcHost: string = null;
  204. public salty: saltyrtc.SaltyRTC = null;
  205. private connectionInfoFuture: Future<ConnectionInfo> = null;
  206. private relayedDataTask: saltyrtc.tasks.relayed_data.RelayedDataTask = null;
  207. private secureDataChannel: UnboundedFlowControlledDataChannel = null;
  208. private secureDataChannelCrypto: saltyrtc.tasks.webrtc.DataChannelCryptoContext = null;
  209. private secureDataChannelChunkLength: number = null;
  210. private secureDataChannelMessageId: number = 0;
  211. public chosenTask: threema.ChosenTask = threema.ChosenTask.None;
  212. private outgoingMessageSequenceNumber: SequenceNumber;
  213. private previousConnectionId: Uint8Array = null;
  214. private currentConnectionId: Uint8Array = null;
  215. private previousIncomingChunkSequenceNumber: SequenceNumber = null;
  216. private currentIncomingChunkSequenceNumber: SequenceNumber;
  217. private previousChunkCache: ChunkCache = null;
  218. private currentChunkCache: ChunkCache = null;
  219. private handshakeCompleted: boolean = false;
  220. private ackTimer: number | null = null;
  221. private pendingAckRequest: number | null = null;
  222. // Message chunking
  223. private unchunker: chunkedDc.UnreliableUnorderedUnchunker = null;
  224. // Messenger data
  225. public messages: threema.Container.Messages;
  226. public conversations: threema.Container.Conversations;
  227. public receivers: threema.Container.Receivers;
  228. public alerts: threema.Alert[] = [];
  229. // Push
  230. private pushToken: string = null;
  231. private pushTokenType: threema.PushTokenType = null;
  232. private pushSession: PushSession | null = null;
  233. private readonly pushSessionConfig: PushSessionConfig;
  234. private readonly pushSessionExpectedPeriodMaxMs: number;
  235. private pushPromise: Promise<any> | null = null;
  236. private deviceUnreachableDialog: ng.IPromise<any> | null = null;
  237. private pushTimer: number | null = null;
  238. private schedulePushAfterCooldown: boolean = false;
  239. // Timeouts
  240. private batteryStatusTimeout: ng.IPromise<void> = null;
  241. // Other
  242. private config: threema.Config;
  243. private container: threema.Container.Factory;
  244. private typingInstance: threema.Container.Typing;
  245. private drafts: threema.Container.Drafts;
  246. private pcHelper: PeerConnectionHelper = null;
  247. private trustedKeyStore: TrustedKeyStoreService;
  248. public clientInfo: threema.ClientInfo = null;
  249. public version = null;
  250. private blobCache = new Map<string, threema.BlobInfo>();
  251. private loadingMessages = new Map<string, boolean>();
  252. public receiverListener: threema.ReceiverListener[] = [];
  253. // Msgpack
  254. private msgpackEncoderOptions: msgpack.EncoderOptions = {
  255. codec: msgpack.createCodec({binarraybuffer: true}),
  256. };
  257. private msgpackDecoderOptions: msgpack.DecoderOptions = {
  258. codec: msgpack.createCodec({binarraybuffer: true}),
  259. };
  260. // Messages that require acknowledgement
  261. private wireMessageFutures: Map<string, Future<any>> = new Map();
  262. public static $inject = [
  263. '$rootScope', '$q', '$state', '$window', '$translate', '$filter', '$timeout', '$mdDialog',
  264. 'LogService', 'Container', 'TrustedKeyStore',
  265. 'StateService', 'NotificationService', 'MessageService', 'PushService', 'BrowserService',
  266. 'TitleService', 'QrCodeService', 'MimeService', 'ReceiverService',
  267. 'VersionService', 'BatteryStatusService', 'ThemeService', 'TimeoutService',
  268. 'CONFIG',
  269. ];
  270. constructor($rootScope: any,
  271. $q: ng.IQService,
  272. $state: UiStateService,
  273. $window: ng.IWindowService,
  274. $translate: ng.translate.ITranslateService,
  275. $filter: ng.IFilterService,
  276. $timeout: ng.ITimeoutService,
  277. $mdDialog: ng.material.IDialogService,
  278. logService: LogService,
  279. container: threema.Container.Factory,
  280. trustedKeyStore: TrustedKeyStoreService,
  281. stateService: StateService,
  282. notificationService: NotificationService,
  283. messageService: MessageService,
  284. pushService: PushService,
  285. browserService: BrowserService,
  286. titleService: TitleService,
  287. qrCodeService: QrCodeService,
  288. mimeService: MimeService,
  289. receiverService: ReceiverService,
  290. versionService: VersionService,
  291. batteryStatusService: BatteryStatusService,
  292. themeService: ThemeService,
  293. timeoutService: TimeoutService,
  294. CONFIG: threema.Config) {
  295. // Angular services
  296. this.$rootScope = $rootScope;
  297. this.$q = $q;
  298. this.$state = $state;
  299. this.$window = $window;
  300. this.$translate = $translate;
  301. this.$filter = $filter;
  302. this.$timeout = $timeout;
  303. this.$mdDialog = $mdDialog;
  304. // Own services
  305. this.batteryStatusService = batteryStatusService;
  306. this.browserService = browserService;
  307. this.logService = logService;
  308. this.messageService = messageService;
  309. this.mimeService = mimeService;
  310. this.notificationService = notificationService;
  311. this.pushService = pushService;
  312. this.qrCodeService = qrCodeService;
  313. this.receiverService = receiverService;
  314. this.themeService = themeService;
  315. this.timeoutService = timeoutService;
  316. this.titleService = titleService;
  317. this.versionService = versionService;
  318. // Configuration object
  319. this.config = CONFIG;
  320. // Logging
  321. this.log = logService.getLogger('WebClient-S', 'color: #fff; background-color: #0066cc');
  322. this.arpLog = logService.getLogger(
  323. 'AppRemoteProtocol', 'color: #fff; background-color: #0099cc', CONFIG.ARP_LOG_LEVEL);
  324. this.arpLogV = logService.getLogger(
  325. 'AppRemoteProtocol', 'color: #fff; background-color: #00ace6', CONFIG.ARP_LOG_TRACE ? 'debug' : 'none');
  326. this.msgpackLog = logService.getLogger(
  327. 'MessagePack', 'color: #fff; background-color: #006699', CONFIG.MSGPACK_LOG_TRACE ? 'debug' : 'none');
  328. // State
  329. this.stateService = stateService;
  330. // Push session configuration
  331. this.pushSessionConfig = PushSession.defaultConfig;
  332. this.pushSessionConfig.triesMax = WebClientService.MAX_CONNECT_ATTEMPTS;
  333. // TODO: Remove below config overwrite lines once the app-related push issues have been resolved in #802
  334. this.pushSessionConfig = {
  335. retryTimeoutInitMs: 14000, retryTimeoutMaxMs: 30000, triesMax: 1, timeToLiveRange: [90],
  336. };
  337. this.pushSessionExpectedPeriodMaxMs = PushSession.expectedPeriodMaxMs(this.pushSessionConfig);
  338. // Other properties
  339. this.container = container;
  340. this.trustedKeyStore = trustedKeyStore;
  341. // Initialize drafts
  342. this.drafts = this.container.createDrafts();
  343. // Setup fields
  344. this._resetFields();
  345. // Register event handlers
  346. this.stateService.evtConnectionBuildupStateChange.attach(
  347. (stateChange: threema.ConnectionBuildupStateChange) => {
  348. if (this.startupPromise !== null) {
  349. this.startupPromise.notify(stateChange);
  350. }
  351. },
  352. );
  353. this.stateService.evtGlobalConnectionStateChange.attach(this.handleGlobalConnectionStateChange.bind(this));
  354. }
  355. /**
  356. * Return whether wire messages can be sent (or queued to be sent).
  357. *
  358. * Note: This will not return `true` before an initial connection has been
  359. * established successfully.
  360. */
  361. get readyToSubmit(): boolean {
  362. return this.stateService.readyToSubmit(this.chosenTask, this.startupDone);
  363. }
  364. get me(): threema.MeReceiver {
  365. return this.receivers.me;
  366. }
  367. get contacts(): Map<string, threema.ContactReceiver> {
  368. return this.receivers.contacts;
  369. }
  370. get groups(): Map<string, threema.GroupReceiver> {
  371. return this.receivers.groups;
  372. }
  373. get distributionLists(): Map<string, threema.DistributionListReceiver> {
  374. return this.receivers.distributionLists;
  375. }
  376. get typing(): threema.Container.Typing {
  377. return this.typingInstance;
  378. }
  379. /**
  380. * Return the amount of unacknowledged wire messages.
  381. */
  382. get unacknowledgedWireMessages(): number {
  383. return this.wireMessageFutures.size;
  384. }
  385. // TODO: Deprecated - remove this attribute and update all references
  386. get requiresTemporaryIdBackwardsCompatibility(): boolean {
  387. return this.chosenTask !== threema.ChosenTask.RelayedData;
  388. }
  389. /**
  390. * Return QR code payload.
  391. */
  392. public buildQrCodePayload(persistent: boolean): string {
  393. return this.qrCodeService.buildQrCodePayload(
  394. this.salty.permanentKeyBytes,
  395. this.salty.authTokenBytes,
  396. hexToU8a(this.config.SALTYRTC_SERVER_KEY),
  397. this.saltyRtcHost, this.config.SALTYRTC_PORT,
  398. persistent);
  399. }
  400. /**
  401. * Initialize the webclient service.
  402. *
  403. * Warning: Do not call this with `flags.resume` set to `false` in case
  404. * messages can be queued by the user.
  405. */
  406. public init(flags: {
  407. keyStore?: saltyrtc.KeyStore,
  408. peerTrustedKey?: Uint8Array,
  409. resume: boolean,
  410. }): void {
  411. let keyStore = flags.keyStore;
  412. let resumeSession = flags.resume;
  413. this.log.info(`Initializing (keyStore=${keyStore !== undefined ? 'yes' : 'no'}, peerTrustedKey=` +
  414. `${flags.peerTrustedKey !== undefined ? 'yes' : 'no'}, resume=${resumeSession})`);
  415. // Reset fields, blob cache, pending requests and pending timeouts in case the session
  416. // should explicitly not be resumed
  417. if (!resumeSession) {
  418. this.clearCache();
  419. this.wireMessageFutures.clear();
  420. this.timeoutService.cancelAll();
  421. }
  422. // Only move the previous connection's instances if the previous
  423. // connection was successful (and if there was one at all).
  424. if (resumeSession) {
  425. if (this.previousConnectionId) {
  426. this.arpLog.debug(`Trying to resume previous session (id=${u8aToHex(this.previousConnectionId)}, ` +
  427. `sn-out=${this.previousChunkCache.sequenceNumber.get()})`);
  428. } else {
  429. resumeSession = false;
  430. this.arpLog.debug('Wanted to resume previous session but none exists');
  431. }
  432. } else {
  433. // Discard session
  434. this.discardSession({ resetMessageSequenceNumber: true });
  435. resumeSession = false;
  436. this.arpLog.debug('Discarded previous session');
  437. }
  438. // Reset handshake completed flag
  439. this.handshakeCompleted = false;
  440. // Initialise connection caches
  441. this.currentConnectionId = null;
  442. this.currentIncomingChunkSequenceNumber = new SequenceNumber(
  443. 0, WebClientService.SEQUENCE_NUMBER_MIN, WebClientService.SEQUENCE_NUMBER_MAX);
  444. const outgoingChunkSequenceNumber = new SequenceNumber(
  445. 0, WebClientService.SEQUENCE_NUMBER_MIN, WebClientService.SEQUENCE_NUMBER_MAX);
  446. this.currentChunkCache = new ChunkCache(outgoingChunkSequenceNumber);
  447. // Reset pending ack request
  448. this.pendingAckRequest = null;
  449. // Create new handshake future
  450. this.connectionInfoFuture = new Future();
  451. // Create tasks
  452. const tasks: saltyrtc.Task[] = [];
  453. // Create WebRTC task instance (if supported)
  454. if (this.browserService.supportsWebrtcTask()) {
  455. // TODO: Remove legacy v0 after a transitional period
  456. tasks.push(new saltyrtcTaskWebrtc.WebRTCTaskBuilder()
  457. .withLoggingLevel(this.config.SALTYRTC_LOG_LEVEL)
  458. .withVersion('v1')
  459. .withHandover(true)
  460. .build());
  461. tasks.push(new saltyrtcTaskWebrtc.WebRTCTaskBuilder()
  462. .withLoggingLevel(this.config.SALTYRTC_LOG_LEVEL)
  463. .withVersion('v0')
  464. .withHandover(true)
  465. .withMaxChunkLength(this.browserService.getBrowser().isFirefox(false) ? 16384 : 65536)
  466. .build());
  467. }
  468. // Create Relayed Data task instance
  469. this.relayedDataTask = new saltyrtcTaskRelayedData.RelayedDataTask(this.config.SALTYRTC_LOG_LEVEL === 'debug');
  470. tasks.push(this.relayedDataTask);
  471. // Create new keystore if necessary
  472. if (!keyStore) {
  473. keyStore = new saltyrtcClient.KeyStore();
  474. }
  475. // Determine SaltyRTC host
  476. if (this.config.SALTYRTC_HOST !== null) {
  477. // Static URL
  478. this.saltyRtcHost = this.config.SALTYRTC_HOST;
  479. } else {
  480. // Construct URL using prefix and suffix
  481. this.saltyRtcHost = this.config.SALTYRTC_HOST_PREFIX
  482. + keyStore.publicKeyHex.substr(0, 2)
  483. + this.config.SALTYRTC_HOST_SUFFIX;
  484. }
  485. // Create SaltyRTC client
  486. let builder = new saltyrtcClient.SaltyRTCBuilder()
  487. .connectTo(this.saltyRtcHost, this.config.SALTYRTC_PORT)
  488. .withLoggingLevel(this.config.SALTYRTC_LOG_LEVEL)
  489. .withServerKey(this.config.SALTYRTC_SERVER_KEY)
  490. .withKeyStore(keyStore)
  491. .usingTasks(tasks)
  492. .withPingInterval(30);
  493. if (flags.peerTrustedKey !== undefined) {
  494. builder = builder.withTrustedPeerKey(flags.peerTrustedKey);
  495. }
  496. this.salty = builder.asInitiator();
  497. this.arpLog.info('Public key:', this.salty.permanentKeyHex);
  498. this.arpLogV.debug('Auth token:', this.salty.authTokenHex);
  499. // We want to know about state changes
  500. this.salty.on('state-change', (ev: saltyrtc.SaltyRTCEvent) => {
  501. const state: saltyrtc.SignalingState = ev.data;
  502. if (!this.startupDone) {
  503. switch (state) {
  504. case 'new':
  505. case 'ws-connecting':
  506. case 'server-handshake':
  507. if (this.stateService.connectionBuildupState !== 'push'
  508. && this.stateService.connectionBuildupState !== 'manual_start') {
  509. this.stateService.updateConnectionBuildupState('connecting');
  510. }
  511. break;
  512. case 'peer-handshake':
  513. // Waiting for peer
  514. if (this.stateService.connectionBuildupState !== 'push'
  515. && this.stateService.connectionBuildupState !== 'manual_start') {
  516. this.stateService.updateConnectionBuildupState('waiting');
  517. }
  518. break;
  519. case 'task':
  520. this.onTaskEstablished(resumeSession);
  521. break;
  522. case 'closing':
  523. case 'closed':
  524. this.stateService.updateConnectionBuildupState('closed');
  525. break;
  526. default:
  527. this.arpLog.warn('Unknown signaling state:', state);
  528. }
  529. }
  530. this.stateService.updateSignalingConnectionState(state, this.chosenTask, this.handoverDone);
  531. });
  532. // Handle disconnecting of a peer
  533. this.salty.on('peer-disconnected', (ev: saltyrtc.SaltyRTCEvent) => {
  534. this.$rootScope.$apply(() => {
  535. this.onPeerDisconnected(ev.data);
  536. });
  537. });
  538. // Wait for handover to be finished
  539. this.salty.on('handover', () => {
  540. this.arpLog.debug('Handover done');
  541. this.onHandover(resumeSession);
  542. });
  543. // Handle SaltyRTC errors
  544. this.salty.on('connection-error', (ev) => {
  545. this.arpLog.error('Connection error:', ev);
  546. });
  547. this.salty.on('connection-closed', (ev) => {
  548. this.arpLog.info('Connection closed:', ev);
  549. });
  550. this.salty.on('no-shared-task', (ev) => {
  551. this.arpLog.warn('No shared task found:', ev.data);
  552. const offeredWebrtc = ev.data.offered.filter((t) => t.endsWith('webrtc.tasks.saltyrtc.org')).length > 0;
  553. this.$rootScope.$apply(() => {
  554. if (!this.browserService.supportsWebrtcTask() && offeredWebrtc) {
  555. this.failSession(false);
  556. this.showWebrtcAndroidWarning();
  557. } else {
  558. this.failSession();
  559. }
  560. });
  561. });
  562. }
  563. /**
  564. * Show a WebRTC on Android warning dialog.
  565. */
  566. private showWebrtcAndroidWarning(): void {
  567. this.$translate.onReady().then(() => {
  568. const confirm = this.$mdDialog.alert()
  569. .title(this.$translate.instant('welcome.BROWSER_NOT_SUPPORTED_ANDROID'))
  570. .htmlContent(this.$translate.instant('welcome.BROWSER_NOT_SUPPORTED_DETAILS'))
  571. .ok(this.$translate.instant('welcome.ABORT'));
  572. this.$mdDialog.show(confirm).then(() => {
  573. // Redirect to Threema website
  574. window.location.replace('https://threema.ch/threema-web');
  575. });
  576. });
  577. }
  578. /**
  579. * Show an alert dialog. Can be called directly after calling `.stop(...)`.
  580. */
  581. private showAlert(alertMessage: string): void {
  582. // Note: A former stop() call above may result in a redirect, which will
  583. // in turn hide all open dialog boxes. Therefore, to avoid
  584. // immediately hiding the alert box, enqueue dialog at end of
  585. // event loop.
  586. this.$timeout(() => {
  587. this.$mdDialog.show(this.$mdDialog.alert()
  588. .title(this.$translate.instant('connection.SESSION_CLOSED_TITLE'))
  589. .textContent(this.$translate.instant(alertMessage))
  590. .ok(this.$translate.instant('common.OK')));
  591. }, 0);
  592. }
  593. /**
  594. * Fail the session and let the remote peer know that an error occurred.
  595. * A dialog will be displayed to let the user know a protocol error
  596. * happened.
  597. */
  598. private failSession(showAlert = true) {
  599. // Stop session
  600. const stop = () => {
  601. this.stop({
  602. reason: DisconnectReason.SessionError,
  603. send: true,
  604. // TODO: Use welcome.error once we have it
  605. close: 'welcome',
  606. connectionBuildupState: 'closed',
  607. });
  608. if (showAlert) {
  609. this.showAlert('connection.SESSION_ERROR');
  610. }
  611. };
  612. // Note: Although this is considered an anti-pattern, we simply don't
  613. // want a digest cycle in most of the network event functionality.
  614. // Thus, it would be pointless 99% of the time to apply a digest
  615. // cycle somewhere higher in the call stack.
  616. if (!this.$rootScope.$$phase) {
  617. this.$rootScope.$apply(() => stop());
  618. } else {
  619. stop();
  620. }
  621. }
  622. /**
  623. * Fail the session on a rejection of a Promise associated to a message.
  624. */
  625. private failSessionOnReject(type: string, subType: string) {
  626. return ((error) => {
  627. this.logOnReject(type, subType)(error);
  628. this.failSession();
  629. });
  630. }
  631. /**
  632. * Log a rejection of a Promise associated to a message.
  633. */
  634. private logOnReject(type: string, subType: string) {
  635. return ((error) => {
  636. this.arpLog.error(`Message ${type}/${subType} has been rejected by the remote: ${error}`);
  637. });
  638. }
  639. /**
  640. * Resume a session via the previous connection's ID and chunk cache.
  641. *
  642. * Returns whether the connection has been resumed.
  643. *
  644. * Important: Caller must invalidate the cache and connection ID after this
  645. * function returned!
  646. */
  647. private maybeResumeSession(resumeSession: boolean, remoteInfo: ConnectionInfo): boolean {
  648. // Validate connection ID
  649. const remoteCurrentConnectionId = new Uint8Array(remoteInfo.id);
  650. if (arraysAreEqual(fakeConnectionId, remoteCurrentConnectionId)) {
  651. this.arpLog.debug('Cannot resume session: Remote did not implement deriving the connection ID');
  652. // TODO: Remove this once it is implemented properly by the app!
  653. return false;
  654. }
  655. if (!arraysAreEqual(this.currentConnectionId, remoteCurrentConnectionId)) {
  656. this.arpLog.info(`Cannot resume session: IDs of previous connection do not match (local=`
  657. + `${u8aToHex(this.currentConnectionId)}, remote=${u8aToHex(remoteCurrentConnectionId)}`);
  658. throw new Error('Derived connection IDs do not match!');
  659. }
  660. // Ensure both local and remote want to resume a session
  661. if (!resumeSession || remoteInfo.resume === undefined) {
  662. this.arpLog.info(`No resumption (local requested: ${resumeSession ? 'yes' : 'no'}, ` +
  663. `remote requested: ${remoteInfo.resume ? 'yes' : 'no'})`);
  664. // Both sides should detect that -> recoverable
  665. return false;
  666. }
  667. // Ensure we want to resume from the same previous connection
  668. const remotePreviousConnectionId = new Uint8Array(remoteInfo.resume.id);
  669. if (!arraysAreEqual(this.previousConnectionId, remotePreviousConnectionId)) {
  670. // Both sides should detect that -> recoverable
  671. this.arpLog.info(`Cannot resume session: IDs of previous connection do not match (local=`
  672. + `${u8aToHex(this.previousConnectionId)}, remote=${u8aToHex(remotePreviousConnectionId)}`);
  673. return false;
  674. }
  675. // Remove chunks that have been received by the remote side
  676. const size = this.previousChunkCache.byteLength;
  677. let result;
  678. this.arpLog.debug(`Pruning cache (local-sn=${this.previousChunkCache.sequenceNumber.get()}, ` +
  679. `remote-sn=${remoteInfo.resume.sequenceNumber})`);
  680. try {
  681. result = this.previousChunkCache.prune(remoteInfo.resume.sequenceNumber);
  682. } catch (error) {
  683. // Not recoverable
  684. throw new Error(`Unable to resume session: ${error}`);
  685. }
  686. this.arpLog.debug(`Chunk cache pruned, acknowledged: ${result.acknowledged}, left: ${result.left}, size: ` +
  687. `${size} -> ${this.previousChunkCache.byteLength}`);
  688. if (this.config.ARP_LOG_TRACE) {
  689. this.arpLog.debug(`Chunks that require acknowledgement: ${this.previousChunkCache.chunks.length}`);
  690. }
  691. // Transfer the cache (filters chunks which should not be retransmitted)
  692. const transferred = this.currentChunkCache.transfer(this.previousChunkCache.chunks);
  693. this.arpLog.debug(`Chunk cache transferred (${transferred} chunks)`);
  694. // Invalidate the previous connection cache & id
  695. // Note: This MUST be done immediately after the session has been
  696. // resumed to prevent re-establishing a session of a connection
  697. // where the handshake has been started but not been completed.
  698. this.previousConnectionId = null;
  699. this.previousIncomingChunkSequenceNumber = null;
  700. this.previousChunkCache = null;
  701. // Resend chunks
  702. const chunks = this.currentChunkCache.chunks;
  703. this.arpLog.debug(`Sending cached chunks: ${chunks.length}`);
  704. for (const chunk of chunks) {
  705. this.sendChunk(chunk, true, false, false);
  706. }
  707. // Resumed!
  708. return true;
  709. }
  710. /**
  711. * Discard the session of a previous connection.
  712. */
  713. private discardSession(flags: { resetMessageSequenceNumber: boolean }): void {
  714. // Reset the outgoing message sequence number and the unchunker
  715. if (flags.resetMessageSequenceNumber) {
  716. this.outgoingMessageSequenceNumber = new SequenceNumber(
  717. 0, WebClientService.SEQUENCE_NUMBER_MIN, WebClientService.SEQUENCE_NUMBER_MAX);
  718. }
  719. this.unchunker = new chunkedDc.UnreliableUnorderedUnchunker();
  720. this.unchunker.onMessage = this.handleIncomingMessageBytes.bind(this);
  721. // Discard previous connection instances
  722. this.previousConnectionId = null;
  723. this.previousIncomingChunkSequenceNumber = null;
  724. this.previousChunkCache = null;
  725. }
  726. /**
  727. * Schedule the connection ack to be sent.
  728. *
  729. * By default, a connection ack message will be sent after 10 seconds
  730. * (as defined by the protocol).
  731. */
  732. private scheduleConnectionAck(timeout: number = 10000): void {
  733. // Don't schedule if already running
  734. if (this.ackTimer === null) {
  735. this.ackTimer = self.setTimeout(() => {
  736. this.ackTimer = null;
  737. this._sendConnectionAck();
  738. }, timeout);
  739. }
  740. }
  741. /**
  742. * Schedule a push to be sent if there is no network activity within a
  743. * specified interval.
  744. */
  745. private schedulePush(timeoutMs: number = 3000): void {
  746. if (this.pushTimer !== null) {
  747. this.schedulePushAfterCooldown = true;
  748. return;
  749. }
  750. // Send a push after the timeout
  751. this.pushTimer = self.setTimeout(() => {
  752. this.pushTimer = null;
  753. this.schedulePushAfterCooldown = false;
  754. this.log.debug('Connection appears to be lost, sending push');
  755. this.sendPush();
  756. }, timeoutMs);
  757. // Send a connection ack.
  758. // Note: This acts as a *ping* but also helps us to keep the caches
  759. // clean.
  760. this._requestConnectionAck();
  761. }
  762. /**
  763. * Cancel a scheduled push.
  764. */
  765. private cancelPush(cooldownMs: number = 10000): void {
  766. if (this.pushTimer !== null) {
  767. self.clearTimeout(this.pushTimer);
  768. this.pushTimer = null;
  769. }
  770. this.schedulePushAfterCooldown = false;
  771. // Start the cooldown of the push timeout (if required)
  772. if (cooldownMs > 0) {
  773. this.pushTimer = self.setTimeout(() => {
  774. this.pushTimer = null;
  775. if (this.schedulePushAfterCooldown) {
  776. this.schedulePush();
  777. }
  778. }, cooldownMs);
  779. }
  780. }
  781. /**
  782. * Once the SaltyRTC task has been established...
  783. *
  784. * - for Android, initiate the peer connection and start the handover,
  785. * - for iOS, no further action is necessary and the connection is
  786. * considered established.
  787. */
  788. private onTaskEstablished(resumeSession: boolean) {
  789. // Pushing complete
  790. this.resetPushSession(true);
  791. // Peer handshake
  792. this.stateService.updateConnectionBuildupState('peer_handshake');
  793. // Determine chosen task
  794. const task = this.salty.getTask();
  795. if (task.getName().indexOf('webrtc.tasks.saltyrtc.org') !== -1) {
  796. this.chosenTask = threema.ChosenTask.WebRTC;
  797. } else if (task.getName().indexOf('relayed-data.tasks.saltyrtc.org') !== -1) {
  798. this.chosenTask = threema.ChosenTask.RelayedData;
  799. } else {
  800. throw new Error('Invalid or unknown task name: ' + task.getName());
  801. }
  802. // If the WebRTC task was chosen, initialize handover.
  803. if (this.chosenTask === threema.ChosenTask.WebRTC) {
  804. const browser = this.browserService.getBrowser();
  805. // Safari does not support our dual-stack TURN servers.
  806. if (browser.isSafari(false)) {
  807. this.skipIceDs();
  808. }
  809. // Create peer connection
  810. this.pcHelper = new PeerConnectionHelper(
  811. this.$q, this.$rootScope,
  812. this.config, this.logService, this.timeoutService,
  813. task as saltyrtc.tasks.webrtc.WebRTCTask, this.config.ICE_SERVERS);
  814. // On state changes in the PeerConnectionHelper class, let state service know about it
  815. this.pcHelper.onConnectionStateChange = (state: threema.TaskConnectionState) => {
  816. this.stateService.updateTaskConnectionState(state);
  817. };
  818. // Initiate handover process
  819. this.pcHelper.handover();
  820. // Otherwise, no handover is necessary.
  821. } else {
  822. this.onHandover(resumeSession);
  823. }
  824. }
  825. /**
  826. * For the WebRTC task, this is called when the DataChannel is open.
  827. * For the relayed data task, this is called once the connection is established.
  828. */
  829. private async onConnectionEstablished(resumeSession: boolean) {
  830. // Send connection info
  831. if (resumeSession) {
  832. const incomingSequenceNumber = this.previousIncomingChunkSequenceNumber.get();
  833. this.arpLog.debug(`Sending connection info (resume=yes, sn-in=${incomingSequenceNumber})`);
  834. this._sendConnectionInfo(
  835. this.currentConnectionId.buffer,
  836. this.previousConnectionId.buffer,
  837. incomingSequenceNumber,
  838. );
  839. } else {
  840. this.arpLog.debug('Sending connection info (resume=no)');
  841. this._sendConnectionInfo(this.currentConnectionId.buffer);
  842. }
  843. // Receive connection info
  844. // Note: We can receive the connectionInfo message here or
  845. // an error which should fail the session.
  846. let remoteInfo: ConnectionInfo;
  847. try {
  848. remoteInfo = await this.connectionInfoFuture;
  849. } catch (error) {
  850. this.arpLog.error(error);
  851. this.failSession();
  852. return;
  853. }
  854. let outgoingSequenceNumber: string | number = 'n/a';
  855. let remoteResume = 'no';
  856. if (remoteInfo.resume !== undefined) {
  857. outgoingSequenceNumber = remoteInfo.resume.sequenceNumber;
  858. remoteResume = 'yes';
  859. }
  860. this.arpLog.debug(`Received connection info (resume=${remoteResume}, ` +
  861. `sn-out=${outgoingSequenceNumber})`);
  862. // Resume the session (if both requested to resume the same connection)
  863. let sessionWasResumed;
  864. try {
  865. sessionWasResumed = this.maybeResumeSession(resumeSession, remoteInfo);
  866. } catch (error) {
  867. this.arpLog.error(error);
  868. this.failSession();
  869. return;
  870. }
  871. // Handshake complete!
  872. this.handshakeCompleted = true;
  873. // If we could not resume for whatever reason
  874. const requiredInitializationSteps = [];
  875. if (!resumeSession || !sessionWasResumed) {
  876. // Note: We cannot reset the message sequence number here any more since
  877. // it has already been used for the connectionInfo message.
  878. this.discardSession({ resetMessageSequenceNumber: false });
  879. this.arpLog.debug('Session discarded');
  880. // Reset fields, blob cache, pending requests and pending timeouts in case the session
  881. // cannot be resumed
  882. this.clearCache();
  883. this.wireMessageFutures.clear();
  884. this.timeoutService.cancelAll();
  885. // Set required initialisation steps
  886. requiredInitializationSteps.push(
  887. InitializationStep.ClientInfo,
  888. InitializationStep.Conversations,
  889. InitializationStep.Receivers,
  890. InitializationStep.Profile,
  891. );
  892. // Request initial data
  893. this._requestInitialData();
  894. } else {
  895. this.arpLog.debug('Session resumed');
  896. }
  897. // Schedule required initialisation steps if we have finished the
  898. // previous connection
  899. if (this.startupPromise !== null) {
  900. this.runAfterInitializationSteps(requiredInitializationSteps, () => {
  901. this.stateService.updateConnectionBuildupState('done');
  902. this.startupPromise.resolve();
  903. this.startupPromise = null;
  904. this.startupDone = true;
  905. this._resetInitializationSteps();
  906. // Hack for #712
  907. // TODO: Remove once we have the ack protocol for Android, too
  908. if (this.chosenTask !== threema.ChosenTask.RelayedData && this.$state.includes('messenger')) {
  909. this.$state.reload().catch((error) => {
  910. this.log.error('Unable to reload state:', error);
  911. });
  912. }
  913. });
  914. }
  915. // In case...
  916. // - we wanted to resume, but
  917. // - we could not resume, and
  918. // - we had a previous connection
  919. if (resumeSession && !sessionWasResumed && this.clientInfo !== null) {
  920. this.$rootScope.$apply(() => {
  921. // TODO: Remove this conditional once we have session
  922. // resumption for Android!
  923. if (this.chosenTask !== threema.ChosenTask.RelayedData) {
  924. return;
  925. }
  926. // Redirect to the conversation overview
  927. if (this.$state.includes('messenger')) {
  928. this.$state.go('messenger.home');
  929. }
  930. });
  931. }
  932. // Fetch current version
  933. // Delay it to prevent the dialog from being closed by the messenger constructor,
  934. // which closes all open dialogs.
  935. this.timeoutService.register(() => this.versionService.checkForUpdate(), 7000, true, 'checkForUpdate');
  936. // Notify state service about data loading
  937. this.stateService.updateConnectionBuildupState('loading');
  938. }
  939. /**
  940. * Handover done.
  941. *
  942. * This can either be a real handover to WebRTC (Android), or simply
  943. * when the relayed data task takes over (iOS).
  944. */
  945. private onHandover(resumeSession: boolean) {
  946. // Initialize NotificationService
  947. this.log.debug('Initializing NotificationService...');
  948. this.notificationService.init();
  949. // Derive connection ID
  950. // Note: We need to make sure this is done before any ARP messages can be received
  951. const connectionIdBox = this.salty.encryptForPeer(new Uint8Array(0), WebClientService.CONNECTION_ID_NONCE);
  952. // Note: We explicitly copy the data here to be able to use the underlying buffer directly
  953. this.currentConnectionId = new Uint8Array(connectionIdBox.data);
  954. // If the WebRTC task was chosen, initialize the data channel
  955. if (this.chosenTask === threema.ChosenTask.WebRTC) {
  956. const task = this.salty.getTask() as saltyrtc.tasks.webrtc.WebRTCTask;
  957. // Create data channel
  958. this.arpLog.debug(`Creating data channel ${WebClientService.DC_LABEL}`);
  959. const dc = this.pcHelper.pc.createDataChannel(WebClientService.DC_LABEL);
  960. dc.binaryType = 'arraybuffer';
  961. // Wrap as unbounded, flow-controlled data channel
  962. this.secureDataChannel = new UnboundedFlowControlledDataChannel(
  963. dc, this.logService, this.config.TRANSPORT_LOG_LEVEL);
  964. // Create crypto context
  965. // Note: We need to apply encrypt-then-chunk for backwards
  966. // compatibility reasons.
  967. this.secureDataChannelCrypto = task.createCryptoContext(dc.id);
  968. // Create unchunker
  969. // Note: We need to use an unreliable unordered unchunker for backwards
  970. // compatibility reasons.
  971. const unchunker = new chunkedDc.UnreliableUnorderedUnchunker();
  972. // Bind events
  973. dc.onopen = () => {
  974. this.arpLog.info(`Data channel ${dc.label} open`);
  975. // Determine chunk length
  976. this.secureDataChannelChunkLength = Math.min(
  977. WebClientService.DATA_CHANNEL_MAX_CHUNK_SIZE, this.pcHelper.pc.sctp.maxMessageSize);
  978. this.arpLog.debug(`Using chunk length: ${this.secureDataChannelChunkLength} for data channel` +
  979. dc.label);
  980. // Connection established
  981. this.onConnectionEstablished(resumeSession).catch((error) => {
  982. this.arpLog.error('Error during handshake:', error);
  983. });
  984. };
  985. dc.onclose = () => {
  986. this.arpLog.error(`Data channel ${dc.label} closed prematurely`);
  987. this.failSession();
  988. };
  989. dc.onerror = (event) => {
  990. this.arpLog.error(`Data channel ${dc.label} error:`, event);
  991. this.failSession();
  992. };
  993. dc.onmessage = (event) => {
  994. this.arpLogV.debug(`Data channel ${dc.label} incoming chunk of length ${event.data.byteLength}`);
  995. unchunker.add(new Uint8Array(event.data));
  996. };
  997. // noinspection JSUndefinedPropertyAssignment
  998. unchunker.onMessage = (array) => {
  999. const box = saltyrtcClient.Box.fromUint8Array(
  1000. array, saltyrtcTaskWebrtc.DataChannelCryptoContext.NONCE_LENGTH);
  1001. const message = this.secureDataChannelCrypto.decrypt(box);
  1002. this.handleIncomingMessageBytes(message);
  1003. };
  1004. // Mark as handed over
  1005. // Note: Even though this method is also "misused" for the relayed
  1006. // data task, only WebRTC really hands over.
  1007. this.handoverDone = true;
  1008. } else if (this.chosenTask === threema.ChosenTask.RelayedData) {
  1009. // Handle messages directly
  1010. this.relayedDataTask.on('data', (ev: saltyrtc.SaltyRTCEvent) => {
  1011. this.receiveChunk(new Uint8Array(ev.data));
  1012. });
  1013. // The communication channel is now open! Fetch initial data
  1014. this.onConnectionEstablished(resumeSession).catch((error) => {
  1015. this.arpLog.error('Error during handshake:', error);
  1016. });
  1017. }
  1018. }
  1019. /**
  1020. * A previously authenticated peer disconnected from the server.
  1021. */
  1022. private onPeerDisconnected(peerId: number) {
  1023. switch (this.chosenTask) {
  1024. case threema.ChosenTask.RelayedData:
  1025. // TODO: Fix "Ignoring peer-disconnected event (state is new)"
  1026. if (this.stateService.taskConnectionState === threema.TaskConnectionState.Connected) {
  1027. this.stateService.updateTaskConnectionState(threema.TaskConnectionState.Reconnecting);
  1028. } else {
  1029. this.arpLog.debug(
  1030. 'Ignoring peer-disconnected event (state is '
  1031. + this.stateService.taskConnectionState + ')',
  1032. );
  1033. }
  1034. break;
  1035. default:
  1036. this.arpLog.debug(
  1037. 'Ignoring peer-disconnected event (chosen task is ' + this.chosenTask + ')',
  1038. );
  1039. }
  1040. }
  1041. /**
  1042. * Send a push message to wake up the peer.
  1043. *
  1044. * Returns the maximum expected period until the promise will be resolved,
  1045. * and the promise itself.
  1046. */
  1047. public sendPush(): [number, Promise<void>] {
  1048. // Create new session
  1049. if (this.pushSession === null) {
  1050. this.pushSession = this.pushService.createSession(this.salty.permanentKeyBytes, this.pushSessionConfig);
  1051. // Start and handle success/error
  1052. this.pushPromise = this.pushSession.start()
  1053. .then(() => this.resetPushSession(true))
  1054. .catch((error) => {
  1055. // Reset push session
  1056. this.resetPushSession(false);
  1057. // Handle errors
  1058. if (error instanceof TimeoutError) {
  1059. this.showDeviceUnreachableDialog();
  1060. } else if (error instanceof PushError && error.statusCode === 400) {
  1061. // Can happen if the push token is invalid
  1062. this.showPushRejectedDialog();
  1063. } else {
  1064. this.failSession();
  1065. }
  1066. });
  1067. // Update state
  1068. if (!this.$rootScope.$$phase) {
  1069. this.$rootScope.$apply(() => this.stateService.updateConnectionBuildupState('push'));
  1070. } else {
  1071. this.stateService.updateConnectionBuildupState('push');
  1072. }
  1073. }
  1074. // Retrieve the expected maximum period
  1075. return [this.pushSessionExpectedPeriodMaxMs, this.pushPromise];
  1076. }
  1077. /**
  1078. * Reset push session (if any) and hide the *device unreachable* dialog
  1079. * (if any and if requested).
  1080. */
  1081. private resetPushSession(hideDeviceUnreachableDialog: boolean = true): void {
  1082. // Hide unreachable dialog (if any)
  1083. if (hideDeviceUnreachableDialog && this.deviceUnreachableDialog !== null) {
  1084. this.$mdDialog.hide();
  1085. }
  1086. // Reset push session (if any)
  1087. if (this.pushSession !== null) {
  1088. this.pushSession.done();
  1089. this.pushSession = null;
  1090. this.pushPromise = null;
  1091. }
  1092. }
  1093. /**
  1094. * Show the *device unreachable* dialog.
  1095. */
  1096. public showDeviceUnreachableDialog(): void {
  1097. // Show device unreachable dialog (if we were already
  1098. // connected and if not already visible).
  1099. if (this.pushService.isAvailable() && this.$state.includes('messenger')
  1100. && this.deviceUnreachableDialog === null) {
  1101. this.deviceUnreachableDialog = this.$mdDialog.show({
  1102. controller: DeviceUnreachableController,
  1103. controllerAs: 'ctrl',
  1104. templateUrl: 'partials/dialog.device-unreachable.html',
  1105. parent: angular.element(document.body),
  1106. escapeToClose: false,
  1107. })
  1108. .finally(() => this.deviceUnreachableDialog = null);
  1109. }
  1110. }
  1111. public showPushRejectedDialog(): void {
  1112. this.$mdDialog.show({
  1113. controller: PushRejectedDialogController,
  1114. controllerAs: 'ctrl',
  1115. templateUrl: 'partials/dialog.push-rejected.html',
  1116. parent: angular.element(document.body),
  1117. escapeToClose: false,
  1118. });
  1119. }
  1120. /**
  1121. * Start the webclient service.
  1122. * Return a promise that resolves once connected.
  1123. */
  1124. public start(skipPush: boolean = false): ng.IPromise<any> {
  1125. this.log.debug('Starting WebClientService...');
  1126. // Promise to track startup state
  1127. if (this.startupPromise !== null) {
  1128. this.log.debug('Reusing startup promise (was not resolved)');
  1129. } else {
  1130. this.log.debug('Creating new startup promise');
  1131. this.startupPromise = this.$q.defer();
  1132. }
  1133. this.startupDone = false;
  1134. this.handoverDone = false;
  1135. // Connect
  1136. this.salty.connect();
  1137. // If push service is available, notify app
  1138. if (this.pushService.isAvailable()) {
  1139. if (skipPush === true) {
  1140. this.log.debug('start(): Skipping push notification');
  1141. } else {
  1142. this.sendPush();
  1143. }
  1144. } else if (this.trustedKeyStore.hasTrustedKey()) {
  1145. this.log.debug('Push service not available');
  1146. this.stateService.updateConnectionBuildupState('manual_start');
  1147. }
  1148. return this.startupPromise.promise;
  1149. }
  1150. /**
  1151. * Stop the webclient service.
  1152. *
  1153. * This is a forced stop, meaning that all connections are being closed.
  1154. *
  1155. * @reason The disconnect reason.
  1156. * @send will send a disconnect message to the remote peer containing the
  1157. * disconnect reason if set to `true`.
  1158. * @close will close the session (meaning all cached data will be
  1159. * invalidated) if set to `true`. Note that the session will always be
  1160. * closed in case `reason` indicates that the session is to be deleted,
  1161. * has been replaced, a protocol error occurred or in case `redirect` has
  1162. * been set to `true`.
  1163. * @redirect will redirect to the welcome page if set to `true`.
  1164. * @connectionBuildupState: The connection buildup state the state service
  1165. * will be reset to.
  1166. */
  1167. public stop(args: threema.WebClientServiceStopArguments): void {
  1168. if (args.close === true) {
  1169. throw new Error('args.close has been set to "true" but requires a redirect state instead');
  1170. }
  1171. this.log.info(`Stopping (reason=${args.reason}, send=${args.send}, close=${args.close}, ` +
  1172. 'connectionBuildupState=' +
  1173. `${args.connectionBuildupState !== undefined ? args.connectionBuildupState : 'n/a'})`);
  1174. let close = args.close !== false;
  1175. let remove = false;
  1176. // Stop push session
  1177. this.resetPushSession(true);
  1178. // Session deleted: Force close and delete
  1179. if (args.reason === DisconnectReason.SessionDeleted) {
  1180. close = true;
  1181. remove = true;
  1182. }
  1183. // Session replaced or error'ed: Force close
  1184. if (args.reason === DisconnectReason.SessionReplaced || args.reason === DisconnectReason.OutOfMemory ||
  1185. args.reason === DisconnectReason.SessionError) {
  1186. close = true;
  1187. }
  1188. // Send disconnect reason to the remote peer if requested
  1189. if (args.send && this.stateService.state === threema.GlobalConnectionState.Ok) {
  1190. // noinspection JSIgnoredPromiseFromCall
  1191. this.sendUpdateWireMessage(WebClientService.SUB_TYPE_CONNECTION_DISCONNECT, false, undefined,
  1192. {reason: args.reason});
  1193. }
  1194. // Stop timer
  1195. if (this.ackTimer !== null) {
  1196. self.clearTimeout(this.ackTimer);
  1197. this.ackTimer = null;
  1198. }
  1199. if (this.pushTimer !== null) {
  1200. this.cancelPush(0);
  1201. }
  1202. this.log.debug('Timer stopped');
  1203. // Reset states
  1204. this.stateService.reset(args.connectionBuildupState);
  1205. // Reset the unread count
  1206. this.resetUnreadCount();
  1207. // Clear stored data (trusted key, push token, etc) if deleting the session
  1208. if (remove) {
  1209. this.trustedKeyStore.clearTrustedKey();
  1210. }
  1211. // Invalidate and clear caches
  1212. if (close) {
  1213. // Clear connection ids & caches
  1214. this.previousConnectionId = null;
  1215. this.previousIncomingChunkSequenceNumber = null;
  1216. this.previousChunkCache = null;
  1217. // Remove chosen task
  1218. // Note: This implicitly prevents automatic connection attempts
  1219. // from the status controller.
  1220. this.chosenTask = threema.ChosenTask.None;
  1221. // Reset general client information
  1222. this.clientInfo = null;
  1223. // Clear fetched messages and the blob cache
  1224. this.clearCache();
  1225. // Remove all pending promises
  1226. this.wireMessageFutures.clear();
  1227. // Cancel pending timeouts
  1228. this.timeoutService.cancelAll();
  1229. // Reset the push service
  1230. this.pushService.reset();
  1231. // Closed!
  1232. this.arpLog.debug('Session closed (cannot be resumed)');
  1233. } else {
  1234. // Only reuse a previous chunk cache if the handshake had been
  1235. // completed
  1236. if (this.handshakeCompleted) {
  1237. // Move instances that we need to re-establish a previous session
  1238. this.previousConnectionId = this.currentConnectionId;
  1239. this.previousIncomingChunkSequenceNumber = this.currentIncomingChunkSequenceNumber;
  1240. this.previousChunkCache = this.currentChunkCache;
  1241. }
  1242. this.arpLog.debug('Session remains open');
  1243. }
  1244. // Close data channel
  1245. if (this.secureDataChannel !== null) {
  1246. this.arpLog.debug('Closing data channel');
  1247. this.secureDataChannel.dc.onopen = null;
  1248. this.secureDataChannel.dc.onmessage = null;
  1249. this.secureDataChannel.dc.onbufferedamountlow = null;
  1250. this.secureDataChannel.dc.onerror = null;
  1251. this.secureDataChannel.dc.onclose = null;
  1252. this.secureDataChannel.dc.close();
  1253. }
  1254. // Close SaltyRTC connection
  1255. if (this.relayedDataTask !== null) {
  1256. this.relayedDataTask.off();
  1257. }
  1258. if (this.salty !== null) {
  1259. this.arpLog.debug('Closing signaling');
  1260. this.salty.off();
  1261. this.salty.disconnect(true);
  1262. }
  1263. // Close peer connection
  1264. if (this.pcHelper !== null) {
  1265. this.pcHelper.onConnectionStateChange = null;
  1266. this.pcHelper.close();
  1267. this.arpLog.debug('Peer connection closed');
  1268. } else {
  1269. this.arpLog.debug('Peer connection was null');
  1270. }
  1271. // Done, redirect now if session closed
  1272. if (close) {
  1273. // Reject startup promise (if any)
  1274. if (this.startupPromise !== null) {
  1275. this.startupPromise.reject();
  1276. this.startupPromise = null;
  1277. this._resetInitializationSteps();
  1278. }
  1279. // Translate close flag
  1280. const state = args.close !== false ? args.close : 'welcome';
  1281. this.$state.go(state);
  1282. }
  1283. }
  1284. /**
  1285. * Safari has issues with dual-stack TURN servers:
  1286. * https://bugs.webkit.org/show_bug.cgi?id=173307#c13
  1287. * As a workaround, replace ds-turn.threema.ch servers
  1288. * in the ICE_SERVERS configuration with turn.threema.ch.
  1289. */
  1290. public skipIceDs(): void {
  1291. this.arpLog.debug('Requested to replace DS servers in ICE configuration');
  1292. const allUrls = [].concat(...this.config.ICE_SERVERS.map((conf) => conf.urls));
  1293. if (allUrls.some((url) => url.includes('ds-turn.threema.ch'))) {
  1294. for (const server of this.config.ICE_SERVERS) {
  1295. // Replace dual stack entries
  1296. const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
  1297. server.urls = urls.map((url) => {
  1298. return url.replace('ds-turn.threema.ch', 'turn.threema.ch');
  1299. });
  1300. }
  1301. } else {
  1302. this.arpLog.debug('No ds-turn ICE server present');
  1303. }
  1304. }
  1305. /**
  1306. * Mark a component as initialized
  1307. */
  1308. public registerInitializationStep(name: threema.InitializationStep) {
  1309. if (this.initialized.has(name) ) {
  1310. this.arpLog.warn('Initialization step "' + name + '" already registered');
  1311. return;
  1312. }
  1313. this.arpLog.debug('Initialization step "' + name + '" done');
  1314. this.initialized.add(name);
  1315. // Check pending routines
  1316. for (const routine of this.pendingInitializationStepRoutines) {
  1317. const ready = routine.requiredSteps.every((requiredStep) => {
  1318. return this.initialized.has(requiredStep);
  1319. });
  1320. if (ready) {
  1321. this.arpLog.debug('Running routine after initialization "' + name + '" completed');
  1322. // Important: Remove the routine BEFORE calling it to prevent
  1323. // it from being called more than once (due to nested
  1324. // calls to .registerInitializationStep).
  1325. this.pendingInitializationStepRoutines.delete(routine);
  1326. routine.callback.apply(this);
  1327. }
  1328. }
  1329. }
  1330. public setReceiverListener(listener: threema.ReceiverListener): void {
  1331. this.receiverListener.push(listener);
  1332. }
  1333. /**
  1334. * Send a connection info update.
  1335. */
  1336. private _sendConnectionInfo(connectionId: ArrayBuffer, resumeId?: ArrayBuffer, sequenceNumber?: number): void {
  1337. const data = {id: connectionId};
  1338. if (resumeId !== undefined && sequenceNumber !== undefined) {
  1339. (data as any).resume = {
  1340. id: resumeId,
  1341. sequenceNumber: sequenceNumber,
  1342. };
  1343. }
  1344. // noinspection JSIgnoredPromiseFromCall
  1345. this.sendUpdateWireMessage(WebClientService.SUB_TYPE_CONNECTION_INFO, false, undefined, data);
  1346. }
  1347. /**
  1348. * Request a connection ack update.
  1349. */
  1350. private _requestConnectionAck(): void {
  1351. // noinspection JSIgnoredPromiseFromCall
  1352. this.sendRequestWireMessage(WebClientService.SUB_TYPE_CONNECTION_ACK, false);
  1353. }
  1354. /**
  1355. * Send a connection ack update.
  1356. */
  1357. private _sendConnectionAck(): void {
  1358. // Send the current incoming sequence number for chunks
  1359. // noinspection JSIgnoredPromiseFromCall
  1360. this.sendUpdateWireMessage(WebClientService.SUB_TYPE_CONNECTION_ACK, false, undefined, {
  1361. sequenceNumber: this.currentIncomingChunkSequenceNumber.get(),
  1362. });
  1363. // Clear pending ack timer (if any)
  1364. if (this.ackTimer !== null) {
  1365. self.clearTimeout(this.ackTimer);
  1366. this.ackTimer = null;
  1367. }
  1368. }
  1369. /**
  1370. * Send a client info request.
  1371. */
  1372. public requestClientInfo(): void {
  1373. this.arpLog.debug('Sending client info request');
  1374. const browser = this.browserService.getBrowser();
  1375. const data: object = {
  1376. [WebClientService.ARGUMENT_USER_AGENT]: navigator.userAgent,
  1377. };
  1378. if (browser.name) {
  1379. data[WebClientService.ARGUMENT_BROWSER_NAME] = browser.name;
  1380. }
  1381. if (browser.version) {
  1382. data[WebClientService.ARGUMENT_BROWSER_VERSION] = browser.version;
  1383. }
  1384. const subType = WebClientService.SUB_TYPE_CLIENT_INFO;
  1385. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility, undefined, data)
  1386. .catch(this.failSessionOnReject(WebClientService.TYPE_REQUEST, subType)); // critical request
  1387. }
  1388. /**
  1389. * Send a receivers request.
  1390. */
  1391. public requestReceivers(): void {
  1392. this.arpLog.debug('Sending receivers request');
  1393. const subType = WebClientService.SUB_TYPE_RECEIVERS;
  1394. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility)
  1395. .catch(this.failSessionOnReject(WebClientService.TYPE_REQUEST, subType)); // critical request
  1396. }
  1397. /**
  1398. * Send a conversation request.
  1399. */
  1400. public requestConversations(): void {
  1401. this.arpLog.debug('Sending conversation request');
  1402. const subType = WebClientService.SUB_TYPE_CONVERSATIONS;
  1403. const args = {[WebClientService.ARGUMENT_MAX_SIZE]: WebClientService.AVATAR_LOW_MAX_SIZE};
  1404. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility, args)
  1405. .catch(this.failSessionOnReject(WebClientService.TYPE_REQUEST, subType)); // critical request
  1406. }
  1407. /**
  1408. * Send a battery status request.
  1409. */
  1410. public requestBatteryStatus(): void {
  1411. this.arpLog.debug('Sending battery status request');
  1412. const subType = WebClientService.SUB_TYPE_BATTERY_STATUS;
  1413. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility)
  1414. .catch(this.failSessionOnReject(WebClientService.TYPE_REQUEST, subType)); // critical request
  1415. }
  1416. /**
  1417. * Send a profile request.
  1418. */
  1419. public requestProfile(): void {
  1420. this.arpLog.debug('Sending profile request');
  1421. const subType = WebClientService.SUB_TYPE_PROFILE;
  1422. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility)
  1423. .catch(this.failSessionOnReject(WebClientService.TYPE_REQUEST, subType)); // critical request
  1424. }
  1425. /**
  1426. * Send a message request for the specified receiver.
  1427. *
  1428. * This method will only be called when initializing a conversation in the
  1429. * webclient. It is used to download all existing messages.
  1430. *
  1431. * New messages are not requested this way, instead they are sent as a
  1432. * message update.
  1433. */
  1434. public requestMessages(receiver: threema.Receiver): string | null {
  1435. this.arpLog.debug('requestMessages');
  1436. // If there are no more messages available, stop here.
  1437. if (!this.messages.hasMore(receiver)) {
  1438. this.messages.notify(receiver, this.$rootScope);
  1439. this.arpLog.debug('requestMessages: No more messages available');
  1440. return null;
  1441. }
  1442. this.loadingMessages.set(receiver.type + receiver.id, true);
  1443. // Check if messages have already been requested
  1444. if (this.messages.isRequested(receiver)) {
  1445. this.arpLog.debug('requestMessages: Already requested');
  1446. return null;
  1447. }
  1448. // Get the reference msg id
  1449. const refMsgId = this.messages.getReferenceMsgId(receiver);
  1450. // Set requested
  1451. this.messages.setRequested(receiver);
  1452. // Create arguments
  1453. const args = {
  1454. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1455. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1456. } as any;
  1457. // If a reference msg id has been set, send it along
  1458. const msgId = this.messages.getReferenceMsgId(receiver);
  1459. if (msgId !== null) {
  1460. args[WebClientService.ARGUMENT_REFERENCE_MSG_ID] = msgId;
  1461. }
  1462. // Send request
  1463. this.arpLog.debug('Sending message request for', receiver.type, receiver.id,
  1464. 'with message id', msgId);
  1465. const subType = WebClientService.SUB_TYPE_MESSAGES;
  1466. // TODO: Return the promise instead to unset the 'requested' flag?
  1467. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility, args)
  1468. .catch(this.logOnReject(WebClientService.TYPE_REQUEST, subType));
  1469. return refMsgId;
  1470. }
  1471. /**
  1472. * Send an avatar request for the specified receiver.
  1473. */
  1474. public requestAvatar(receiver: threema.Receiver, highResolution: boolean): Promise<ArrayBuffer> {
  1475. // Check if the receiver has an avatar or the avatar already exists
  1476. const resolution = highResolution ? 'high' : 'low';
  1477. const receiverInfo = this.receivers.getData(receiver);
  1478. if (receiverInfo && receiverInfo.avatar && receiverInfo.avatar[resolution]) {
  1479. // Avatar already exists
  1480. // TODO: Do we get avatar changes via update?
  1481. return Promise.resolve(receiverInfo.avatar[resolution]);
  1482. }
  1483. // If we're requesting our own avatar, change type from "me" to "contact"
  1484. let receiverType = receiver.type;
  1485. if (receiverType === 'me') {
  1486. receiverType = 'contact';
  1487. }
  1488. // Create arguments and send request
  1489. const args = {
  1490. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiverType,
  1491. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1492. [WebClientService.ARGUMENT_AVATAR_HIGH_RESOLUTION]: highResolution,
  1493. } as any;
  1494. if (!highResolution) {
  1495. args[WebClientService.ARGUMENT_MAX_SIZE] = WebClientService.AVATAR_LOW_MAX_SIZE;
  1496. }
  1497. this.arpLog.debug('Sending', resolution, 'res avatar request for', receiver.type, receiver.id);
  1498. const subType = WebClientService.SUB_TYPE_AVATAR;
  1499. return this.sendRequestWireMessage(subType, true, args);
  1500. }
  1501. /**
  1502. * Send a thumbnail request for the specified receiver.
  1503. */
  1504. public requestThumbnail(receiver: threema.Receiver, message: threema.Message): Promise<any> {
  1505. // Check if the receiver has an avatar or the avatar already exists
  1506. if (message.thumbnail !== undefined && message.thumbnail.img !== undefined) {
  1507. return new Promise<any>((e) => {
  1508. e(message.thumbnail.img);
  1509. });
  1510. }
  1511. // Create arguments and send request
  1512. const args = {
  1513. [WebClientService.ARGUMENT_MESSAGE_ID]: message.id.toString(),
  1514. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1515. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1516. };
  1517. this.arpLog.debug('Sending thumbnail request for', receiver.type, message.id);
  1518. const subType = WebClientService.SUB_TYPE_THUMBNAIL;
  1519. return this.sendRequestWireMessage(subType, true, args);
  1520. }
  1521. /**
  1522. * Request a blob.
  1523. */
  1524. public requestBlob(msgId: string, receiver: threema.Receiver): Promise<threema.BlobInfo> {
  1525. const cached = this.blobCache.get(msgId + receiver.type);
  1526. if (cached !== undefined) {
  1527. this.arpLog.debug('Use cached blob');
  1528. return new Promise((resolve) => {
  1529. resolve(cached);
  1530. });
  1531. }
  1532. const args = {
  1533. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1534. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1535. [WebClientService.ARGUMENT_MESSAGE_ID]: msgId,
  1536. };
  1537. this.arpLog.debug('Sending blob request for message', msgId);
  1538. return this.sendRequestWireMessage(WebClientService.SUB_TYPE_BLOB, true, args);
  1539. }
  1540. /**
  1541. * Mark a message as read.
  1542. */
  1543. public requestRead(receiver, newestMessage: threema.Message): void {
  1544. if (newestMessage.id === undefined) {
  1545. // Message that hasn't been sent yet
  1546. this.arpLog.warn('Called requestRead on a message without id');
  1547. return;
  1548. }
  1549. if (newestMessage.type === 'status') {
  1550. this.arpLog.warn('Called requestRead on a status message');
  1551. return;
  1552. }
  1553. // Create arguments and send request
  1554. const args = {
  1555. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1556. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1557. [WebClientService.ARGUMENT_MESSAGE_ID]: newestMessage.id.toString(),
  1558. };
  1559. this.arpLog.debug('Sending read request for', receiver.type, receiver.id, '(msg ' + newestMessage.id + ')');
  1560. const subType = WebClientService.SUB_TYPE_READ;
  1561. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility, args)
  1562. .catch(this.logOnReject(WebClientService.TYPE_REQUEST, subType));
  1563. }
  1564. public requestContactDetail(contactReceiver: threema.ContactReceiver): Promise<any> {
  1565. const args = {
  1566. [WebClientService.ARGUMENT_IDENTITY]: contactReceiver.id,
  1567. };
  1568. return this.sendRequestWireMessage(WebClientService.SUB_TYPE_CONTACT_DETAIL, true, args);
  1569. }
  1570. /**
  1571. * Send a message to the specified receiver.
  1572. */
  1573. public async sendMessage(
  1574. baseReceiver: threema.BaseReceiver,
  1575. sendType: threema.MessageContentType,
  1576. data: threema.MessageData,
  1577. options: {
  1578. previewDataUrl?: string,
  1579. waitUntilAcknowledged?: boolean,
  1580. } = {},
  1581. ): Promise<any> {
  1582. // This is the expected message type that will be reflected
  1583. // back once the message has been created successfully.
  1584. let reflectedType: threema.MessageType;
  1585. // Try to load receiver
  1586. const receiver = this.receivers.getData(baseReceiver);
  1587. // Check blocked flag
  1588. if (isContactReceiver(receiver) && receiver.isBlocked) {
  1589. throw this.$translate.instant('error.CONTACT_BLOCKED');
  1590. }
  1591. // Decide on subtype
  1592. let subType;
  1593. switch (sendType) {
  1594. case 'text':
  1595. reflectedType = 'text';
  1596. subType = WebClientService.SUB_TYPE_TEXT_MESSAGE;
  1597. const textData = data as threema.TextMessageData;
  1598. const msgLength = textData.text.length;
  1599. // Ignore empty text messages
  1600. if (msgLength === 0) {
  1601. this.log.warn('Ignored empty text message');
  1602. throw this.$translate.instant('error.ERROR_OCCURRED');
  1603. }
  1604. // Note: Not validating message length again here, since that
  1605. // would require us to re-encode the text a second time (since
  1606. // the compose area already checks the length). If we still end
  1607. // up with messages that are too large for some unexpected
  1608. // reason, we'd get an error message from the app.
  1609. break;
  1610. case 'file':
  1611. const fileData = data as threema.FileMessageData;
  1612. // Validate max file size
  1613. if (this.chosenTask === threema.ChosenTask.WebRTC) {
  1614. const task = this.salty.getTask() as saltyrtc.tasks.webrtc.WebRTCTask;
  1615. if (task.version === 'v0' && fileData.size > WebClientService.MAX_FILE_SIZE_WEBRTC_TASK_V0) {
  1616. throw this.$translate.instant('error.FILE_TOO_LARGE_WEB');
  1617. }
  1618. } else {
  1619. if (fileData.size > this.clientInfo.capabilities.maxFileSize) {
  1620. throw this.$translate.instant('error.FILE_TOO_LARGE', {
  1621. maxmb: Math.floor(this.clientInfo.capabilities.maxFileSize / 1024 / 1024),
  1622. });
  1623. }
  1624. }
  1625. // Determine reflected type and required feature mask
  1626. reflectedType = 'file';
  1627. let requiredFeature = ContactReceiverFeature.FILE;
  1628. let invalidFeatureMessage = 'error.FILE_MESSAGES_NOT_SUPPORTED';
  1629. if (fileData.sendAsFile !== true) {
  1630. // File will be dispatched to the app as a file but the actual type sent
  1631. // to the recipient depends on the MIME type.
  1632. const mimeType = fileData.fileType;
  1633. if (this.mimeService.isAudio(mimeType, this.clientInfo.os)) {
  1634. reflectedType = 'audio';
  1635. requiredFeature = ContactReceiverFeature.AUDIO;
  1636. invalidFeatureMessage = 'error.AUDIO_MESSAGES_NOT_SUPPORTED';
  1637. } else if (this.mimeService.isImage(mimeType)) {
  1638. reflectedType = 'image';
  1639. } else if (this.mimeService.isVideo(mimeType)) {
  1640. reflectedType = 'video';
  1641. }
  1642. }
  1643. subType = WebClientService.SUB_TYPE_FILE_MESSAGE;
  1644. // check receiver
  1645. switch (receiver.type) {
  1646. case 'group':
  1647. case 'distributionList':
  1648. const unsupportedMembers = [];
  1649. let members: string[];
  1650. switch (receiver.type) {
  1651. case 'group':
  1652. const group = this.groups.get(receiver.id);
  1653. if (group === undefined) {
  1654. this.log.error(`Group ${receiver.id} not found`);
  1655. throw this.$translate.instant('error.ERROR_OCCURRED');
  1656. }
  1657. members = group.members;
  1658. break;
  1659. case 'distributionList':
  1660. const distributionList = this.distributionLists.get(receiver.id);
  1661. if (distributionList === undefined) {
  1662. this.log.error(`Distribution list ${receiver.id} not found`);
  1663. throw this.$translate.instant('error.ERROR_OCCURRED');
  1664. }
  1665. members = distributionList.members;
  1666. break;
  1667. }
  1668. for (const identity of members) {
  1669. if (identity !== this.me.id) {
  1670. // tslint:disable-next-line: no-shadowed-variable
  1671. const contact = this.contacts.get(identity);
  1672. if (contact === undefined) {
  1673. // This shouldn't actually happen. But if it happens, log an error
  1674. // and assume image support. It's much more likely that the contact
  1675. // can receive images (feature flag 0x01) than otherwise. And if one
  1676. // of the contacts really cannot receive images, the app will return
  1677. // an error message.
  1678. this.log.error(`Cannot retrieve contact ${identity}`);
  1679. } else if (!hasFeature(contact, requiredFeature, this.log)) {
  1680. unsupportedMembers.push(contact.displayName);
  1681. }
  1682. }
  1683. }
  1684. if (unsupportedMembers.length > 0) {
  1685. throw this.$translate.instant(
  1686. invalidFeatureMessage, {receiverName: unsupportedMembers.join(',')},
  1687. );
  1688. }
  1689. break;
  1690. case 'contact':
  1691. const contact = this.contacts.get(receiver.id);
  1692. if (contact === undefined) {
  1693. this.log.error('Cannot retrieve contact');
  1694. throw this.$translate.instant('error.ERROR_OCCURRED');
  1695. } else if (!hasFeature(contact, requiredFeature, this.log)) {
  1696. this.log.debug('Cannot send message: Feature level mismatch:',
  1697. contact.featureMask, 'does not include', requiredFeature);
  1698. throw this.$translate.instant(invalidFeatureMessage, {
  1699. receiverName: contact.displayName});
  1700. }
  1701. break;
  1702. default:
  1703. this.log.error('Invalid receiver type:', receiver.type);
  1704. throw this.$translate.instant('error.ERROR_OCCURRED');
  1705. }
  1706. break;
  1707. default:
  1708. this.log.error('Invalid message type:', sendType);
  1709. throw this.$translate.instant('error.ERROR_OCCURRED');
  1710. }
  1711. // Request the conversation to be loaded
  1712. // Note: This is required since we need to retrieve updates of the
  1713. // message we're going to send.
  1714. if (this.messages.getList(receiver).length === 0) {
  1715. await this.requestMessages(receiver);
  1716. }
  1717. // Create temporary message to be displayed until acknowledged by the
  1718. // mobile device
  1719. const id = this.createRandomWireMessageId();
  1720. let temporaryMessage: threema.Message;
  1721. try {
  1722. temporaryMessage = this.messageService.createTemporary(
  1723. id, receiver, reflectedType, data, options.previewDataUrl);
  1724. } catch (error) {
  1725. this.log.error(error);
  1726. throw this.$translate.instant('error.ERROR_OCCURRED');
  1727. }
  1728. this.messages.addNewer(receiver, [temporaryMessage]);
  1729. const args = {
  1730. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1731. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1732. };
  1733. // Send message
  1734. const sendPromise = this.sendCreateWireMessage(subType, true, args, data, id);
  1735. sendPromise.catch((error) => {
  1736. this.arpLog.error('Error sending message:', error);
  1737. // Remove temporary message
  1738. this.messages.removeTemporary(receiver, temporaryMessage.temporaryId);
  1739. // Determine error message
  1740. let errorMessage;
  1741. switch (error) {
  1742. case 'file_too_large': // TODO: deprecated
  1743. case 'fileTooLarge':
  1744. errorMessage = this.$translate.instant('error.FILE_TOO_LARGE_GENERIC');
  1745. break;
  1746. case 'blocked':
  1747. errorMessage = this.$translate.instant('error.CONTACT_BLOCKED');
  1748. break;
  1749. default:
  1750. errorMessage = this.$translate.instant('error.ERROR_OCCURRED');
  1751. }
  1752. // Show alert
  1753. this.alerts.push({
  1754. source: 'sendMessage',
  1755. type: 'alert',
  1756. message: errorMessage,
  1757. } as threema.Alert);
  1758. });
  1759. // Wait until the wire message has been acknowledged (if requested)
  1760. if (options.waitUntilAcknowledged) {
  1761. await sendPromise;
  1762. }
  1763. }
  1764. /**
  1765. * Send a message a ack/decline message
  1766. */
  1767. public ackMessage(receiver, message: threema.Message, acknowledged: boolean = true): void {
  1768. // Ignore empty text messages
  1769. // TODO check into a util class
  1770. if (message === null
  1771. || message === undefined
  1772. || message.isOutbox) {
  1773. return;
  1774. }
  1775. const args = {
  1776. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1777. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1778. [WebClientService.ARGUMENT_MESSAGE_ID]: message.id.toString(),
  1779. [WebClientService.ARGUMENT_MESSAGE_ACKNOWLEDGED]: acknowledged,
  1780. };
  1781. const subType = WebClientService.SUB_TYPE_ACK;
  1782. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility, args)
  1783. .catch(this.logOnReject(WebClientService.TYPE_REQUEST, subType));
  1784. }
  1785. /**
  1786. * Delete a message.
  1787. */
  1788. public deleteMessage(receiver, message: threema.Message): void {
  1789. // Ignore empty text messages
  1790. if (message === null || message === undefined) {
  1791. return;
  1792. }
  1793. const args = {
  1794. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1795. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1796. [WebClientService.ARGUMENT_MESSAGE_ID]: message.id.toString(),
  1797. };
  1798. const subType = WebClientService.SUB_TYPE_MESSAGE;
  1799. // TODO: ARP defines error codes but they aren't handled by the caller
  1800. this.sendDeleteWireMessage(subType, true, args)
  1801. .catch(this.logOnReject(WebClientService.TYPE_DELETE, subType));
  1802. }
  1803. public sendMeIsTyping(receiver: threema.ContactReceiver, isTyping: boolean): void {
  1804. const args = {[WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id};
  1805. const data = {[WebClientService.ARGUMENT_IS_TYPING]: isTyping};
  1806. // noinspection JSIgnoredPromiseFromCall
  1807. this.sendUpdateWireMessage(WebClientService.SUB_TYPE_TYPING, false, args, data);
  1808. }
  1809. public sendKeyPersisted(): void {
  1810. const subType = WebClientService.SUB_TYPE_KEY_PERSISTED;
  1811. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility)
  1812. .catch(this.logOnReject(WebClientService.TYPE_REQUEST, subType));
  1813. }
  1814. /**
  1815. * Add a contact receiver.
  1816. */
  1817. public addContact(threemaId: string): Promise<threema.ContactReceiver> {
  1818. const data = {
  1819. [WebClientService.ARGUMENT_IDENTITY]: threemaId,
  1820. };
  1821. const subType = WebClientService.SUB_TYPE_CONTACT;
  1822. return this.sendCreateWireMessage(subType, true, undefined, data);
  1823. }
  1824. /**
  1825. * Modify a contact name or an avatar
  1826. */
  1827. public modifyContact(
  1828. threemaId: string,
  1829. firstName?: string,
  1830. lastName?: string,
  1831. avatar?: ArrayBuffer | null,
  1832. ): Promise<threema.ContactReceiver> {
  1833. // Prepare payload data
  1834. const data = {};
  1835. if (firstName !== undefined) {
  1836. data[WebClientService.ARGUMENT_FIRST_NAME] = firstName;
  1837. }
  1838. if (lastName !== undefined) {
  1839. data[WebClientService.ARGUMENT_LAST_NAME] = lastName;
  1840. }
  1841. if (avatar !== undefined) {
  1842. data[WebClientService.ARGUMENT_AVATAR] = avatar;
  1843. }
  1844. // Get contact
  1845. const contact: threema.ContactReceiver = this.contacts.get(threemaId);
  1846. // If no changes happened, resolve the promise immediately.
  1847. if (Object.keys(data).length === 0) {
  1848. this.arpLog.warn('Trying to modify contact without any changes');
  1849. return Promise.resolve(contact);
  1850. }
  1851. // Send update
  1852. const args = {
  1853. [WebClientService.ARGUMENT_IDENTITY]: threemaId,
  1854. };
  1855. const subType = WebClientService.SUB_TYPE_CONTACT;
  1856. const promise = this.sendUpdateWireMessage(subType, true, args, data);
  1857. // If necessary, force an avatar reload
  1858. if (avatar !== undefined) {
  1859. this.contacts.get(threemaId).avatar = {};
  1860. // noinspection JSIgnoredPromiseFromCall
  1861. this.requestAvatar(contact, false);
  1862. }
  1863. return promise;
  1864. }
  1865. /*
  1866. * Modify a conversation.
  1867. */
  1868. public modifyConversation(conversation: threema.Conversation, isPinned?: boolean): Promise<null> {
  1869. const DATA_STARRED = 'isStarred';
  1870. // Prepare payload data
  1871. const args = {
  1872. [WebClientService.ARGUMENT_RECEIVER_TYPE]: conversation.type,
  1873. [WebClientService.ARGUMENT_RECEIVER_ID]: conversation.id,
  1874. };
  1875. const data = {};
  1876. if (hasValue(isPinned)) {
  1877. data[DATA_STARRED] = isPinned;
  1878. }
  1879. // If no changes happened, resolve the promise immediately.
  1880. if (Object.keys(data).length === 0) {
  1881. this.arpLog.warn('Trying to modify conversation without any changes');
  1882. return Promise.resolve(null);
  1883. }
  1884. // Send update
  1885. const subType = WebClientService.SUB_TYPE_CONVERSATION;
  1886. return this.sendUpdateWireMessage(subType, true, args, data);
  1887. }
  1888. /**
  1889. * Create a group receiver.
  1890. */
  1891. public createGroup(
  1892. members: string[],
  1893. name: string | null = null,
  1894. avatar?: ArrayBuffer | null,
  1895. ): Promise<threema.GroupReceiver> {
  1896. const data = {
  1897. [WebClientService.ARGUMENT_MEMBERS]: members,
  1898. [WebClientService.ARGUMENT_NAME]: name,
  1899. } as object;
  1900. if (hasValue(avatar)) {
  1901. data[WebClientService.ARGUMENT_AVATAR] = avatar;
  1902. }
  1903. const subType = WebClientService.SUB_TYPE_GROUP;
  1904. return this.sendCreateWireMessage(subType, true, undefined, data);
  1905. }
  1906. /**
  1907. * Modify a group receiver.
  1908. */
  1909. public modifyGroup(
  1910. id: string,
  1911. members: string[],
  1912. name?: string,
  1913. avatar?: ArrayBuffer | null,
  1914. ): Promise<threema.GroupReceiver> {
  1915. // Prepare payload data
  1916. const data = {
  1917. [WebClientService.ARGUMENT_MEMBERS]: members,
  1918. } as object;
  1919. if (name !== undefined) {
  1920. data[WebClientService.ARGUMENT_NAME] = name;
  1921. }
  1922. if (avatar !== undefined) {
  1923. data[WebClientService.ARGUMENT_AVATAR] = avatar;
  1924. }
  1925. // Send update
  1926. const args = {
  1927. [WebClientService.ARGUMENT_RECEIVER_ID]: id,
  1928. };
  1929. const subType = WebClientService.SUB_TYPE_GROUP;
  1930. const promise = this.sendUpdateWireMessage(subType, true, args, data);
  1931. // If necessary, reset avatar to force a avatar reload
  1932. if (avatar !== undefined) {
  1933. this.groups.get(id).avatar = {};
  1934. }
  1935. return promise;
  1936. }
  1937. public leaveGroup(group: threema.GroupReceiver): Promise<any> {
  1938. if (group === null || group === undefined || !group.access.canLeave) {
  1939. // TODO: Not a valid error code (see ARP)
  1940. return Promise.reject('not allowed');
  1941. }
  1942. const args = {
  1943. [WebClientService.ARGUMENT_RECEIVER_ID]: group.id,
  1944. [WebClientService.ARGUMENT_DELETE_TYPE]: WebClientService.DELETE_GROUP_TYPE_LEAVE,
  1945. };
  1946. const subType = WebClientService.SUB_TYPE_GROUP;
  1947. return this.sendDeleteWireMessage(subType, true, args);
  1948. }
  1949. public deleteGroup(group: threema.GroupReceiver): Promise<any> {
  1950. if (group === null || group === undefined || !group.access.canDelete) {
  1951. // TODO: Not a valid error code (see ARP)
  1952. return Promise.reject('not allowed');
  1953. }
  1954. const args = {
  1955. [WebClientService.ARGUMENT_RECEIVER_ID]: group.id,
  1956. [WebClientService.ARGUMENT_DELETE_TYPE]: WebClientService.DELETE_GROUP_TYPE_DELETE,
  1957. };
  1958. const subType = WebClientService.SUB_TYPE_GROUP;
  1959. return this.sendDeleteWireMessage(subType, true, args);
  1960. }
  1961. /**
  1962. * Force-sync a group.
  1963. */
  1964. public syncGroup(group: threema.GroupReceiver): Promise<any> {
  1965. if (group === null || group === undefined || !group.access.canSync) {
  1966. // TODO: Not a valid error code (see ARP)
  1967. return Promise.reject('not allowed');
  1968. }
  1969. const args = {
  1970. [WebClientService.ARGUMENT_RECEIVER_ID]: group.id,
  1971. };
  1972. const subType = WebClientService.SUB_TYPE_GROUP_SYNC;
  1973. return this.sendRequestWireMessage(subType, true, args);
  1974. }
  1975. /**
  1976. * Create a new distribution list receiver.
  1977. */
  1978. public createDistributionList(
  1979. members: string[],
  1980. name: string = null,
  1981. ): Promise<threema.DistributionListReceiver> {
  1982. const data = {
  1983. [WebClientService.ARGUMENT_MEMBERS]: members,
  1984. [WebClientService.ARGUMENT_NAME]: name,
  1985. };
  1986. const subType = WebClientService.SUB_TYPE_DISTRIBUTION_LIST;
  1987. return this.sendCreateWireMessage(subType, true, undefined, data);
  1988. }
  1989. public modifyDistributionList(
  1990. id: string,
  1991. members: string[],
  1992. name: string = null,
  1993. ): Promise<threema.DistributionListReceiver> {
  1994. const args = {
  1995. [WebClientService.ARGUMENT_RECEIVER_ID]: id,
  1996. };
  1997. const data = {
  1998. [WebClientService.ARGUMENT_MEMBERS]: members,
  1999. [WebClientService.ARGUMENT_NAME]: name,
  2000. } as any;
  2001. const subType = WebClientService.SUB_TYPE_DISTRIBUTION_LIST;
  2002. return this.sendUpdateWireMessage(subType, true, args, data);
  2003. }
  2004. public deleteDistributionList(distributionList: threema.DistributionListReceiver): Promise<any> {
  2005. if (distributionList === null || distributionList === undefined || !distributionList.access.canDelete) {
  2006. // TODO: Not a valid error code (see ARP)
  2007. return Promise.reject('not allowed');
  2008. }
  2009. const args = {
  2010. [WebClientService.ARGUMENT_RECEIVER_ID]: distributionList.id,
  2011. };
  2012. const subType = WebClientService.SUB_TYPE_DISTRIBUTION_LIST;
  2013. return this.sendDeleteWireMessage(subType, true, args);
  2014. }
  2015. /**
  2016. * Remove all messages of a receiver
  2017. * @param {threema.Receiver} receiver
  2018. * @returns {Promise<any>}
  2019. */
  2020. public cleanReceiverConversation(receiver: threema.Receiver): Promise<any> {
  2021. if (receiver === null || receiver === undefined) {
  2022. return Promise.reject('invalidIdentity');
  2023. }
  2024. const args = {
  2025. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  2026. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  2027. };
  2028. const subType = WebClientService.SUB_TYPE_CLEAN_RECEIVER_CONVERSATION;
  2029. return this.sendDeleteWireMessage(subType, true, args);
  2030. }
  2031. /**
  2032. * Modify own profile.
  2033. */
  2034. public modifyProfile(nickname?: string, avatar?: ArrayBuffer | null): Promise<null> {
  2035. // Prepare payload data
  2036. const data = {};
  2037. if (nickname !== undefined && nickname !== null) {
  2038. data[WebClientService.ARGUMENT_NICKNAME] = nickname;
  2039. }
  2040. if (avatar !== undefined) {
  2041. data[WebClientService.ARGUMENT_AVATAR] = avatar;
  2042. }
  2043. // If no changes happened, resolve the promise immediately.
  2044. if (Object.keys(data).length === 0) {
  2045. this.arpLog.warn('Trying to modify profile without any changes');
  2046. return Promise.resolve(null);
  2047. }
  2048. const subType = WebClientService.SUB_TYPE_PROFILE;
  2049. return this.sendUpdateWireMessage(subType, true, undefined, data);
  2050. }
  2051. /**
  2052. * Return whether the specified contact is currently typing.
  2053. */
  2054. public isTyping(contact: threema.ContactReceiver): boolean {
  2055. return this.typing.isTyping(contact);
  2056. }
  2057. /**
  2058. * Return the curring quoted message model
  2059. */
  2060. public getQuote(receiver: threema.Receiver): threema.Quote {
  2061. return this.drafts.getQuote(receiver);
  2062. }
  2063. /**
  2064. * Set or remove (if message is null) a quoted message model.
  2065. */
  2066. public setQuote(receiver: threema.Receiver, message: threema.Message = null): void {
  2067. // Remove current quote
  2068. this.drafts.removeQuote(receiver);
  2069. if (message !== null) {
  2070. const quoteText = this.messageService.getQuoteText(message);
  2071. if (quoteText !== undefined && quoteText !== null) {
  2072. const quote = {
  2073. identity: message.isOutbox ? this.me.id : message.partnerId,
  2074. text: quoteText,
  2075. } as threema.Quote;
  2076. this.drafts.setQuote(receiver, quote);
  2077. this.$rootScope.$broadcast('onQuoted', {
  2078. receiver: receiver,
  2079. quote: quote,
  2080. });
  2081. }
  2082. }
  2083. }
  2084. /**
  2085. * Set or remove (if string is null) a draft message
  2086. */
  2087. public setDraft(receiver: threema.Receiver, message: string = null): void {
  2088. if (message === null || message.trim().length === 0) {
  2089. this.drafts.removeText(receiver);
  2090. } else {
  2091. this.drafts.setText(receiver, message.trim());
  2092. }
  2093. }
  2094. /**
  2095. * return draft text
  2096. */
  2097. public getDraft(receiver: threema.Receiver): string {
  2098. return this.drafts.getText(receiver);
  2099. }
  2100. /**
  2101. * Reset data related to initialization.
  2102. */
  2103. private _resetInitializationSteps(): void {
  2104. this.arpLog.debug('Reset initialization steps');
  2105. this.initialized.clear();
  2106. this.pendingInitializationStepRoutines = new Set();
  2107. }
  2108. /**
  2109. * Reset data fields.
  2110. */
  2111. private _resetFields(): void {
  2112. // Reset initialization data
  2113. this._resetInitializationSteps();
  2114. // Create container instances
  2115. this.receivers = this.container.createReceivers();
  2116. this.conversations = this.container.createConversations();
  2117. this.messages = this.container.createMessages();
  2118. this.typingInstance = this.container.createTyping();
  2119. // Add converters (pre-processors)
  2120. this.conversations.setConverter(this.container.Converter.addReceiverToConversation(this.receivers));
  2121. // Add filters
  2122. this.conversations.setFilter(this.container.Filters.hasData(this.receivers));
  2123. }
  2124. private _requestInitialData(): void {
  2125. // If all conversations are reloaded, clear the message cache
  2126. // to get in sync (we don't know if a message was removed, updated etc..)
  2127. this.messages.clear(this.$rootScope);
  2128. // Request initial data
  2129. this.requestClientInfo();
  2130. this.requestProfile();
  2131. this.requestReceivers();
  2132. this.requestConversations();
  2133. this.requestBatteryStatus();
  2134. }
  2135. // TODO: Deprecated, remove soon.
  2136. private _receiveResponseConfirmAction(message: threema.WireMessage): void {
  2137. this.arpLog.debug('Received confirmAction response');
  2138. const future = this.popWireMessageFuture(message);
  2139. if (!message.ack.success) {
  2140. future.reject(message.ack.error);
  2141. } else {
  2142. future.resolve();
  2143. }
  2144. }
  2145. private _receiveResponseReceivers(message: threema.WireMessage): void {
  2146. this.arpLog.debug('Received receivers response');
  2147. const future = this.popWireMessageFuture(message, this.requiresTemporaryIdBackwardsCompatibility);
  2148. // Handle error (if any)
  2149. if ((!this.requiresTemporaryIdBackwardsCompatibility && message.ack !== undefined) && !message.ack.success) {
  2150. future.reject(message.ack.error);
  2151. }
  2152. // Unpack and validate data
  2153. const data = message.data;
  2154. if (data === undefined) {
  2155. this.arpLog.warn('Invalid receivers response, data missing');
  2156. return future.reject('invalidResponse');
  2157. }
  2158. // Run delayed as it requires the profile to be initialised
  2159. this.runAfterInitializationSteps([
  2160. InitializationStep.Profile,
  2161. ], () => {
  2162. // Store receivers
  2163. this.sortContacts(data.contact);
  2164. this.receivers.set(data);
  2165. this.registerInitializationStep(InitializationStep.Receivers);
  2166. future.resolve();
  2167. });
  2168. }
  2169. private _receiveResponseContactDetail(message: threema.WireMessage): void {
  2170. this.arpLog.debug('Received contact detail response');
  2171. const future = this.popWireMessageFuture(message);
  2172. // Handle error (if any)
  2173. if (!message.ack.success) {
  2174. return future.reject(message.ack.error);
  2175. }
  2176. // Unpack and validate data
  2177. const args = message.args;
  2178. const data = message.data;
  2179. if (args === undefined || data === undefined) {
  2180. this.arpLog.error('Invalid contact response, args or data missing');
  2181. return future.reject('invalidResponse');
  2182. }
  2183. // Set contact detail
  2184. const contactReceiver = this.receivers.contacts
  2185. .get(args[WebClientService.ARGUMENT_IDENTITY]) as threema.ContactReceiver;
  2186. const receiver = data[WebClientService.SUB_TYPE_RECEIVER];
  2187. if (hasValue(receiver)) {
  2188. contactReceiver.systemContact =
  2189. receiver[WebClientService.ARGUMENT_SYSTEM_CONTACT];
  2190. }
  2191. future.resolve(contactReceiver);
  2192. }
  2193. private _receiveUpdateAlert(message: threema.WireMessage): void {
  2194. this.arpLog.debug('Received alert');
  2195. this.alerts.push({
  2196. source: message.args.source,
  2197. type: message.args.type,
  2198. message: message.data.message,
  2199. } as threema.Alert);
  2200. }
  2201. /**
  2202. * A connectionAck request arrived.
  2203. */
  2204. private _receiveRequestConnectionAck(message: threema.WireMessage) {
  2205. this._sendConnectionAck();
  2206. }
  2207. /**
  2208. * A connectionAck update arrived.
  2209. */
  2210. private _receiveUpdateConnectionAck(message: threema.WireMessage) {
  2211. this.arpLog.debug('Received connection ack');
  2212. if (!hasValue(message.data)) {
  2213. this.arpLog.warn('Invalid connectionAck message: data missing');
  2214. return;
  2215. }
  2216. if (!hasValue(message.data.sequenceNumber)) {
  2217. this.arpLog.warn('Invalid connectionAck message: sequenceNumber missing');
  2218. return;
  2219. }
  2220. const sequenceNumber = message.data.sequenceNumber;
  2221. // Remove chunks which have already been received by the remote side
  2222. const size = this.currentChunkCache.byteLength;
  2223. let result;
  2224. this.arpLog.debug(`Pruning cache (local-sn=${this.currentChunkCache.sequenceNumber.get()}, ` +
  2225. `remote-sn=${sequenceNumber})`);
  2226. try {
  2227. result = this.currentChunkCache.prune(sequenceNumber);
  2228. } catch (error) {
  2229. this.arpLog.error(error);
  2230. this.failSession();
  2231. return;
  2232. }
  2233. this.arpLog.debug(`Chunk cache pruned, acknowledged: ${result.acknowledged}, left: ${result.left}, size: ` +
  2234. `${size} -> ${this.currentChunkCache.byteLength}`);
  2235. // Clear pending ack requests
  2236. if (this.pendingAckRequest !== null && sequenceNumber >= this.pendingAckRequest) {
  2237. this.pendingAckRequest = null;
  2238. }
  2239. }
  2240. /**
  2241. * A connectionDisconnect message arrived.
  2242. */
  2243. private _receiveUpdateConnectionDisconnect(message: threema.WireMessage) {
  2244. this.arpLog.debug('Received connectionDisconnect');
  2245. if (!hasValue(message.data) || !hasValue(message.data.reason)) {
  2246. this.arpLog.warn('Invalid connectionDisconnect message: data or reason missing');
  2247. return;
  2248. }
  2249. const reason = message.data.reason;
  2250. this.arpLog.debug(`Disconnecting requested (reason: ${reason})`);
  2251. let alertMessage: string;
  2252. switch (reason) {
  2253. case DisconnectReason.SessionStopped:
  2254. alertMessage = 'connection.SESSION_STOPPED';
  2255. break;
  2256. case DisconnectReason.SessionDeleted:
  2257. alertMessage = 'connection.SESSION_DELETED';
  2258. break;
  2259. case DisconnectReason.WebclientDisabled:
  2260. alertMessage = 'connection.WEBCLIENT_DISABLED';
  2261. break;
  2262. case DisconnectReason.SessionReplaced:
  2263. alertMessage = 'connection.SESSION_REPLACED';
  2264. break;
  2265. case DisconnectReason.OutOfMemory:
  2266. alertMessage = 'connection.OUT_OF_MEMORY';
  2267. break;
  2268. case DisconnectReason.SessionError:
  2269. alertMessage = 'connection.SESSION_ERROR';
  2270. break;
  2271. default:
  2272. alertMessage = 'connection.SESSION_ERROR';
  2273. this.arpLog.error('Unknown disconnect reason:', reason);
  2274. break;
  2275. }
  2276. // Stop and show an alert on the welcome page
  2277. const isWelcome = this.$state.includes('welcome');
  2278. this.stop({
  2279. reason: reason,
  2280. send: false,
  2281. // TODO: Use welcome.{reason} once we have it
  2282. close: 'welcome',
  2283. });
  2284. // Note: This is required to reset the mode and potentially
  2285. // re-establish a connection if needed.
  2286. // TODO: Remove once we have created pages for each mode on the
  2287. // 'welcome' page.
  2288. if (isWelcome) {
  2289. this.$state.reload().catch((error) => {
  2290. this.log.error('Unable to reload state:', error);
  2291. });
  2292. }
  2293. this.showAlert(alertMessage);
  2294. }
  2295. /**
  2296. * A connectionInfo message arrived.
  2297. */
  2298. private _receiveConnectionInfo(message: threema.WireMessage) {
  2299. this.arpLog.debug('Received connectionInfo from device');
  2300. if (!hasValue(message.data)) {
  2301. this.connectionInfoFuture.reject('Invalid connectionInfo message: data missing');
  2302. return;
  2303. }
  2304. if (!hasValue(message.data.id)) {
  2305. this.connectionInfoFuture.reject('Invalid connectionInfo message: data.id is missing');
  2306. return;
  2307. }
  2308. if (!(message.data.id instanceof ArrayBuffer)) {
  2309. this.connectionInfoFuture.reject('Invalid connectionInfo message: data.id is of invalid type');
  2310. return;
  2311. }
  2312. const resume = message.data.resume;
  2313. if (resume !== undefined) {
  2314. if (!hasValue(resume.id)) {
  2315. this.connectionInfoFuture.reject('Invalid connectionInfo message: data.resume.id is missing');
  2316. return;
  2317. }
  2318. if (!hasValue(resume.sequenceNumber)) {
  2319. const error = 'Invalid connectionInfo message: data.resume.sequenceNumber is missing';
  2320. this.connectionInfoFuture.reject(error);
  2321. return;
  2322. }
  2323. if (!(resume.id instanceof ArrayBuffer)) {
  2324. this.connectionInfoFuture.reject('Invalid connectionInfo message: data.resume.id is of invalid type');
  2325. return;
  2326. }
  2327. if (resume.sequenceNumber < 0 || resume.sequenceNumber > WebClientService.SEQUENCE_NUMBER_MAX) {
  2328. const error = 'Invalid connectionInfo message: data.resume.sequenceNumber is invalid';
  2329. this.connectionInfoFuture.reject(error);
  2330. return;
  2331. }
  2332. }
  2333. this.connectionInfoFuture.resolve(message.data);
  2334. }
  2335. /**
  2336. * Process an incoming 'contact', 'group' or 'distributionList' message as
  2337. * a reply to a previous 'create' or 'update' message of that sub-type.
  2338. */
  2339. private _receiveReplyReceiver<T extends threema.Receiver>(
  2340. message: threema.WireMessage,
  2341. receiverType: threema.ReceiverType,
  2342. future: Future<any>,
  2343. ): void {
  2344. this.arpLog.debug(`Received ${receiverType} ${message.subType}`);
  2345. // Handle error (if any)
  2346. if (message.ack !== undefined && !message.ack.success) {
  2347. return future.reject(message.ack.error);
  2348. }
  2349. // Unpack and validate data
  2350. const data = message.data;
  2351. if (data === undefined) {
  2352. this.arpLog.error(`Invalid ${receiverType} response, 'data' is missing`);
  2353. return future.reject('invalidResponse');
  2354. }
  2355. // Get receiver instance
  2356. const receiver = data[WebClientService.SUB_TYPE_RECEIVER] as T;
  2357. // Update receiver type if not set
  2358. if (receiver.type === undefined) {
  2359. receiver.type = receiverType;
  2360. }
  2361. // Extend models
  2362. if (isContactReceiver(receiver)) {
  2363. this.receivers.extendContact(receiver);
  2364. } else if (isGroupReceiver(receiver)) {
  2365. this.receivers.extendGroup(receiver);
  2366. } else if (isDistributionListReceiver(receiver)) {
  2367. this.receivers.extendDistributionList(receiver);
  2368. }
  2369. future.resolve(receiver);
  2370. }
  2371. private _receiveCreateContact(message: threema.WireMessage): void {
  2372. const future = this.popWireMessageFuture(message);
  2373. this._receiveReplyReceiver(message, 'contact', future);
  2374. }
  2375. private _receiveCreateGroup(message: threema.WireMessage): void {
  2376. const future = this.popWireMessageFuture(message);
  2377. this._receiveReplyReceiver(message, 'group', future);
  2378. }
  2379. private _receiveCreateDistributionList(message: threema.WireMessage): void {
  2380. const future = this.popWireMessageFuture(message);
  2381. this._receiveReplyReceiver(message, 'distributionList', future);
  2382. }
  2383. private _receiveCreateMessage(wireMessage: threema.WireMessage): void {
  2384. this.arpLog.debug('Received create message response');
  2385. const future = this.popWireMessageFuture(wireMessage);
  2386. // Handle error (if any)
  2387. if (!wireMessage.ack.success) {
  2388. return future.reject(wireMessage.ack.error);
  2389. }
  2390. // Unpack data and arguments
  2391. const args = wireMessage.args;
  2392. const data = wireMessage.data;
  2393. if (args === undefined || data === undefined) {
  2394. this.arpLog.warn('Invalid create message received, arguments or data missing');
  2395. return future.reject('invalidResponse');
  2396. }
  2397. const receiverType: threema.ReceiverType = args[WebClientService.ARGUMENT_RECEIVER_TYPE];
  2398. const receiverId: string = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2399. const messageId: string = data[WebClientService.ARGUMENT_MESSAGE_ID];
  2400. if (receiverType === undefined || receiverId === undefined || messageId === undefined) {
  2401. this.arpLog.warn("Invalid create received: 'type', 'id' or 'messageId' missing");
  2402. return future.reject('invalidResponse');
  2403. }
  2404. // Map the previously used temporary id to the one chosen by the app
  2405. const receiver = {
  2406. type: receiverType,
  2407. id: receiverId,
  2408. } as threema.Receiver;
  2409. const message = this.messages.bindTemporaryToMessageId(
  2410. receiver,
  2411. wireMessage.ack.id,
  2412. messageId,
  2413. );
  2414. future.resolve(messageId);
  2415. // Add a special future that resolves once the message has been
  2416. // identified as sent. As long as an unacknowledged wire message future
  2417. // exists, the app will be continuously awoken if the connection
  2418. // has been lost.
  2419. if (!this.messageService.isSentOrSendingFailed(message)) {
  2420. const sentId = `${message.id}-sent`;
  2421. this.wireMessageFutures.set(sentId, new Future());
  2422. this.arpLogV.debug(`Added special wire message future: ${sentId}`);
  2423. }
  2424. }
  2425. private _receiveResponseConversations(message: threema.WireMessage) {
  2426. this.arpLog.debug('Received conversations response');
  2427. const future = this.popWireMessageFuture(message, this.requiresTemporaryIdBackwardsCompatibility);
  2428. // Handle error (if any)
  2429. if ((!this.requiresTemporaryIdBackwardsCompatibility && message.ack !== undefined) && !message.ack.success) {
  2430. future.reject(message.ack.error);
  2431. }
  2432. // Validate data
  2433. const data = message.data as threema.Conversation[];
  2434. if (data === undefined) {
  2435. this.arpLog.warn('Invalid conversation response, data missing');
  2436. return future.reject('invalidResponse');
  2437. }
  2438. // Run delayed as it requires the receivers to be available
  2439. this.runAfterInitializationSteps([
  2440. InitializationStep.Receivers,
  2441. ], () => {
  2442. // If a avatar was set on a conversation, convert and copy to the receiver
  2443. for (const conversation of data) {
  2444. if (conversation.avatar !== undefined && conversation.avatar !== null) {
  2445. const receiver: threema.Receiver = this.receivers.getData({
  2446. id: conversation.id,
  2447. type: conversation.type,
  2448. });
  2449. if (receiver !== undefined && receiver.avatar === undefined) {
  2450. receiver.avatar = {
  2451. low: conversation.avatar,
  2452. };
  2453. }
  2454. // Remove avatar from conversation
  2455. delete conversation.avatar;
  2456. }
  2457. }
  2458. // Store conversations & done
  2459. this.conversations.set(data);
  2460. this.updateUnreadCount();
  2461. this.registerInitializationStep(InitializationStep.Conversations);
  2462. future.resolve();
  2463. });
  2464. }
  2465. private _receiveResponseMessages(message: threema.WireMessage): void {
  2466. this.arpLog.debug('Received messages response');
  2467. const future = this.popWireMessageFuture(message, this.requiresTemporaryIdBackwardsCompatibility);
  2468. // Handle error (if any)
  2469. if ((!this.requiresTemporaryIdBackwardsCompatibility && message.ack !== undefined) && !message.ack.success) {
  2470. future.reject(message.ack.error);
  2471. }
  2472. // Unpack data and arguments
  2473. const args = message.args;
  2474. const data = message.data as threema.Message[];
  2475. if (args === undefined || data === undefined) {
  2476. this.arpLog.warn('Invalid messages response, data or arguments missing');
  2477. return future.reject('invalidResponse');
  2478. }
  2479. // Unpack required argument fields
  2480. const type: string = args[WebClientService.ARGUMENT_RECEIVER_TYPE];
  2481. const id: string = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2482. let more: boolean = args[WebClientService.ARGUMENT_HAS_MORE];
  2483. if (type === undefined || id === undefined || more === undefined) {
  2484. this.arpLog.warn('Invalid messages response, argument field missing');
  2485. return future.reject('invalidResponse');
  2486. }
  2487. if (!isValidReceiverType(type)) {
  2488. this.arpLog.warn('Invalid messages response, unknown receiver type (' + type + ')');
  2489. return future.reject('invalidResponse');
  2490. }
  2491. if (this.config.ARP_LOG_TRACE) {
  2492. this.logChatMessages(message.type, message.subType, type, id, 'new', data);
  2493. }
  2494. const receiver: threema.BaseReceiver = {type: type, id: id};
  2495. // If there's no data returned, override `more` field.
  2496. if (data.length === 0) {
  2497. more = false;
  2498. }
  2499. // Set as loaded
  2500. this.loadingMessages.delete(receiver.type + receiver.id);
  2501. // Check if the messages have been requested
  2502. // TODO: Isn't this a bogus check since we know that we have made the
  2503. // request at this point?
  2504. if (!this.messages.isRequested(receiver)) {
  2505. this.arpLog.warn("Ignoring message response that hasn't been requested");
  2506. return future.reject('invalidResponse');
  2507. }
  2508. // Add messages
  2509. this.messages.addOlder(receiver, data);
  2510. // Clear pending request
  2511. this.messages.clearRequested(receiver);
  2512. // Set "more" flag to indicate that more (older) messages are available.
  2513. this.messages.setMore(receiver, more);
  2514. // Notify listeners
  2515. this.messages.notify(receiver, this.$rootScope);
  2516. // Done
  2517. future.resolve();
  2518. }
  2519. private _receiveResponseAvatar(message: threema.WireMessage): void {
  2520. this.arpLog.debug('Received avatar response');
  2521. const future = this.popWireMessageFuture(message);
  2522. // Handle error (if any)
  2523. if (!message.ack.success) {
  2524. future.reject(message.ack.error);
  2525. }
  2526. // Unpack data and arguments
  2527. const args = message.args;
  2528. if (args === undefined) {
  2529. this.arpLog.warn('Invalid message response: arguments missing');
  2530. return future.reject('invalidResponse');
  2531. }
  2532. // Check for avatar data
  2533. const avatar = message.data;
  2534. if (avatar === undefined) {
  2535. // A receiver without an avatar - fine!
  2536. return future.resolve(null);
  2537. }
  2538. // Unpack required argument fields
  2539. const type = args[WebClientService.ARGUMENT_RECEIVER_TYPE];
  2540. const id = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2541. const highResolution = args[WebClientService.ARGUMENT_AVATAR_HIGH_RESOLUTION];
  2542. if (type === undefined || id === undefined || highResolution === undefined) {
  2543. this.arpLog.warn('Invalid avatar response, argument field missing');
  2544. return future.reject('invalidResponse');
  2545. }
  2546. // Set avatar for receiver according to resolution
  2547. const field: string = highResolution ? 'high' : 'low';
  2548. const receiverData = this.receivers.getData(args);
  2549. if (!hasValue(receiverData.avatar)) {
  2550. receiverData.avatar = {};
  2551. }
  2552. receiverData.avatar[field] = avatar;
  2553. future.resolve(avatar);
  2554. }
  2555. private _receiveResponseThumbnail(message: threema.WireMessage): void {
  2556. this.arpLog.debug('Received thumbnail response');
  2557. const future = this.popWireMessageFuture(message);
  2558. // Handle error (if any)
  2559. if (!message.ack.success) {
  2560. future.reject(message.ack.error);
  2561. }
  2562. // Unpack data and arguments
  2563. const args = message.args;
  2564. if (args === undefined) {
  2565. this.arpLog.warn('Invalid message response: arguments missing');
  2566. return future.reject('invalidResponse');
  2567. }
  2568. // Check for thumbnail data
  2569. const thumbnail = message.data;
  2570. if (thumbnail === undefined) {
  2571. // A message without a thumbnail - fine!
  2572. return future.resolve(null);
  2573. }
  2574. // Unpack required argument fields
  2575. const type = args[WebClientService.ARGUMENT_RECEIVER_TYPE];
  2576. const id = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2577. const messageId: string = args[WebClientService.ARGUMENT_MESSAGE_ID];
  2578. if (type === undefined || id === undefined || messageId === undefined ) {
  2579. this.arpLog.warn('Invalid thumbnail response, argument field missing');
  2580. return future.reject('invalidResponse');
  2581. }
  2582. // Set thumbnail
  2583. this.messages.setThumbnail( this.receivers.getData(args), messageId, thumbnail);
  2584. future.resolve(thumbnail);
  2585. }
  2586. private _receiveResponseBlob(message: threema.WireMessage): void {
  2587. this.arpLog.debug('Received blob response');
  2588. const future = this.popWireMessageFuture(message);
  2589. // Handle error (if any)
  2590. if (!message.ack.success) {
  2591. return future.reject(message.ack.error);
  2592. }
  2593. // Unpack data and arguments
  2594. const args = message.args;
  2595. const data = message.data;
  2596. if (args === undefined) {
  2597. this.arpLog.warn('Invalid message response, args missing');
  2598. return future.reject('invalidResponse');
  2599. }
  2600. // Unpack required argument fields
  2601. const receiverType = args[WebClientService.ARGUMENT_RECEIVER_TYPE];
  2602. const receiverId = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2603. const msgId: string = args[WebClientService.ARGUMENT_MESSAGE_ID];
  2604. if (receiverType === undefined || receiverId === undefined || msgId === undefined) {
  2605. this.arpLog.warn('Invalid blob response, argument field missing');
  2606. return future.reject('invalidResponse');
  2607. }
  2608. // Unpack data
  2609. const blobInfo: threema.BlobInfo = {
  2610. buffer: data[WebClientService.DATA_FIELD_BLOB_BLOB],
  2611. mimetype: data[WebClientService.DATA_FIELD_BLOB_TYPE],
  2612. filename: data[WebClientService.DATA_FIELD_BLOB_NAME],
  2613. };
  2614. if (blobInfo.buffer === undefined || blobInfo.mimetype === undefined || blobInfo.filename === undefined) {
  2615. this.arpLog.warn('Invalid blob response, data field missing');
  2616. return future.reject('invalidResponse');
  2617. }
  2618. // Store blob
  2619. this.blobCache.set(msgId + receiverType, blobInfo);
  2620. future.resolve(blobInfo);
  2621. }
  2622. private _receiveUpdateConfirm(message: threema.WireMessage): void {
  2623. this.arpLog.debug('Received wire message acknowledgement');
  2624. const future = this.popWireMessageFuture(message);
  2625. if (!message.ack.success) {
  2626. future.reject(message.ack.error);
  2627. } else {
  2628. future.resolve();
  2629. }
  2630. }
  2631. private _receiveUpdateMessages(wireMessage: threema.WireMessage): void {
  2632. this.arpLog.debug('Received messages update');
  2633. const future = this.popWireMessageFuture(wireMessage, true);
  2634. // Handle error (if any)
  2635. if (wireMessage.ack !== undefined && !wireMessage.ack.success) {
  2636. return future.reject(wireMessage.ack.error);
  2637. }
  2638. // Unpack data and arguments
  2639. const args = wireMessage.args;
  2640. const data: threema.Message[] = wireMessage.data;
  2641. if (args === undefined || data === undefined) {
  2642. this.arpLog.warn('Invalid message update, data or arguments missing');
  2643. return future.reject('invalidResponse');
  2644. }
  2645. // Unpack required argument fields
  2646. const type: string = args[WebClientService.ARGUMENT_RECEIVER_TYPE];
  2647. const id: string = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2648. const mode: string = args[WebClientService.ARGUMENT_MODE];
  2649. if (type === undefined || id === undefined || mode === undefined) {
  2650. this.arpLog.warn('Invalid message update, argument field missing');
  2651. return future.reject('invalidResponse');
  2652. }
  2653. if (!isValidReceiverType(type)) {
  2654. this.arpLog.warn('Invalid messages update, unknown receiver type (' + type + ')');
  2655. return future.reject('invalidResponse');
  2656. }
  2657. if (this.config.ARP_LOG_TRACE) {
  2658. this.logChatMessages(wireMessage.type, wireMessage.subType, type, id, mode, data);
  2659. }
  2660. const receiver: threema.BaseReceiver = {type: type, id: id};
  2661. // React depending on mode
  2662. let notify = false;
  2663. for (const message of data) {
  2664. // Pop special future to be resolved if the message has been
  2665. // identified as sent.
  2666. if (this.messageService.isSentOrSendingFailed(message)) {
  2667. const sentId = `${message.id}-sent`;
  2668. const sentFuture = this.wireMessageFutures.get(sentId);
  2669. if (sentFuture !== undefined) {
  2670. this.wireMessageFutures.delete(sentId);
  2671. this.arpLogV.debug(`Removed special wire message future: ${sentId}`);
  2672. sentFuture.resolve();
  2673. }
  2674. }
  2675. switch (mode) {
  2676. case WebClientService.ARGUMENT_MODE_NEW:
  2677. // It's possible that this message already exists (placeholder message on send).
  2678. // Try to update it first. If not, add it as a new msg.
  2679. if (!this.messages.update(receiver, message)) {
  2680. this.messages.addNewer(receiver, [message]);
  2681. // If we have received a new message, it is highly unlikely that the contact is still typing
  2682. this.typing.unsetTyping(receiver);
  2683. }
  2684. notify = true;
  2685. break;
  2686. case WebClientService.ARGUMENT_MODE_MODIFIED:
  2687. if (!this.messages.update(receiver, message)) {
  2688. const log = `Received message update for unknown message (id ${message.id})`;
  2689. this.arpLog.error(log);
  2690. if (this.config.ARP_LOG_TRACE) {
  2691. this.messages.addStatusMessage(receiver, 'Warning: ' + log);
  2692. notify = true;
  2693. }
  2694. }
  2695. break;
  2696. case WebClientService.ARGUMENT_MODE_REMOVED:
  2697. if (!this.messages.remove(receiver, message.id)) {
  2698. this.arpLog.error(`Received message deletion for unknown message (id ${message.id})`);
  2699. }
  2700. notify = true;
  2701. break;
  2702. default:
  2703. this.arpLog.warn('Invalid message response, unknown mode:', mode);
  2704. }
  2705. }
  2706. if (notify) {
  2707. this.messages.notify(receiver, this.$rootScope);
  2708. }
  2709. future.resolve();
  2710. }
  2711. private _receiveUpdateReceiver(message: threema.WireMessage): void {
  2712. this.arpLog.debug('Received receiver update');
  2713. // Unpack data and arguments
  2714. const args = message.args;
  2715. const data = message.data;
  2716. if (args === undefined || data === undefined) {
  2717. this.arpLog.warn('Invalid receiver update, data or arguments missing');
  2718. return;
  2719. }
  2720. // Unpack required argument fields
  2721. const type = args[WebClientService.ARGUMENT_RECEIVER_TYPE] as threema.ReceiverType;
  2722. const id = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2723. const mode: 'new' | 'modified' | 'removed' = args[WebClientService.ARGUMENT_MODE];
  2724. if (type === undefined || mode === undefined || id === undefined) {
  2725. this.arpLog.warn('Invalid receiver update, argument field missing');
  2726. return;
  2727. }
  2728. // React depending on mode
  2729. switch (mode) {
  2730. case WebClientService.ARGUMENT_MODE_NEW:
  2731. case WebClientService.ARGUMENT_MODE_MODIFIED:
  2732. // Add or update a certain receiver
  2733. const updatedReceiver = this.receivers.extend(type, data);
  2734. // Remove all cached messages if the receiver was moved to "locked" state
  2735. if (updatedReceiver !== undefined && updatedReceiver.locked) {
  2736. this.messages.clearReceiverMessages(updatedReceiver);
  2737. }
  2738. break;
  2739. case WebClientService.ARGUMENT_MODE_REMOVED:
  2740. // Remove a certain receiver
  2741. (this.receivers.get(type) as Map<string, threema.Receiver>).delete(id);
  2742. break;
  2743. default:
  2744. this.arpLog.warn('Invalid receiver response, unknown mode:', mode);
  2745. }
  2746. }
  2747. private _receiveUpdateReceivers(message: threema.WireMessage): void {
  2748. this.arpLog.debug('Received receivers update');
  2749. // Unpack data and arguments
  2750. const args = message.args;
  2751. const data = message.data;
  2752. if (args === undefined || data === undefined) {
  2753. this.arpLog.warn('Invalid receiver update, data or arguments missing');
  2754. return;
  2755. }
  2756. // Unpack required argument fields
  2757. const type = args[WebClientService.ARGUMENT_RECEIVER_TYPE] as threema.ReceiverType;
  2758. if (type === undefined) {
  2759. this.arpLog.warn('Invalid receivers update, argument field missing');
  2760. return;
  2761. }
  2762. // Refresh lists of receivers
  2763. switch (type) {
  2764. case 'contact':
  2765. this.sortContacts(data);
  2766. this.receivers.setContacts(data);
  2767. break;
  2768. case 'group':
  2769. this.receivers.setGroups(data);
  2770. break;
  2771. case 'distributionList':
  2772. this.receivers.setDistributionLists(data);
  2773. break;
  2774. default:
  2775. this.arpLog.warn('Unknown receiver type:', type);
  2776. }
  2777. }
  2778. private _receiveUpdateTyping(message: threema.WireMessage): void {
  2779. this.arpLog.debug('Received typing update');
  2780. // Unpack data and arguments
  2781. const args = message.args;
  2782. const data = message.data;
  2783. if (args === undefined || data === undefined) {
  2784. this.arpLog.warn('Invalid typing update, data or arguments missing');
  2785. return;
  2786. }
  2787. // Unpack required argument fields
  2788. const identity: string = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2789. if (identity === undefined) {
  2790. this.arpLog.warn('Invalid typing update, argument field missing');
  2791. return;
  2792. }
  2793. // Unpack required data fields
  2794. const isTyping: boolean = data[WebClientService.ARGUMENT_IS_TYPING];
  2795. if (isTyping === undefined) {
  2796. this.arpLog.warn('Invalid typing update, data field missing');
  2797. return;
  2798. }
  2799. // Store or remove typing notification.
  2800. // Note that we know that the receiver must be a contact, because
  2801. // groups and distribution lists can't type.
  2802. const receiver = {id: identity, type: 'contact'} as threema.ContactReceiver;
  2803. if (isTyping === true) {
  2804. this.typing.setTyping(receiver);
  2805. } else {
  2806. this.typing.unsetTyping(receiver);
  2807. }
  2808. }
  2809. private _receiveUpdateConversation(message: threema.WireMessage) {
  2810. this.arpLog.debug('Received conversation update');
  2811. // Validate data
  2812. const args = message.args;
  2813. const data = message.data as threema.ConversationWithPosition;
  2814. if (args === undefined || data === undefined) {
  2815. this.arpLog.warn('Invalid conversation update, data or arguments missing');
  2816. return;
  2817. }
  2818. // Get receiver
  2819. const receiver = this.receivers.getData({type: data.type, id: data.id});
  2820. if (!hasValue(receiver)) {
  2821. const log = `Received conversation update for unknown ${data.type} receiver`;
  2822. this.arpLog.error(log);
  2823. return;
  2824. }
  2825. // Unpack required argument fields
  2826. const type: string = args[WebClientService.ARGUMENT_MODE];
  2827. switch (type) {
  2828. case WebClientService.ARGUMENT_MODE_NEW:
  2829. if (this.conversations.find(data) !== null) {
  2830. this.arpLog.error('Received update/conversation with mode=new for existing conversation');
  2831. // Ignore message
  2832. break;
  2833. }
  2834. this.conversations.add(data);
  2835. break;
  2836. case WebClientService.ARGUMENT_MODE_MODIFIED:
  2837. // A conversation update *can* mean that a new message arrived.
  2838. // To find out, we'll look at the unread count. If it has been
  2839. // incremented, it must be a new message.
  2840. if (data.unreadCount > 0) {
  2841. const oldConversation = this.conversations.updateOrAdd(data, true);
  2842. if (oldConversation === null) {
  2843. this.onNewMessage(data.latestMessage, data, receiver);
  2844. } else {
  2845. // Check for unread count changes
  2846. const unreadCountIncreased = data.unreadCount > oldConversation.unreadCount;
  2847. const unreadCountDecreased = data.unreadCount < oldConversation.unreadCount;
  2848. // If the unreadcount has increased, we received a new message.
  2849. // Otherwise, if it has decreased, hide the notification.
  2850. if (unreadCountIncreased) {
  2851. this.onNewMessage(data.latestMessage, data, receiver);
  2852. } else if (unreadCountDecreased) {
  2853. this.notificationService.hideNotification(data.type + '-' + data.id);
  2854. }
  2855. }
  2856. } else {
  2857. // Update the conversation and hide any notifications
  2858. this.conversations.updateOrAdd(data, false);
  2859. this.notificationService.hideNotification(data.type + '-' + data.id);
  2860. }
  2861. break;
  2862. case WebClientService.ARGUMENT_MODE_REMOVED:
  2863. // Remove conversation
  2864. this.conversations.remove(data);
  2865. // Remove all cached messages for the receiver
  2866. this.messages.clearReceiverMessages(receiver);
  2867. // Call on-removed listener
  2868. this.receiverListener.forEach((listener: threema.ReceiverListener) => {
  2869. this.arpLog.debug('Call on removed listener');
  2870. listener.onConversationRemoved(receiver);
  2871. });
  2872. break;
  2873. default:
  2874. this.arpLog.warn('Received conversation without a mode');
  2875. break;
  2876. }
  2877. this.updateUnreadCount();
  2878. }
  2879. private _receiveUpdateAvatar(message: threema.WireMessage) {
  2880. this.arpLog.debug('Received avatar update');
  2881. const args = message.args;
  2882. const data = message.data as ArrayBuffer;
  2883. if (args === undefined) {
  2884. this.arpLog.warn('Invalid avatar update, arguments missing');
  2885. return;
  2886. }
  2887. // Get receiver
  2888. const receiver = this.receivers.getData({type: args.type, id: args.id});
  2889. if (receiver === undefined) {
  2890. this.arpLog.error('Received avatar update for nonexistent receiver');
  2891. return;
  2892. }
  2893. // Set (or clear) low-res avatar, invalidate high-res avatar
  2894. receiver.avatar = {
  2895. low: hasValue(data) ? data : undefined,
  2896. high: undefined,
  2897. };
  2898. }
  2899. /**
  2900. * Process an incoming battery status message.
  2901. */
  2902. private _receiveUpdateBatteryStatus(message: threema.WireMessage): void {
  2903. this.arpLog.debug('Received battery status');
  2904. const future = this.popWireMessageFuture(message, true);
  2905. // Handle error (if any)
  2906. if (message.ack !== undefined && !message.ack.success) {
  2907. return future.reject(message.ack.error);
  2908. }
  2909. // Unpack data and arguments
  2910. const data = message.data as threema.BatteryStatus;
  2911. if (data === undefined) {
  2912. this.arpLog.warn('Invalid battery status message, data missing');
  2913. return future.reject('invalidResponse');
  2914. }
  2915. // Set battery status
  2916. this.batteryStatusService.setStatus(data);
  2917. future.resolve();
  2918. }
  2919. private _receiveUpdateContact(message: threema.WireMessage): void {
  2920. const future = this.popWireMessageFuture(message);
  2921. this._receiveReplyReceiver(message, 'contact', future);
  2922. }
  2923. private _receiveUpdateGroup(message: threema.WireMessage): void {
  2924. const future = this.popWireMessageFuture(message);
  2925. this._receiveReplyReceiver(message, 'group', future);
  2926. }
  2927. private _receiveUpdateDistributionList(message: threema.WireMessage): void {
  2928. const future = this.popWireMessageFuture(message);
  2929. this._receiveReplyReceiver(message, 'distributionList', future);
  2930. }
  2931. /**
  2932. * Process an incoming profile update message.
  2933. */
  2934. private _receiveUpdateProfile(message: threema.WireMessage): void {
  2935. this.arpLog.debug('Received profile update');
  2936. // Unpack data and arguments
  2937. const data = message.data as threema.ProfileUpdate;
  2938. if (data === undefined) {
  2939. this.arpLog.warn('Invalid profile update message, data missing');
  2940. return;
  2941. }
  2942. // Update public nickname
  2943. if (data.publicNickname !== undefined) {
  2944. this.me.publicNickname = data.publicNickname;
  2945. this.me.displayName = this.me.publicNickname || this.me.id;
  2946. }
  2947. // Update avatar
  2948. if (data.avatar !== undefined) {
  2949. if (data.avatar === null) {
  2950. this.me.avatar = {};
  2951. } else {
  2952. this.me.avatar = { high: data.avatar };
  2953. }
  2954. // Request new low-res avatar
  2955. // noinspection JSIgnoredPromiseFromCall
  2956. this.requestAvatar(this.me, false);
  2957. }
  2958. }
  2959. /**
  2960. * The peer sends the device information string. This can be used to
  2961. * identify the active session.
  2962. */
  2963. private _receiveResponseClientInfo(message: threema.WireMessage): void {
  2964. this.arpLog.debug('Received client info response');
  2965. const future = this.popWireMessageFuture(message, this.requiresTemporaryIdBackwardsCompatibility);
  2966. // Handle error (if any)
  2967. if ((!this.requiresTemporaryIdBackwardsCompatibility && message.ack !== undefined) && !message.ack.success) {
  2968. future.reject(message.ack.error);
  2969. }
  2970. // Validate data
  2971. const data = message.data;
  2972. if (data === undefined) {
  2973. this.arpLog.warn('Invalid client info, data field missing');
  2974. return future.reject('invalidResponse');
  2975. }
  2976. /**
  2977. * Return the field if it's not undefined, otherwise return the default.
  2978. */
  2979. function getOrDefault<T>(field: T, defaultVal: T): T {
  2980. if (field === undefined) {
  2981. return defaultVal;
  2982. }
  2983. return field;
  2984. }
  2985. // Set clientInfo attribute
  2986. this.clientInfo = {
  2987. device: data.device,
  2988. os: data.os,
  2989. osVersion: data.osVersion,
  2990. isWork: hasValue(data.isWork) ? data.isWork : false, // TODO: Backwards compat hack, remove after 08/2019
  2991. pushToken: data.pushToken,
  2992. configuration: {
  2993. voipEnabled: getOrDefault<boolean>(data.configuration.voipEnabled, true),
  2994. voipForceTurn: getOrDefault<boolean>(data.configuration.voipForceTurn, false),
  2995. largeSingleEmoji: getOrDefault<boolean>(data.configuration.largeSingleEmoji, true),
  2996. showInactiveIDs: getOrDefault<boolean>(data.configuration.showInactiveIDs, true),
  2997. },
  2998. capabilities: {
  2999. maxGroupSize: getOrDefault<number>(data.capabilities.maxGroupSize, 50),
  3000. maxFileSize: getOrDefault<number>(data.capabilities.maxFileSize, 50 * 1024 * 1024),
  3001. maxMessageBodySize: getOrDefault<number>(data.capabilities.maxMessageBodySize, 3500),
  3002. distributionLists: getOrDefault<boolean>(data.capabilities.distributionLists, true),
  3003. imageFormat: data.capabilities.imageFormat,
  3004. mdm: data.capabilities.mdm,
  3005. },
  3006. };
  3007. this.arpLog.debug('Client device:', this.clientInfo.device);
  3008. // Store push token
  3009. if (this.clientInfo.pushToken) {
  3010. this.pushToken = this.clientInfo.pushToken;
  3011. switch (this.clientInfo.os) {
  3012. case threema.OperatingSystem.Android:
  3013. this.pushTokenType = threema.PushTokenType.Gcm;
  3014. break;
  3015. case threema.OperatingSystem.Ios:
  3016. this.pushTokenType = threema.PushTokenType.Apns;
  3017. break;
  3018. default:
  3019. this.arpLog.error('Invalid operating system in client info');
  3020. }
  3021. }
  3022. if (this.pushToken !== null && this.pushTokenType !== null) {
  3023. this.pushService.init(this.pushToken, this.pushTokenType);
  3024. }
  3025. // If this is a work app, set a class on the HTML body
  3026. // that can be used for customization.
  3027. if (this.clientInfo.isWork) {
  3028. this.themeService.changeTheme(threema.Theme.Work);
  3029. }
  3030. this.registerInitializationStep(InitializationStep.ClientInfo);
  3031. future.resolve();
  3032. }
  3033. /**
  3034. * The peer sends information about the current user profile.
  3035. */
  3036. private _receiveResponseProfile(message: threema.WireMessage): void {
  3037. this.arpLog.debug('Received profile response');
  3038. const future = this.popWireMessageFuture(message, this.requiresTemporaryIdBackwardsCompatibility);
  3039. // Handle error (if any)
  3040. if ((!this.requiresTemporaryIdBackwardsCompatibility && message.ack !== undefined) && !message.ack.success) {
  3041. future.reject(message.ack.error);
  3042. }
  3043. // Validate data
  3044. const data = message.data as threema.Profile;
  3045. if (data === undefined) {
  3046. this.arpLog.warn('Invalid client info, data field missing');
  3047. return future.reject('invalidResponse');
  3048. }
  3049. // Create 'me' receiver with profile + dummy data
  3050. // TODO: Send both high-res and low-res avatars
  3051. this.receivers.setMe({
  3052. type: 'me',
  3053. id: data.identity,
  3054. publicNickname: data.publicNickname,
  3055. displayName: data.publicNickname || data.identity,
  3056. publicKey: data.publicKey,
  3057. avatar: {
  3058. high: data.avatar,
  3059. },
  3060. featureMask: 0xFF,
  3061. verificationLevel: 3,
  3062. state: 'ACTIVE',
  3063. locked: false,
  3064. visible: true,
  3065. hidden: false,
  3066. access: {
  3067. canChangeAvatar: true,
  3068. canChangeFirstName: true,
  3069. canChangeLastName: true,
  3070. },
  3071. color: '#000000',
  3072. });
  3073. this.registerInitializationStep(InitializationStep.Profile);
  3074. future.resolve();
  3075. }
  3076. public setPassword(password: string) {
  3077. // If a password has been set, store trusted key and push token
  3078. if (this._maybeTrustKeys(password)) {
  3079. // Saved trusted key, send information to client
  3080. this.sendKeyPersisted();
  3081. }
  3082. }
  3083. /**
  3084. * Reset all Fields and clear the blob cache
  3085. */
  3086. public clearCache(): void {
  3087. this._resetFields();
  3088. this.blobCache.clear();
  3089. }
  3090. /**
  3091. * Return the max text length
  3092. */
  3093. public getMaxTextLength(): number {
  3094. return this.clientInfo.capabilities.maxMessageBodySize;
  3095. }
  3096. /**
  3097. * Returns the max group member size
  3098. */
  3099. public getMaxGroupMemberSize(): number {
  3100. return this.clientInfo.capabilities.maxGroupSize;
  3101. }
  3102. /**
  3103. * Whether a notification should be triggered.
  3104. */
  3105. private shouldNotify(settings: threema.SimplifiedNotificationSettings, message: threema.Message): boolean {
  3106. if (settings.dnd.enabled) {
  3107. // Do not show any notifications on muted chats
  3108. if (settings.dnd.mentionOnly) {
  3109. let textToSearch = '';
  3110. if (message.type === 'text') {
  3111. textToSearch = message.body;
  3112. } else if (message.caption) {
  3113. textToSearch = message.caption;
  3114. }
  3115. let quotedMe = false;
  3116. if (message.quote) {
  3117. textToSearch += ' ' + message.quote.text;
  3118. quotedMe = message.quote.identity === this.me.id;
  3119. }
  3120. const forMe = textToSearch.indexOf('@[' + this.me.id + ']') !== -1;
  3121. const forAll = textToSearch.indexOf('@[@@@@@@@@]') !== -1;
  3122. return forMe || forAll || quotedMe;
  3123. } else {
  3124. return false;
  3125. }
  3126. } else {
  3127. return true;
  3128. }
  3129. }
  3130. /**
  3131. * Called when a new message arrives.
  3132. */
  3133. private onNewMessage(
  3134. message: threema.Message,
  3135. conversation: threema.Conversation,
  3136. sender: threema.Receiver,
  3137. ): void {
  3138. // Ignore message from active receivers (and if the browser tab is visible)
  3139. if (document.hasFocus()
  3140. && this.receiverService.compare(conversation, this.receiverService.getActive())) {
  3141. return;
  3142. }
  3143. // Do not show any notifications on private chats
  3144. if (sender.locked === true) {
  3145. return;
  3146. }
  3147. // Consider conversation notification settings
  3148. const simplifiedNotification = this.notificationService.getAppNotificationSettings(conversation);
  3149. if (!this.shouldNotify(simplifiedNotification, message)) {
  3150. return;
  3151. }
  3152. // Determine sender and partner name (used for notification)
  3153. let senderName = sender.id;
  3154. if (sender.displayName) {
  3155. senderName = sender.displayName;
  3156. } else if (isContactReceiver(sender)) {
  3157. senderName = '~' + sender.publicNickname;
  3158. }
  3159. const partner = this.receivers.getData({
  3160. id: message.partnerId,
  3161. type: 'contact',
  3162. } as threema.Receiver) as threema.ContactReceiver;
  3163. const partnerName = partner.displayName || ('~' + partner.publicNickname);
  3164. // Show notification
  3165. this.$translate('messenger.MESSAGE_NOTIFICATION_SUBJECT', {messageCount: conversation.unreadCount})
  3166. .then((titlePrefix) => {
  3167. const title = `${titlePrefix} ${senderName}`;
  3168. let body = '';
  3169. const messageType = message.type;
  3170. const caption = message.caption;
  3171. let captionString = '';
  3172. if (caption !== undefined) {
  3173. captionString = captionString + ': ' + caption;
  3174. }
  3175. const messageTypeString = this.$translate.instant('messageTypes.' + messageType);
  3176. switch (messageType as threema.MessageType) {
  3177. case 'text':
  3178. body = message.body;
  3179. break;
  3180. case 'location':
  3181. body = messageTypeString + ': ' + message.location.description;
  3182. break;
  3183. case 'file':
  3184. if (message.file.type === 'image/gif') {
  3185. body = this.$translate.instant('messageTypes.' + 'gif') + captionString;
  3186. break;
  3187. }
  3188. // Display caption, if available otherwise use filename
  3189. if (captionString.length > 0) {
  3190. body = messageTypeString + captionString;
  3191. } else {
  3192. body = messageTypeString + ': ' + message.file.name;
  3193. }
  3194. break;
  3195. case 'ballot':
  3196. // TODO Show ballot title if ballot messages are implemented in the web version
  3197. body = messageTypeString;
  3198. break;
  3199. case 'voipStatus':
  3200. let translationKey: string;
  3201. switch ((message as threema.Message).voip.status) {
  3202. case 1:
  3203. translationKey = 'CALL_MISSED';
  3204. break;
  3205. case 2:
  3206. translationKey = message.isOutbox ? 'CALL_FINISHED_IN' : 'CALL_FINISHED_OUT';
  3207. break;
  3208. case 3:
  3209. translationKey = 'CALL_REJECTED';
  3210. break;
  3211. case 4:
  3212. translationKey = 'CALL_ABORTED';
  3213. break;
  3214. default:
  3215. // No default
  3216. }
  3217. if (translationKey !== undefined) {
  3218. body = this.$translate.instant('voip.' + translationKey);
  3219. }
  3220. break;
  3221. default:
  3222. // Image, video and audio
  3223. body = messageTypeString + captionString;
  3224. }
  3225. if (conversation.type === 'group') {
  3226. body = partnerName + ': ' + body;
  3227. }
  3228. const tag = conversation.type + '-' + conversation.id;
  3229. const avatar = (sender.avatar && sender.avatar.low)
  3230. ? bufferToUrl(sender.avatar.low, 'image/png', this.arpLog)
  3231. : null;
  3232. this.notificationService.showNotification(tag, title, body, avatar, () => {
  3233. this.$state.go('messenger.home.conversation', {
  3234. type: conversation.type,
  3235. id: conversation.id,
  3236. initParams: null,
  3237. });
  3238. }, undefined, undefined, simplifiedNotification.sound.muted);
  3239. });
  3240. }
  3241. /**
  3242. * If a password has been set, store own private permanent key and public
  3243. * key of the peer in the trusted key store.
  3244. */
  3245. private _maybeTrustKeys(password: string): boolean {
  3246. if (password !== undefined && password !== null && password.length > 0) {
  3247. this.trustedKeyStore.storeTrustedKey(
  3248. this.salty.keyStore.publicKeyBytes,
  3249. this.salty.keyStore.secretKeyBytes,
  3250. this.salty.peerPermanentKeyBytes,
  3251. this.pushToken,
  3252. this.pushTokenType,
  3253. password,
  3254. );
  3255. this.log.info('Stored trusted key');
  3256. return true;
  3257. }
  3258. return false;
  3259. }
  3260. public updatePushToken(token: string, tokenType: threema.PushTokenType): void {
  3261. this.pushToken = token;
  3262. this.pushTokenType = tokenType;
  3263. }
  3264. private sendRequestWireMessage(
  3265. subType: string,
  3266. retransmit: boolean,
  3267. args?: object,
  3268. data?: any,
  3269. id?: string,
  3270. ): Promise<any> {
  3271. return this.sendWireMessage(WebClientService.TYPE_REQUEST, subType, retransmit, args, data, id);
  3272. }
  3273. private sendUpdateWireMessage(
  3274. subType: string,
  3275. retransmit: boolean,
  3276. args?: object,
  3277. data?: any,
  3278. id?: string,
  3279. ): Promise<any> {
  3280. return this.sendWireMessage(WebClientService.TYPE_UPDATE, subType, retransmit, args, data, id);
  3281. }
  3282. private sendCreateWireMessage(
  3283. subType: string,
  3284. retransmit: boolean,
  3285. args?: object,
  3286. data?: any,
  3287. id?: string,
  3288. ): Promise<any> {
  3289. return this.sendWireMessage(WebClientService.TYPE_CREATE, subType, retransmit, args, data, id);
  3290. }
  3291. private sendDeleteWireMessage(
  3292. subType: string,
  3293. retransmit: boolean,
  3294. args?: object,
  3295. data?: any,
  3296. id?: string,
  3297. ): Promise<any> {
  3298. return this.sendWireMessage(WebClientService.TYPE_DELETE, subType, retransmit, args, data, id);
  3299. }
  3300. private createRandomWireMessageId() {
  3301. let id;
  3302. do {
  3303. id = randomString(6);
  3304. } while (this.wireMessageFutures.has(id));
  3305. return id;
  3306. }
  3307. private sendWireMessage(
  3308. type: string,
  3309. subType: string,
  3310. retransmit: boolean,
  3311. args?: object,
  3312. data?: any,
  3313. id?: string,
  3314. ): Promise<any> {
  3315. const message: threema.WireMessage = {
  3316. type: type,
  3317. subType: subType,
  3318. };
  3319. // Create a promise with a random ID (if retransmitting)
  3320. // Note: We do this in order to keep track of which messages the app
  3321. // has processed (NOT only received). A message that has not been
  3322. // processed yet is an indicator to wake the app up again after a
  3323. // connection loss.
  3324. let promise: Promise<any>;
  3325. if (retransmit) {
  3326. // Ensure ID uniqueness (if supplied) or create random ID
  3327. if (id === undefined) {
  3328. id = this.createRandomWireMessageId();
  3329. } else if (this.wireMessageFutures.has(id)) {
  3330. throw new Error('Duplicate id for wire message detected');
  3331. }
  3332. message.id = id;
  3333. // TODO: Remove when removing temporaryId backwards compatibility
  3334. // Set temporary ID
  3335. if (args === undefined) {
  3336. args = {};
  3337. }
  3338. args[WebClientService.ARGUMENT_TEMPORARY_ID] = message.id;
  3339. // Create & store future
  3340. const future: Future<any> = new Future();
  3341. this.arpLogV.debug(`Added wire message future: ${id} -> ${type}/${subType}`);
  3342. this.wireMessageFutures.set(message.id, future);
  3343. promise = future;
  3344. } else {
  3345. promise = Promise.resolve({
  3346. id: '',
  3347. success: true,
  3348. });
  3349. }
  3350. // Set args and data (if any)
  3351. if (args !== undefined) {
  3352. message.args = args;
  3353. }
  3354. if (data !== undefined) {
  3355. message.data = data;
  3356. }
  3357. // Send message & return promise (or undefined)
  3358. this.send(message, retransmit);
  3359. return promise;
  3360. }
  3361. private static validateWireMessageAcknowledgement(ack: threema.WireMessageAcknowledgement): void {
  3362. if (!hasValue(ack.id)) {
  3363. throw new Error("Invalid wire message acknowledgement: 'id' is missing");
  3364. }
  3365. if (!hasValue(ack.success)) {
  3366. throw new Error("Invalid wire message acknowledgement: 'success' is missing");
  3367. }
  3368. switch (ack.success) {
  3369. case true:
  3370. break;
  3371. case false:
  3372. if (!hasValue(ack.error)) {
  3373. throw new Error("Invalid wire message acknowledgement: 'error' is missing");
  3374. }
  3375. break;
  3376. default:
  3377. throw new Error("Invalid wire message acknowledgement: 'success' is not a boolean");
  3378. }
  3379. }
  3380. /**
  3381. * Find and return the wire message future corresponding to the message.
  3382. *
  3383. * This will automatically validate that the 'ack' field of the message is
  3384. * correct. Also, note that the future will be removed from the map of
  3385. * pending wire message futures.
  3386. *
  3387. * @param message The message that (may) contain an acknowledgement.
  3388. * @param optional If set to `true`, no error will be thrown if the message
  3389. * did not contain an acknowledgement.
  3390. *
  3391. * Throws an exception in case the acknowledgement field is invalid.
  3392. * Throws an exception in case the wire message does not contain an
  3393. * acknowledgement and the acknowledgement is not optional.
  3394. * Throws an exception if no future could be found.
  3395. *
  3396. * In any exception case, if the associated future could be found, it will
  3397. * be rejected with 'invalidResponse' before the exception is being
  3398. * thrown. The case of 'ack.success == false' does NOT count as an
  3399. * exception case.
  3400. */
  3401. private popWireMessageFuture(message: threema.WireMessage, optional = false): Future<any> {
  3402. // Transfer old temporaryId-related fields into new 'ack' field.
  3403. // TODO: Remove when removing temporaryId backwards compatibility
  3404. if (message.ack === undefined &&
  3405. message.args !== undefined &&
  3406. message.args[WebClientService.ARGUMENT_TEMPORARY_ID] !== undefined
  3407. ) {
  3408. // Not all messages with 'temporaryId' had a 'success' field, so
  3409. // we need to patch it.
  3410. if (message.args[WebClientService.ARGUMENT_SUCCESS] === undefined) {
  3411. message.args[WebClientService.ARGUMENT_SUCCESS] = true;
  3412. }
  3413. message.ack = {
  3414. id: message.args[WebClientService.ARGUMENT_TEMPORARY_ID],
  3415. success: message.args[WebClientService.ARGUMENT_SUCCESS],
  3416. error: message.args[WebClientService.ARGUMENT_ERROR],
  3417. };
  3418. }
  3419. // Validate message
  3420. let error: Error;
  3421. if (hasValue(message.ack)) {
  3422. try {
  3423. WebClientService.validateWireMessageAcknowledgement(message.ack);
  3424. } catch (e) {
  3425. error = e;
  3426. }
  3427. } else if (!optional) {
  3428. throw new Error('Wire message did not contain an acknowledgement');
  3429. } else {
  3430. // Nit: We could use a fake future here for performance
  3431. return new Future();
  3432. }
  3433. const id = message.ack.id;
  3434. // Get associated future
  3435. const future = this.wireMessageFutures.get(id);
  3436. if (future !== undefined) {
  3437. // Remove the future from the map
  3438. this.wireMessageFutures.delete(id);
  3439. this.arpLogV.debug(`Removed wire message future: ${id} -> ` +
  3440. `${message.type}/${message.subType}`);
  3441. } else if (error === undefined) {
  3442. error = new Error(`Wire message future not found for id: ${id}`);
  3443. }
  3444. // Handle error (reject future and throw)
  3445. if (error !== undefined) {
  3446. if (future !== undefined) {
  3447. future.reject('invalidResponse');
  3448. }
  3449. throw error;
  3450. }
  3451. // Done
  3452. return future;
  3453. }
  3454. private _receiveRequest(type: string, message: threema.WireMessage): void {
  3455. switch (type) {
  3456. case WebClientService.SUB_TYPE_CONNECTION_ACK:
  3457. this._receiveRequestConnectionAck(message);
  3458. break;
  3459. default:
  3460. this.arpLog.warn(`Ignored request/${type}`);
  3461. break;
  3462. }
  3463. }
  3464. private _receiveResponse(type: string, message: threema.WireMessage): void {
  3465. switch (type) {
  3466. case WebClientService.SUB_TYPE_CONFIRM_ACTION:
  3467. this._receiveResponseConfirmAction(message);
  3468. break;
  3469. case WebClientService.SUB_TYPE_RECEIVERS:
  3470. this._receiveResponseReceivers(message);
  3471. break;
  3472. case WebClientService.SUB_TYPE_CONVERSATIONS:
  3473. this._receiveResponseConversations(message);
  3474. break;
  3475. case WebClientService.SUB_TYPE_MESSAGES:
  3476. this._receiveResponseMessages(message);
  3477. break;
  3478. case WebClientService.SUB_TYPE_AVATAR:
  3479. this._receiveResponseAvatar(message);
  3480. break;
  3481. case WebClientService.SUB_TYPE_THUMBNAIL:
  3482. this._receiveResponseThumbnail(message);
  3483. break;
  3484. case WebClientService.SUB_TYPE_BLOB:
  3485. this._receiveResponseBlob(message);
  3486. break;
  3487. case WebClientService.SUB_TYPE_CLIENT_INFO:
  3488. this._receiveResponseClientInfo(message);
  3489. break;
  3490. case WebClientService.SUB_TYPE_PROFILE:
  3491. this._receiveResponseProfile(message);
  3492. break;
  3493. case WebClientService.SUB_TYPE_CONTACT_DETAIL:
  3494. this._receiveResponseContactDetail(message);
  3495. break;
  3496. default:
  3497. this.arpLog.warn(`Ignored response/${type}`);
  3498. break;
  3499. }
  3500. }
  3501. private _receiveUpdate(type: string, message: threema.WireMessage): void {
  3502. switch (type) {
  3503. case WebClientService.SUB_TYPE_CONFIRM:
  3504. this._receiveUpdateConfirm(message);
  3505. break;
  3506. case WebClientService.SUB_TYPE_RECEIVER:
  3507. this._receiveUpdateReceiver(message);
  3508. break;
  3509. case WebClientService.SUB_TYPE_RECEIVERS:
  3510. this._receiveUpdateReceivers(message);
  3511. break;
  3512. case WebClientService.SUB_TYPE_MESSAGES:
  3513. this._receiveUpdateMessages(message);
  3514. break;
  3515. case WebClientService.SUB_TYPE_TYPING:
  3516. this._receiveUpdateTyping(message);
  3517. break;
  3518. case WebClientService.SUB_TYPE_CONVERSATION:
  3519. this._receiveUpdateConversation(message);
  3520. break;
  3521. case WebClientService.SUB_TYPE_AVATAR:
  3522. this._receiveUpdateAvatar(message);
  3523. break;
  3524. case WebClientService.SUB_TYPE_BATTERY_STATUS:
  3525. this._receiveUpdateBatteryStatus(message);
  3526. break;
  3527. case WebClientService.SUB_TYPE_CONTACT:
  3528. this._receiveUpdateContact(message);
  3529. break;
  3530. case WebClientService.SUB_TYPE_GROUP:
  3531. this._receiveUpdateGroup(message);
  3532. break;
  3533. case WebClientService.SUB_TYPE_DISTRIBUTION_LIST:
  3534. this._receiveUpdateDistributionList(message);
  3535. break;
  3536. case WebClientService.SUB_TYPE_PROFILE:
  3537. this._receiveUpdateProfile(message);
  3538. break;
  3539. case WebClientService.SUB_TYPE_ALERT:
  3540. this._receiveUpdateAlert(message);
  3541. break;
  3542. case WebClientService.SUB_TYPE_CONNECTION_ACK:
  3543. this._receiveUpdateConnectionAck(message);
  3544. break;
  3545. case WebClientService.SUB_TYPE_CONNECTION_DISCONNECT:
  3546. this._receiveUpdateConnectionDisconnect(message);
  3547. break;
  3548. default:
  3549. this.arpLog.warn(`Ignored update/${type}`);
  3550. break;
  3551. }
  3552. }
  3553. private _receiveCreate(type: string, message: threema.WireMessage): void {
  3554. switch (type) {
  3555. case WebClientService.SUB_TYPE_CONTACT:
  3556. this._receiveCreateContact(message);
  3557. break;
  3558. case WebClientService.SUB_TYPE_GROUP:
  3559. this._receiveCreateGroup(message);
  3560. break;
  3561. case WebClientService.SUB_TYPE_DISTRIBUTION_LIST:
  3562. this._receiveCreateDistributionList(message);
  3563. break;
  3564. case WebClientService.SUB_TYPE_TEXT_MESSAGE: // fallthrough
  3565. case WebClientService.SUB_TYPE_FILE_MESSAGE:
  3566. this._receiveCreateMessage(message);
  3567. break;
  3568. default:
  3569. this.arpLog.warn(`Ignored response/${type}`);
  3570. break;
  3571. }
  3572. }
  3573. /**
  3574. * Encode an object using the msgpack format.
  3575. */
  3576. private msgpackEncode(data: any): Uint8Array {
  3577. return msgpack.encode(data, this.msgpackEncoderOptions);
  3578. }
  3579. /**
  3580. * Decode an object using the msgpack format.
  3581. */
  3582. private msgpackDecode(bytes: Uint8Array): any {
  3583. return msgpack.decode(bytes, this.msgpackDecoderOptions);
  3584. }
  3585. /**
  3586. * Send a message via the underlying transport.
  3587. */
  3588. private send(message: threema.WireMessage, retransmit: boolean): void {
  3589. this.arpLog.debug('Sending', message.type + '/' + message.subType, 'message');
  3590. if (this.config.ARP_LOG_TRACE) {
  3591. // Sanitise outgoing message before logging
  3592. this.arpLogV.debug('Outgoing:', message.type, '/', message.subType, new ConfidentialWireMessage(message));
  3593. }
  3594. // TODO: Fix chosenTask may be different between connections in the
  3595. // future. Do not rely on it when sending while not being
  3596. // connected.
  3597. switch (this.chosenTask) {
  3598. case threema.ChosenTask.WebRTC:
  3599. {
  3600. // Send bytes through WebRTC DataChannel
  3601. const bytes: Uint8Array = this.msgpackEncode(message);
  3602. if (this.config.MSGPACK_LOG_TRACE) {
  3603. this.msgpackLog.debug('Outgoing message payload: ' + msgpackVisualizer(bytes));
  3604. }
  3605. const box = this.secureDataChannelCrypto.encrypt(bytes);
  3606. const chunker = new chunkedDc.UnreliableUnorderedChunker(
  3607. this.secureDataChannelMessageId++, box.toUint8Array(), this.secureDataChannelChunkLength);
  3608. for (const chunk of chunker) {
  3609. this.arpLogV.debug(`Data channel ${this.secureDataChannel.dc.label} outgoing ` +
  3610. `chunk of length ${chunk.byteLength}`);
  3611. this.secureDataChannel.write(chunk);
  3612. }
  3613. }
  3614. break;
  3615. case threema.ChosenTask.RelayedData:
  3616. {
  3617. // Don't queue handshake messages
  3618. // TODO: Add this as a method argument
  3619. const canQueue = message.subType !== WebClientService.SUB_TYPE_CONNECTION_INFO;
  3620. // Send bytes through e2e encrypted WebSocket
  3621. const bytes: Uint8Array = this.msgpackEncode(message);
  3622. if (this.config.MSGPACK_LOG_TRACE) {
  3623. this.msgpackLog.debug('Outgoing message payload: ' + msgpackVisualizer(bytes));
  3624. }
  3625. // Increment the outgoing message sequence number
  3626. const messageSequenceNumber = this.outgoingMessageSequenceNumber.increment();
  3627. const chunker = new chunkedDc.UnreliableUnorderedChunker(
  3628. messageSequenceNumber, bytes, WebClientService.RELAYED_DATA_CHUNK_SIZE);
  3629. for (const chunk of chunker) {
  3630. // Send (and cache)
  3631. this.sendChunk(chunk, retransmit, canQueue, true);
  3632. }
  3633. // Check if we need to request an acknowledgement
  3634. // Note: We only request if none is pending.
  3635. if (this.pendingAckRequest === null &&
  3636. this.currentChunkCache.byteLength > WebClientService.CHUNK_CACHE_SIZE_MAX) {
  3637. // Warning: This field MUST be set before requesting the
  3638. // connection ack or you will end up with an
  3639. // infinite recursion.
  3640. this.pendingAckRequest = this.currentChunkCache.sequenceNumber.get();
  3641. this._requestConnectionAck();
  3642. }
  3643. }
  3644. break;
  3645. default:
  3646. this.arpLog.error('Trying to send message, but no chosen task set');
  3647. }
  3648. }
  3649. /**
  3650. * Send a chunk via the underlying transport.
  3651. */
  3652. private sendChunk(chunk: Uint8Array, retransmit: boolean, canQueue: boolean, cache: boolean): void {
  3653. // TODO: Support for sending in chunks via data channels will be added later
  3654. if (this.chosenTask !== threema.ChosenTask.RelayedData) {
  3655. throw new Error(`Cannot send chunk, not supported by task: ${this.chosenTask}`);
  3656. }
  3657. const shouldQueue = canQueue && this.previousChunkCache !== null;
  3658. let chunkCache: ChunkCache;
  3659. // Enqueue in the chunk cache that is pending to be transferred and
  3660. // send a wakeup push.
  3661. if (shouldQueue) {
  3662. chunkCache = this.previousChunkCache;
  3663. this.arpLog.debug('Currently not connected, queueing chunk');
  3664. if (!this.pushService.isAvailable()) {
  3665. this.log.warn('Push service not available, cannot wake up peer!');
  3666. retransmit = false;
  3667. }
  3668. if (retransmit) {
  3669. // TODO: Apply the chunk **push** blacklist instead of the
  3670. // retransmit flag!
  3671. this.sendPush();
  3672. }
  3673. } else {
  3674. chunkCache = this.currentChunkCache;
  3675. }
  3676. // Add to chunk cache
  3677. if (cache) {
  3678. this.arpLogV.debug(`Caching chunk (retransmit/push=${retransmit}:`, chunk);
  3679. try {
  3680. chunkCache.append(retransmit ? chunk : null);
  3681. } catch (error) {
  3682. this.arpLog.error(error);
  3683. this.failSession();
  3684. return;
  3685. }
  3686. }
  3687. // Send if ready
  3688. if (!shouldQueue) {
  3689. this.arpLogV.debug(`Sending chunk (retransmit/push=${retransmit}:`, chunk);
  3690. // Send chunk
  3691. this.relayedDataTask.sendMessage(chunk.buffer);
  3692. // Send a push if no incoming chunks within the next two seconds.
  3693. // Note: This has a cooldown phase of 10 seconds.
  3694. if (retransmit && this.startupDone) {
  3695. this.schedulePush();
  3696. }
  3697. }
  3698. }
  3699. /**
  3700. * Handle an incoming chunk from the underlying transport.
  3701. */
  3702. private receiveChunk(chunk: Uint8Array): void {
  3703. this.arpLogV.debug('Received chunk:', chunk);
  3704. // Update incoming sequence number
  3705. try {
  3706. this.currentIncomingChunkSequenceNumber.increment();
  3707. } catch (error) {
  3708. this.arpLog.error(`Unable to continue session: ${error}`);
  3709. this.failSession();
  3710. return;
  3711. }
  3712. // Schedule the periodic ack timer
  3713. this.scheduleConnectionAck();
  3714. // Cancel scheduled push since data has been received
  3715. this.cancelPush();
  3716. // Process chunk
  3717. // Warning: Nothing should be called after the unchunker has processed
  3718. // the chunk since the message event is synchronous and can
  3719. // result in a call to .stop!
  3720. this.unchunker.add(chunk);
  3721. }
  3722. /**
  3723. * Handle incoming message bytes from the SecureDataChannel.
  3724. */
  3725. private handleIncomingMessageBytes(bytes: Uint8Array): void {
  3726. this.arpLog.debug('New incoming message (' + bytes.byteLength + ' bytes)');
  3727. if (this.config.MSGPACK_LOG_TRACE) {
  3728. this.msgpackLog.debug('Incoming message payload: ' + msgpackVisualizer(bytes));
  3729. }
  3730. // Decode bytes
  3731. const message: threema.WireMessage = this.msgpackDecode(bytes);
  3732. return this.handleIncomingMessage(message);
  3733. }
  3734. /**
  3735. * Handle incoming incoming from the SecureDataChannel
  3736. * or from the relayed data WebSocket.
  3737. */
  3738. private handleIncomingMessage(message: threema.WireMessage): void {
  3739. this.arpLog.debug(`Received ${message.type}/${message.subType} message`);
  3740. // Validate message to keep contract defined by `threema.WireMessage` type
  3741. if (message.type === undefined) {
  3742. this.arpLog.warn('Ignoring invalid message (no type attribute)');
  3743. return;
  3744. } else if (message.subType === undefined) {
  3745. this.arpLog.warn('Ignoring invalid message (no subType attribute)');
  3746. return;
  3747. }
  3748. // If desired, log message type / subtype
  3749. if (this.config.ARP_LOG_TRACE) {
  3750. // Sanitise incoming message before logging
  3751. // Note: Deep-copy message to prevent issues with JS debugger
  3752. this.arpLogV.debug(`Incoming: ${message.type}/${message.subType}`,
  3753. new ConfidentialWireMessage(copyDeepOrReference(message)));
  3754. }
  3755. // Process data
  3756. this.$rootScope.$apply(() => {
  3757. this.receive(message);
  3758. });
  3759. }
  3760. /**
  3761. * Receive a new incoming decrypted message.
  3762. * This method runs inside the digest loop.
  3763. */
  3764. private receive(message: threema.WireMessage): void {
  3765. // Intercept handshake message
  3766. if (!this.connectionInfoFuture.done) {
  3767. // Check for unexpected messages
  3768. if (message.type !== WebClientService.TYPE_UPDATE ||
  3769. message.subType !== WebClientService.SUB_TYPE_CONNECTION_INFO) {
  3770. this.arpLog.error('Unexpected message before handshake has been completed');
  3771. this.failSession();
  3772. return;
  3773. }
  3774. // Dispatch and return
  3775. this._receiveConnectionInfo(message);
  3776. return;
  3777. }
  3778. // Determine message handler
  3779. let messageHandler: (type, message) => void;
  3780. switch (message.type) {
  3781. case WebClientService.TYPE_REQUEST:
  3782. messageHandler = this._receiveRequest;
  3783. break;
  3784. case WebClientService.TYPE_RESPONSE:
  3785. messageHandler = this._receiveResponse;
  3786. break;
  3787. case WebClientService.TYPE_CREATE:
  3788. messageHandler = this._receiveCreate;
  3789. break;
  3790. case WebClientService.TYPE_UPDATE:
  3791. messageHandler = this._receiveUpdate;
  3792. break;
  3793. default:
  3794. this.arpLog.warn(`Ignored message ${message.type}/${message.subType}`);
  3795. break;
  3796. }
  3797. // Dispatch message
  3798. if (messageHandler !== undefined) {
  3799. try {
  3800. messageHandler.apply(this, [message.subType, message]);
  3801. } catch (error) {
  3802. this.arpLog.error('Unable to handle incoming wire message:', error);
  3803. console.trace(error); // tslint:disable-line:no-console
  3804. return;
  3805. }
  3806. }
  3807. // Catch unhandled wire message acknowledgements
  3808. // Nit: We could cache that we have already scraped the message for a
  3809. // wire message acknowledgement instead of double-parsing.
  3810. let future: Future<any>;
  3811. try {
  3812. future = this.popWireMessageFuture(message);
  3813. } catch {
  3814. // Yes, I really know what I'm doing, thanks eslint...
  3815. }
  3816. if (future !== undefined) {
  3817. this.arpLog.warn(`Unhandled message acknowledgement for type ${message.type}:`, message.ack);
  3818. future.reject('unhandled');
  3819. }
  3820. }
  3821. private runAfterInitializationSteps(requiredSteps: threema.InitializationStep[], callback: any): void {
  3822. for (const requiredStep of requiredSteps) {
  3823. if (!this.initialized.has(requiredStep)) {
  3824. this.arpLog.debug('Required initialization step', requiredStep, 'not completed, add pending routine');
  3825. this.pendingInitializationStepRoutines.add({
  3826. requiredSteps: requiredSteps,
  3827. callback: callback,
  3828. } as threema.InitializationStepRoutine);
  3829. return;
  3830. }
  3831. }
  3832. callback.apply(this);
  3833. }
  3834. /**
  3835. * Update the unread count in the window title.
  3836. */
  3837. private updateUnreadCount(): void {
  3838. const totalUnreadCount = this.conversations
  3839. .get()
  3840. .reduce((a: number, b: threema.Conversation) => a + b.unreadCount, 0);
  3841. this.stateService.unreadCount = totalUnreadCount;
  3842. }
  3843. /**
  3844. * Reset the unread count in the window title
  3845. */
  3846. private resetUnreadCount(): void {
  3847. this.stateService.unreadCount = 0;
  3848. }
  3849. /**
  3850. * Return the configuration object from the client info data.
  3851. */
  3852. public get appConfig(): threema.AppConfig {
  3853. return this.clientInfo.configuration;
  3854. }
  3855. /**
  3856. * Return the capabilities object from the client info data.
  3857. */
  3858. public get appCapabilities(): threema.AppCapabilities {
  3859. return this.clientInfo.capabilities;
  3860. }
  3861. /**
  3862. * Sort a list of contacts in-place.
  3863. */
  3864. private sortContacts(contacts: threema.ContactReceiver[]): void {
  3865. const getSortableName = (name: string) => name.startsWith('~') ? name.substr(1) : name;
  3866. let options;
  3867. if (this.browserService.supportsExtendedLocaleCompare()) {
  3868. options = {
  3869. usage: 'sort',
  3870. sensitivity: 'variant',
  3871. };
  3872. }
  3873. const compareFunc = (a: threema.Receiver, b: threema.Receiver) => {
  3874. if (a.id.startsWith('*') && !b.id.startsWith('*')) { return 1; }
  3875. if (!a.id.startsWith('*') && b.id.startsWith('*')) { return -1; }
  3876. const left = getSortableName(a.displayName);
  3877. const right = getSortableName(b.displayName);
  3878. return left.localeCompare(right, undefined, options);
  3879. };
  3880. contacts.sort(compareFunc);
  3881. }
  3882. /**
  3883. * Clear all "is typing" flags.
  3884. */
  3885. public clearIsTypingFlags(): void {
  3886. this.typing.clearAll();
  3887. }
  3888. private handleGlobalConnectionStateChange(stateChange: threema.GlobalConnectionStateChange): void {
  3889. const isOk = stateChange.state === threema.GlobalConnectionState.Ok;
  3890. const wasOk = stateChange.prevState === threema.GlobalConnectionState.Ok;
  3891. if (!isOk && wasOk && this.batteryStatusService.dataAvailable) {
  3892. this.batteryStatusTimeout = this.timeoutService.register(
  3893. () => {
  3894. this.batteryStatusService.clearStatus();
  3895. this.batteryStatusTimeout = null;
  3896. },
  3897. 60000,
  3898. true,
  3899. 'batteryStatusHide',
  3900. );
  3901. } else if (isOk && this.batteryStatusTimeout !== null) {
  3902. this.timeoutService.cancel(this.batteryStatusTimeout);
  3903. this.batteryStatusTimeout = null;
  3904. }
  3905. }
  3906. /**
  3907. * Log chat message's metadata for debugging purposes.
  3908. */
  3909. private logChatMessages(
  3910. type: string, subType: string, receiverType: string, receiver: string, mode: string,
  3911. messages: threema.Message[],
  3912. ) {
  3913. for (const message of messages) {
  3914. let id: string = message.id;
  3915. if (this.clientInfo.os === threema.OperatingSystem.Ios) {
  3916. try {
  3917. id = u8aToHex(base64ToU8a(message.id));
  3918. } catch { /* ignored */ }
  3919. }
  3920. this.arpLogV.debug('Chat message:', `${type}/${subType}: receiver=${receiverType}/${receiver}, ` +
  3921. `mode=${mode}, direction=${message.isOutbox ? 'out' : 'in'}, id=${id}, type=${message.type}, ` +
  3922. `state=${message.state !== undefined ? message.state : '?'}, is-status=${message.isStatus}, ` +
  3923. `date=${message.date}`);
  3924. }
  3925. }
  3926. }