webclient.ts 170 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371
  1. /**
  2. * This file is part of Threema Web.
  3. *
  4. * Threema Web is free software: you can redistribute it and/or modify it
  5. * under the terms of the GNU Affero General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or (at
  7. * your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Affero General Public License
  15. * along with Threema Web. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. /// <reference types="@saltyrtc/chunked-dc" />
  18. /// <reference types="@saltyrtc/task-webrtc" />
  19. /// <reference types="@saltyrtc/task-relayed-data" />
  20. import {StateService as UiStateService} from '@uirouter/angularjs';
  21. import {Logger} from 'ts-log';
  22. import * as msgpack from 'msgpack-lite';
  23. import {
  24. arraysAreEqual,
  25. base64ToU8a,
  26. bufferToUrl,
  27. copyDeepOrReference,
  28. hasFeature,
  29. hasValue,
  30. hexToU8a,
  31. msgpackVisualizer,
  32. randomString,
  33. stringToUtf8a,
  34. u8aToHex,
  35. } from '../helpers';
  36. import {
  37. isContactReceiver,
  38. isDistributionListReceiver,
  39. isGroupReceiver,
  40. isValidReceiverType,
  41. } from '../typeguards';
  42. import {BatteryStatusService} from './battery';
  43. import {BrowserService} from './browser';
  44. import {TrustedKeyStoreService} from './keystore';
  45. import {LogService} from './log';
  46. import {MessageService} from './message';
  47. import {MimeService} from './mime';
  48. import {NotificationService} from './notification';
  49. import {PeerConnectionHelper} from './peerconnection';
  50. import {PushService, PushSession} from './push';
  51. import {QrCodeService} from './qrcode';
  52. import {ReceiverService} from './receiver';
  53. import {StateService} from './state';
  54. import {TimeoutService} from './timeout';
  55. import {TitleService} from './title';
  56. import {VersionService} from './version';
  57. import {TimeoutError} from '../exceptions';
  58. import {ConfidentialWireMessage} from '../helpers/confidential';
  59. import {UnboundedFlowControlledDataChannel} from '../helpers/data_channel';
  60. import {DeviceUnreachableController} from '../partials/messenger';
  61. import {ChunkCache} from '../protocol/cache';
  62. import {SequenceNumber} from '../protocol/sequence_number';
  63. // Aliases
  64. import InitializationStep = threema.InitializationStep;
  65. import ContactReceiverFeature = threema.ContactReceiverFeature;
  66. import DisconnectReason = threema.DisconnectReason;
  67. import PushSessionConfig = threema.PushSessionConfig;
  68. /**
  69. * Payload of a connectionInfo message.
  70. */
  71. interface ConnectionInfo {
  72. id: ArrayBuffer;
  73. resume?: {
  74. id: ArrayBuffer;
  75. sequenceNumber: number;
  76. };
  77. }
  78. const fakeConnectionId = Uint8Array.from([
  79. 1, 2, 3, 4, 5, 6, 7, 8,
  80. 1, 2, 3, 4, 5, 6, 7, 8,
  81. 1, 2, 3, 4, 5, 6, 7, 8,
  82. 1, 2, 3, 4, 5, 6, 7, 8,
  83. ]);
  84. /**
  85. * This service handles everything related to the communication with the peer.
  86. */
  87. export class WebClientService {
  88. public static readonly MAX_CONNECT_ATTEMPTS = 3;
  89. private static DATA_CHANNEL_MAX_CHUNK_SIZE = 256 * 1024;
  90. private static RELAYED_DATA_CHUNK_SIZE = 64 * 1024;
  91. private static SEQUENCE_NUMBER_MIN = 0;
  92. private static SEQUENCE_NUMBER_MAX = (2 ** 32) - 1;
  93. private static CHUNK_CACHE_SIZE_MAX = 2 * 1024 * 1024;
  94. private static AVATAR_LOW_MAX_SIZE = 48;
  95. private static MAX_TEXT_LENGTH = 3500;
  96. private static MAX_FILE_SIZE_WEBRTC_TASK_V0 = 15 * 1024 * 1024;
  97. private static CONNECTION_ID_NONCE = stringToUtf8a('connectionidconnectionid');
  98. private static TYPE_REQUEST = 'request';
  99. private static TYPE_RESPONSE = 'response';
  100. private static TYPE_UPDATE = 'update';
  101. private static TYPE_CREATE = 'create';
  102. private static TYPE_DELETE = 'delete';
  103. private static SUB_TYPE_RECEIVER = 'receiver';
  104. private static SUB_TYPE_RECEIVERS = 'receivers';
  105. private static SUB_TYPE_CONVERSATIONS = 'conversations';
  106. private static SUB_TYPE_CONVERSATION = 'conversation';
  107. private static SUB_TYPE_MESSAGE = 'message';
  108. private static SUB_TYPE_MESSAGES = 'messages';
  109. private static SUB_TYPE_TEXT_MESSAGE = 'textMessage';
  110. private static SUB_TYPE_FILE_MESSAGE = 'fileMessage';
  111. private static SUB_TYPE_AVATAR = 'avatar';
  112. private static SUB_TYPE_THUMBNAIL = 'thumbnail';
  113. private static SUB_TYPE_BLOB = 'blob';
  114. private static SUB_TYPE_TYPING = 'typing';
  115. private static SUB_TYPE_READ = 'read';
  116. private static SUB_TYPE_CLIENT_INFO = 'clientInfo';
  117. private static SUB_TYPE_KEY_PERSISTED = 'keyPersisted';
  118. private static SUB_TYPE_ACK = 'ack';
  119. private static SUB_TYPE_CONTACT_DETAIL = 'contactDetail';
  120. private static SUB_TYPE_CONTACT = 'contact';
  121. private static SUB_TYPE_GROUP = 'group';
  122. private static SUB_TYPE_DISTRIBUTION_LIST = 'distributionList';
  123. private static SUB_TYPE_ALERT = 'alert';
  124. private static SUB_TYPE_GROUP_SYNC = 'groupSync';
  125. private static SUB_TYPE_BATTERY_STATUS = 'batteryStatus';
  126. private static SUB_TYPE_CLEAN_RECEIVER_CONVERSATION = 'cleanReceiverConversation';
  127. private static SUB_TYPE_CONFIRM = 'confirm';
  128. private static SUB_TYPE_CONFIRM_ACTION = 'confirmAction'; // TODO: deprecated
  129. private static SUB_TYPE_PROFILE = 'profile';
  130. private static SUB_TYPE_CONNECTION_ACK = 'connectionAck';
  131. private static SUB_TYPE_CONNECTION_DISCONNECT = 'connectionDisconnect';
  132. private static SUB_TYPE_CONNECTION_INFO = 'connectionInfo';
  133. private static ARGUMENT_MODE = 'mode';
  134. private static ARGUMENT_MODE_NEW = 'new';
  135. private static ARGUMENT_MODE_MODIFIED = 'modified';
  136. private static ARGUMENT_MODE_REMOVED = 'removed';
  137. private static ARGUMENT_RECEIVER_TYPE = 'type';
  138. private static ARGUMENT_RECEIVER_ID = 'id';
  139. private static ARGUMENT_TEMPORARY_ID = 'temporaryId'; // TODO: deprecated
  140. private static ARGUMENT_REFERENCE_MSG_ID = 'refMsgId';
  141. private static ARGUMENT_AVATAR = 'avatar';
  142. private static ARGUMENT_AVATAR_HIGH_RESOLUTION = 'highResolution';
  143. private static ARGUMENT_NICKNAME = 'publicNickname';
  144. private static ARGUMENT_IS_TYPING = 'isTyping';
  145. private static ARGUMENT_MESSAGE_ID = 'messageId';
  146. private static ARGUMENT_HAS_MORE = 'more';
  147. private static ARGUMENT_MESSAGE_ACKNOWLEDGED = 'acknowledged';
  148. private static ARGUMENT_IDENTITY = 'identity';
  149. private static ARGUMENT_SUCCESS = 'success'; // TODO: deprecated
  150. private static ARGUMENT_SYSTEM_CONTACT = 'systemContact';
  151. private static ARGUMENT_NAME = 'name';
  152. private static ARGUMENT_MEMBERS = 'members';
  153. private static ARGUMENT_FIRST_NAME = 'firstName';
  154. private static ARGUMENT_LAST_NAME = 'lastName';
  155. private static ARGUMENT_DELETE_TYPE = 'deleteType';
  156. private static ARGUMENT_ERROR = 'error'; // TODO: deprecated
  157. private static ARGUMENT_MAX_SIZE = 'maxSize';
  158. private static ARGUMENT_USER_AGENT = 'userAgent';
  159. private static ARGUMENT_BROWSER_NAME = 'browserName';
  160. private static ARGUMENT_BROWSER_VERSION = 'browserVersion';
  161. private static DELETE_GROUP_TYPE_LEAVE = 'leave';
  162. private static DELETE_GROUP_TYPE_DELETE = 'delete';
  163. private static DATA_FIELD_BLOB_BLOB = 'blob';
  164. private static DATA_FIELD_BLOB_TYPE = 'type';
  165. private static DATA_FIELD_BLOB_NAME = 'name';
  166. private static DC_LABEL = 'THREEMA';
  167. // Angular services
  168. private $state: UiStateService;
  169. private $rootScope: any;
  170. private $q: ng.IQService;
  171. private $window: ng.IWindowService;
  172. private $translate: ng.translate.ITranslateService;
  173. private $filter: any;
  174. private $timeout: ng.ITimeoutService;
  175. private $mdDialog: ng.material.IDialogService;
  176. // Custom services
  177. private batteryStatusService: BatteryStatusService;
  178. private browserService: BrowserService;
  179. private logService: LogService;
  180. private messageService: MessageService;
  181. private mimeService: MimeService;
  182. private notificationService: NotificationService;
  183. private pushService: PushService;
  184. private qrCodeService: QrCodeService;
  185. private receiverService: ReceiverService;
  186. private timeoutService: TimeoutService;
  187. private titleService: TitleService; // Don't remove, needs to be initialized to handle events
  188. private versionService: VersionService;
  189. // Logging
  190. private readonly log: Logger;
  191. private readonly arpLog: Logger;
  192. private readonly arpLogV: Logger;
  193. private readonly msgpackLog: Logger;
  194. // State handling
  195. private startupPromise: ng.IDeferred<{}> = null; // TODO: deferred type
  196. public startupDone: boolean = false;
  197. private handoverDone: boolean = false;
  198. private pendingInitializationStepRoutines: Set<threema.InitializationStepRoutine> = new Set();
  199. private initialized: Set<threema.InitializationStep> = new Set();
  200. private stateService: StateService;
  201. // Session connection
  202. private saltyRtcHost: string = null;
  203. public salty: saltyrtc.SaltyRTC = null;
  204. private connectionInfoFuture: Future<ConnectionInfo> = null;
  205. private relayedDataTask: saltyrtc.tasks.relayed_data.RelayedDataTask = null;
  206. private secureDataChannel: UnboundedFlowControlledDataChannel = null;
  207. private secureDataChannelCrypto: saltyrtc.tasks.webrtc.DataChannelCryptoContext = null;
  208. private secureDataChannelChunkLength: number = null;
  209. private secureDataChannelMessageId: number = 0;
  210. public chosenTask: threema.ChosenTask = threema.ChosenTask.None;
  211. private outgoingMessageSequenceNumber: SequenceNumber;
  212. private previousConnectionId: Uint8Array = null;
  213. private currentConnectionId: Uint8Array = null;
  214. private previousIncomingChunkSequenceNumber: SequenceNumber = null;
  215. private currentIncomingChunkSequenceNumber: SequenceNumber;
  216. private previousChunkCache: ChunkCache = null;
  217. private currentChunkCache: ChunkCache = null;
  218. private handshakeCompleted: boolean = false;
  219. private ackTimer: number | null = null;
  220. private pendingAckRequest: number | null = null;
  221. // Message chunking
  222. private unchunker: chunkedDc.UnreliableUnorderedUnchunker = null;
  223. // Messenger data
  224. public messages: threema.Container.Messages;
  225. public conversations: threema.Container.Conversations;
  226. public receivers: threema.Container.Receivers;
  227. public alerts: threema.Alert[] = [];
  228. // Push
  229. private pushToken: string = null;
  230. private pushTokenType: threema.PushTokenType = null;
  231. private pushSession: PushSession | null = null;
  232. private readonly pushSessionConfig: PushSessionConfig;
  233. private readonly pushSessionExpectedPeriodMaxMs: number;
  234. private pushPromise: Promise<any> | null = null;
  235. private deviceUnreachableDialog: ng.IPromise<any> | null = null;
  236. private pushTimer: number | null = null;
  237. private schedulePushAfterCooldown: boolean = false;
  238. // Timeouts
  239. private batteryStatusTimeout: ng.IPromise<void> = null;
  240. // Other
  241. private config: threema.Config;
  242. private container: threema.Container.Factory;
  243. private typingInstance: threema.Container.Typing;
  244. private drafts: threema.Container.Drafts;
  245. private pcHelper: PeerConnectionHelper = null;
  246. private trustedKeyStore: TrustedKeyStoreService;
  247. public clientInfo: threema.ClientInfo = null;
  248. public version = null;
  249. private blobCache = new Map<string, threema.BlobInfo>();
  250. private loadingMessages = new Map<string, boolean>();
  251. public receiverListener: threema.ReceiverListener[] = [];
  252. // Msgpack
  253. private msgpackEncoderOptions: msgpack.EncoderOptions = {
  254. codec: msgpack.createCodec({binarraybuffer: true}),
  255. };
  256. private msgpackDecoderOptions: msgpack.DecoderOptions = {
  257. codec: msgpack.createCodec({binarraybuffer: true}),
  258. };
  259. // Messages that require acknowledgement
  260. private wireMessageFutures: Map<string, Future<any>> = new Map();
  261. public static $inject = [
  262. '$rootScope', '$q', '$state', '$window', '$translate', '$filter', '$timeout', '$mdDialog',
  263. 'LogService', 'Container', 'TrustedKeyStore',
  264. 'StateService', 'NotificationService', 'MessageService', 'PushService', 'BrowserService',
  265. 'TitleService', 'QrCodeService', 'MimeService', 'ReceiverService',
  266. 'VersionService', 'BatteryStatusService', 'TimeoutService',
  267. 'CONFIG',
  268. ];
  269. constructor($rootScope: any,
  270. $q: ng.IQService,
  271. $state: UiStateService,
  272. $window: ng.IWindowService,
  273. $translate: ng.translate.ITranslateService,
  274. $filter: ng.IFilterService,
  275. $timeout: ng.ITimeoutService,
  276. $mdDialog: ng.material.IDialogService,
  277. logService: LogService,
  278. container: threema.Container.Factory,
  279. trustedKeyStore: TrustedKeyStoreService,
  280. stateService: StateService,
  281. notificationService: NotificationService,
  282. messageService: MessageService,
  283. pushService: PushService,
  284. browserService: BrowserService,
  285. titleService: TitleService,
  286. qrCodeService: QrCodeService,
  287. mimeService: MimeService,
  288. receiverService: ReceiverService,
  289. versionService: VersionService,
  290. batteryStatusService: BatteryStatusService,
  291. timeoutService: TimeoutService,
  292. CONFIG: threema.Config) {
  293. // Angular services
  294. this.$rootScope = $rootScope;
  295. this.$q = $q;
  296. this.$state = $state;
  297. this.$window = $window;
  298. this.$translate = $translate;
  299. this.$filter = $filter;
  300. this.$timeout = $timeout;
  301. this.$mdDialog = $mdDialog;
  302. // Own services
  303. this.batteryStatusService = batteryStatusService;
  304. this.browserService = browserService;
  305. this.logService = logService;
  306. this.messageService = messageService;
  307. this.mimeService = mimeService;
  308. this.notificationService = notificationService;
  309. this.pushService = pushService;
  310. this.qrCodeService = qrCodeService;
  311. this.receiverService = receiverService;
  312. this.timeoutService = timeoutService;
  313. this.titleService = titleService;
  314. this.versionService = versionService;
  315. // Configuration object
  316. this.config = CONFIG;
  317. // Logging
  318. this.log = logService.getLogger('WebClient-S', 'color: #fff; background-color: #0066cc');
  319. this.arpLog = logService.getLogger(
  320. 'AppRemoteProtocol', 'color: #fff; background-color: #0099cc', CONFIG.ARP_LOG_LEVEL);
  321. this.arpLogV = logService.getLogger(
  322. 'AppRemoteProtocol', 'color: #fff; background-color: #00ace6', CONFIG.ARP_LOG_TRACE ? 'debug' : 'none');
  323. this.msgpackLog = logService.getLogger(
  324. 'MessagePack', 'color: #fff; background-color: #006699', CONFIG.MSGPACK_LOG_TRACE ? 'debug' : 'none');
  325. // State
  326. this.stateService = stateService;
  327. // Push session configuration
  328. this.pushSessionConfig = PushSession.defaultConfig;
  329. this.pushSessionConfig.triesMax = WebClientService.MAX_CONNECT_ATTEMPTS;
  330. // TODO: Remove below config overwrite lines once the app-related push issues have been resolved in #802
  331. this.pushSessionConfig = {
  332. retryTimeoutInitMs: 14000, retryTimeoutMaxMs: 30000, triesMax: 1, timeToLiveRange: [90],
  333. };
  334. this.pushSessionExpectedPeriodMaxMs = PushSession.expectedPeriodMaxMs(this.pushSessionConfig);
  335. // Other properties
  336. this.container = container;
  337. this.trustedKeyStore = trustedKeyStore;
  338. // Initialize drafts
  339. this.drafts = this.container.createDrafts();
  340. // Setup fields
  341. this._resetFields();
  342. // Register event handlers
  343. this.stateService.evtConnectionBuildupStateChange.attach(
  344. (stateChange: threema.ConnectionBuildupStateChange) => {
  345. if (this.startupPromise !== null) {
  346. this.startupPromise.notify(stateChange);
  347. }
  348. },
  349. );
  350. this.stateService.evtGlobalConnectionStateChange.attach(this.handleGlobalConnectionStateChange.bind(this));
  351. }
  352. /**
  353. * Return whether wire messages can be sent (or queued to be sent).
  354. *
  355. * Note: This will not return `true` before an initial connection has been
  356. * established successfully.
  357. */
  358. get readyToSubmit(): boolean {
  359. return this.stateService.readyToSubmit(this.chosenTask, this.startupDone);
  360. }
  361. get me(): threema.MeReceiver {
  362. return this.receivers.me;
  363. }
  364. get contacts(): Map<string, threema.ContactReceiver> {
  365. return this.receivers.contacts;
  366. }
  367. get groups(): Map<string, threema.GroupReceiver> {
  368. return this.receivers.groups;
  369. }
  370. get distributionLists(): Map<string, threema.DistributionListReceiver> {
  371. return this.receivers.distributionLists;
  372. }
  373. get typing(): threema.Container.Typing {
  374. return this.typingInstance;
  375. }
  376. /**
  377. * Return the amount of unacknowledged wire messages.
  378. */
  379. get unacknowledgedWireMessages(): number {
  380. return this.wireMessageFutures.size;
  381. }
  382. // TODO: Deprecated - remove this attribute and update all references
  383. get requiresTemporaryIdBackwardsCompatibility(): boolean {
  384. return this.chosenTask !== threema.ChosenTask.RelayedData;
  385. }
  386. /**
  387. * Return QR code payload.
  388. */
  389. public buildQrCodePayload(persistent: boolean): string {
  390. return this.qrCodeService.buildQrCodePayload(
  391. this.salty.permanentKeyBytes,
  392. this.salty.authTokenBytes,
  393. hexToU8a(this.config.SALTYRTC_SERVER_KEY),
  394. this.saltyRtcHost, this.config.SALTYRTC_PORT,
  395. persistent);
  396. }
  397. /**
  398. * Initialize the webclient service.
  399. *
  400. * Warning: Do not call this with `flags.resume` set to `false` in case
  401. * messages can be queued by the user.
  402. */
  403. public init(flags: {
  404. keyStore?: saltyrtc.KeyStore,
  405. peerTrustedKey?: Uint8Array,
  406. resume: boolean,
  407. }): void {
  408. let keyStore = flags.keyStore;
  409. let resumeSession = flags.resume;
  410. this.log.info(`Initializing (keyStore=${keyStore !== undefined ? 'yes' : 'no'}, peerTrustedKey=` +
  411. `${flags.peerTrustedKey !== undefined ? 'yes' : 'no'}, resume=${resumeSession})`);
  412. // Reset fields, blob cache, pending requests and pending timeouts in case the session
  413. // should explicitly not be resumed
  414. if (!resumeSession) {
  415. this.clearCache();
  416. this.wireMessageFutures.clear();
  417. this.timeoutService.cancelAll();
  418. }
  419. // Only move the previous connection's instances if the previous
  420. // connection was successful (and if there was one at all).
  421. if (resumeSession) {
  422. if (this.previousConnectionId) {
  423. this.arpLog.debug(`Trying to resume previous session (id=${u8aToHex(this.previousConnectionId)}, ` +
  424. `sn-out=${this.previousChunkCache.sequenceNumber.get()})`);
  425. } else {
  426. resumeSession = false;
  427. this.arpLog.debug('Wanted to resume previous session but none exists');
  428. }
  429. } else {
  430. // Discard session
  431. this.discardSession({ resetMessageSequenceNumber: true });
  432. resumeSession = false;
  433. this.arpLog.debug('Discarded previous session');
  434. }
  435. // Reset handshake completed flag
  436. this.handshakeCompleted = false;
  437. // Initialise connection caches
  438. this.currentConnectionId = null;
  439. this.currentIncomingChunkSequenceNumber = new SequenceNumber(
  440. 0, WebClientService.SEQUENCE_NUMBER_MIN, WebClientService.SEQUENCE_NUMBER_MAX);
  441. const outgoingChunkSequenceNumber = new SequenceNumber(
  442. 0, WebClientService.SEQUENCE_NUMBER_MIN, WebClientService.SEQUENCE_NUMBER_MAX);
  443. this.currentChunkCache = new ChunkCache(outgoingChunkSequenceNumber);
  444. // Reset pending ack request
  445. this.pendingAckRequest = null;
  446. // Create new handshake future
  447. this.connectionInfoFuture = new Future();
  448. // Create tasks
  449. const tasks: saltyrtc.Task[] = [];
  450. // Create WebRTC task instance (if supported)
  451. if (this.browserService.supportsWebrtcTask()) {
  452. // TODO: Remove legacy v0 after a transitional period
  453. tasks.push(new saltyrtcTaskWebrtc.WebRTCTaskBuilder()
  454. .withLoggingLevel(this.config.SALTYRTC_LOG_LEVEL)
  455. .withVersion('v1')
  456. .withHandover(true)
  457. .build());
  458. tasks.push(new saltyrtcTaskWebrtc.WebRTCTaskBuilder()
  459. .withLoggingLevel(this.config.SALTYRTC_LOG_LEVEL)
  460. .withVersion('v0')
  461. .withHandover(true)
  462. .withMaxChunkLength(this.browserService.getBrowser().isFirefox(false) ? 16384 : 65536)
  463. .build());
  464. }
  465. // Create Relayed Data task instance
  466. this.relayedDataTask = new saltyrtcTaskRelayedData.RelayedDataTask(this.config.SALTYRTC_LOG_LEVEL === 'debug');
  467. tasks.push(this.relayedDataTask);
  468. // Create new keystore if necessary
  469. if (!keyStore) {
  470. keyStore = new saltyrtcClient.KeyStore();
  471. }
  472. // Determine SaltyRTC host
  473. if (this.config.SALTYRTC_HOST !== null) {
  474. // Static URL
  475. this.saltyRtcHost = this.config.SALTYRTC_HOST;
  476. } else {
  477. // Construct URL using prefix and suffix
  478. this.saltyRtcHost = this.config.SALTYRTC_HOST_PREFIX
  479. + keyStore.publicKeyHex.substr(0, 2)
  480. + this.config.SALTYRTC_HOST_SUFFIX;
  481. }
  482. // Create SaltyRTC client
  483. let builder = new saltyrtcClient.SaltyRTCBuilder()
  484. .connectTo(this.saltyRtcHost, this.config.SALTYRTC_PORT)
  485. .withLoggingLevel(this.config.SALTYRTC_LOG_LEVEL)
  486. .withServerKey(this.config.SALTYRTC_SERVER_KEY)
  487. .withKeyStore(keyStore)
  488. .usingTasks(tasks)
  489. .withPingInterval(30);
  490. if (flags.peerTrustedKey !== undefined) {
  491. builder = builder.withTrustedPeerKey(flags.peerTrustedKey);
  492. }
  493. this.salty = builder.asInitiator();
  494. this.arpLog.info('Public key:', this.salty.permanentKeyHex);
  495. this.arpLogV.debug('Auth token:', this.salty.authTokenHex);
  496. // We want to know about state changes
  497. this.salty.on('state-change', (ev: saltyrtc.SaltyRTCEvent) => {
  498. const state: saltyrtc.SignalingState = ev.data;
  499. if (!this.startupDone) {
  500. switch (state) {
  501. case 'new':
  502. case 'ws-connecting':
  503. case 'server-handshake':
  504. if (this.stateService.connectionBuildupState !== 'push'
  505. && this.stateService.connectionBuildupState !== 'manual_start') {
  506. this.stateService.updateConnectionBuildupState('connecting');
  507. }
  508. break;
  509. case 'peer-handshake':
  510. // Waiting for peer
  511. if (this.stateService.connectionBuildupState !== 'push'
  512. && this.stateService.connectionBuildupState !== 'manual_start') {
  513. this.stateService.updateConnectionBuildupState('waiting');
  514. }
  515. break;
  516. case 'task':
  517. this.onTaskEstablished(resumeSession);
  518. break;
  519. case 'closing':
  520. case 'closed':
  521. this.stateService.updateConnectionBuildupState('closed');
  522. break;
  523. default:
  524. this.arpLog.warn('Unknown signaling state:', state);
  525. }
  526. }
  527. this.stateService.updateSignalingConnectionState(state, this.chosenTask, this.handoverDone);
  528. });
  529. // Handle disconnecting of a peer
  530. this.salty.on('peer-disconnected', (ev: saltyrtc.SaltyRTCEvent) => {
  531. this.$rootScope.$apply(() => {
  532. this.onPeerDisconnected(ev.data);
  533. });
  534. });
  535. // Wait for handover to be finished
  536. this.salty.on('handover', () => {
  537. this.arpLog.debug('Handover done');
  538. this.onHandover(resumeSession);
  539. });
  540. // Handle SaltyRTC errors
  541. this.salty.on('connection-error', (ev) => {
  542. this.arpLog.error('Connection error:', ev);
  543. });
  544. this.salty.on('connection-closed', (ev) => {
  545. this.arpLog.info('Connection closed:', ev);
  546. });
  547. this.salty.on('no-shared-task', (ev) => {
  548. this.arpLog.warn('No shared task found:', ev.data);
  549. const offeredWebrtc = ev.data.offered.filter((t) => t.endsWith('webrtc.tasks.saltyrtc.org')).length > 0;
  550. this.$rootScope.$apply(() => {
  551. if (!this.browserService.supportsWebrtcTask() && offeredWebrtc) {
  552. this.failSession(false);
  553. this.showWebrtcAndroidWarning();
  554. } else {
  555. this.failSession();
  556. }
  557. });
  558. });
  559. }
  560. /**
  561. * Show a WebRTC on Android warning dialog.
  562. */
  563. private showWebrtcAndroidWarning(): void {
  564. this.$translate.onReady().then(() => {
  565. const confirm = this.$mdDialog.alert()
  566. .title(this.$translate.instant('welcome.BROWSER_NOT_SUPPORTED_ANDROID'))
  567. .htmlContent(this.$translate.instant('welcome.BROWSER_NOT_SUPPORTED_DETAILS'))
  568. .ok(this.$translate.instant('welcome.ABORT'));
  569. this.$mdDialog.show(confirm).then(() => {
  570. // Redirect to Threema website
  571. window.location.replace('https://threema.ch/threema-web');
  572. });
  573. });
  574. }
  575. /**
  576. * Show an alert dialog. Can be called directly after calling `.stop(...)`.
  577. */
  578. private showAlert(alertMessage: string): void {
  579. // Note: A former stop() call above may result in a redirect, which will
  580. // in turn hide all open dialog boxes. Therefore, to avoid
  581. // immediately hiding the alert box, enqueue dialog at end of
  582. // event loop.
  583. this.$timeout(() => {
  584. this.$mdDialog.show(this.$mdDialog.alert()
  585. .title(this.$translate.instant('connection.SESSION_CLOSED_TITLE'))
  586. .textContent(this.$translate.instant(alertMessage))
  587. .ok(this.$translate.instant('common.OK')));
  588. }, 0);
  589. }
  590. /**
  591. * Fail the session and let the remote peer know that an error occurred.
  592. * A dialog will be displayed to let the user know a protocol error
  593. * happened.
  594. */
  595. private failSession(showAlert = true) {
  596. // Stop session
  597. const stop = () => {
  598. this.stop({
  599. reason: DisconnectReason.SessionError,
  600. send: true,
  601. // TODO: Use welcome.error once we have it
  602. close: 'welcome',
  603. connectionBuildupState: 'closed',
  604. });
  605. if (showAlert) {
  606. this.showAlert('connection.SESSION_ERROR');
  607. }
  608. };
  609. // Note: Although this is considered an anti-pattern, we simply don't
  610. // want a digest cycle in most of the network event functionality.
  611. // Thus, it would be pointless 99% of the time to apply a digest
  612. // cycle somewhere higher in the call stack.
  613. if (!this.$rootScope.$$phase) {
  614. this.$rootScope.$apply(() => stop());
  615. } else {
  616. stop();
  617. }
  618. }
  619. /**
  620. * Fail the session on a rejection of a Promise associated to a message.
  621. */
  622. private failSessionOnReject(type: string, subType: string) {
  623. return ((error) => {
  624. this.logOnReject(type, subType)(error);
  625. this.failSession();
  626. });
  627. }
  628. /**
  629. * Log a rejection of a Promise associated to a message.
  630. */
  631. private logOnReject(type: string, subType: string) {
  632. return ((error) => {
  633. this.arpLog.error(`Message ${type}/${subType} has been rejected by the remote: ${error}`);
  634. });
  635. }
  636. /**
  637. * Resume a session via the previous connection's ID and chunk cache.
  638. *
  639. * Returns whether the connection has been resumed.
  640. *
  641. * Important: Caller must invalidate the cache and connection ID after this
  642. * function returned!
  643. */
  644. private maybeResumeSession(resumeSession: boolean, remoteInfo: ConnectionInfo): boolean {
  645. // Validate connection ID
  646. const remoteCurrentConnectionId = new Uint8Array(remoteInfo.id);
  647. if (arraysAreEqual(fakeConnectionId, remoteCurrentConnectionId)) {
  648. this.arpLog.debug('Cannot resume session: Remote did not implement deriving the connection ID');
  649. // TODO: Remove this once it is implemented properly by the app!
  650. return false;
  651. }
  652. if (!arraysAreEqual(this.currentConnectionId, remoteCurrentConnectionId)) {
  653. this.arpLog.info(`Cannot resume session: IDs of previous connection do not match (local=`
  654. + `${u8aToHex(this.currentConnectionId)}, remote=${u8aToHex(remoteCurrentConnectionId)}`);
  655. throw new Error('Derived connection IDs do not match!');
  656. }
  657. // Ensure both local and remote want to resume a session
  658. if (!resumeSession || remoteInfo.resume === undefined) {
  659. this.arpLog.info(`No resumption (local requested: ${resumeSession ? 'yes' : 'no'}, ` +
  660. `remote requested: ${remoteInfo.resume ? 'yes' : 'no'})`);
  661. // Both sides should detect that -> recoverable
  662. return false;
  663. }
  664. // Ensure we want to resume from the same previous connection
  665. const remotePreviousConnectionId = new Uint8Array(remoteInfo.resume.id);
  666. if (!arraysAreEqual(this.previousConnectionId, remotePreviousConnectionId)) {
  667. // Both sides should detect that -> recoverable
  668. this.arpLog.info(`Cannot resume session: IDs of previous connection do not match (local=`
  669. + `${u8aToHex(this.previousConnectionId)}, remote=${u8aToHex(remotePreviousConnectionId)}`);
  670. return false;
  671. }
  672. // Remove chunks that have been received by the remote side
  673. const size = this.previousChunkCache.byteLength;
  674. let result;
  675. this.arpLog.debug(`Pruning cache (local-sn=${this.previousChunkCache.sequenceNumber.get()}, ` +
  676. `remote-sn=${remoteInfo.resume.sequenceNumber})`);
  677. try {
  678. result = this.previousChunkCache.prune(remoteInfo.resume.sequenceNumber);
  679. } catch (error) {
  680. // Not recoverable
  681. throw new Error(`Unable to resume session: ${error}`);
  682. }
  683. this.arpLog.debug(`Chunk cache pruned, acknowledged: ${result.acknowledged}, left: ${result.left}, size: ` +
  684. `${size} -> ${this.previousChunkCache.byteLength}`);
  685. if (this.config.ARP_LOG_TRACE) {
  686. this.arpLog.debug(`Chunks that require acknowledgement: ${this.previousChunkCache.chunks.length}`);
  687. }
  688. // Transfer the cache (filters chunks which should not be retransmitted)
  689. const transferred = this.currentChunkCache.transfer(this.previousChunkCache.chunks);
  690. this.arpLog.debug(`Chunk cache transferred (${transferred} chunks)`);
  691. // Invalidate the previous connection cache & id
  692. // Note: This MUST be done immediately after the session has been
  693. // resumed to prevent re-establishing a session of a connection
  694. // where the handshake has been started but not been completed.
  695. this.previousConnectionId = null;
  696. this.previousIncomingChunkSequenceNumber = null;
  697. this.previousChunkCache = null;
  698. // Resend chunks
  699. const chunks = this.currentChunkCache.chunks;
  700. this.arpLog.debug(`Sending cached chunks: ${chunks.length}`);
  701. for (const chunk of chunks) {
  702. this.sendChunk(chunk, true, false, false);
  703. }
  704. // Resumed!
  705. return true;
  706. }
  707. /**
  708. * Discard the session of a previous connection.
  709. */
  710. private discardSession(flags: { resetMessageSequenceNumber: boolean }): void {
  711. // Reset the outgoing message sequence number and the unchunker
  712. if (flags.resetMessageSequenceNumber) {
  713. this.outgoingMessageSequenceNumber = new SequenceNumber(
  714. 0, WebClientService.SEQUENCE_NUMBER_MIN, WebClientService.SEQUENCE_NUMBER_MAX);
  715. }
  716. this.unchunker = new chunkedDc.UnreliableUnorderedUnchunker();
  717. this.unchunker.onMessage = this.handleIncomingMessageBytes.bind(this);
  718. // Discard previous connection instances
  719. this.previousConnectionId = null;
  720. this.previousIncomingChunkSequenceNumber = null;
  721. this.previousChunkCache = null;
  722. }
  723. /**
  724. * Schedule the connection ack to be sent.
  725. *
  726. * By default, a connection ack message will be sent after 10 seconds
  727. * (as defined by the protocol).
  728. */
  729. private scheduleConnectionAck(timeout: number = 10000): void {
  730. // Don't schedule if already running
  731. if (this.ackTimer === null) {
  732. this.ackTimer = self.setTimeout(() => {
  733. this.ackTimer = null;
  734. this._sendConnectionAck();
  735. }, timeout);
  736. }
  737. }
  738. /**
  739. * Schedule a push to be sent if there is no network activity within a
  740. * specified interval.
  741. */
  742. private schedulePush(timeoutMs: number = 3000): void {
  743. if (this.pushTimer !== null) {
  744. this.schedulePushAfterCooldown = true;
  745. return;
  746. }
  747. // Send a push after the timeout
  748. this.pushTimer = self.setTimeout(() => {
  749. this.pushTimer = null;
  750. this.schedulePushAfterCooldown = false;
  751. this.log.debug('Connection appears to be lost, sending push');
  752. this.sendPush();
  753. }, timeoutMs);
  754. // Send a connection ack.
  755. // Note: This acts as a *ping* but also helps us to keep the caches
  756. // clean.
  757. this._requestConnectionAck();
  758. }
  759. /**
  760. * Cancel a scheduled push.
  761. */
  762. private cancelPush(cooldownMs: number = 10000): void {
  763. if (this.pushTimer !== null) {
  764. self.clearTimeout(this.pushTimer);
  765. this.pushTimer = null;
  766. }
  767. this.schedulePushAfterCooldown = false;
  768. // Start the cooldown of the push timeout (if required)
  769. if (cooldownMs > 0) {
  770. this.pushTimer = self.setTimeout(() => {
  771. this.pushTimer = null;
  772. if (this.schedulePushAfterCooldown) {
  773. this.schedulePush();
  774. }
  775. }, cooldownMs);
  776. }
  777. }
  778. /**
  779. * Once the SaltyRTC task has been established...
  780. *
  781. * - for Android, initiate the peer connection and start the handover,
  782. * - for iOS, no further action is necessary and the connection is
  783. * considered established.
  784. */
  785. private onTaskEstablished(resumeSession: boolean) {
  786. // Pushing complete
  787. this.resetPushSession(true);
  788. // Peer handshake
  789. this.stateService.updateConnectionBuildupState('peer_handshake');
  790. // Determine chosen task
  791. const task = this.salty.getTask();
  792. if (task.getName().indexOf('webrtc.tasks.saltyrtc.org') !== -1) {
  793. this.chosenTask = threema.ChosenTask.WebRTC;
  794. } else if (task.getName().indexOf('relayed-data.tasks.saltyrtc.org') !== -1) {
  795. this.chosenTask = threema.ChosenTask.RelayedData;
  796. } else {
  797. throw new Error('Invalid or unknown task name: ' + task.getName());
  798. }
  799. // If the WebRTC task was chosen, initialize handover.
  800. if (this.chosenTask === threema.ChosenTask.WebRTC) {
  801. const browser = this.browserService.getBrowser();
  802. // Safari does not support our dual-stack TURN servers.
  803. if (browser.isSafari(false)) {
  804. this.skipIceDs();
  805. }
  806. // Create peer connection
  807. this.pcHelper = new PeerConnectionHelper(
  808. this.$q, this.$rootScope,
  809. this.config, this.logService, this.timeoutService,
  810. task as saltyrtc.tasks.webrtc.WebRTCTask, this.config.ICE_SERVERS);
  811. // On state changes in the PeerConnectionHelper class, let state service know about it
  812. this.pcHelper.onConnectionStateChange = (state: threema.TaskConnectionState) => {
  813. this.stateService.updateTaskConnectionState(state);
  814. };
  815. // Initiate handover process
  816. this.pcHelper.handover();
  817. // Otherwise, no handover is necessary.
  818. } else {
  819. this.onHandover(resumeSession);
  820. }
  821. }
  822. /**
  823. * For the WebRTC task, this is called when the DataChannel is open.
  824. * For the relayed data task, this is called once the connection is established.
  825. */
  826. private async onConnectionEstablished(resumeSession: boolean) {
  827. // Send connection info
  828. if (resumeSession) {
  829. const incomingSequenceNumber = this.previousIncomingChunkSequenceNumber.get();
  830. this.arpLog.debug(`Sending connection info (resume=yes, sn-in=${incomingSequenceNumber})`);
  831. this._sendConnectionInfo(
  832. this.currentConnectionId.buffer,
  833. this.previousConnectionId.buffer,
  834. incomingSequenceNumber,
  835. );
  836. } else {
  837. this.arpLog.debug('Sending connection info (resume=no)');
  838. this._sendConnectionInfo(this.currentConnectionId.buffer);
  839. }
  840. // Receive connection info
  841. // Note: We can receive the connectionInfo message here or
  842. // an error which should fail the session.
  843. let remoteInfo: ConnectionInfo;
  844. try {
  845. remoteInfo = await this.connectionInfoFuture;
  846. } catch (error) {
  847. this.arpLog.error(error);
  848. this.failSession();
  849. return;
  850. }
  851. let outgoingSequenceNumber: string | number = 'n/a';
  852. let remoteResume = 'no';
  853. if (remoteInfo.resume !== undefined) {
  854. outgoingSequenceNumber = remoteInfo.resume.sequenceNumber;
  855. remoteResume = 'yes';
  856. }
  857. this.arpLog.debug(`Received connection info (resume=${remoteResume}, ` +
  858. `sn-out=${outgoingSequenceNumber})`);
  859. // Resume the session (if both requested to resume the same connection)
  860. let sessionWasResumed;
  861. try {
  862. sessionWasResumed = this.maybeResumeSession(resumeSession, remoteInfo);
  863. } catch (error) {
  864. this.arpLog.error(error);
  865. this.failSession();
  866. return;
  867. }
  868. // Handshake complete!
  869. this.handshakeCompleted = true;
  870. // If we could not resume for whatever reason
  871. const requiredInitializationSteps = [];
  872. if (!resumeSession || !sessionWasResumed) {
  873. // Note: We cannot reset the message sequence number here any more since
  874. // it has already been used for the connectionInfo message.
  875. this.discardSession({ resetMessageSequenceNumber: false });
  876. this.arpLog.debug('Session discarded');
  877. // Reset fields, blob cache, pending requests and pending timeouts in case the session
  878. // cannot be resumed
  879. this.clearCache();
  880. this.wireMessageFutures.clear();
  881. this.timeoutService.cancelAll();
  882. // Set required initialisation steps
  883. requiredInitializationSteps.push(
  884. InitializationStep.ClientInfo,
  885. InitializationStep.Conversations,
  886. InitializationStep.Receivers,
  887. InitializationStep.Profile,
  888. );
  889. // Request initial data
  890. this._requestInitialData();
  891. } else {
  892. this.arpLog.debug('Session resumed');
  893. }
  894. // Schedule required initialisation steps if we have finished the
  895. // previous connection
  896. if (this.startupPromise !== null) {
  897. this.runAfterInitializationSteps(requiredInitializationSteps, () => {
  898. this.stateService.updateConnectionBuildupState('done');
  899. this.startupPromise.resolve();
  900. this.startupPromise = null;
  901. this.startupDone = true;
  902. this._resetInitializationSteps();
  903. // Hack for #712
  904. // TODO: Remove once we have the ack protocol for Android, too
  905. if (this.chosenTask !== threema.ChosenTask.RelayedData && this.$state.includes('messenger')) {
  906. this.$state.reload().catch((error) => {
  907. this.log.error('Unable to reload state:', error);
  908. });
  909. }
  910. });
  911. }
  912. // In case...
  913. // - we wanted to resume, but
  914. // - we could not resume, and
  915. // - we had a previous connection
  916. if (resumeSession && !sessionWasResumed && this.clientInfo !== null) {
  917. this.$rootScope.$apply(() => {
  918. // TODO: Remove this conditional once we have session
  919. // resumption for Android!
  920. if (this.chosenTask !== threema.ChosenTask.RelayedData) {
  921. return;
  922. }
  923. // Redirect to the conversation overview
  924. if (this.$state.includes('messenger')) {
  925. this.$state.go('messenger.home');
  926. }
  927. });
  928. }
  929. // Fetch current version
  930. // Delay it to prevent the dialog from being closed by the messenger constructor,
  931. // which closes all open dialogs.
  932. this.timeoutService.register(() => this.versionService.checkForUpdate(), 7000, true, 'checkForUpdate');
  933. // Notify state service about data loading
  934. this.stateService.updateConnectionBuildupState('loading');
  935. }
  936. /**
  937. * Handover done.
  938. *
  939. * This can either be a real handover to WebRTC (Android), or simply
  940. * when the relayed data task takes over (iOS).
  941. */
  942. private onHandover(resumeSession: boolean) {
  943. // Initialize NotificationService
  944. this.log.debug('Initializing NotificationService...');
  945. this.notificationService.init();
  946. // Derive connection ID
  947. // Note: We need to make sure this is done before any ARP messages can be received
  948. const connectionIdBox = this.salty.encryptForPeer(new Uint8Array(0), WebClientService.CONNECTION_ID_NONCE);
  949. // Note: We explicitly copy the data here to be able to use the underlying buffer directly
  950. this.currentConnectionId = new Uint8Array(connectionIdBox.data);
  951. // If the WebRTC task was chosen, initialize the data channel
  952. if (this.chosenTask === threema.ChosenTask.WebRTC) {
  953. const task = this.salty.getTask() as saltyrtc.tasks.webrtc.WebRTCTask;
  954. // Create data channel
  955. this.arpLog.debug(`Creating data channel ${WebClientService.DC_LABEL}`);
  956. const dc = this.pcHelper.pc.createDataChannel(WebClientService.DC_LABEL);
  957. dc.binaryType = 'arraybuffer';
  958. // Wrap as unbounded, flow-controlled data channel
  959. this.secureDataChannel = new UnboundedFlowControlledDataChannel(
  960. dc, this.logService, this.config.TRANSPORT_LOG_LEVEL);
  961. // Create crypto context
  962. // Note: We need to apply encrypt-then-chunk for backwards
  963. // compatibility reasons.
  964. this.secureDataChannelCrypto = task.createCryptoContext(dc.id);
  965. // Create unchunker
  966. // Note: We need to use an unreliable unordered unchunker for backwards
  967. // compatibility reasons.
  968. const unchunker = new chunkedDc.UnreliableUnorderedUnchunker();
  969. // Bind events
  970. dc.onopen = () => {
  971. this.arpLog.info(`Data channel ${dc.label} open`);
  972. // Determine chunk length
  973. this.secureDataChannelChunkLength = Math.min(
  974. WebClientService.DATA_CHANNEL_MAX_CHUNK_SIZE, this.pcHelper.pc.sctp.maxMessageSize);
  975. this.arpLog.debug(`Using chunk length: ${this.secureDataChannelChunkLength} for data channel` +
  976. dc.label);
  977. // Connection established
  978. this.onConnectionEstablished(resumeSession).catch((error) => {
  979. this.arpLog.error('Error during handshake:', error);
  980. });
  981. };
  982. dc.onclose = () => {
  983. this.arpLog.error(`Data channel ${dc.label} closed prematurely`);
  984. this.failSession();
  985. };
  986. dc.onerror = (event) => {
  987. this.arpLog.error(`Data channel ${dc.label} error:`, event);
  988. this.failSession();
  989. };
  990. dc.onmessage = (event) => {
  991. this.arpLogV.debug(`Data channel ${dc.label} incoming chunk of length ${event.data.byteLength}`);
  992. unchunker.add(new Uint8Array(event.data));
  993. };
  994. // noinspection JSUndefinedPropertyAssignment
  995. unchunker.onMessage = (array) => {
  996. const box = saltyrtcClient.Box.fromUint8Array(
  997. array, saltyrtcTaskWebrtc.DataChannelCryptoContext.NONCE_LENGTH);
  998. const message = this.secureDataChannelCrypto.decrypt(box);
  999. this.handleIncomingMessageBytes(message);
  1000. };
  1001. // Mark as handed over
  1002. // Note: Even though this method is also "misused" for the relayed
  1003. // data task, only WebRTC really hands over.
  1004. this.handoverDone = true;
  1005. } else if (this.chosenTask === threema.ChosenTask.RelayedData) {
  1006. // Handle messages directly
  1007. this.relayedDataTask.on('data', (ev: saltyrtc.SaltyRTCEvent) => {
  1008. this.receiveChunk(new Uint8Array(ev.data));
  1009. });
  1010. // The communication channel is now open! Fetch initial data
  1011. this.onConnectionEstablished(resumeSession).catch((error) => {
  1012. this.arpLog.error('Error during handshake:', error);
  1013. });
  1014. }
  1015. }
  1016. /**
  1017. * A previously authenticated peer disconnected from the server.
  1018. */
  1019. private onPeerDisconnected(peerId: number) {
  1020. switch (this.chosenTask) {
  1021. case threema.ChosenTask.RelayedData:
  1022. // TODO: Fix "Ignoring peer-disconnected event (state is new)"
  1023. if (this.stateService.taskConnectionState === threema.TaskConnectionState.Connected) {
  1024. this.stateService.updateTaskConnectionState(threema.TaskConnectionState.Reconnecting);
  1025. } else {
  1026. this.arpLog.debug(
  1027. 'Ignoring peer-disconnected event (state is '
  1028. + this.stateService.taskConnectionState + ')',
  1029. );
  1030. }
  1031. break;
  1032. default:
  1033. this.arpLog.debug(
  1034. 'Ignoring peer-disconnected event (chosen task is ' + this.chosenTask + ')',
  1035. );
  1036. }
  1037. }
  1038. /**
  1039. * Send a push message to wake up the peer.
  1040. *
  1041. * Returns the maximum expected period until the promise will be resolved,
  1042. * and the promise itself.
  1043. */
  1044. public sendPush(): [number, Promise<void>] {
  1045. // Create new session
  1046. if (this.pushSession === null) {
  1047. this.pushSession = this.pushService.createSession(this.salty.permanentKeyBytes, this.pushSessionConfig);
  1048. // Start and handle success/error
  1049. this.pushPromise = this.pushSession.start()
  1050. .then(() => this.resetPushSession(true))
  1051. .catch((error) => {
  1052. // Reset push session
  1053. this.resetPushSession(false);
  1054. // Handle error
  1055. if (error instanceof TimeoutError) {
  1056. this.showDeviceUnreachableDialog();
  1057. } else {
  1058. this.failSession();
  1059. }
  1060. });
  1061. // Update state
  1062. if (!this.$rootScope.$$phase) {
  1063. this.$rootScope.$apply(() => this.stateService.updateConnectionBuildupState('push'));
  1064. } else {
  1065. this.stateService.updateConnectionBuildupState('push');
  1066. }
  1067. }
  1068. // Retrieve the expected maximum period
  1069. return [this.pushSessionExpectedPeriodMaxMs, this.pushPromise];
  1070. }
  1071. /**
  1072. * Reset push session (if any) and hide the *device unreachable* dialog
  1073. * (if any and if requested).
  1074. */
  1075. private resetPushSession(hideDeviceUnreachableDialog: boolean = true): void {
  1076. // Hide unreachable dialog (if any)
  1077. if (hideDeviceUnreachableDialog && this.deviceUnreachableDialog !== null) {
  1078. this.$mdDialog.hide();
  1079. }
  1080. // Reset push session (if any)
  1081. if (this.pushSession !== null) {
  1082. this.pushSession.done();
  1083. this.pushSession = null;
  1084. this.pushPromise = null;
  1085. }
  1086. }
  1087. /**
  1088. * Show the *device unreachable* dialog.
  1089. */
  1090. public showDeviceUnreachableDialog(): void {
  1091. // Show device unreachable dialog (if we were already
  1092. // connected and if not already visible).
  1093. if (this.pushService.isAvailable() && this.$state.includes('messenger')
  1094. && this.deviceUnreachableDialog === null) {
  1095. this.deviceUnreachableDialog = this.$mdDialog.show({
  1096. controller: DeviceUnreachableController,
  1097. controllerAs: 'ctrl',
  1098. templateUrl: 'partials/dialog.device-unreachable.html',
  1099. parent: angular.element(document.body),
  1100. escapeToClose: false,
  1101. })
  1102. .finally(() => this.deviceUnreachableDialog = null);
  1103. }
  1104. }
  1105. /**
  1106. * Start the webclient service.
  1107. * Return a promise that resolves once connected.
  1108. */
  1109. public start(skipPush: boolean = false): ng.IPromise<any> {
  1110. this.log.debug('Starting WebClientService...');
  1111. // Promise to track startup state
  1112. if (this.startupPromise !== null) {
  1113. this.log.debug('Reusing startup promise (was not resolved)');
  1114. } else {
  1115. this.log.debug('Creating new startup promise');
  1116. this.startupPromise = this.$q.defer();
  1117. }
  1118. this.startupDone = false;
  1119. this.handoverDone = false;
  1120. // Connect
  1121. this.salty.connect();
  1122. // If push service is available, notify app
  1123. if (this.pushService.isAvailable()) {
  1124. if (skipPush === true) {
  1125. this.log.debug('start(): Skipping push notification');
  1126. } else {
  1127. this.sendPush();
  1128. }
  1129. } else if (this.trustedKeyStore.hasTrustedKey()) {
  1130. this.log.debug('Push service not available');
  1131. this.stateService.updateConnectionBuildupState('manual_start');
  1132. }
  1133. return this.startupPromise.promise;
  1134. }
  1135. /**
  1136. * Stop the webclient service.
  1137. *
  1138. * This is a forced stop, meaning that all connections are being closed.
  1139. *
  1140. * @reason The disconnect reason.
  1141. * @send will send a disconnect message to the remote peer containing the
  1142. * disconnect reason if set to `true`.
  1143. * @close will close the session (meaning all cached data will be
  1144. * invalidated) if set to `true`. Note that the session will always be
  1145. * closed in case `reason` indicates that the session is to be deleted,
  1146. * has been replaced, a protocol error occurred or in case `redirect` has
  1147. * been set to `true`.
  1148. * @redirect will redirect to the welcome page if set to `true`.
  1149. * @connectionBuildupState: The connection buildup state the state service
  1150. * will be reset to.
  1151. */
  1152. public stop(args: threema.WebClientServiceStopArguments): void {
  1153. if (args.close === true) {
  1154. throw new Error('args.close has been set to "true" but requires a redirect state instead');
  1155. }
  1156. this.log.info(`Stopping (reason=${args.reason}, send=${args.send}, close=${args.close}, ` +
  1157. 'connectionBuildupState=' +
  1158. `${args.connectionBuildupState !== undefined ? args.connectionBuildupState : 'n/a'})`);
  1159. let close = args.close !== false;
  1160. let remove = false;
  1161. // Stop push session
  1162. this.resetPushSession(true);
  1163. // Session deleted: Force close and delete
  1164. if (args.reason === DisconnectReason.SessionDeleted) {
  1165. close = true;
  1166. remove = true;
  1167. }
  1168. // Session replaced or error'ed: Force close
  1169. if (args.reason === DisconnectReason.SessionReplaced || args.reason === DisconnectReason.OutOfMemory ||
  1170. args.reason === DisconnectReason.SessionError) {
  1171. close = true;
  1172. }
  1173. // Send disconnect reason to the remote peer if requested
  1174. if (args.send && this.stateService.state === threema.GlobalConnectionState.Ok) {
  1175. // noinspection JSIgnoredPromiseFromCall
  1176. this.sendUpdateWireMessage(WebClientService.SUB_TYPE_CONNECTION_DISCONNECT, false, undefined,
  1177. {reason: args.reason});
  1178. }
  1179. // Stop timer
  1180. if (this.ackTimer !== null) {
  1181. self.clearTimeout(this.ackTimer);
  1182. this.ackTimer = null;
  1183. }
  1184. if (this.pushTimer !== null) {
  1185. this.cancelPush(0);
  1186. }
  1187. this.log.debug('Timer stopped');
  1188. // Reset states
  1189. this.stateService.reset(args.connectionBuildupState);
  1190. // Reset the unread count
  1191. this.resetUnreadCount();
  1192. // Clear stored data (trusted key, push token, etc) if deleting the session
  1193. if (remove) {
  1194. this.trustedKeyStore.clearTrustedKey();
  1195. }
  1196. // Invalidate and clear caches
  1197. if (close) {
  1198. // Clear connection ids & caches
  1199. this.previousConnectionId = null;
  1200. this.previousIncomingChunkSequenceNumber = null;
  1201. this.previousChunkCache = null;
  1202. // Remove chosen task
  1203. // Note: This implicitly prevents automatic connection attempts
  1204. // from the status controller.
  1205. this.chosenTask = threema.ChosenTask.None;
  1206. // Reset general client information
  1207. this.clientInfo = null;
  1208. // Clear fetched messages and the blob cache
  1209. this.clearCache();
  1210. // Remove all pending promises
  1211. this.wireMessageFutures.clear();
  1212. // Cancel pending timeouts
  1213. this.timeoutService.cancelAll();
  1214. // Reset the push service
  1215. this.pushService.reset();
  1216. // Closed!
  1217. this.arpLog.debug('Session closed (cannot be resumed)');
  1218. } else {
  1219. // Only reuse a previous chunk cache if the handshake had been
  1220. // completed
  1221. if (this.handshakeCompleted) {
  1222. // Move instances that we need to re-establish a previous session
  1223. this.previousConnectionId = this.currentConnectionId;
  1224. this.previousIncomingChunkSequenceNumber = this.currentIncomingChunkSequenceNumber;
  1225. this.previousChunkCache = this.currentChunkCache;
  1226. }
  1227. this.arpLog.debug('Session remains open');
  1228. }
  1229. // Close data channel
  1230. if (this.secureDataChannel !== null) {
  1231. this.arpLog.debug('Closing data channel');
  1232. this.secureDataChannel.dc.onopen = null;
  1233. this.secureDataChannel.dc.onmessage = null;
  1234. this.secureDataChannel.dc.onbufferedamountlow = null;
  1235. this.secureDataChannel.dc.onerror = null;
  1236. this.secureDataChannel.dc.onclose = null;
  1237. this.secureDataChannel.dc.close();
  1238. }
  1239. // Close SaltyRTC connection
  1240. if (this.relayedDataTask !== null) {
  1241. this.relayedDataTask.off();
  1242. }
  1243. if (this.salty !== null) {
  1244. this.arpLog.debug('Closing signaling');
  1245. this.salty.off();
  1246. this.salty.disconnect(true);
  1247. }
  1248. // Close peer connection
  1249. if (this.pcHelper !== null) {
  1250. this.pcHelper.onConnectionStateChange = null;
  1251. this.pcHelper.close();
  1252. this.arpLog.debug('Peer connection closed');
  1253. } else {
  1254. this.arpLog.debug('Peer connection was null');
  1255. }
  1256. // Done, redirect now if session closed
  1257. if (close) {
  1258. // Reject startup promise (if any)
  1259. if (this.startupPromise !== null) {
  1260. this.startupPromise.reject();
  1261. this.startupPromise = null;
  1262. this._resetInitializationSteps();
  1263. }
  1264. // Translate close flag
  1265. const state = args.close !== false ? args.close : 'welcome';
  1266. this.$state.go(state);
  1267. }
  1268. }
  1269. /**
  1270. * Safari has issues with dual-stack TURN servers:
  1271. * https://bugs.webkit.org/show_bug.cgi?id=173307#c13
  1272. * As a workaround, replace ds-turn.threema.ch servers
  1273. * in the ICE_SERVERS configuration with turn.threema.ch.
  1274. */
  1275. public skipIceDs(): void {
  1276. this.arpLog.debug('Requested to replace DS servers in ICE configuration');
  1277. const allUrls = [].concat(...this.config.ICE_SERVERS.map((conf) => conf.urls));
  1278. if (allUrls.some((url) => url.includes('ds-turn.threema.ch'))) {
  1279. for (const server of this.config.ICE_SERVERS) {
  1280. // Replace dual stack entries
  1281. const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
  1282. server.urls = urls.map((url) => {
  1283. return url.replace('ds-turn.threema.ch', 'turn.threema.ch');
  1284. });
  1285. }
  1286. } else {
  1287. this.arpLog.debug('No ds-turn ICE server present');
  1288. }
  1289. }
  1290. /**
  1291. * Mark a component as initialized
  1292. */
  1293. public registerInitializationStep(name: threema.InitializationStep) {
  1294. if (this.initialized.has(name) ) {
  1295. this.arpLog.warn('Initialization step "' + name + '" already registered');
  1296. return;
  1297. }
  1298. this.arpLog.debug('Initialization step "' + name + '" done');
  1299. this.initialized.add(name);
  1300. // Check pending routines
  1301. for (const routine of this.pendingInitializationStepRoutines) {
  1302. const ready = routine.requiredSteps.every((requiredStep) => {
  1303. return this.initialized.has(requiredStep);
  1304. });
  1305. if (ready) {
  1306. this.arpLog.debug('Running routine after initialization "' + name + '" completed');
  1307. // Important: Remove the routine BEFORE calling it to prevent
  1308. // it from being called more than once (due to nested
  1309. // calls to .registerInitializationStep).
  1310. this.pendingInitializationStepRoutines.delete(routine);
  1311. routine.callback.apply(this);
  1312. }
  1313. }
  1314. }
  1315. public setReceiverListener(listener: threema.ReceiverListener): void {
  1316. this.receiverListener.push(listener);
  1317. }
  1318. /**
  1319. * Send a connection info update.
  1320. */
  1321. private _sendConnectionInfo(connectionId: ArrayBuffer, resumeId?: ArrayBuffer, sequenceNumber?: number): void {
  1322. const data = {id: connectionId};
  1323. if (resumeId !== undefined && sequenceNumber !== undefined) {
  1324. (data as any).resume = {
  1325. id: resumeId,
  1326. sequenceNumber: sequenceNumber,
  1327. };
  1328. }
  1329. // noinspection JSIgnoredPromiseFromCall
  1330. this.sendUpdateWireMessage(WebClientService.SUB_TYPE_CONNECTION_INFO, false, undefined, data);
  1331. }
  1332. /**
  1333. * Request a connection ack update.
  1334. */
  1335. private _requestConnectionAck(): void {
  1336. // noinspection JSIgnoredPromiseFromCall
  1337. this.sendRequestWireMessage(WebClientService.SUB_TYPE_CONNECTION_ACK, false);
  1338. }
  1339. /**
  1340. * Send a connection ack update.
  1341. */
  1342. private _sendConnectionAck(): void {
  1343. // Send the current incoming sequence number for chunks
  1344. // noinspection JSIgnoredPromiseFromCall
  1345. this.sendUpdateWireMessage(WebClientService.SUB_TYPE_CONNECTION_ACK, false, undefined, {
  1346. sequenceNumber: this.currentIncomingChunkSequenceNumber.get(),
  1347. });
  1348. // Clear pending ack timer (if any)
  1349. if (this.ackTimer !== null) {
  1350. self.clearTimeout(this.ackTimer);
  1351. this.ackTimer = null;
  1352. }
  1353. }
  1354. /**
  1355. * Send a client info request.
  1356. */
  1357. public requestClientInfo(): void {
  1358. this.arpLog.debug('Sending client info request');
  1359. const browser = this.browserService.getBrowser();
  1360. const data: object = {
  1361. [WebClientService.ARGUMENT_USER_AGENT]: navigator.userAgent,
  1362. };
  1363. if (browser.name) {
  1364. data[WebClientService.ARGUMENT_BROWSER_NAME] = browser.name;
  1365. }
  1366. if (browser.version) {
  1367. data[WebClientService.ARGUMENT_BROWSER_VERSION] = browser.version;
  1368. }
  1369. const subType = WebClientService.SUB_TYPE_CLIENT_INFO;
  1370. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility, undefined, data)
  1371. .catch(this.failSessionOnReject(WebClientService.TYPE_REQUEST, subType)); // critical request
  1372. }
  1373. /**
  1374. * Send a receivers request.
  1375. */
  1376. public requestReceivers(): void {
  1377. this.arpLog.debug('Sending receivers request');
  1378. const subType = WebClientService.SUB_TYPE_RECEIVERS;
  1379. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility)
  1380. .catch(this.failSessionOnReject(WebClientService.TYPE_REQUEST, subType)); // critical request
  1381. }
  1382. /**
  1383. * Send a conversation request.
  1384. */
  1385. public requestConversations(): void {
  1386. this.arpLog.debug('Sending conversation request');
  1387. const subType = WebClientService.SUB_TYPE_CONVERSATIONS;
  1388. const args = {[WebClientService.ARGUMENT_MAX_SIZE]: WebClientService.AVATAR_LOW_MAX_SIZE};
  1389. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility, args)
  1390. .catch(this.failSessionOnReject(WebClientService.TYPE_REQUEST, subType)); // critical request
  1391. }
  1392. /**
  1393. * Send a battery status request.
  1394. */
  1395. public requestBatteryStatus(): void {
  1396. this.arpLog.debug('Sending battery status request');
  1397. const subType = WebClientService.SUB_TYPE_BATTERY_STATUS;
  1398. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility)
  1399. .catch(this.failSessionOnReject(WebClientService.TYPE_REQUEST, subType)); // critical request
  1400. }
  1401. /**
  1402. * Send a profile request.
  1403. */
  1404. public requestProfile(): void {
  1405. this.arpLog.debug('Sending profile request');
  1406. const subType = WebClientService.SUB_TYPE_PROFILE;
  1407. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility)
  1408. .catch(this.failSessionOnReject(WebClientService.TYPE_REQUEST, subType)); // critical request
  1409. }
  1410. /**
  1411. * Send a message request for the specified receiver.
  1412. *
  1413. * This method will only be called when initializing a conversation in the
  1414. * webclient. It is used to download all existing messages.
  1415. *
  1416. * New messages are not requested this way, instead they are sent as a
  1417. * message update.
  1418. */
  1419. public requestMessages(receiver: threema.Receiver): string | null {
  1420. this.arpLog.debug('requestMessages');
  1421. // If there are no more messages available, stop here.
  1422. if (!this.messages.hasMore(receiver)) {
  1423. this.messages.notify(receiver, this.$rootScope);
  1424. this.arpLog.debug('requestMessages: No more messages available');
  1425. return null;
  1426. }
  1427. this.loadingMessages.set(receiver.type + receiver.id, true);
  1428. // Check if messages have already been requested
  1429. if (this.messages.isRequested(receiver)) {
  1430. this.arpLog.debug('requestMessages: Already requested');
  1431. return null;
  1432. }
  1433. // Get the reference msg id
  1434. const refMsgId = this.messages.getReferenceMsgId(receiver);
  1435. // Set requested
  1436. this.messages.setRequested(receiver);
  1437. // Create arguments
  1438. const args = {
  1439. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1440. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1441. } as any;
  1442. // If a reference msg id has been set, send it along
  1443. const msgId = this.messages.getReferenceMsgId(receiver);
  1444. if (msgId !== null) {
  1445. args[WebClientService.ARGUMENT_REFERENCE_MSG_ID] = msgId;
  1446. }
  1447. // Send request
  1448. this.arpLog.debug('Sending message request for', receiver.type, receiver.id,
  1449. 'with message id', msgId);
  1450. const subType = WebClientService.SUB_TYPE_MESSAGES;
  1451. // TODO: Return the promise instead to unset the 'requested' flag?
  1452. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility, args)
  1453. .catch(this.logOnReject(WebClientService.TYPE_REQUEST, subType));
  1454. return refMsgId;
  1455. }
  1456. /**
  1457. * Send an avatar request for the specified receiver.
  1458. */
  1459. public requestAvatar(receiver: threema.Receiver, highResolution: boolean): Promise<ArrayBuffer> {
  1460. // Check if the receiver has an avatar or the avatar already exists
  1461. const resolution = highResolution ? 'high' : 'low';
  1462. const receiverInfo = this.receivers.getData(receiver);
  1463. if (receiverInfo && receiverInfo.avatar && receiverInfo.avatar[resolution]) {
  1464. // Avatar already exists
  1465. // TODO: Do we get avatar changes via update?
  1466. return Promise.resolve(receiverInfo.avatar[resolution]);
  1467. }
  1468. // If we're requesting our own avatar, change type from "me" to "contact"
  1469. let receiverType = receiver.type;
  1470. if (receiverType === 'me') {
  1471. receiverType = 'contact';
  1472. }
  1473. // Create arguments and send request
  1474. const args = {
  1475. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiverType,
  1476. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1477. [WebClientService.ARGUMENT_AVATAR_HIGH_RESOLUTION]: highResolution,
  1478. } as any;
  1479. if (!highResolution) {
  1480. args[WebClientService.ARGUMENT_MAX_SIZE] = WebClientService.AVATAR_LOW_MAX_SIZE;
  1481. }
  1482. this.arpLog.debug('Sending', resolution, 'res avatar request for', receiver.type, receiver.id);
  1483. const subType = WebClientService.SUB_TYPE_AVATAR;
  1484. return this.sendRequestWireMessage(subType, true, args);
  1485. }
  1486. /**
  1487. * Send a thumbnail request for the specified receiver.
  1488. */
  1489. public requestThumbnail(receiver: threema.Receiver, message: threema.Message): Promise<any> {
  1490. // Check if the receiver has an avatar or the avatar already exists
  1491. if (message.thumbnail !== undefined && message.thumbnail.img !== undefined) {
  1492. return new Promise<any>((e) => {
  1493. e(message.thumbnail.img);
  1494. });
  1495. }
  1496. // Create arguments and send request
  1497. const args = {
  1498. [WebClientService.ARGUMENT_MESSAGE_ID]: message.id.toString(),
  1499. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1500. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1501. };
  1502. this.arpLog.debug('Sending thumbnail request for', receiver.type, message.id);
  1503. const subType = WebClientService.SUB_TYPE_THUMBNAIL;
  1504. return this.sendRequestWireMessage(subType, true, args);
  1505. }
  1506. /**
  1507. * Request a blob.
  1508. */
  1509. public requestBlob(msgId: string, receiver: threema.Receiver): Promise<threema.BlobInfo> {
  1510. const cached = this.blobCache.get(msgId + receiver.type);
  1511. if (cached !== undefined) {
  1512. this.arpLog.debug('Use cached blob');
  1513. return new Promise((resolve) => {
  1514. resolve(cached);
  1515. });
  1516. }
  1517. const args = {
  1518. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1519. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1520. [WebClientService.ARGUMENT_MESSAGE_ID]: msgId,
  1521. };
  1522. this.arpLog.debug('Sending blob request for message', msgId);
  1523. return this.sendRequestWireMessage(WebClientService.SUB_TYPE_BLOB, true, args);
  1524. }
  1525. /**
  1526. * Mark a message as read.
  1527. */
  1528. public requestRead(receiver, newestMessage: threema.Message): void {
  1529. if (newestMessage.id === undefined) {
  1530. // Message that hasn't been sent yet
  1531. this.arpLog.warn('Called requestRead on a message without id');
  1532. return;
  1533. }
  1534. if (newestMessage.type === 'status') {
  1535. this.arpLog.warn('Called requestRead on a status message');
  1536. return;
  1537. }
  1538. // Create arguments and send request
  1539. const args = {
  1540. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1541. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1542. [WebClientService.ARGUMENT_MESSAGE_ID]: newestMessage.id.toString(),
  1543. };
  1544. this.arpLog.debug('Sending read request for', receiver.type, receiver.id, '(msg ' + newestMessage.id + ')');
  1545. const subType = WebClientService.SUB_TYPE_READ;
  1546. this.sendRequestWireMessage(subType, !this.requiresTemporaryIdBackwardsCompatibility, args)
  1547. .catch(this.logOnReject(WebClientService.TYPE_REQUEST, subType));
  1548. }
  1549. public requestContactDetail(contactReceiver: threema.ContactReceiver): Promise<any> {
  1550. const args = {
  1551. [WebClientService.ARGUMENT_IDENTITY]: contactReceiver.id,
  1552. };
  1553. return this.sendRequestWireMessage(WebClientService.SUB_TYPE_CONTACT_DETAIL, true, args);
  1554. }
  1555. /**
  1556. * Send a message to the specified receiver.
  1557. */
  1558. public async sendMessage(
  1559. baseReceiver: threema.BaseReceiver,
  1560. sendType: threema.MessageContentType,
  1561. data: threema.MessageData,
  1562. options: {
  1563. previewDataUrl?: string,
  1564. waitUntilAcknowledged?: boolean,
  1565. } = {},
  1566. ): Promise<any> {
  1567. // This is the expected message type that will be reflected
  1568. // back once the message has been created successfully.
  1569. let reflectedType: threema.MessageType;
  1570. // Try to load receiver
  1571. const receiver = this.receivers.getData(baseReceiver);
  1572. // Check blocked flag
  1573. if (isContactReceiver(receiver) && receiver.isBlocked) {
  1574. throw this.$translate.instant('error.CONTACT_BLOCKED');
  1575. }
  1576. // Decide on subtype
  1577. let subType;
  1578. switch (sendType) {
  1579. case 'text':
  1580. reflectedType = 'text';
  1581. subType = WebClientService.SUB_TYPE_TEXT_MESSAGE;
  1582. const textData = data as threema.TextMessageData;
  1583. const msgLength = textData.text.length;
  1584. // Ignore empty text messages
  1585. if (msgLength === 0) {
  1586. this.log.warn('Ignored empty text message');
  1587. throw this.$translate.instant('error.ERROR_OCCURRED');
  1588. }
  1589. // Ignore text messages that are too long.
  1590. if (msgLength > WebClientService.MAX_TEXT_LENGTH) {
  1591. throw this.$translate.instant('error.TEXT_TOO_LONG', {
  1592. max: WebClientService.MAX_TEXT_LENGTH,
  1593. });
  1594. }
  1595. break;
  1596. case 'file':
  1597. const fileData = data as threema.FileMessageData;
  1598. // Validate max file size
  1599. if (this.chosenTask === threema.ChosenTask.WebRTC) {
  1600. const task = this.salty.getTask() as saltyrtc.tasks.webrtc.WebRTCTask;
  1601. if (task.version === 'v0' && fileData.size > WebClientService.MAX_FILE_SIZE_WEBRTC_TASK_V0) {
  1602. throw this.$translate.instant('error.FILE_TOO_LARGE_WEB');
  1603. }
  1604. } else {
  1605. if (fileData.size > this.clientInfo.capabilities.maxFileSize) {
  1606. throw this.$translate.instant('error.FILE_TOO_LARGE', {
  1607. maxmb: Math.floor(this.clientInfo.capabilities.maxFileSize / 1024 / 1024),
  1608. });
  1609. }
  1610. }
  1611. // Determine reflected type and required feature mask
  1612. reflectedType = 'file';
  1613. let requiredFeature = ContactReceiverFeature.FILE;
  1614. let invalidFeatureMessage = 'error.FILE_MESSAGES_NOT_SUPPORTED';
  1615. if (fileData.sendAsFile !== true) {
  1616. // File will be dispatched to the app as a file but the actual type sent
  1617. // to the recipient depends on the MIME type.
  1618. const mimeType = fileData.fileType;
  1619. if (this.mimeService.isAudio(mimeType, this.clientInfo.os)) {
  1620. reflectedType = 'audio';
  1621. requiredFeature = ContactReceiverFeature.AUDIO;
  1622. invalidFeatureMessage = 'error.AUDIO_MESSAGES_NOT_SUPPORTED';
  1623. } else if (this.mimeService.isImage(mimeType)) {
  1624. reflectedType = 'image';
  1625. } else if (this.mimeService.isVideo(mimeType)) {
  1626. reflectedType = 'video';
  1627. }
  1628. }
  1629. subType = WebClientService.SUB_TYPE_FILE_MESSAGE;
  1630. // check receiver
  1631. switch (receiver.type) {
  1632. case 'group':
  1633. case 'distributionList':
  1634. const unsupportedMembers = [];
  1635. let members: string[];
  1636. switch (receiver.type) {
  1637. case 'group':
  1638. const group = this.groups.get(receiver.id);
  1639. if (group === undefined) {
  1640. this.log.error(`Group ${receiver.id} not found`);
  1641. throw this.$translate.instant('error.ERROR_OCCURRED');
  1642. }
  1643. members = group.members;
  1644. break;
  1645. case 'distributionList':
  1646. const distributionList = this.distributionLists.get(receiver.id);
  1647. if (distributionList === undefined) {
  1648. this.log.error(`Distribution list ${receiver.id} not found`);
  1649. throw this.$translate.instant('error.ERROR_OCCURRED');
  1650. }
  1651. members = distributionList.members;
  1652. break;
  1653. }
  1654. for (const identity of members) {
  1655. if (identity !== this.me.id) {
  1656. // tslint:disable-next-line: no-shadowed-variable
  1657. const contact = this.contacts.get(identity);
  1658. if (contact === undefined) {
  1659. // This shouldn't actually happen. But if it happens, log an error
  1660. // and assume image support. It's much more likely that the contact
  1661. // can receive images (feature flag 0x01) than otherwise. And if one
  1662. // of the contacts really cannot receive images, the app will return
  1663. // an error message.
  1664. this.log.error(`Cannot retrieve contact ${identity}`);
  1665. } else if (!hasFeature(contact, requiredFeature, this.log)) {
  1666. unsupportedMembers.push(contact.displayName);
  1667. }
  1668. }
  1669. }
  1670. if (unsupportedMembers.length > 0) {
  1671. throw this.$translate.instant(
  1672. invalidFeatureMessage, {receiverName: unsupportedMembers.join(',')},
  1673. );
  1674. }
  1675. break;
  1676. case 'contact':
  1677. const contact = this.contacts.get(receiver.id);
  1678. if (contact === undefined) {
  1679. this.log.error('Cannot retrieve contact');
  1680. throw this.$translate.instant('error.ERROR_OCCURRED');
  1681. } else if (!hasFeature(contact, requiredFeature, this.log)) {
  1682. this.log.debug('Cannot send message: Feature level mismatch:',
  1683. contact.featureMask, 'does not include', requiredFeature);
  1684. throw this.$translate.instant(invalidFeatureMessage, {
  1685. receiverName: contact.displayName});
  1686. }
  1687. break;
  1688. default:
  1689. this.log.error('Invalid receiver type:', receiver.type);
  1690. throw this.$translate.instant('error.ERROR_OCCURRED');
  1691. }
  1692. break;
  1693. default:
  1694. this.log.error('Invalid message type:', sendType);
  1695. throw this.$translate.instant('error.ERROR_OCCURRED');
  1696. }
  1697. // Request the conversation to be loaded
  1698. // Note: This is required since we need to retrieve updates of the
  1699. // message we're going to send.
  1700. if (this.messages.getList(receiver).length === 0) {
  1701. await this.requestMessages(receiver);
  1702. }
  1703. // Create temporary message to be displayed until acknowledged by the
  1704. // mobile device
  1705. const id = this.createRandomWireMessageId();
  1706. let temporaryMessage: threema.Message;
  1707. try {
  1708. temporaryMessage = this.messageService.createTemporary(
  1709. id, receiver, reflectedType, data, options.previewDataUrl);
  1710. } catch (error) {
  1711. this.log.error(error);
  1712. throw this.$translate.instant('error.ERROR_OCCURRED');
  1713. }
  1714. this.messages.addNewer(receiver, [temporaryMessage]);
  1715. const args = {
  1716. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1717. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1718. };
  1719. // Send message
  1720. const sendPromise = this.sendCreateWireMessage(subType, true, args, data, id);
  1721. sendPromise.catch((error) => {
  1722. this.arpLog.error('Error sending message:', error);
  1723. // Remove temporary message
  1724. this.messages.removeTemporary(receiver, temporaryMessage.temporaryId);
  1725. // Determine error message
  1726. let errorMessage;
  1727. switch (error) {
  1728. case 'file_too_large': // TODO: deprecated
  1729. case 'fileTooLarge':
  1730. errorMessage = this.$translate.instant('error.FILE_TOO_LARGE_GENERIC');
  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 {
  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 = null): 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. // Unpack required argument fields
  2807. const type: string = args[WebClientService.ARGUMENT_MODE];
  2808. switch (type) {
  2809. case WebClientService.ARGUMENT_MODE_NEW:
  2810. if (this.conversations.find(data) !== null) {
  2811. this.arpLog.error('Received update/conversation with mode=new for existing conversation');
  2812. // Ignore message
  2813. break;
  2814. }
  2815. this.conversations.add(data);
  2816. break;
  2817. case WebClientService.ARGUMENT_MODE_MODIFIED:
  2818. // A conversation update *can* mean that a new message arrived.
  2819. // To find out, we'll look at the unread count. If it has been
  2820. // incremented, it must be a new message.
  2821. if (data.unreadCount > 0) {
  2822. const oldConversation = this.conversations.updateOrAdd(data, true);
  2823. if (oldConversation === null) {
  2824. this.onNewMessage(data.latestMessage, data, receiver);
  2825. } else {
  2826. // Check for unread count changes
  2827. const unreadCountIncreased = data.unreadCount > oldConversation.unreadCount;
  2828. const unreadCountDecreased = data.unreadCount < oldConversation.unreadCount;
  2829. // If the unreadcount has increased, we received a new message.
  2830. // Otherwise, if it has decreased, hide the notification.
  2831. if (unreadCountIncreased) {
  2832. this.onNewMessage(data.latestMessage, data, receiver);
  2833. } else if (unreadCountDecreased) {
  2834. this.notificationService.hideNotification(data.type + '-' + data.id);
  2835. }
  2836. }
  2837. } else {
  2838. // Update the conversation and hide any notifications
  2839. this.conversations.updateOrAdd(data, false);
  2840. this.notificationService.hideNotification(data.type + '-' + data.id);
  2841. }
  2842. break;
  2843. case WebClientService.ARGUMENT_MODE_REMOVED:
  2844. // Remove conversation
  2845. this.conversations.remove(data);
  2846. // Remove all cached messages for the receiver
  2847. this.messages.clearReceiverMessages(receiver);
  2848. // Call on-removed listener
  2849. this.receiverListener.forEach((listener: threema.ReceiverListener) => {
  2850. this.arpLog.debug('Call on removed listener');
  2851. listener.onConversationRemoved(receiver);
  2852. });
  2853. break;
  2854. default:
  2855. this.arpLog.warn('Received conversation without a mode');
  2856. break;
  2857. }
  2858. this.updateUnreadCount();
  2859. }
  2860. private _receiveUpdateAvatar(message: threema.WireMessage) {
  2861. this.arpLog.debug('Received avatar update');
  2862. const args = message.args;
  2863. const data = message.data as ArrayBuffer;
  2864. if (args === undefined) {
  2865. this.arpLog.warn('Invalid avatar update, arguments missing');
  2866. return;
  2867. }
  2868. // Get receiver
  2869. const receiver = this.receivers.getData({type: args.type, id: args.id});
  2870. if (receiver === undefined) {
  2871. this.arpLog.error('Received avatar update for nonexistent receiver');
  2872. return;
  2873. }
  2874. // Set (or clear) low-res avatar, invalidate high-res avatar
  2875. receiver.avatar = {
  2876. low: hasValue(data) ? data : undefined,
  2877. high: undefined,
  2878. };
  2879. }
  2880. /**
  2881. * Process an incoming battery status message.
  2882. */
  2883. private _receiveUpdateBatteryStatus(message: threema.WireMessage): void {
  2884. this.arpLog.debug('Received battery status');
  2885. const future = this.popWireMessageFuture(message, true);
  2886. // Handle error (if any)
  2887. if (message.ack !== undefined && !message.ack.success) {
  2888. return future.reject(message.ack.error);
  2889. }
  2890. // Unpack data and arguments
  2891. const data = message.data as threema.BatteryStatus;
  2892. if (data === undefined) {
  2893. this.arpLog.warn('Invalid battery status message, data missing');
  2894. return future.reject('invalidResponse');
  2895. }
  2896. // Set battery status
  2897. this.batteryStatusService.setStatus(data);
  2898. future.resolve();
  2899. }
  2900. private _receiveUpdateContact(message: threema.WireMessage): void {
  2901. const future = this.popWireMessageFuture(message);
  2902. this._receiveReplyReceiver(message, 'contact', future);
  2903. }
  2904. private _receiveUpdateGroup(message: threema.WireMessage): void {
  2905. const future = this.popWireMessageFuture(message);
  2906. this._receiveReplyReceiver(message, 'group', future);
  2907. }
  2908. private _receiveUpdateDistributionList(message: threema.WireMessage): void {
  2909. const future = this.popWireMessageFuture(message);
  2910. this._receiveReplyReceiver(message, 'distributionList', future);
  2911. }
  2912. /**
  2913. * Process an incoming profile update message.
  2914. */
  2915. private _receiveUpdateProfile(message: threema.WireMessage): void {
  2916. this.arpLog.debug('Received profile update');
  2917. // Unpack data and arguments
  2918. const data = message.data as threema.ProfileUpdate;
  2919. if (data === undefined) {
  2920. this.arpLog.warn('Invalid profile update message, data missing');
  2921. return;
  2922. }
  2923. // Update public nickname
  2924. if (data.publicNickname !== undefined) {
  2925. this.me.publicNickname = data.publicNickname;
  2926. this.me.displayName = this.me.publicNickname || this.me.id;
  2927. }
  2928. // Update avatar
  2929. if (data.avatar !== undefined) {
  2930. if (data.avatar === null) {
  2931. this.me.avatar = {};
  2932. } else {
  2933. this.me.avatar = { high: data.avatar };
  2934. }
  2935. // Request new low-res avatar
  2936. // noinspection JSIgnoredPromiseFromCall
  2937. this.requestAvatar(this.me, false);
  2938. }
  2939. }
  2940. /**
  2941. * The peer sends the device information string. This can be used to
  2942. * identify the active session.
  2943. */
  2944. private _receiveResponseClientInfo(message: threema.WireMessage): void {
  2945. this.arpLog.debug('Received client info response');
  2946. const future = this.popWireMessageFuture(message, this.requiresTemporaryIdBackwardsCompatibility);
  2947. // Handle error (if any)
  2948. if ((!this.requiresTemporaryIdBackwardsCompatibility && message.ack !== undefined) && !message.ack.success) {
  2949. future.reject(message.ack.error);
  2950. }
  2951. // Validate data
  2952. const data = message.data;
  2953. if (data === undefined) {
  2954. this.arpLog.warn('Invalid client info, data field missing');
  2955. return future.reject('invalidResponse');
  2956. }
  2957. /**
  2958. * Return the field if it's not undefined, otherwise return the default.
  2959. */
  2960. function getOrDefault<T>(field: T, defaultVal: T): T {
  2961. if (field === undefined) {
  2962. return defaultVal;
  2963. }
  2964. return field;
  2965. }
  2966. // Set clientInfo attribute
  2967. this.clientInfo = {
  2968. device: data.device,
  2969. os: data.os,
  2970. osVersion: data.osVersion,
  2971. isWork: hasValue(data.isWork) ? data.isWork : false, // TODO: Backwards compat hack, remove after 08/2019
  2972. pushToken: data.pushToken,
  2973. configuration: {
  2974. voipEnabled: getOrDefault<boolean>(data.configuration.voipEnabled, true),
  2975. voipForceTurn: getOrDefault<boolean>(data.configuration.voipForceTurn, false),
  2976. largeSingleEmoji: getOrDefault<boolean>(data.configuration.largeSingleEmoji, true),
  2977. showInactiveIDs: getOrDefault<boolean>(data.configuration.showInactiveIDs, true),
  2978. },
  2979. capabilities: {
  2980. maxGroupSize: getOrDefault<number>(data.capabilities.maxGroupSize, 50),
  2981. maxFileSize: getOrDefault<number>(data.capabilities.maxFileSize, 50 * 1024 * 1024),
  2982. distributionLists: getOrDefault<boolean>(data.capabilities.distributionLists, true),
  2983. imageFormat: data.capabilities.imageFormat,
  2984. mdm: data.capabilities.mdm,
  2985. },
  2986. };
  2987. this.arpLog.debug('Client device:', this.clientInfo.device);
  2988. // Store push token
  2989. if (this.clientInfo.pushToken) {
  2990. this.pushToken = this.clientInfo.pushToken;
  2991. switch (this.clientInfo.os) {
  2992. case threema.OperatingSystem.Android:
  2993. this.pushTokenType = threema.PushTokenType.Gcm;
  2994. break;
  2995. case threema.OperatingSystem.Ios:
  2996. this.pushTokenType = threema.PushTokenType.Apns;
  2997. break;
  2998. default:
  2999. this.arpLog.error('Invalid operating system in client info');
  3000. }
  3001. }
  3002. if (this.pushToken !== null && this.pushTokenType !== null) {
  3003. this.pushService.init(this.pushToken, this.pushTokenType);
  3004. }
  3005. this.registerInitializationStep(InitializationStep.ClientInfo);
  3006. future.resolve();
  3007. }
  3008. /**
  3009. * The peer sends information about the current user profile.
  3010. */
  3011. private _receiveResponseProfile(message: threema.WireMessage): void {
  3012. this.arpLog.debug('Received profile response');
  3013. const future = this.popWireMessageFuture(message, this.requiresTemporaryIdBackwardsCompatibility);
  3014. // Handle error (if any)
  3015. if ((!this.requiresTemporaryIdBackwardsCompatibility && message.ack !== undefined) && !message.ack.success) {
  3016. future.reject(message.ack.error);
  3017. }
  3018. // Validate data
  3019. const data = message.data as threema.Profile;
  3020. if (data === undefined) {
  3021. this.arpLog.warn('Invalid client info, data field missing');
  3022. return future.reject('invalidResponse');
  3023. }
  3024. // Create 'me' receiver with profile + dummy data
  3025. // TODO: Send both high-res and low-res avatars
  3026. this.receivers.setMe({
  3027. type: 'me',
  3028. id: data.identity,
  3029. publicNickname: data.publicNickname,
  3030. displayName: data.publicNickname || data.identity,
  3031. publicKey: data.publicKey,
  3032. avatar: {
  3033. high: data.avatar,
  3034. },
  3035. featureMask: 0xFF,
  3036. verificationLevel: 3,
  3037. state: 'ACTIVE',
  3038. locked: false,
  3039. visible: true,
  3040. hidden: false,
  3041. access: {
  3042. canChangeAvatar: true,
  3043. canChangeFirstName: true,
  3044. canChangeLastName: true,
  3045. },
  3046. color: '#000000',
  3047. });
  3048. this.registerInitializationStep(InitializationStep.Profile);
  3049. future.resolve();
  3050. }
  3051. public setPassword(password: string) {
  3052. // If a password has been set, store trusted key and push token
  3053. if (this._maybeTrustKeys(password)) {
  3054. // Saved trusted key, send information to client
  3055. this.sendKeyPersisted();
  3056. }
  3057. }
  3058. /**
  3059. * Reset all Fields and clear the blob cache
  3060. */
  3061. public clearCache(): void {
  3062. this._resetFields();
  3063. this.blobCache.clear();
  3064. }
  3065. /**
  3066. * Return the max text length
  3067. */
  3068. public getMaxTextLength(): number {
  3069. return WebClientService.MAX_TEXT_LENGTH;
  3070. }
  3071. /**
  3072. * Returns the max group member size
  3073. */
  3074. public getMaxGroupMemberSize(): number {
  3075. return this.clientInfo.capabilities.maxGroupSize;
  3076. }
  3077. /**
  3078. * Whether a notification should be triggered.
  3079. */
  3080. private shouldNotify(settings: threema.SimplifiedNotificationSettings, message: threema.Message): boolean {
  3081. if (settings.dnd.enabled) {
  3082. // Do not show any notifications on muted chats
  3083. if (settings.dnd.mentionOnly) {
  3084. let textToSearch = '';
  3085. if (message.type === 'text') {
  3086. textToSearch = message.body;
  3087. } else if (message.caption) {
  3088. textToSearch = message.caption;
  3089. }
  3090. let quotedMe = false;
  3091. if (message.quote) {
  3092. textToSearch += ' ' + message.quote.text;
  3093. quotedMe = message.quote.identity === this.me.id;
  3094. }
  3095. const forMe = textToSearch.indexOf('@[' + this.me.id + ']') !== -1;
  3096. const forAll = textToSearch.indexOf('@[@@@@@@@@]') !== -1;
  3097. return forMe || forAll || quotedMe;
  3098. } else {
  3099. return false;
  3100. }
  3101. } else {
  3102. return true;
  3103. }
  3104. }
  3105. /**
  3106. * Called when a new message arrives.
  3107. */
  3108. private onNewMessage(
  3109. message: threema.Message,
  3110. conversation: threema.Conversation,
  3111. sender: threema.Receiver,
  3112. ): void {
  3113. // Ignore message from active receivers (and if the browser tab is visible)
  3114. if (document.hasFocus()
  3115. && this.receiverService.compare(conversation, this.receiverService.getActive())) {
  3116. return;
  3117. }
  3118. // Do not show any notifications on private chats
  3119. if (sender.locked === true) {
  3120. return;
  3121. }
  3122. // Consider conversation notification settings
  3123. const simplifiedNotification = this.notificationService.getAppNotificationSettings(conversation);
  3124. if (!this.shouldNotify(simplifiedNotification, message)) {
  3125. return;
  3126. }
  3127. // Determine sender and partner name (used for notification)
  3128. let senderName = sender.id;
  3129. if (sender.displayName) {
  3130. senderName = sender.displayName;
  3131. } else if (isContactReceiver(sender)) {
  3132. senderName = '~' + sender.publicNickname;
  3133. }
  3134. const partner = this.receivers.getData({
  3135. id: message.partnerId,
  3136. type: 'contact',
  3137. } as threema.Receiver) as threema.ContactReceiver;
  3138. const partnerName = partner.displayName || ('~' + partner.publicNickname);
  3139. // Show notification
  3140. this.$translate('messenger.MESSAGE_NOTIFICATION_SUBJECT', {messageCount: conversation.unreadCount})
  3141. .then((titlePrefix) => {
  3142. const title = `${titlePrefix} ${senderName}`;
  3143. let body = '';
  3144. const messageType = message.type;
  3145. const caption = message.caption;
  3146. let captionString = '';
  3147. if (caption !== undefined) {
  3148. captionString = captionString + ': ' + caption;
  3149. }
  3150. const messageTypeString = this.$translate.instant('messageTypes.' + messageType);
  3151. switch (messageType as threema.MessageType) {
  3152. case 'text':
  3153. body = message.body;
  3154. break;
  3155. case 'location':
  3156. body = messageTypeString + ': ' + message.location.description;
  3157. break;
  3158. case 'file':
  3159. if (message.file.type === 'image/gif') {
  3160. body = this.$translate.instant('messageTypes.' + 'gif') + captionString;
  3161. break;
  3162. }
  3163. // Display caption, if available otherwise use filename
  3164. if (captionString.length > 0) {
  3165. body = messageTypeString + captionString;
  3166. } else {
  3167. body = messageTypeString + ': ' + message.file.name;
  3168. }
  3169. break;
  3170. case 'ballot':
  3171. // TODO Show ballot title if ballot messages are implemented in the web version
  3172. body = messageTypeString;
  3173. break;
  3174. case 'voipStatus':
  3175. let translationKey: string;
  3176. switch ((message as threema.Message).voip.status) {
  3177. case 1:
  3178. translationKey = 'CALL_MISSED';
  3179. break;
  3180. case 2:
  3181. translationKey = message.isOutbox ? 'CALL_FINISHED_IN' : 'CALL_FINISHED_OUT';
  3182. break;
  3183. case 3:
  3184. translationKey = 'CALL_REJECTED';
  3185. break;
  3186. case 4:
  3187. translationKey = 'CALL_ABORTED';
  3188. break;
  3189. default:
  3190. // No default
  3191. }
  3192. if (translationKey !== undefined) {
  3193. body = this.$translate.instant('voip.' + translationKey);
  3194. }
  3195. break;
  3196. default:
  3197. // Image, video and audio
  3198. body = messageTypeString + captionString;
  3199. }
  3200. if (conversation.type === 'group') {
  3201. body = partnerName + ': ' + body;
  3202. }
  3203. const tag = conversation.type + '-' + conversation.id;
  3204. const avatar = (sender.avatar && sender.avatar.low)
  3205. ? bufferToUrl(sender.avatar.low, 'image/png', this.arpLog)
  3206. : null;
  3207. this.notificationService.showNotification(tag, title, body, avatar, () => {
  3208. this.$state.go('messenger.home.conversation', {
  3209. type: conversation.type,
  3210. id: conversation.id,
  3211. initParams: null,
  3212. });
  3213. }, undefined, undefined, simplifiedNotification.sound.muted);
  3214. });
  3215. }
  3216. /**
  3217. * If a password has been set, store own private permanent key and public
  3218. * key of the peer in the trusted key store.
  3219. */
  3220. private _maybeTrustKeys(password: string): boolean {
  3221. if (password !== undefined && password !== null && password.length > 0) {
  3222. this.trustedKeyStore.storeTrustedKey(
  3223. this.salty.keyStore.publicKeyBytes,
  3224. this.salty.keyStore.secretKeyBytes,
  3225. this.salty.peerPermanentKeyBytes,
  3226. this.pushToken,
  3227. this.pushTokenType,
  3228. password,
  3229. );
  3230. this.log.info('Stored trusted key');
  3231. return true;
  3232. }
  3233. return false;
  3234. }
  3235. public updatePushToken(token: string, tokenType: threema.PushTokenType): void {
  3236. this.pushToken = token;
  3237. this.pushTokenType = tokenType;
  3238. }
  3239. private sendRequestWireMessage(
  3240. subType: string,
  3241. retransmit: boolean,
  3242. args?: object,
  3243. data?: any,
  3244. id?: string,
  3245. ): Promise<any> {
  3246. return this.sendWireMessage(WebClientService.TYPE_REQUEST, subType, retransmit, args, data, id);
  3247. }
  3248. private sendUpdateWireMessage(
  3249. subType: string,
  3250. retransmit: boolean,
  3251. args?: object,
  3252. data?: any,
  3253. id?: string,
  3254. ): Promise<any> {
  3255. return this.sendWireMessage(WebClientService.TYPE_UPDATE, subType, retransmit, args, data, id);
  3256. }
  3257. private sendCreateWireMessage(
  3258. subType: string,
  3259. retransmit: boolean,
  3260. args?: object,
  3261. data?: any,
  3262. id?: string,
  3263. ): Promise<any> {
  3264. return this.sendWireMessage(WebClientService.TYPE_CREATE, subType, retransmit, args, data, id);
  3265. }
  3266. private sendDeleteWireMessage(
  3267. subType: string,
  3268. retransmit: boolean,
  3269. args?: object,
  3270. data?: any,
  3271. id?: string,
  3272. ): Promise<any> {
  3273. return this.sendWireMessage(WebClientService.TYPE_DELETE, subType, retransmit, args, data, id);
  3274. }
  3275. private createRandomWireMessageId() {
  3276. let id;
  3277. do {
  3278. id = randomString(6);
  3279. } while (this.wireMessageFutures.has(id));
  3280. return id;
  3281. }
  3282. private sendWireMessage(
  3283. type: string,
  3284. subType: string,
  3285. retransmit: boolean,
  3286. args?: object,
  3287. data?: any,
  3288. id?: string,
  3289. ): Promise<any> {
  3290. const message: threema.WireMessage = {
  3291. type: type,
  3292. subType: subType,
  3293. };
  3294. // Create a promise with a random ID (if retransmitting)
  3295. // Note: We do this in order to keep track of which messages the app
  3296. // has processed (NOT only received). A message that has not been
  3297. // processed yet is an indicator to wake the app up again after a
  3298. // connection loss.
  3299. let promise: Promise<any>;
  3300. if (retransmit) {
  3301. // Ensure ID uniqueness (if supplied) or create random ID
  3302. if (id === undefined) {
  3303. id = this.createRandomWireMessageId();
  3304. } else if (this.wireMessageFutures.has(id)) {
  3305. throw new Error('Duplicate id for wire message detected');
  3306. }
  3307. message.id = id;
  3308. // TODO: Remove when removing temporaryId backwards compatibility
  3309. // Set temporary ID
  3310. if (args === undefined) {
  3311. args = {};
  3312. }
  3313. args[WebClientService.ARGUMENT_TEMPORARY_ID] = message.id;
  3314. // Create & store future
  3315. const future: Future<any> = new Future();
  3316. this.arpLogV.debug(`Added wire message future: ${id} -> ${type}/${subType}`);
  3317. this.wireMessageFutures.set(message.id, future);
  3318. promise = future;
  3319. } else {
  3320. promise = Promise.resolve({
  3321. id: '',
  3322. success: true,
  3323. });
  3324. }
  3325. // Set args and data (if any)
  3326. if (args !== undefined) {
  3327. message.args = args;
  3328. }
  3329. if (data !== undefined) {
  3330. message.data = data;
  3331. }
  3332. // Send message & return promise (or undefined)
  3333. this.send(message, retransmit);
  3334. return promise;
  3335. }
  3336. private static validateWireMessageAcknowledgement(ack: threema.WireMessageAcknowledgement): void {
  3337. if (!hasValue(ack.id)) {
  3338. throw new Error("Invalid wire message acknowledgement: 'id' is missing");
  3339. }
  3340. if (!hasValue(ack.success)) {
  3341. throw new Error("Invalid wire message acknowledgement: 'success' is missing");
  3342. }
  3343. switch (ack.success) {
  3344. case true:
  3345. break;
  3346. case false:
  3347. if (!hasValue(ack.error)) {
  3348. throw new Error("Invalid wire message acknowledgement: 'error' is missing");
  3349. }
  3350. break;
  3351. default:
  3352. throw new Error("Invalid wire message acknowledgement: 'success' is not a boolean");
  3353. }
  3354. }
  3355. /**
  3356. * Find and return the wire message future corresponding to the message.
  3357. *
  3358. * This will automatically validate that the 'ack' field of the message is
  3359. * correct. Also, note that the future will be removed from the map of
  3360. * pending wire message futures.
  3361. *
  3362. * @param message The message that (may) contain an acknowledgement.
  3363. * @param optional If set to `true`, no error will be thrown if the message
  3364. * did not contain an acknowledgement.
  3365. *
  3366. * Throws an exception in case the acknowledgement field is invalid.
  3367. * Throws an exception in case the wire message does not contain an
  3368. * acknowledgement and the acknowledgement is not optional.
  3369. * Throws an exception if no future could be found.
  3370. *
  3371. * In any exception case, if the associated future could be found, it will
  3372. * be rejected with 'invalidResponse' before the exception is being
  3373. * thrown. The case of 'ack.success == false' does NOT count as an
  3374. * exception case.
  3375. */
  3376. private popWireMessageFuture(message: threema.WireMessage, optional = false): Future<any> {
  3377. // Transfer old temporaryId-related fields into new 'ack' field.
  3378. // TODO: Remove when removing temporaryId backwards compatibility
  3379. if (message.ack === undefined &&
  3380. message.args !== undefined &&
  3381. message.args[WebClientService.ARGUMENT_TEMPORARY_ID] !== undefined
  3382. ) {
  3383. // Not all messages with 'temporaryId' had a 'success' field, so
  3384. // we need to patch it.
  3385. if (message.args[WebClientService.ARGUMENT_SUCCESS] === undefined) {
  3386. message.args[WebClientService.ARGUMENT_SUCCESS] = true;
  3387. }
  3388. message.ack = {
  3389. id: message.args[WebClientService.ARGUMENT_TEMPORARY_ID],
  3390. success: message.args[WebClientService.ARGUMENT_SUCCESS],
  3391. error: message.args[WebClientService.ARGUMENT_ERROR],
  3392. };
  3393. }
  3394. // Validate message
  3395. let error: Error;
  3396. if (hasValue(message.ack)) {
  3397. try {
  3398. WebClientService.validateWireMessageAcknowledgement(message.ack);
  3399. } catch (e) {
  3400. error = e;
  3401. }
  3402. } else if (!optional) {
  3403. throw new Error('Wire message did not contain an acknowledgement');
  3404. } else {
  3405. // Nit: We could use a fake future here for performance
  3406. return new Future();
  3407. }
  3408. const id = message.ack.id;
  3409. // Get associated future
  3410. const future = this.wireMessageFutures.get(id);
  3411. if (future !== undefined) {
  3412. // Remove the future from the map
  3413. this.wireMessageFutures.delete(id);
  3414. this.arpLogV.debug(`Removed wire message future: ${id} -> ` +
  3415. `${message.type}/${message.subType}`);
  3416. } else if (error === undefined) {
  3417. error = new Error(`Wire message future not found for id: ${id}`);
  3418. }
  3419. // Handle error (reject future and throw)
  3420. if (error !== undefined) {
  3421. if (future !== undefined) {
  3422. future.reject('invalidResponse');
  3423. }
  3424. throw error;
  3425. }
  3426. // Done
  3427. return future;
  3428. }
  3429. private _receiveRequest(type: string, message: threema.WireMessage): void {
  3430. switch (type) {
  3431. case WebClientService.SUB_TYPE_CONNECTION_ACK:
  3432. this._receiveRequestConnectionAck(message);
  3433. break;
  3434. default:
  3435. this.arpLog.warn(`Ignored request/${type}`);
  3436. break;
  3437. }
  3438. }
  3439. private _receiveResponse(type: string, message: threema.WireMessage): void {
  3440. switch (type) {
  3441. case WebClientService.SUB_TYPE_CONFIRM_ACTION:
  3442. this._receiveResponseConfirmAction(message);
  3443. break;
  3444. case WebClientService.SUB_TYPE_RECEIVERS:
  3445. this._receiveResponseReceivers(message);
  3446. break;
  3447. case WebClientService.SUB_TYPE_CONVERSATIONS:
  3448. this._receiveResponseConversations(message);
  3449. break;
  3450. case WebClientService.SUB_TYPE_MESSAGES:
  3451. this._receiveResponseMessages(message);
  3452. break;
  3453. case WebClientService.SUB_TYPE_AVATAR:
  3454. this._receiveResponseAvatar(message);
  3455. break;
  3456. case WebClientService.SUB_TYPE_THUMBNAIL:
  3457. this._receiveResponseThumbnail(message);
  3458. break;
  3459. case WebClientService.SUB_TYPE_BLOB:
  3460. this._receiveResponseBlob(message);
  3461. break;
  3462. case WebClientService.SUB_TYPE_CLIENT_INFO:
  3463. this._receiveResponseClientInfo(message);
  3464. break;
  3465. case WebClientService.SUB_TYPE_PROFILE:
  3466. this._receiveResponseProfile(message);
  3467. break;
  3468. case WebClientService.SUB_TYPE_CONTACT_DETAIL:
  3469. this._receiveResponseContactDetail(message);
  3470. break;
  3471. default:
  3472. this.arpLog.warn(`Ignored response/${type}`);
  3473. break;
  3474. }
  3475. }
  3476. private _receiveUpdate(type: string, message: threema.WireMessage): void {
  3477. switch (type) {
  3478. case WebClientService.SUB_TYPE_CONFIRM:
  3479. this._receiveUpdateConfirm(message);
  3480. break;
  3481. case WebClientService.SUB_TYPE_RECEIVER:
  3482. this._receiveUpdateReceiver(message);
  3483. break;
  3484. case WebClientService.SUB_TYPE_RECEIVERS:
  3485. this._receiveUpdateReceivers(message);
  3486. break;
  3487. case WebClientService.SUB_TYPE_MESSAGES:
  3488. this._receiveUpdateMessages(message);
  3489. break;
  3490. case WebClientService.SUB_TYPE_TYPING:
  3491. this._receiveUpdateTyping(message);
  3492. break;
  3493. case WebClientService.SUB_TYPE_CONVERSATION:
  3494. this._receiveUpdateConversation(message);
  3495. break;
  3496. case WebClientService.SUB_TYPE_AVATAR:
  3497. this._receiveUpdateAvatar(message);
  3498. break;
  3499. case WebClientService.SUB_TYPE_BATTERY_STATUS:
  3500. this._receiveUpdateBatteryStatus(message);
  3501. break;
  3502. case WebClientService.SUB_TYPE_CONTACT:
  3503. this._receiveUpdateContact(message);
  3504. break;
  3505. case WebClientService.SUB_TYPE_GROUP:
  3506. this._receiveUpdateGroup(message);
  3507. break;
  3508. case WebClientService.SUB_TYPE_DISTRIBUTION_LIST:
  3509. this._receiveUpdateDistributionList(message);
  3510. break;
  3511. case WebClientService.SUB_TYPE_PROFILE:
  3512. this._receiveUpdateProfile(message);
  3513. break;
  3514. case WebClientService.SUB_TYPE_ALERT:
  3515. this._receiveUpdateAlert(message);
  3516. break;
  3517. case WebClientService.SUB_TYPE_CONNECTION_ACK:
  3518. this._receiveUpdateConnectionAck(message);
  3519. break;
  3520. case WebClientService.SUB_TYPE_CONNECTION_DISCONNECT:
  3521. this._receiveUpdateConnectionDisconnect(message);
  3522. break;
  3523. default:
  3524. this.arpLog.warn(`Ignored update/${type}`);
  3525. break;
  3526. }
  3527. }
  3528. private _receiveCreate(type: string, message: threema.WireMessage): void {
  3529. switch (type) {
  3530. case WebClientService.SUB_TYPE_CONTACT:
  3531. this._receiveCreateContact(message);
  3532. break;
  3533. case WebClientService.SUB_TYPE_GROUP:
  3534. this._receiveCreateGroup(message);
  3535. break;
  3536. case WebClientService.SUB_TYPE_DISTRIBUTION_LIST:
  3537. this._receiveCreateDistributionList(message);
  3538. break;
  3539. case WebClientService.SUB_TYPE_TEXT_MESSAGE: // fallthrough
  3540. case WebClientService.SUB_TYPE_FILE_MESSAGE:
  3541. this._receiveCreateMessage(message);
  3542. break;
  3543. default:
  3544. this.arpLog.warn(`Ignored response/${type}`);
  3545. break;
  3546. }
  3547. }
  3548. /**
  3549. * Encode an object using the msgpack format.
  3550. */
  3551. private msgpackEncode(data: any): Uint8Array {
  3552. return msgpack.encode(data, this.msgpackEncoderOptions);
  3553. }
  3554. /**
  3555. * Decode an object using the msgpack format.
  3556. */
  3557. private msgpackDecode(bytes: Uint8Array): any {
  3558. return msgpack.decode(bytes, this.msgpackDecoderOptions);
  3559. }
  3560. /**
  3561. * Send a message via the underlying transport.
  3562. */
  3563. private send(message: threema.WireMessage, retransmit: boolean): void {
  3564. this.arpLog.debug('Sending', message.type + '/' + message.subType, 'message');
  3565. if (this.config.ARP_LOG_TRACE) {
  3566. // Sanitise outgoing message before logging
  3567. this.arpLogV.debug('Outgoing:', message.type, '/', message.subType, new ConfidentialWireMessage(message));
  3568. }
  3569. // TODO: Fix chosenTask may be different between connections in the
  3570. // future. Do not rely on it when sending while not being
  3571. // connected.
  3572. switch (this.chosenTask) {
  3573. case threema.ChosenTask.WebRTC:
  3574. {
  3575. // Send bytes through WebRTC DataChannel
  3576. const bytes: Uint8Array = this.msgpackEncode(message);
  3577. if (this.config.MSGPACK_LOG_TRACE) {
  3578. this.msgpackLog.debug('Outgoing message payload: ' + msgpackVisualizer(bytes));
  3579. }
  3580. const box = this.secureDataChannelCrypto.encrypt(bytes);
  3581. const chunker = new chunkedDc.UnreliableUnorderedChunker(
  3582. this.secureDataChannelMessageId++, box.toUint8Array(), this.secureDataChannelChunkLength);
  3583. for (const chunk of chunker) {
  3584. this.arpLogV.debug(`Data channel ${this.secureDataChannel.dc.label} outgoing ` +
  3585. `chunk of length ${chunk.byteLength}`);
  3586. this.secureDataChannel.write(chunk);
  3587. }
  3588. }
  3589. break;
  3590. case threema.ChosenTask.RelayedData:
  3591. {
  3592. // Don't queue handshake messages
  3593. // TODO: Add this as a method argument
  3594. const canQueue = message.subType !== WebClientService.SUB_TYPE_CONNECTION_INFO;
  3595. // Send bytes through e2e encrypted WebSocket
  3596. const bytes: Uint8Array = this.msgpackEncode(message);
  3597. if (this.config.MSGPACK_LOG_TRACE) {
  3598. this.msgpackLog.debug('Outgoing message payload: ' + msgpackVisualizer(bytes));
  3599. }
  3600. // Increment the outgoing message sequence number
  3601. const messageSequenceNumber = this.outgoingMessageSequenceNumber.increment();
  3602. const chunker = new chunkedDc.UnreliableUnorderedChunker(
  3603. messageSequenceNumber, bytes, WebClientService.RELAYED_DATA_CHUNK_SIZE);
  3604. for (const chunk of chunker) {
  3605. // Send (and cache)
  3606. this.sendChunk(chunk, retransmit, canQueue, true);
  3607. }
  3608. // Check if we need to request an acknowledgement
  3609. // Note: We only request if none is pending.
  3610. if (this.pendingAckRequest === null &&
  3611. this.currentChunkCache.byteLength > WebClientService.CHUNK_CACHE_SIZE_MAX) {
  3612. // Warning: This field MUST be set before requesting the
  3613. // connection ack or you will end up with an
  3614. // infinite recursion.
  3615. this.pendingAckRequest = this.currentChunkCache.sequenceNumber.get();
  3616. this._requestConnectionAck();
  3617. }
  3618. }
  3619. break;
  3620. default:
  3621. this.arpLog.error('Trying to send message, but no chosen task set');
  3622. }
  3623. }
  3624. /**
  3625. * Send a chunk via the underlying transport.
  3626. */
  3627. private sendChunk(chunk: Uint8Array, retransmit: boolean, canQueue: boolean, cache: boolean): void {
  3628. // TODO: Support for sending in chunks via data channels will be added later
  3629. if (this.chosenTask !== threema.ChosenTask.RelayedData) {
  3630. throw new Error(`Cannot send chunk, not supported by task: ${this.chosenTask}`);
  3631. }
  3632. const shouldQueue = canQueue && this.previousChunkCache !== null;
  3633. let chunkCache: ChunkCache;
  3634. // Enqueue in the chunk cache that is pending to be transferred and
  3635. // send a wakeup push.
  3636. if (shouldQueue) {
  3637. chunkCache = this.previousChunkCache;
  3638. this.arpLog.debug('Currently not connected, queueing chunk');
  3639. if (!this.pushService.isAvailable()) {
  3640. this.log.warn('Push service not available, cannot wake up peer!');
  3641. retransmit = false;
  3642. }
  3643. if (retransmit) {
  3644. // TODO: Apply the chunk **push** blacklist instead of the
  3645. // retransmit flag!
  3646. this.sendPush();
  3647. }
  3648. } else {
  3649. chunkCache = this.currentChunkCache;
  3650. }
  3651. // Add to chunk cache
  3652. if (cache) {
  3653. this.arpLogV.debug(`Caching chunk (retransmit/push=${retransmit}:`, chunk);
  3654. try {
  3655. chunkCache.append(retransmit ? chunk : null);
  3656. } catch (error) {
  3657. this.arpLog.error(error);
  3658. this.failSession();
  3659. return;
  3660. }
  3661. }
  3662. // Send if ready
  3663. if (!shouldQueue) {
  3664. this.arpLogV.debug(`Sending chunk (retransmit/push=${retransmit}:`, chunk);
  3665. // Send chunk
  3666. this.relayedDataTask.sendMessage(chunk.buffer);
  3667. // Send a push if no incoming chunks within the next two seconds.
  3668. // Note: This has a cooldown phase of 10 seconds.
  3669. if (retransmit && this.startupDone) {
  3670. this.schedulePush();
  3671. }
  3672. }
  3673. }
  3674. /**
  3675. * Handle an incoming chunk from the underlying transport.
  3676. */
  3677. private receiveChunk(chunk: Uint8Array): void {
  3678. this.arpLogV.debug('Received chunk:', chunk);
  3679. // Update incoming sequence number
  3680. try {
  3681. this.currentIncomingChunkSequenceNumber.increment();
  3682. } catch (error) {
  3683. this.arpLog.error(`Unable to continue session: ${error}`);
  3684. this.failSession();
  3685. return;
  3686. }
  3687. // Schedule the periodic ack timer
  3688. this.scheduleConnectionAck();
  3689. // Cancel scheduled push since data has been received
  3690. this.cancelPush();
  3691. // Process chunk
  3692. // Warning: Nothing should be called after the unchunker has processed
  3693. // the chunk since the message event is synchronous and can
  3694. // result in a call to .stop!
  3695. this.unchunker.add(chunk);
  3696. }
  3697. /**
  3698. * Handle incoming message bytes from the SecureDataChannel.
  3699. */
  3700. private handleIncomingMessageBytes(bytes: Uint8Array): void {
  3701. this.arpLog.debug('New incoming message (' + bytes.byteLength + ' bytes)');
  3702. if (this.config.MSGPACK_LOG_TRACE) {
  3703. this.msgpackLog.debug('Incoming message payload: ' + msgpackVisualizer(bytes));
  3704. }
  3705. // Decode bytes
  3706. const message: threema.WireMessage = this.msgpackDecode(bytes);
  3707. return this.handleIncomingMessage(message);
  3708. }
  3709. /**
  3710. * Handle incoming incoming from the SecureDataChannel
  3711. * or from the relayed data WebSocket.
  3712. */
  3713. private handleIncomingMessage(message: threema.WireMessage): void {
  3714. this.arpLog.debug(`Received ${message.type}/${message.subType} message`);
  3715. // Validate message to keep contract defined by `threema.WireMessage` type
  3716. if (message.type === undefined) {
  3717. this.arpLog.warn('Ignoring invalid message (no type attribute)');
  3718. return;
  3719. } else if (message.subType === undefined) {
  3720. this.arpLog.warn('Ignoring invalid message (no subType attribute)');
  3721. return;
  3722. }
  3723. // If desired, log message type / subtype
  3724. if (this.config.ARP_LOG_TRACE) {
  3725. // Sanitise incoming message before logging
  3726. // Note: Deep-copy message to prevent issues with JS debugger
  3727. this.arpLogV.debug(`Incoming: ${message.type}/${message.subType}`,
  3728. new ConfidentialWireMessage(copyDeepOrReference(message)));
  3729. }
  3730. // Process data
  3731. this.$rootScope.$apply(() => {
  3732. this.receive(message);
  3733. });
  3734. }
  3735. /**
  3736. * Receive a new incoming decrypted message.
  3737. * This method runs inside the digest loop.
  3738. */
  3739. private receive(message: threema.WireMessage): void {
  3740. // Intercept handshake message
  3741. if (!this.connectionInfoFuture.done) {
  3742. // Check for unexpected messages
  3743. if (message.type !== WebClientService.TYPE_UPDATE ||
  3744. message.subType !== WebClientService.SUB_TYPE_CONNECTION_INFO) {
  3745. this.arpLog.error('Unexpected message before handshake has been completed');
  3746. this.failSession();
  3747. return;
  3748. }
  3749. // Dispatch and return
  3750. this._receiveConnectionInfo(message);
  3751. return;
  3752. }
  3753. // Determine message handler
  3754. let messageHandler: (type, message) => void;
  3755. switch (message.type) {
  3756. case WebClientService.TYPE_REQUEST:
  3757. messageHandler = this._receiveRequest;
  3758. break;
  3759. case WebClientService.TYPE_RESPONSE:
  3760. messageHandler = this._receiveResponse;
  3761. break;
  3762. case WebClientService.TYPE_CREATE:
  3763. messageHandler = this._receiveCreate;
  3764. break;
  3765. case WebClientService.TYPE_UPDATE:
  3766. messageHandler = this._receiveUpdate;
  3767. break;
  3768. default:
  3769. this.arpLog.warn(`Ignored message ${message.type}/${message.subType}`);
  3770. break;
  3771. }
  3772. // Dispatch message
  3773. if (messageHandler !== undefined) {
  3774. try {
  3775. messageHandler.apply(this, [message.subType, message]);
  3776. } catch (error) {
  3777. this.arpLog.error('Unable to handle incoming wire message:', error);
  3778. console.trace(error); // tslint:disable-line:no-console
  3779. return;
  3780. }
  3781. }
  3782. // Catch unhandled wire message acknowledgements
  3783. // Nit: We could cache that we have already scraped the message for a
  3784. // wire message acknowledgement instead of double-parsing.
  3785. let future: Future<any>;
  3786. try {
  3787. future = this.popWireMessageFuture(message);
  3788. } catch {
  3789. // Yes, I really know what I'm doing, thanks eslint...
  3790. }
  3791. if (future !== undefined) {
  3792. this.arpLog.warn(`Unhandled message acknowledgement for type ${message.type}:`, message.ack);
  3793. future.reject('unhandled');
  3794. }
  3795. }
  3796. private runAfterInitializationSteps(requiredSteps: threema.InitializationStep[], callback: any): void {
  3797. for (const requiredStep of requiredSteps) {
  3798. if (!this.initialized.has(requiredStep)) {
  3799. this.arpLog.debug('Required initialization step', requiredStep, 'not completed, add pending routine');
  3800. this.pendingInitializationStepRoutines.add({
  3801. requiredSteps: requiredSteps,
  3802. callback: callback,
  3803. } as threema.InitializationStepRoutine);
  3804. return;
  3805. }
  3806. }
  3807. callback.apply(this);
  3808. }
  3809. /**
  3810. * Update the unread count in the window title.
  3811. */
  3812. private updateUnreadCount(): void {
  3813. const totalUnreadCount = this.conversations
  3814. .get()
  3815. .reduce((a: number, b: threema.Conversation) => a + b.unreadCount, 0);
  3816. this.stateService.unreadCount = totalUnreadCount;
  3817. }
  3818. /**
  3819. * Reset the unread count in the window title
  3820. */
  3821. private resetUnreadCount(): void {
  3822. this.stateService.unreadCount = 0;
  3823. }
  3824. /**
  3825. * Return the configuration object from the client info data.
  3826. */
  3827. public get appConfig(): threema.AppConfig {
  3828. return this.clientInfo.configuration;
  3829. }
  3830. /**
  3831. * Return the capabilities object from the client info data.
  3832. */
  3833. public get appCapabilities(): threema.AppCapabilities {
  3834. return this.clientInfo.capabilities;
  3835. }
  3836. /**
  3837. * Sort a list of contacts in-place.
  3838. */
  3839. private sortContacts(contacts: threema.ContactReceiver[]): void {
  3840. const getSortableName = (name: string) => name.startsWith('~') ? name.substr(1) : name;
  3841. let options;
  3842. if (this.browserService.supportsExtendedLocaleCompare()) {
  3843. options = {
  3844. usage: 'sort',
  3845. sensitivity: 'variant',
  3846. };
  3847. }
  3848. const compareFunc = (a: threema.Receiver, b: threema.Receiver) => {
  3849. if (a.id.startsWith('*') && !b.id.startsWith('*')) { return 1; }
  3850. if (!a.id.startsWith('*') && b.id.startsWith('*')) { return -1; }
  3851. const left = getSortableName(a.displayName);
  3852. const right = getSortableName(b.displayName);
  3853. return left.localeCompare(right, undefined, options);
  3854. };
  3855. contacts.sort(compareFunc);
  3856. }
  3857. /**
  3858. * Clear all "is typing" flags.
  3859. */
  3860. public clearIsTypingFlags(): void {
  3861. this.typing.clearAll();
  3862. }
  3863. private handleGlobalConnectionStateChange(stateChange: threema.GlobalConnectionStateChange): void {
  3864. const isOk = stateChange.state === threema.GlobalConnectionState.Ok;
  3865. const wasOk = stateChange.prevState === threema.GlobalConnectionState.Ok;
  3866. if (!isOk && wasOk && this.batteryStatusService.dataAvailable) {
  3867. this.batteryStatusTimeout = this.timeoutService.register(
  3868. () => {
  3869. this.batteryStatusService.clearStatus();
  3870. this.batteryStatusTimeout = null;
  3871. },
  3872. 60000,
  3873. true,
  3874. 'batteryStatusHide',
  3875. );
  3876. } else if (isOk && this.batteryStatusTimeout !== null) {
  3877. this.timeoutService.cancel(this.batteryStatusTimeout);
  3878. this.batteryStatusTimeout = null;
  3879. }
  3880. }
  3881. /**
  3882. * Log chat message's metadata for debugging purposes.
  3883. */
  3884. private logChatMessages(
  3885. type: string, subType: string, receiverType: string, receiver: string, mode: string,
  3886. messages: threema.Message[],
  3887. ) {
  3888. for (const message of messages) {
  3889. let id: string = message.id;
  3890. if (this.clientInfo.os === threema.OperatingSystem.Ios) {
  3891. try {
  3892. id = u8aToHex(base64ToU8a(message.id));
  3893. } catch { /* ignored */ }
  3894. }
  3895. this.arpLogV.debug('Chat message:', `${type}/${subType}: receiver=${receiverType}/${receiver}, ` +
  3896. `mode=${mode}, direction=${message.isOutbox ? 'out' : 'in'}, id=${id}, type=${message.type}, ` +
  3897. `state=${message.state !== undefined ? message.state : '?'}, is-status=${message.isStatus}, ` +
  3898. `date=${message.date}`);
  3899. }
  3900. }
  3901. }