webclient.ts 172 KB

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