webclient.ts 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642
  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 * as msgpack from 'msgpack-lite';
  22. import {arraysAreEqual, hasFeature, hasValue, hexToU8a, msgpackVisualizer, stringToUtf8a} from '../helpers';
  23. import {isContactReceiver, isDistributionListReceiver, isGroupReceiver, isValidReceiverType} from '../typeguards';
  24. import {BatteryStatusService} from './battery';
  25. import {BrowserService} from './browser';
  26. import {TrustedKeyStoreService} from './keystore';
  27. import {MessageService} from './message';
  28. import {MimeService} from './mime';
  29. import {NotificationService} from './notification';
  30. import {PeerConnectionHelper} from './peerconnection';
  31. import {PushService} from './push';
  32. import {QrCodeService} from './qrcode';
  33. import {ReceiverService} from './receiver';
  34. import {StateService} from './state';
  35. import {TitleService} from './title';
  36. import {VersionService} from './version';
  37. import {ChunkCache} from '../protocol/cache';
  38. import {SequenceNumber} from '../protocol/sequence_number';
  39. // Aliases
  40. import InitializationStep = threema.InitializationStep;
  41. import ContactReceiverFeature = threema.ContactReceiverFeature;
  42. import DisconnectReason = threema.DisconnectReason;
  43. /**
  44. * This service handles everything related to the communication with the peer.
  45. */
  46. export class WebClientService {
  47. private static CHUNK_SIZE = 64 * 1024;
  48. private static SEQUENCE_NUMBER_MIN = 0;
  49. private static SEQUENCE_NUMBER_MAX = (2 ** 32) - 1;
  50. private static CHUNK_CACHE_SIZE_MAX = 2 * 1024 * 1024;
  51. private static AVATAR_LOW_MAX_SIZE = 48;
  52. private static MAX_TEXT_LENGTH = 3500;
  53. private static MAX_FILE_SIZE_WEBRTC = 15 * 1024 * 1024;
  54. private static CONNECTION_ID_NONCE = stringToUtf8a('connectionidconnectionid');
  55. private static TYPE_REQUEST = 'request';
  56. private static TYPE_RESPONSE = 'response';
  57. private static TYPE_UPDATE = 'update';
  58. private static TYPE_CREATE = 'create';
  59. private static TYPE_DELETE = 'delete';
  60. private static SUB_TYPE_RECEIVER = 'receiver';
  61. private static SUB_TYPE_RECEIVERS = 'receivers';
  62. private static SUB_TYPE_CONVERSATIONS = 'conversations';
  63. private static SUB_TYPE_CONVERSATION = 'conversation';
  64. private static SUB_TYPE_MESSAGE = 'message';
  65. private static SUB_TYPE_MESSAGES = 'messages';
  66. private static SUB_TYPE_TEXT_MESSAGE = 'textMessage';
  67. private static SUB_TYPE_FILE_MESSAGE = 'fileMessage';
  68. private static SUB_TYPE_AVATAR = 'avatar';
  69. private static SUB_TYPE_THUMBNAIL = 'thumbnail';
  70. private static SUB_TYPE_BLOB = 'blob';
  71. private static SUB_TYPE_TYPING = 'typing';
  72. private static SUB_TYPE_READ = 'read';
  73. private static SUB_TYPE_CLIENT_INFO = 'clientInfo';
  74. private static SUB_TYPE_KEY_PERSISTED = 'keyPersisted';
  75. private static SUB_TYPE_ACK = 'ack';
  76. private static SUB_TYPE_CONTACT_DETAIL = 'contactDetail';
  77. private static SUB_TYPE_CONTACT = 'contact';
  78. private static SUB_TYPE_GROUP = 'group';
  79. private static SUB_TYPE_DISTRIBUTION_LIST = 'distributionList';
  80. private static SUB_TYPE_ALERT = 'alert';
  81. private static SUB_TYPE_GROUP_SYNC = 'groupSync';
  82. private static SUB_TYPE_BATTERY_STATUS = 'batteryStatus';
  83. private static SUB_TYPE_CLEAN_RECEIVER_CONVERSATION = 'cleanReceiverConversation';
  84. private static SUB_TYPE_CONFIRM_ACTION = 'confirmAction';
  85. private static SUB_TYPE_PROFILE = 'profile';
  86. private static SUB_TYPE_CONNECTION_ACK = 'connectionAck';
  87. private static SUB_TYPE_CONNECTION_DISCONNECT = 'connectionDisconnect';
  88. private static SUB_TYPE_CONNECTION_INFO = 'connectionInfo';
  89. private static ARGUMENT_MODE = 'mode';
  90. private static ARGUMENT_MODE_NEW = 'new';
  91. private static ARGUMENT_MODE_MODIFIED = 'modified';
  92. private static ARGUMENT_MODE_REMOVED = 'removed';
  93. private static ARGUMENT_RECEIVER_TYPE = 'type';
  94. private static ARGUMENT_RECEIVER_ID = 'id';
  95. private static ARGUMENT_TEMPORARY_ID = 'temporaryId';
  96. private static ARGUMENT_REFERENCE_MSG_ID = 'refMsgId';
  97. private static ARGUMENT_AVATAR = 'avatar';
  98. private static ARGUMENT_AVATAR_HIGH_RESOLUTION = 'highResolution';
  99. private static ARGUMENT_NICKNAME = 'publicNickname';
  100. private static ARGUMENT_IS_TYPING = 'isTyping';
  101. private static ARGUMENT_MESSAGE_ID = 'messageId';
  102. private static ARGUMENT_HAS_MORE = 'more';
  103. private static ARGUMENT_MESSAGE_ACKNOWLEDGED = 'acknowledged';
  104. private static ARGUMENT_IDENTITY = 'identity';
  105. private static ARGUMENT_SUCCESS = 'success';
  106. private static ARGUMENT_MESSAGE = 'message';
  107. private static ARGUMENT_SYSTEM_CONTACT = 'systemContact';
  108. private static ARGUMENT_NAME = 'name';
  109. private static ARGUMENT_MEMBERS = 'members';
  110. private static ARGUMENT_FIRST_NAME = 'firstName';
  111. private static ARGUMENT_LAST_NAME = 'lastName';
  112. private static ARGUMENT_DELETE_TYPE = 'deleteType';
  113. private static ARGUMENT_ERROR = 'error';
  114. private static ARGUMENT_MAX_SIZE = 'maxSize';
  115. private static ARGUMENT_USER_AGENT = 'userAgent';
  116. private static ARGUMENT_BROWSER_NAME = 'browserName';
  117. private static ARGUMENT_BROWSER_VERSION = 'browserVersion';
  118. private static DELETE_GROUP_TYPE_LEAVE = 'leave';
  119. private static DELETE_GROUP_TYPE_DELETE = 'delete';
  120. private static DATA_FIELD_BLOB_BLOB = 'blob';
  121. private static DATA_FIELD_BLOB_TYPE = 'type';
  122. private static DATA_FIELD_BLOB_NAME = 'name';
  123. private static DC_LABEL = 'THREEMA';
  124. private logTag: string = '[WebClientService]';
  125. // Angular services
  126. private $state: UiStateService;
  127. private $log: ng.ILogService;
  128. private $rootScope: any;
  129. private $q: ng.IQService;
  130. private $window: ng.IWindowService;
  131. private $translate: ng.translate.ITranslateService;
  132. private $filter: any;
  133. private $timeout: ng.ITimeoutService;
  134. private $mdDialog: ng.material.IDialogService;
  135. // Custom services
  136. private batteryStatusService: BatteryStatusService;
  137. private browserService: BrowserService;
  138. private messageService: MessageService;
  139. private mimeService: MimeService;
  140. private notificationService: NotificationService;
  141. private pushService: PushService;
  142. private qrCodeService: QrCodeService;
  143. private receiverService: ReceiverService;
  144. private titleService: TitleService;
  145. private versionService: VersionService;
  146. // State handling
  147. private startupPromise: ng.IDeferred<{}> = null; // TODO: deferred type
  148. private startupDone: boolean = false;
  149. private pendingInitializationStepRoutines: threema.InitializationStepRoutine[] = [];
  150. private initialized: Set<threema.InitializationStep> = new Set();
  151. private stateService: StateService;
  152. private lastPush: Date = null;
  153. // Session connection
  154. private saltyRtcHost: string = null;
  155. public salty: saltyrtc.SaltyRTC = null;
  156. private connectionInfoFuture: Future<any> = null;
  157. private webrtcTask: saltyrtc.tasks.webrtc.WebRTCTask = null;
  158. private relayedDataTask: saltyrtc.tasks.relayed_data.RelayedDataTask = null;
  159. private secureDataChannel: saltyrtc.tasks.webrtc.SecureDataChannel = null;
  160. public chosenTask: threema.ChosenTask = threema.ChosenTask.None;
  161. private outgoingMessageSequenceNumber: SequenceNumber;
  162. private previousConnectionId: Uint8Array = null;
  163. private currentConnectionId: Uint8Array = null;
  164. private previousIncomingChunkSequenceNumber: SequenceNumber = null;
  165. private currentIncomingChunkSequenceNumber: SequenceNumber;
  166. private previousChunkCache: ChunkCache = null;
  167. private currentChunkCache: ChunkCache = null;
  168. private ackTimer: number | null = null;
  169. private pendingAckRequest: number | null = null;
  170. // Message chunking
  171. private unchunker: chunkedDc.Unchunker = null;
  172. // Messenger data
  173. public messages: threema.Container.Messages;
  174. public conversations: threema.Container.Conversations;
  175. public receivers: threema.Container.Receivers;
  176. public alerts: threema.Alert[] = [];
  177. private pushToken: string = null;
  178. private pushTokenType: threema.PushTokenType = null;
  179. // Other
  180. private config: threema.Config;
  181. private container: threema.Container.Factory;
  182. private typingInstance: threema.Container.Typing;
  183. private drafts: threema.Container.Drafts;
  184. private pcHelper: PeerConnectionHelper = null;
  185. private trustedKeyStore: TrustedKeyStoreService;
  186. public clientInfo: threema.ClientInfo;
  187. public version = null;
  188. private batteryStatusTimeout: ng.IPromise<void> = null;
  189. private blobCache = new Map<string, threema.BlobInfo>();
  190. private loadingMessages = new Map<string, boolean>();
  191. public receiverListener: threema.ReceiverListener[] = [];
  192. // Msgpack
  193. private msgpackEncoderOptions: msgpack.EncoderOptions = {
  194. codec: msgpack.createCodec({binarraybuffer: true}),
  195. };
  196. private msgpackDecoderOptions: msgpack.DecoderOptions = {
  197. codec: msgpack.createCodec({binarraybuffer: true}),
  198. };
  199. // pending rtc promises
  200. private requestPromises: Map<string, threema.PromiseCallbacks> = new Map();
  201. public static $inject = [
  202. '$log', '$rootScope', '$q', '$state', '$window', '$translate', '$filter', '$timeout', '$mdDialog',
  203. 'Container', 'TrustedKeyStore',
  204. 'StateService', 'NotificationService', 'MessageService', 'PushService', 'BrowserService',
  205. 'TitleService', 'QrCodeService', 'MimeService', 'ReceiverService',
  206. 'VersionService', 'BatteryStatusService',
  207. 'CONFIG',
  208. ];
  209. constructor($log: ng.ILogService,
  210. $rootScope: any,
  211. $q: ng.IQService,
  212. $state: UiStateService,
  213. $window: ng.IWindowService,
  214. $translate: ng.translate.ITranslateService,
  215. $filter: ng.IFilterService,
  216. $timeout: ng.ITimeoutService,
  217. $mdDialog: ng.material.IDialogService,
  218. container: threema.Container.Factory,
  219. trustedKeyStore: TrustedKeyStoreService,
  220. stateService: StateService,
  221. notificationService: NotificationService,
  222. messageService: MessageService,
  223. pushService: PushService,
  224. browserService: BrowserService,
  225. titleService: TitleService,
  226. qrCodeService: QrCodeService,
  227. mimeService: MimeService,
  228. receiverService: ReceiverService,
  229. versionService: VersionService,
  230. batteryStatusService: BatteryStatusService,
  231. CONFIG: threema.Config) {
  232. // Angular services
  233. this.$log = $log;
  234. this.$rootScope = $rootScope;
  235. this.$q = $q;
  236. this.$state = $state;
  237. this.$window = $window;
  238. this.$translate = $translate;
  239. this.$filter = $filter;
  240. this.$timeout = $timeout;
  241. this.$mdDialog = $mdDialog;
  242. // Own services
  243. this.batteryStatusService = batteryStatusService;
  244. this.browserService = browserService;
  245. this.messageService = messageService;
  246. this.mimeService = mimeService;
  247. this.notificationService = notificationService;
  248. this.pushService = pushService;
  249. this.qrCodeService = qrCodeService;
  250. this.receiverService = receiverService;
  251. this.titleService = titleService;
  252. this.versionService = versionService;
  253. // Configuration object
  254. this.config = CONFIG;
  255. // State
  256. this.stateService = stateService;
  257. // Other properties
  258. this.container = container;
  259. this.trustedKeyStore = trustedKeyStore;
  260. // Initialize drafts
  261. this.drafts = this.container.createDrafts();
  262. // Setup fields
  263. this._resetFields();
  264. // Register event handlers
  265. this.stateService.evtConnectionBuildupStateChange.attach(
  266. (stateChange: threema.ConnectionBuildupStateChange) => {
  267. if (this.startupPromise !== null) {
  268. this.startupPromise.notify(stateChange);
  269. }
  270. },
  271. );
  272. this.stateService.evtGlobalConnectionStateChange.attach(this.handleGlobalConnectionStateChange.bind(this));
  273. }
  274. get me(): threema.MeReceiver {
  275. return this.receivers.me;
  276. }
  277. get contacts(): Map<string, threema.ContactReceiver> {
  278. return this.receivers.contacts;
  279. }
  280. get groups(): Map<string, threema.GroupReceiver> {
  281. return this.receivers.groups;
  282. }
  283. get distributionLists(): Map<string, threema.DistributionListReceiver> {
  284. return this.receivers.distributionLists;
  285. }
  286. get typing(): threema.Container.Typing {
  287. return this.typingInstance;
  288. }
  289. /**
  290. * Return QR code payload.
  291. */
  292. public buildQrCodePayload(persistent: boolean): string {
  293. return this.qrCodeService.buildQrCodePayload(
  294. this.salty.permanentKeyBytes,
  295. this.salty.authTokenBytes,
  296. hexToU8a(this.config.SALTYRTC_SERVER_KEY),
  297. this.saltyRtcHost, this.config.SALTYRTC_PORT,
  298. persistent);
  299. }
  300. /**
  301. * Initialize the webclient service.
  302. *
  303. * Warning: Do not call this with `resumeSession` set to `false` in case
  304. * messages can be queued by the user.
  305. */
  306. public init(keyStore?: saltyrtc.KeyStore, peerTrustedKey?: Uint8Array, resumeSession = true): void {
  307. // Reset state
  308. this.stateService.reset();
  309. // Only move the previous connection's instances if the previous
  310. // connection was successful (and if there was one at all).
  311. if (resumeSession &&
  312. this.outgoingMessageSequenceNumber && this.unchunker &&
  313. this.previousChunkCache === this.currentChunkCache) {
  314. // Move instances that we need to re-establish a previous session
  315. this.previousConnectionId = this.currentConnectionId;
  316. this.previousIncomingChunkSequenceNumber = this.currentIncomingChunkSequenceNumber;
  317. this.previousChunkCache = this.currentChunkCache;
  318. } else {
  319. // Reset the outgoing message sequence number and the unchunker
  320. this.outgoingMessageSequenceNumber = new SequenceNumber(
  321. 0, WebClientService.SEQUENCE_NUMBER_MIN, WebClientService.SEQUENCE_NUMBER_MAX);
  322. this.unchunker = new chunkedDc.Unchunker();
  323. this.unchunker.onMessage = this.handleIncomingMessageBytes.bind(this);
  324. // Discard previous connection instances
  325. this.previousConnectionId = null;
  326. this.previousIncomingChunkSequenceNumber = null;
  327. this.previousChunkCache = null;
  328. // Not resuming
  329. resumeSession = false;
  330. }
  331. // Initialise connection cashes
  332. this.currentConnectionId = null;
  333. this.currentIncomingChunkSequenceNumber = new SequenceNumber(
  334. 0, WebClientService.SEQUENCE_NUMBER_MIN, WebClientService.SEQUENCE_NUMBER_MAX);
  335. const outgoingChunkSequenceNumber = new SequenceNumber(
  336. 0, WebClientService.SEQUENCE_NUMBER_MIN, WebClientService.SEQUENCE_NUMBER_MAX);
  337. this.currentChunkCache = new ChunkCache(outgoingChunkSequenceNumber);
  338. // Reset pending ack request
  339. this.pendingAckRequest = null;
  340. // Create new handshake future
  341. this.connectionInfoFuture = new Future();
  342. // Create WebRTC task instance
  343. const maxPacketSize = this.browserService.getBrowser().isFirefox(false) ? 16384 : 65536;
  344. this.webrtcTask = new saltyrtcTaskWebrtc.WebRTCTask(true, maxPacketSize);
  345. // Create Relayed Data task instance
  346. this.relayedDataTask = new saltyrtcTaskRelayedData.RelayedDataTask(this.config.DEBUG);
  347. // Create new keystore if necessary
  348. if (!keyStore) {
  349. keyStore = new saltyrtcClient.KeyStore();
  350. }
  351. // Determine SaltyRTC host
  352. if (this.config.SALTYRTC_HOST !== null) {
  353. // Static URL
  354. this.saltyRtcHost = this.config.SALTYRTC_HOST;
  355. } else {
  356. // Construct URL using prefix and suffix
  357. this.saltyRtcHost = this.config.SALTYRTC_HOST_PREFIX
  358. + keyStore.publicKeyHex.substr(0, 2)
  359. + this.config.SALTYRTC_HOST_SUFFIX;
  360. }
  361. // Determine SaltyRTC tasks
  362. let tasks;
  363. if (this.browserService.supportsWebrtcTask()) {
  364. tasks = [this.webrtcTask, this.relayedDataTask];
  365. } else {
  366. tasks = [this.relayedDataTask];
  367. }
  368. // Create SaltyRTC client
  369. let builder = new saltyrtcClient.SaltyRTCBuilder()
  370. .connectTo(this.saltyRtcHost, this.config.SALTYRTC_PORT)
  371. .withServerKey(this.config.SALTYRTC_SERVER_KEY)
  372. .withKeyStore(keyStore)
  373. .usingTasks(tasks)
  374. .withPingInterval(30);
  375. if (keyStore !== undefined && peerTrustedKey !== undefined) {
  376. builder = builder.withTrustedPeerKey(peerTrustedKey);
  377. }
  378. this.salty = builder.asInitiator();
  379. if (this.config.DEBUG) {
  380. this.$log.debug('Public key:', this.salty.permanentKeyHex);
  381. this.$log.debug('Auth token:', this.salty.authTokenHex);
  382. }
  383. // We want to know about new responders.
  384. this.salty.on('new-responder', () => {
  385. if (!this.startupDone) {
  386. // Peer handshake
  387. this.stateService.updateConnectionBuildupState('peer_handshake');
  388. }
  389. });
  390. // We want to know about state changes
  391. this.salty.on('state-change', (ev: saltyrtc.SaltyRTCEvent) => {
  392. // Wrap this in a $timeout to execute at the end of the event loop.
  393. this.$timeout(() => {
  394. const state: saltyrtc.SignalingState = ev.data;
  395. if (!this.startupDone) {
  396. switch (state) {
  397. case 'new':
  398. case 'ws-connecting':
  399. case 'server-handshake':
  400. if (this.stateService.connectionBuildupState !== 'push'
  401. && this.stateService.connectionBuildupState !== 'manual_start') {
  402. this.stateService.updateConnectionBuildupState('connecting');
  403. }
  404. break;
  405. case 'peer-handshake':
  406. // Waiting for peer
  407. if (this.stateService.connectionBuildupState !== 'push'
  408. && this.stateService.connectionBuildupState !== 'manual_start') {
  409. this.stateService.updateConnectionBuildupState('waiting');
  410. }
  411. break;
  412. case 'task':
  413. // Do nothing, state will be updated once SecureDataChannel is open
  414. break;
  415. case 'closing':
  416. case 'closed':
  417. this.stateService.updateConnectionBuildupState('closed');
  418. break;
  419. default:
  420. this.$log.warn(this.logTag, 'Unknown signaling state:', state);
  421. }
  422. }
  423. this.stateService.updateSignalingConnectionState(state, this.chosenTask);
  424. }, 0);
  425. });
  426. // Once the connection is established, if this is a WebRTC connection,
  427. // initiate the peer connection and start the handover.
  428. this.salty.once('state-change:task', () => {
  429. // Determine chosen task
  430. const task = this.salty.getTask();
  431. if (task.getName().indexOf('webrtc.tasks.saltyrtc.org') !== -1) {
  432. this.chosenTask = threema.ChosenTask.WebRTC;
  433. } else if (task.getName().indexOf('relayed-data.tasks.saltyrtc.org') !== -1) {
  434. this.chosenTask = threema.ChosenTask.RelayedData;
  435. } else {
  436. throw new Error('Invalid or unknown task name: ' + task.getName());
  437. }
  438. // If the WebRTC task was chosen, initialize handover.
  439. if (this.chosenTask === threema.ChosenTask.WebRTC) {
  440. const browser = this.browserService.getBrowser();
  441. // Firefox <53 does not yet support TLS. Skip it, to save allocations.
  442. if (browser.isFirefox(true) && browser.version < 53) {
  443. this.skipIceTls();
  444. }
  445. // Safari does not support our dual-stack TURN servers.
  446. if (browser.isSafari(false)) {
  447. this.skipIceDs();
  448. }
  449. this.pcHelper = new PeerConnectionHelper(this.$log, this.$q, this.$timeout,
  450. this.$rootScope, this.webrtcTask,
  451. this.config.ICE_SERVERS,
  452. !this.config.ICE_DEBUGGING);
  453. // On state changes in the PeerConnectionHelper class, let state service know about it
  454. this.pcHelper.onConnectionStateChange = (state: threema.TaskConnectionState) => {
  455. this.stateService.updateTaskConnectionState(state);
  456. };
  457. // Initiate handover
  458. this.webrtcTask.handover(this.pcHelper.peerConnection);
  459. // Otherwise, no handover is necessary.
  460. } else {
  461. this.onHandover(resumeSession);
  462. return;
  463. }
  464. });
  465. // Handle disconnecting of a peer
  466. this.salty.on('peer-disconnected', (ev: saltyrtc.SaltyRTCEvent) => {
  467. this.$rootScope.$apply(() => {
  468. this.onPeerDisconnected(ev.data);
  469. });
  470. });
  471. // Wait for handover to be finished
  472. this.salty.on('handover', () => {
  473. this.$log.debug(this.logTag, 'Handover done');
  474. this.onHandover(resumeSession);
  475. });
  476. // Handle SaltyRTC errors
  477. this.salty.on('connection-error', (ev) => {
  478. this.$log.error('Connection error:', ev);
  479. });
  480. this.salty.on('connection-closed', (ev) => {
  481. this.$log.warn('Connection closed:', ev);
  482. });
  483. this.salty.on('no-shared-task', (ev) => {
  484. this.$log.warn('No shared task found:', ev.data);
  485. const offeredWebrtc = ev.data.offered.filter((t) => t.endsWith('webrtc.tasks.saltyrtc.org')).length > 0;
  486. if (!this.browserService.supportsWebrtcTask() && offeredWebrtc) {
  487. this.showWebrtcAndroidWarning();
  488. } else {
  489. this.$mdDialog.show(this.$mdDialog.alert()
  490. .title('Error')
  491. .htmlContent('No shared SaltyRTC task found')
  492. .ok('OK'));
  493. }
  494. });
  495. }
  496. /**
  497. * Show a WebRTC on Android warning dialog.
  498. */
  499. private showWebrtcAndroidWarning(): void {
  500. this.$translate.onReady().then(() => {
  501. const confirm = this.$mdDialog.alert()
  502. .title(this.$translate.instant('welcome.BROWSER_NOT_SUPPORTED_ANDROID'))
  503. .htmlContent(this.$translate.instant('welcome.BROWSER_NOT_SUPPORTED_DETAILS'))
  504. .ok(this.$translate.instant('welcome.ABORT'));
  505. this.$mdDialog.show(confirm).then(() => {
  506. // Redirect to Threema website
  507. window.location.replace('https://threema.ch/threema-web');
  508. });
  509. });
  510. }
  511. /**
  512. * Show an alert dialog. Can be called directly after calling `.stop(...)`.
  513. */
  514. private showAlert(alertMessage: string): void {
  515. // Note: A former stop() call above may result in a redirect, which will
  516. // in turn hide all open dialog boxes. Therefore, to avoid
  517. // immediately hiding the alert box, enqueue dialog at end of
  518. // event loop.
  519. this.$timeout(() => {
  520. this.$mdDialog.show(this.$mdDialog.alert()
  521. .title(this.$translate.instant('connection.SESSION_CLOSED_TITLE'))
  522. .textContent(this.$translate.instant(alertMessage))
  523. .ok(this.$translate.instant('common.OK')));
  524. }, 0);
  525. }
  526. /**
  527. * Fail the session and let the remote peer know that an error occurred.
  528. * A dialog will be displayed to let the user know a protocol error
  529. * happened.
  530. */
  531. private failSession() {
  532. // Stop session
  533. this.stop(DisconnectReason.SessionError, true, true, true);
  534. // Show an alert
  535. this.showAlert('connection.SESSION_ERROR');
  536. }
  537. /**
  538. * Resume a session via the previous connection's ID and chunk cache.
  539. *
  540. * Important: Caller must invalidate the cache and connection ID after this
  541. * function returned!
  542. */
  543. private resumeSession(remoteInfo: any): void {
  544. // Ensure we want to resume from the same previous connection
  545. if (!arraysAreEqual(this.previousConnectionId, remoteInfo.resume.id)) {
  546. this.$log.info('Cannot resume session: IDs of previous connection do not match');
  547. // Both sides should detect that -> recoverable
  548. return;
  549. }
  550. // Acknowledge chunks that have been received by the remote side
  551. try {
  552. this.previousChunkCache.acknowledge(remoteInfo.resume.sequenceNumber);
  553. } catch (error) {
  554. // Not recoverable
  555. this.$log.error(this.logTag, `Unable to resume session: ${error}`);
  556. this.failSession();
  557. return;
  558. }
  559. // Transfer the cache (filters chunks which should not be retransmitted)
  560. this.currentChunkCache.transfer(this.previousChunkCache.chunks);
  561. // Resend chunks
  562. for (const chunk of this.currentChunkCache.chunks) {
  563. this.sendChunk(chunk, true);
  564. }
  565. // Done, yay!
  566. this.$log.debug(this.logTag, 'Session resumed');
  567. }
  568. /**
  569. * Schedule (or reschedule) the connection ack to be sent.
  570. *
  571. * By default, a connection ack message will be sent after 10 seconds
  572. * (as defined by the protocol).
  573. */
  574. private scheduleConnectionAck(timeout: number = 10000): void {
  575. if (this.ackTimer !== null) {
  576. clearTimeout(this.ackTimer);
  577. }
  578. this.ackTimer = self.setTimeout(() => {
  579. // Send
  580. this._sendConnectionAck();
  581. }, timeout);
  582. }
  583. /**
  584. * For the WebRTC task, this is called when the DataChannel is open.
  585. * For the relayed data task, this is called once the connection is established.
  586. */
  587. private async onConnectionEstablished(resumeSession: boolean) {
  588. // Send connection info
  589. resumeSession = resumeSession &&
  590. this.previousConnectionId !== null &&
  591. this.previousIncomingChunkSequenceNumber !== null &&
  592. this.previousChunkCache !== null;
  593. this.$log.debug(this.logTag, 'Sending connection info');
  594. if (resumeSession) {
  595. this._sendConnectionInfo(
  596. this.currentConnectionId.buffer,
  597. this.previousConnectionId.buffer,
  598. this.previousIncomingChunkSequenceNumber.get(),
  599. );
  600. } else {
  601. this._sendConnectionInfo(this.currentConnectionId.buffer);
  602. }
  603. // Receive connection info
  604. // Note: We can receive the connectionInfo message here, or
  605. // null in case the remote side does not want to resume, or
  606. // an error which should fail the connection.
  607. let remoteInfo;
  608. try {
  609. remoteInfo = await this.connectionInfoFuture;
  610. } catch (error) {
  611. this.$log.error(this.logTag, error);
  612. this.failSession();
  613. return;
  614. }
  615. if (remoteInfo !== null) {
  616. this.$log.debug(this.logTag, 'Received connection info');
  617. // Validate connection ID
  618. if (!arraysAreEqual(this.currentConnectionId, remoteInfo.id)) {
  619. this.$log.error(this.logTag, 'Derived connection IDs do not match!');
  620. this.failSession();
  621. return;
  622. }
  623. // Try to resume the session if both local and remote want to resume
  624. if (resumeSession && remoteInfo.resume !== undefined) {
  625. this.resumeSession(remoteInfo);
  626. } else {
  627. this.$log.debug(this.logTag, `No resumption (local requested: ${resumeSession ? 'yes' : 'no'}, ` +
  628. `remote requested: ${remoteInfo.resume ? 'yes' : 'no'}`);
  629. }
  630. } else {
  631. this.$log.debug(this.logTag, 'Remote side does not want to resume');
  632. }
  633. // Invalidate the previous connection cache & id
  634. // Note: This MUST be done immediately after the session has been
  635. // resumed to prevent re-establishing a session of a connection
  636. // where the handshake has been started but not been completed.
  637. this.previousConnectionId = null;
  638. this.previousIncomingChunkSequenceNumber = null;
  639. this.previousChunkCache = null;
  640. // Schedule the periodic ack timer
  641. this.scheduleConnectionAck();
  642. // Reset fields and request initial data if not resuming the session
  643. const requiredInitializationSteps = [];
  644. if (!resumeSession) {
  645. requiredInitializationSteps.push(
  646. InitializationStep.ClientInfo,
  647. InitializationStep.Conversations,
  648. InitializationStep.Receivers,
  649. InitializationStep.Profile,
  650. );
  651. this._resetFields();
  652. }
  653. // Resolve startup promise once initialization is done
  654. if (this.startupPromise !== null) {
  655. this.runAfterInitializationSteps(requiredInitializationSteps, () => {
  656. this.stateService.updateConnectionBuildupState('done');
  657. this.startupPromise.resolve();
  658. this.startupPromise = null;
  659. this.startupDone = true;
  660. this._resetInitializationSteps();
  661. });
  662. }
  663. // Request initial data if not resuming the session
  664. if (!resumeSession) {
  665. this._requestInitialData();
  666. }
  667. // Fetch current version
  668. // Delay it to prevent the dialog from being closed by the messenger constructor,
  669. // which closes all open dialogs.
  670. this.$timeout(() => this.versionService.checkForUpdate(), 7000);
  671. // Notify state service about data loading
  672. this.stateService.updateConnectionBuildupState('loading');
  673. }
  674. /**
  675. * Handover done.
  676. *
  677. * This can either be a real handover to WebRTC (Android), or simply
  678. * when the relayed data task takes over (iOS).
  679. */
  680. private onHandover(resumeSession: boolean) {
  681. // Initialize NotificationService
  682. this.$log.debug(this.logTag, 'Initializing NotificationService...');
  683. this.notificationService.init();
  684. // Derive connection ID
  685. // Note: We need to make sure this is done before any ARP messages can be received
  686. const box = this.salty.encryptForPeer(new Uint8Array(0), WebClientService.CONNECTION_ID_NONCE);
  687. // Note: We explicitly copy the data here to be able to use the underlying buffer directly
  688. this.currentConnectionId = new Uint8Array(box.data);
  689. // If the WebRTC task was chosen, initialize the data channel
  690. if (this.chosenTask === threema.ChosenTask.WebRTC) {
  691. // Create secure data channel
  692. this.$log.debug(this.logTag, 'Create SecureDataChannel "' + WebClientService.DC_LABEL + '"...');
  693. this.secureDataChannel = this.pcHelper.createSecureDataChannel(
  694. WebClientService.DC_LABEL,
  695. (event: Event) => {
  696. this.$log.debug(this.logTag, 'SecureDataChannel open');
  697. this.onConnectionEstablished(resumeSession).catch((error) => {
  698. this.$log.error(this.logTag, 'Error during handshake:', error);
  699. });
  700. },
  701. );
  702. // Handle incoming messages
  703. this.secureDataChannel.onmessage = (ev: MessageEvent) => {
  704. const bytes = new Uint8Array(ev.data);
  705. this.handleIncomingMessageBytes(bytes);
  706. };
  707. this.secureDataChannel.onbufferedamountlow = (ev: Event) => {
  708. this.$log.debug('Secure data channel: Buffered amount low');
  709. };
  710. this.secureDataChannel.onerror = (e: ErrorEvent) => {
  711. this.$log.warn('Secure data channel: Error:', e.message);
  712. this.$log.debug(e);
  713. };
  714. this.secureDataChannel.onclose = (ev: Event) => {
  715. this.$log.warn('Secure data channel: Closed');
  716. };
  717. } else if (this.chosenTask === threema.ChosenTask.RelayedData) {
  718. // Handle messages directly
  719. this.relayedDataTask.on('data', (ev: saltyrtc.SaltyRTCEvent) => {
  720. this.receiveChunk(new Uint8Array(ev.data));
  721. });
  722. // The communication channel is now open! Fetch initial data
  723. this.onConnectionEstablished(resumeSession).catch((error) => {
  724. this.$log.error(this.logTag, 'Error during handshake:', error);
  725. });
  726. }
  727. }
  728. /**
  729. * A previously authenticated peer disconnected from the server.
  730. */
  731. private onPeerDisconnected(peerId: number) {
  732. switch (this.chosenTask) {
  733. case threema.ChosenTask.RelayedData:
  734. if (this.stateService.taskConnectionState === threema.TaskConnectionState.Connected) {
  735. this.stateService.updateTaskConnectionState(threema.TaskConnectionState.Reconnecting);
  736. } else {
  737. this.$log.debug(
  738. this.logTag,
  739. 'Ignoring peer-disconnected event (state is '
  740. + this.stateService.taskConnectionState + ')',
  741. );
  742. }
  743. break;
  744. default:
  745. this.$log.debug(
  746. this.logTag,
  747. 'Ignoring peer-disconnected event (chosen task is ' + this.chosenTask + ')',
  748. );
  749. }
  750. }
  751. /**
  752. * Send a push message to wake up the peer.
  753. * The push message will only be sent if the last push is less than 2 seconds ago.
  754. */
  755. private sendPush(wakeupType: threema.WakeupType): void {
  756. // Make sure not to flood the target device with pushes
  757. const minPushInterval = 2000;
  758. const now = new Date();
  759. if (this.lastPush !== null && (now.getTime() - this.lastPush.getTime()) < minPushInterval) {
  760. this.$log.debug(this.logTag,
  761. 'Skipping push, last push was requested less than ' + (minPushInterval / 1000) + 's ago');
  762. return;
  763. }
  764. this.lastPush = now;
  765. // Actually send the push notification
  766. this.pushService.sendPush(this.salty.permanentKeyBytes, wakeupType)
  767. .catch(() => this.$log.warn(this.logTag, 'Could not notify app!'))
  768. .then(() => {
  769. const wakeupTypeString = wakeupType === threema.WakeupType.FullReconnect ? 'reconnect' : 'wakeup';
  770. this.$log.debug(this.logTag, 'Requested app', wakeupTypeString, 'via', this.pushTokenType, 'push');
  771. this.$rootScope.$apply(() => {
  772. this.stateService.updateConnectionBuildupState('push');
  773. });
  774. });
  775. }
  776. /**
  777. * Start the webclient service.
  778. * Return a promise that resolves once connected.
  779. */
  780. public start(skipPush: boolean = false): ng.IPromise<any> {
  781. this.$log.debug(this.logTag, 'Starting WebClientService...');
  782. // Promise to track startup state
  783. this.startupPromise = this.$q.defer();
  784. this.startupDone = false;
  785. // Connect
  786. this.salty.connect();
  787. // If push service is available, notify app
  788. if (skipPush === true) {
  789. this.$log.debug(this.logTag, 'start(): Skipping push notification');
  790. } else if (this.pushService.isAvailable()) {
  791. this.sendPush(threema.WakeupType.FullReconnect);
  792. } else if (this.trustedKeyStore.hasTrustedKey()) {
  793. this.$log.debug(this.logTag, 'Push service not available');
  794. this.stateService.updateConnectionBuildupState('manual_start');
  795. }
  796. return this.startupPromise.promise;
  797. }
  798. /**
  799. * Stop the webclient service.
  800. *
  801. * This is a forced stop, meaning that all connections are being closed.
  802. *
  803. * @reason The disconnect reason.
  804. * @send will send a disconnect message to the remote peer containing the
  805. * disconnect reason if set to `true`.
  806. * @close will close the session (meaning all cached data will be
  807. * invalidated) if set to `true`. Note that the session will always be
  808. * closed in case `reason` indicates that the session is to be deleted,
  809. * has been replaced, a protocol error occurred or in case `redirect` has
  810. * been set to `true`.
  811. * @redirect will redirect to the welcome page if set to `true`.
  812. */
  813. public stop(
  814. reason: DisconnectReason,
  815. send: boolean,
  816. close: boolean,
  817. redirect: boolean,
  818. ): void {
  819. this.$log.info(this.logTag, 'Disconnecting...');
  820. let remove = false;
  821. // A redirect to the welcome page always implies a close
  822. if (redirect) {
  823. close = true;
  824. }
  825. // Session deleted: Force close and delete
  826. if (reason === DisconnectReason.SessionDeleted) {
  827. close = true;
  828. remove = true;
  829. }
  830. // Session replaced or error'ed: Force close
  831. if (reason === DisconnectReason.SessionReplaced || reason === DisconnectReason.SessionError) {
  832. close = true;
  833. }
  834. // Send disconnect reason to the remote peer if requested
  835. if (send && this.stateService.state === threema.GlobalConnectionState.Ok) {
  836. this._sendUpdate(WebClientService.SUB_TYPE_CONNECTION_DISCONNECT, false, undefined, {reason: reason});
  837. }
  838. // Stop ack timer
  839. if (this.ackTimer !== null) {
  840. clearTimeout(this.ackTimer);
  841. this.ackTimer = null;
  842. this.$log.debug(this.logTag, 'Timer stopped');
  843. }
  844. // Reset states
  845. this.stateService.reset();
  846. // Reset the unread count
  847. this.resetUnreadCount();
  848. // Clear stored data (trusted key, push token, etc) if deleting the session
  849. if (remove) {
  850. this.trustedKeyStore.clearTrustedKey();
  851. }
  852. // Invalidate and clear caches
  853. if (close) {
  854. this.previousConnectionId = null;
  855. this.currentConnectionId = null;
  856. this.previousIncomingChunkSequenceNumber = null;
  857. this.currentIncomingChunkSequenceNumber = new SequenceNumber(
  858. 0, WebClientService.SEQUENCE_NUMBER_MIN, WebClientService.SEQUENCE_NUMBER_MAX);
  859. this.previousChunkCache = null;
  860. this.currentChunkCache = null;
  861. this.pushService.reset();
  862. this.$log.debug(this.logTag, 'Session closed (cannot be resumed)');
  863. } else {
  864. this.previousChunkCache = this.currentChunkCache;
  865. this.$log.debug(this.logTag, 'Session remains open (can be resumed)');
  866. }
  867. // Close data channel
  868. if (this.secureDataChannel !== null) {
  869. this.$log.debug(this.logTag, 'Closing secure datachannel');
  870. this.secureDataChannel.close();
  871. }
  872. // Close SaltyRTC connection
  873. if (this.salty !== null) {
  874. this.$log.debug(this.logTag, 'Closing signaling');
  875. this.salty.disconnect();
  876. }
  877. // Close peer connection
  878. if (this.pcHelper !== null) {
  879. this.pcHelper.close();
  880. this.$log.debug(this.logTag, 'Peer connection closed');
  881. } else {
  882. this.$log.debug(this.logTag, 'Peer connection was null');
  883. }
  884. // Done, redirect now if requested
  885. if (redirect) {
  886. this.$timeout(() => {
  887. this.$state.go('welcome');
  888. }, 0);
  889. }
  890. }
  891. /**
  892. * Remove "turns:" servers from the ICE_SERVERS configuration
  893. * if at least one "turn:" server with tcp transport is in the list.
  894. */
  895. public skipIceTls(): void {
  896. this.$log.debug(this.logTag, 'Requested to remove TURNS server from ICE configuration');
  897. const allUrls = [].concat(...this.config.ICE_SERVERS.map((conf) => conf.urls));
  898. if (allUrls.some((url) => url.startsWith('turn:') && url.endsWith('=tcp'))) {
  899. // There's at least one TURN server with TCP transport in the list
  900. for (const server of this.config.ICE_SERVERS) {
  901. // Remove TLS entries
  902. server.urls = server.urls.filter((url) => !url.startsWith('turns:'));
  903. }
  904. } else {
  905. this.$log.debug(this.logTag, 'No fallback TURN TCP server present, keeping TURNS server');
  906. }
  907. }
  908. /**
  909. * Safari has issues with dual-stack TURN servers:
  910. * https://bugs.webkit.org/show_bug.cgi?id=173307#c13
  911. * As a workaround, replace ds-turn.threema.ch servers
  912. * in the ICE_SERVERS configuration with turn.threema.ch.
  913. */
  914. public skipIceDs(): void {
  915. this.$log.debug(this.logTag, 'Requested to replace DS servers in ICE configuration');
  916. const allUrls = [].concat(...this.config.ICE_SERVERS.map((conf) => conf.urls));
  917. if (allUrls.some((url) => url.includes('ds-turn.threema.ch'))) {
  918. for (const server of this.config.ICE_SERVERS) {
  919. // Replace dual stack entries
  920. server.urls = server.urls.map((url) => {
  921. return url.replace('ds-turn.threema.ch', 'turn.threema.ch');
  922. });
  923. }
  924. } else {
  925. this.$log.debug(this.logTag, 'No ds-turn ICE server present');
  926. }
  927. }
  928. /**
  929. * Mark a component as initialized
  930. */
  931. public registerInitializationStep(name: threema.InitializationStep) {
  932. if (this.initialized.has(name) ) {
  933. this.$log.warn(this.logTag, 'Initialization step "' + name + '" already registered');
  934. return;
  935. }
  936. this.$log.debug(this.logTag, 'Initialization step "' + name + '" done');
  937. this.initialized.add(name);
  938. // Check pending routines
  939. this.pendingInitializationStepRoutines = this.pendingInitializationStepRoutines.filter((routine) => {
  940. let isValid = true;
  941. for (const requiredStep of routine.requiredSteps) {
  942. if (!this.initialized.has(requiredStep)) {
  943. isValid = false;
  944. break;
  945. }
  946. }
  947. if (isValid) {
  948. this.$log.debug(this.logTag, 'Running routine after initialization "' + name + '" completed');
  949. routine.callback();
  950. }
  951. return !isValid;
  952. });
  953. }
  954. public setReceiverListener(listener: threema.ReceiverListener): void {
  955. this.receiverListener.push(listener);
  956. }
  957. /**
  958. * Send a connection info update.
  959. */
  960. private _sendConnectionInfo(connectionId: ArrayBuffer, resumeId?: ArrayBuffer, sequenceNumber?: number): void {
  961. const args = undefined;
  962. const data = {id: connectionId};
  963. if (resumeId !== undefined && sequenceNumber !== undefined) {
  964. (data as any).resume = {
  965. id: resumeId,
  966. sequenceNumber: sequenceNumber,
  967. };
  968. }
  969. this._sendUpdate(WebClientService.SUB_TYPE_CONNECTION_INFO, false, args, data);
  970. }
  971. /**
  972. * Request a connection ack update.
  973. */
  974. private _requestConnectionAck(): void {
  975. this._sendRequest(WebClientService.SUB_TYPE_CONNECTION_ACK, false);
  976. }
  977. /**
  978. * Send a connection ack update.
  979. */
  980. private _sendConnectionAck(): void {
  981. // Send the current incoming sequence number for chunks
  982. this._sendUpdate(WebClientService.SUB_TYPE_CONNECTION_ACK, false, undefined, {
  983. sequenceNumber: this.currentIncomingChunkSequenceNumber.get(),
  984. });
  985. // Re-schedule sending a connection ack
  986. this.scheduleConnectionAck();
  987. }
  988. /**
  989. * Send a client info request.
  990. */
  991. public requestClientInfo(): void {
  992. this.$log.debug('Sending client info request');
  993. const browser = this.browserService.getBrowser();
  994. const data: object = {
  995. [WebClientService.ARGUMENT_USER_AGENT]: navigator.userAgent,
  996. };
  997. if (browser.name) {
  998. data[WebClientService.ARGUMENT_BROWSER_NAME] = browser.name;
  999. }
  1000. if (browser.version) {
  1001. data[WebClientService.ARGUMENT_BROWSER_VERSION] = browser.version;
  1002. }
  1003. this._sendRequest(WebClientService.SUB_TYPE_CLIENT_INFO, true, undefined, data);
  1004. }
  1005. /**
  1006. * Send a receivers request.
  1007. */
  1008. public requestReceivers(): void {
  1009. this.$log.debug('Sending receivers request');
  1010. this._sendRequest(WebClientService.SUB_TYPE_RECEIVERS, true);
  1011. }
  1012. /**
  1013. * Send a conversation request.
  1014. */
  1015. public requestConversations(): void {
  1016. this.$log.debug('Sending conversation request');
  1017. this._sendRequest(WebClientService.SUB_TYPE_CONVERSATIONS, true, {
  1018. [WebClientService.ARGUMENT_MAX_SIZE]: WebClientService.AVATAR_LOW_MAX_SIZE,
  1019. });
  1020. }
  1021. /**
  1022. * Send a battery status request.
  1023. */
  1024. public requestBatteryStatus(): void {
  1025. this.$log.debug('Sending battery status request');
  1026. this._sendRequest(WebClientService.SUB_TYPE_BATTERY_STATUS, true);
  1027. }
  1028. /**
  1029. * Send a profile request.
  1030. */
  1031. public requestProfile(): void {
  1032. this.$log.debug('Sending profile request');
  1033. this._sendRequest(WebClientService.SUB_TYPE_PROFILE, true);
  1034. }
  1035. /**
  1036. * Send a message request for the specified receiver.
  1037. *
  1038. * This method will only be called when initializing a conversation in the
  1039. * webclient. It is used to download all existing messages.
  1040. *
  1041. * New messages are not requested this way, instead they are sent as a
  1042. * message update.
  1043. */
  1044. public requestMessages(receiver: threema.Receiver): string {
  1045. // If there are no more messages available, stop here.
  1046. if (!this.messages.hasMore(receiver)) {
  1047. this.messages.notify(receiver, this.$rootScope);
  1048. return null;
  1049. }
  1050. this.loadingMessages.set(receiver.type + receiver.id, true);
  1051. // Check if messages have already been requested
  1052. if (this.messages.isRequested(receiver)) {
  1053. return null;
  1054. }
  1055. // Get the reference msg id
  1056. const refMsgId = this.messages.getReferenceMsgId(receiver);
  1057. // Set requested
  1058. // TODO: Add timeout to reset flag
  1059. this.messages.setRequested(receiver);
  1060. // Create arguments
  1061. const args = {
  1062. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1063. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1064. } as any;
  1065. // If a reference msg id has been set, send it along
  1066. const msgId = this.messages.getReferenceMsgId(receiver);
  1067. if (msgId !== null) {
  1068. args[WebClientService.ARGUMENT_REFERENCE_MSG_ID] = msgId;
  1069. }
  1070. // Send request
  1071. this.$log.debug('Sending message request for', receiver.type, receiver.id,
  1072. 'with message id', msgId);
  1073. this._sendRequest(WebClientService.SUB_TYPE_MESSAGES, true, args);
  1074. return refMsgId;
  1075. }
  1076. /**
  1077. * Send an avatar request for the specified receiver.
  1078. */
  1079. public requestAvatar(receiver: threema.Receiver, highResolution: boolean): Promise<ArrayBuffer> {
  1080. // Check if the receiver has an avatar or the avatar already exists
  1081. const resolution = highResolution ? 'high' : 'low';
  1082. const receiverInfo = this.receivers.getData(receiver);
  1083. if (receiverInfo && receiverInfo.avatar && receiverInfo.avatar[resolution]) {
  1084. // Avatar already exists
  1085. // TODO: Do we get avatar changes via update?
  1086. return Promise.resolve(receiverInfo.avatar[resolution]);
  1087. }
  1088. // If we're requesting our own avatar, change type from "me" to "contact"
  1089. let receiverType = receiver.type;
  1090. if (receiverType === 'me') {
  1091. receiverType = 'contact';
  1092. }
  1093. // Create arguments and send request
  1094. const args = {
  1095. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiverType,
  1096. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1097. [WebClientService.ARGUMENT_AVATAR_HIGH_RESOLUTION]: highResolution,
  1098. } as any;
  1099. if (!highResolution) {
  1100. args[WebClientService.ARGUMENT_MAX_SIZE] = WebClientService.AVATAR_LOW_MAX_SIZE;
  1101. }
  1102. this.$log.debug('Sending', resolution, 'res avatar request for', receiver.type, receiver.id);
  1103. return this._sendRequestPromise(WebClientService.SUB_TYPE_AVATAR, true, args, 10000);
  1104. }
  1105. /**
  1106. * Send an thumbnail request for the specified receiver.
  1107. */
  1108. public requestThumbnail(receiver: threema.Receiver, message: threema.Message): Promise<any> {
  1109. // Check if the receiver has an avatar or the avatar already exists
  1110. if (message.thumbnail !== undefined && message.thumbnail.img !== undefined) {
  1111. return new Promise<any>((e) => {
  1112. e(message.thumbnail.img);
  1113. });
  1114. }
  1115. // Create arguments and send request
  1116. const args = {
  1117. [WebClientService.ARGUMENT_MESSAGE_ID]: message.id.toString(),
  1118. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1119. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1120. };
  1121. this.$log.debug('Sending', 'thumbnail request for', receiver.type, message.id);
  1122. return this._sendRequestPromise(WebClientService.SUB_TYPE_THUMBNAIL, true, args, 10000);
  1123. }
  1124. /**
  1125. * Request a blob.
  1126. */
  1127. public requestBlob(msgId: string, receiver: threema.Receiver): Promise<threema.BlobInfo> {
  1128. const cached = this.blobCache.get(msgId + receiver.type);
  1129. if (cached !== undefined) {
  1130. this.$log.debug(this.logTag, 'Use cached blob');
  1131. return new Promise((resolve) => {
  1132. resolve(cached);
  1133. });
  1134. }
  1135. const args = {
  1136. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1137. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1138. [WebClientService.ARGUMENT_MESSAGE_ID]: msgId,
  1139. };
  1140. this.$log.debug('Sending blob request for message', msgId);
  1141. return this._sendRequestPromise(WebClientService.SUB_TYPE_BLOB, true, args);
  1142. }
  1143. /**
  1144. * Mark a message as read.
  1145. */
  1146. public requestRead(receiver, newestMessage: threema.Message): void {
  1147. if (newestMessage.id === undefined) {
  1148. // Message that hasn't been sent yet
  1149. this.$log.warn(this.logTag, 'Called requestRead on a message without id');
  1150. return;
  1151. }
  1152. if (newestMessage.type === 'status') {
  1153. this.$log.warn(this.logTag, 'Called requestRead on a status message');
  1154. return;
  1155. }
  1156. // Create arguments and send request
  1157. const args = {
  1158. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1159. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1160. [WebClientService.ARGUMENT_MESSAGE_ID]: newestMessage.id.toString(),
  1161. };
  1162. this.$log.debug('Sending read request for', receiver.type, receiver.id, '(msg ' + newestMessage.id + ')');
  1163. this._sendRequest(WebClientService.SUB_TYPE_READ, true, args);
  1164. }
  1165. public requestContactDetail(contactReceiver: threema.ContactReceiver): Promise<any> {
  1166. return this._sendRequestPromise(WebClientService.SUB_TYPE_CONTACT_DETAIL, true, {
  1167. [WebClientService.ARGUMENT_IDENTITY]: contactReceiver.id,
  1168. });
  1169. }
  1170. /**
  1171. * Send a message to the specified receiver.
  1172. */
  1173. public sendMessage(
  1174. receiver,
  1175. type: threema.MessageContentType,
  1176. retransmit: boolean,
  1177. message: threema.MessageData,
  1178. ): Promise<Promise<any>> {
  1179. return new Promise<any> (
  1180. (resolve, reject) => {
  1181. // Try to load receiver object
  1182. const receiverObject = this.receivers.getData(receiver);
  1183. // Check blocked flag
  1184. if (isContactReceiver(receiverObject) && receiverObject.isBlocked) {
  1185. return reject(this.$translate.instant('error.CONTACT_BLOCKED'));
  1186. }
  1187. // Decide on subtype
  1188. let subType;
  1189. switch (type) {
  1190. case 'text':
  1191. subType = WebClientService.SUB_TYPE_TEXT_MESSAGE;
  1192. const textMessage = message as threema.TextMessageData;
  1193. const msgLength = textMessage.text.length;
  1194. // Ignore empty text messages
  1195. if (msgLength === 0) {
  1196. return reject();
  1197. }
  1198. // Ignore text messages that are too long.
  1199. if (msgLength > WebClientService.MAX_TEXT_LENGTH) {
  1200. return reject(this.$translate.instant('error.TEXT_TOO_LONG', {
  1201. max: WebClientService.MAX_TEXT_LENGTH,
  1202. }));
  1203. }
  1204. break;
  1205. case 'file':
  1206. // Validate max file size
  1207. if (this.chosenTask === threema.ChosenTask.WebRTC) {
  1208. if ((message as threema.FileMessageData).size > WebClientService.MAX_FILE_SIZE_WEBRTC) {
  1209. return reject(this.$translate.instant('error.FILE_TOO_LARGE_WEB'));
  1210. }
  1211. } else {
  1212. if ((message as threema.FileMessageData).size > this.clientInfo.capabilities.maxFileSize) {
  1213. return reject(this.$translate.instant('error.FILE_TOO_LARGE', {
  1214. maxmb: Math.floor(this.clientInfo.capabilities.maxFileSize / 1024 / 1024),
  1215. }));
  1216. }
  1217. }
  1218. // Determine required feature mask
  1219. let requiredFeature: ContactReceiverFeature = ContactReceiverFeature.FILE;
  1220. let invalidFeatureMessage = 'error.FILE_MESSAGES_NOT_SUPPORTED';
  1221. if ((message as threema.FileMessageData).sendAsFile !== true) {
  1222. // check mime type
  1223. const mime = (message as threema.FileMessageData).fileType;
  1224. if (this.mimeService.isAudio(mime)) {
  1225. requiredFeature = ContactReceiverFeature.AUDIO;
  1226. invalidFeatureMessage = 'error.AUDIO_MESSAGES_NOT_SUPPORTED';
  1227. } else if (this.mimeService.isImage(mime)
  1228. || this.mimeService.isVideo(mime)) {
  1229. requiredFeature = ContactReceiverFeature.AUDIO;
  1230. invalidFeatureMessage = 'error.MESSAGE_NOT_SUPPORTED';
  1231. }
  1232. }
  1233. subType = WebClientService.SUB_TYPE_FILE_MESSAGE;
  1234. // check receiver
  1235. switch (receiver.type) {
  1236. case 'distributionList':
  1237. return reject(this.$translate.instant(invalidFeatureMessage, {
  1238. receiverName: receiver.displayName}));
  1239. case 'group':
  1240. const unsupportedMembers = [];
  1241. const group = this.groups.get(receiver.id);
  1242. if (group === undefined) {
  1243. return reject();
  1244. }
  1245. group.members.forEach((identity: string) => {
  1246. if (identity !== this.me.id) {
  1247. // tslint:disable-next-line: no-shadowed-variable
  1248. const contact = this.contacts.get(identity);
  1249. if (contact === undefined
  1250. || !hasFeature(contact, requiredFeature, this.$log)) {
  1251. unsupportedMembers.push(contact.displayName);
  1252. }
  1253. }
  1254. });
  1255. if (unsupportedMembers.length > 0) {
  1256. return reject(this.$translate.instant(invalidFeatureMessage, {
  1257. receiverName: unsupportedMembers.join(',')}));
  1258. }
  1259. break;
  1260. case 'contact':
  1261. const contact = this.contacts.get(receiver.id);
  1262. if (contact === undefined) {
  1263. this.$log.error('Cannot retrieve contact');
  1264. return reject(this.$translate.instant('error.ERROR_OCCURRED'));
  1265. } else if (!hasFeature(contact, requiredFeature, this.$log)) {
  1266. this.$log.debug('Cannot send message: Feature level mismatch:',
  1267. contact.featureMask, 'does not include', requiredFeature);
  1268. return reject(this.$translate.instant(invalidFeatureMessage, {
  1269. receiverName: contact.displayName}));
  1270. }
  1271. break;
  1272. default:
  1273. return reject();
  1274. }
  1275. break;
  1276. default:
  1277. this.$log.warn('Invalid message type:', type);
  1278. return reject();
  1279. }
  1280. const temporaryMessage = this.messageService.createTemporary(receiver, type, message);
  1281. this.messages.addNewer(receiver, [temporaryMessage]);
  1282. const args = {
  1283. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1284. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1285. [WebClientService.ARGUMENT_TEMPORARY_ID]: temporaryMessage.temporaryId,
  1286. };
  1287. // Send message and handling error promise
  1288. this._sendCreatePromise(subType, retransmit, args, message).catch((error) => {
  1289. this.$log.error('Error sending message:', error);
  1290. // Remove temporary message
  1291. this.messages.removeTemporary(receiver, temporaryMessage.temporaryId);
  1292. // Determine error message
  1293. let errorMessage;
  1294. switch (error) {
  1295. case 'file_too_large':
  1296. errorMessage = this.$translate.instant('error.FILE_TOO_LARGE_GENERIC');
  1297. break;
  1298. case 'blocked':
  1299. errorMessage = this.$translate.instant('error.CONTACT_BLOCKED');
  1300. break;
  1301. default:
  1302. errorMessage = this.$translate.instant('error.ERROR_OCCURRED');
  1303. }
  1304. // Show alert
  1305. this.alerts.push({
  1306. source: 'sendMessage',
  1307. type: 'alert',
  1308. message: errorMessage,
  1309. } as threema.Alert);
  1310. });
  1311. resolve();
  1312. });
  1313. }
  1314. /**
  1315. * Send a message a ack/decline message
  1316. */
  1317. public ackMessage(receiver, message: threema.Message, acknowledged: boolean = true): void {
  1318. // Ignore empty text messages
  1319. // TODO check into a util class
  1320. if (message === null
  1321. || message === undefined
  1322. || message.isOutbox) {
  1323. return;
  1324. }
  1325. const args = {
  1326. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1327. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1328. [WebClientService.ARGUMENT_MESSAGE_ID]: message.id.toString(),
  1329. [WebClientService.ARGUMENT_MESSAGE_ACKNOWLEDGED]: acknowledged,
  1330. };
  1331. this._sendRequest(WebClientService.SUB_TYPE_ACK, true, args);
  1332. }
  1333. /**
  1334. * Delete a message.
  1335. */
  1336. public deleteMessage(receiver, message: threema.Message): void {
  1337. // Ignore empty text messages
  1338. if (message === null || message === undefined) {
  1339. return;
  1340. }
  1341. const args = {
  1342. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1343. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1344. [WebClientService.ARGUMENT_MESSAGE_ID]: message.id.toString(),
  1345. };
  1346. this._sendDeletePromise(WebClientService.SUB_TYPE_MESSAGE, true, args);
  1347. }
  1348. public sendMeIsTyping(receiver: threema.ContactReceiver, isTyping: boolean): void {
  1349. const args = {[WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id};
  1350. const data = {[WebClientService.ARGUMENT_IS_TYPING]: isTyping};
  1351. this._sendUpdate(WebClientService.SUB_TYPE_TYPING, false, args, data);
  1352. }
  1353. public sendKeyPersisted(): void {
  1354. this._sendRequest(WebClientService.SUB_TYPE_KEY_PERSISTED, true);
  1355. }
  1356. /**
  1357. * Add a contact receiver.
  1358. */
  1359. public addContact(threemaId: string): Promise<threema.ContactReceiver> {
  1360. const args = null;
  1361. const data = {
  1362. [WebClientService.ARGUMENT_IDENTITY]: threemaId,
  1363. };
  1364. return this._sendCreatePromise(WebClientService.SUB_TYPE_CONTACT, true, args, data);
  1365. }
  1366. /**
  1367. * Modify a contact name or a avatar
  1368. */
  1369. public modifyContact(threemaId: string,
  1370. firstName?: string,
  1371. lastName?: string,
  1372. avatar?: ArrayBuffer): Promise<threema.ContactReceiver> {
  1373. // Prepare payload data
  1374. const data = {};
  1375. if (firstName !== undefined) {
  1376. data[WebClientService.ARGUMENT_FIRST_NAME] = firstName;
  1377. }
  1378. if (lastName !== undefined) {
  1379. data[WebClientService.ARGUMENT_LAST_NAME] = lastName;
  1380. }
  1381. if (avatar !== undefined) {
  1382. data[WebClientService.ARGUMENT_AVATAR] = avatar;
  1383. }
  1384. // Get contact
  1385. const contact: threema.ContactReceiver = this.contacts.get(threemaId);
  1386. // If no changes happened, resolve the promise immediately.
  1387. if (Object.keys(data).length === 0) {
  1388. this.$log.warn(this.logTag, 'Trying to modify contact without any changes');
  1389. return Promise.resolve(contact);
  1390. }
  1391. // Send update
  1392. const args = {
  1393. [WebClientService.ARGUMENT_IDENTITY]: threemaId,
  1394. };
  1395. const promise = this._sendUpdatePromise(WebClientService.SUB_TYPE_CONTACT, true, args, data);
  1396. // If necessary, force an avatar reload
  1397. if (avatar !== undefined) {
  1398. this.contacts.get(threemaId).avatar = {};
  1399. this.requestAvatar(contact, false);
  1400. }
  1401. return promise;
  1402. }
  1403. /**
  1404. * Create a group receiver.
  1405. */
  1406. public createGroup(
  1407. members: string[],
  1408. name: string = null,
  1409. avatar?: ArrayBuffer,
  1410. ): Promise<threema.GroupReceiver> {
  1411. const args = null;
  1412. const data = {
  1413. [WebClientService.ARGUMENT_MEMBERS]: members,
  1414. [WebClientService.ARGUMENT_NAME]: name,
  1415. } as object;
  1416. if (avatar !== undefined) {
  1417. data[WebClientService.ARGUMENT_AVATAR] = avatar;
  1418. }
  1419. return this._sendCreatePromise(WebClientService.SUB_TYPE_GROUP, true, args, data);
  1420. }
  1421. /**
  1422. * Modify a group receiver.
  1423. */
  1424. public modifyGroup(id: string,
  1425. members: string[],
  1426. name?: string,
  1427. avatar?: ArrayBuffer): Promise<threema.GroupReceiver> {
  1428. // Prepare payload data
  1429. const data = {
  1430. [WebClientService.ARGUMENT_MEMBERS]: members,
  1431. } as object;
  1432. if (name !== undefined) {
  1433. data[WebClientService.ARGUMENT_NAME] = name;
  1434. }
  1435. if (avatar !== undefined) {
  1436. data[WebClientService.ARGUMENT_AVATAR] = avatar;
  1437. }
  1438. // Send update
  1439. const args = {
  1440. [WebClientService.ARGUMENT_RECEIVER_ID]: id,
  1441. };
  1442. const promise = this._sendUpdatePromise(WebClientService.SUB_TYPE_GROUP, true, args, data);
  1443. // If necessary, reset avatar to force a avatar reload
  1444. if (avatar !== undefined) {
  1445. this.groups.get(id).avatar = {};
  1446. }
  1447. return promise;
  1448. }
  1449. public leaveGroup(group: threema.GroupReceiver): Promise<any> {
  1450. if (group === null || group === undefined || !group.access.canLeave) {
  1451. return new Promise((resolve, reject) => reject('not allowed'));
  1452. }
  1453. const args = {
  1454. [WebClientService.ARGUMENT_RECEIVER_ID]: group.id,
  1455. [WebClientService.ARGUMENT_DELETE_TYPE]: WebClientService.DELETE_GROUP_TYPE_LEAVE,
  1456. };
  1457. return this._sendDeletePromise(WebClientService.SUB_TYPE_GROUP, true, args);
  1458. }
  1459. public deleteGroup(group: threema.GroupReceiver): Promise<any> {
  1460. if (group === null || group === undefined || !group.access.canDelete) {
  1461. return new Promise<any> (
  1462. (resolve, reject) => {
  1463. reject('not allowed');
  1464. });
  1465. }
  1466. const args = {
  1467. [WebClientService.ARGUMENT_RECEIVER_ID]: group.id,
  1468. [WebClientService.ARGUMENT_DELETE_TYPE]: WebClientService.DELETE_GROUP_TYPE_DELETE,
  1469. };
  1470. return this._sendDeletePromise(WebClientService.SUB_TYPE_GROUP, true, args);
  1471. }
  1472. /**
  1473. * Force-sync a group.
  1474. */
  1475. public syncGroup(group: threema.GroupReceiver): Promise<any> {
  1476. if (group === null || group === undefined || !group.access.canSync) {
  1477. return Promise.reject('not allowed');
  1478. }
  1479. const args = {
  1480. [WebClientService.ARGUMENT_RECEIVER_ID]: group.id,
  1481. };
  1482. return this._sendRequestPromise(WebClientService.SUB_TYPE_GROUP_SYNC, true, args, 10000);
  1483. }
  1484. /**
  1485. * Create a new distribution list receiver.
  1486. */
  1487. public createDistributionList(
  1488. members: string[],
  1489. name: string = null,
  1490. ): Promise<threema.DistributionListReceiver> {
  1491. const args = null;
  1492. const data = {
  1493. [WebClientService.ARGUMENT_MEMBERS]: members,
  1494. [WebClientService.ARGUMENT_NAME]: name,
  1495. };
  1496. return this._sendCreatePromise(WebClientService.SUB_TYPE_DISTRIBUTION_LIST, true, args, data);
  1497. }
  1498. public modifyDistributionList(id: string,
  1499. members: string[],
  1500. name: string = null): Promise<threema.DistributionListReceiver> {
  1501. const data = {
  1502. [WebClientService.ARGUMENT_MEMBERS]: members,
  1503. [WebClientService.ARGUMENT_NAME]: name,
  1504. } as any;
  1505. return this._sendUpdatePromise(WebClientService.SUB_TYPE_DISTRIBUTION_LIST, true, {
  1506. [WebClientService.ARGUMENT_RECEIVER_ID]: id,
  1507. }, data);
  1508. }
  1509. public deleteDistributionList(distributionList: threema.DistributionListReceiver): Promise<any> {
  1510. if (distributionList === null || distributionList === undefined || !distributionList.access.canDelete) {
  1511. return new Promise((resolve, reject) => reject('not allowed'));
  1512. }
  1513. const args = {
  1514. [WebClientService.ARGUMENT_RECEIVER_ID]: distributionList.id,
  1515. };
  1516. return this._sendDeletePromise(WebClientService.SUB_TYPE_DISTRIBUTION_LIST, true, args);
  1517. }
  1518. /**
  1519. * Remove all messages of a receiver
  1520. * @param {threema.Receiver} receiver
  1521. * @returns {Promise<any>}
  1522. */
  1523. public cleanReceiverConversation(receiver: threema.Receiver): Promise<any> {
  1524. if (receiver === null || receiver === undefined) {
  1525. return new Promise((resolve, reject) => reject('invalid receiver'));
  1526. }
  1527. const args = {
  1528. [WebClientService.ARGUMENT_RECEIVER_TYPE]: receiver.type,
  1529. [WebClientService.ARGUMENT_RECEIVER_ID]: receiver.id,
  1530. };
  1531. return this._sendDeletePromise(WebClientService.SUB_TYPE_CLEAN_RECEIVER_CONVERSATION, true, args);
  1532. }
  1533. /**
  1534. * Modify own profile.
  1535. */
  1536. public modifyProfile(nickname?: string,
  1537. avatar?: ArrayBuffer): Promise<null> {
  1538. // Prepare payload data
  1539. const data = {};
  1540. if (nickname !== undefined && nickname !== null) {
  1541. data[WebClientService.ARGUMENT_NICKNAME] = nickname;
  1542. }
  1543. if (avatar !== undefined) {
  1544. data[WebClientService.ARGUMENT_AVATAR] = avatar;
  1545. }
  1546. // If no changes happened, resolve the promise immediately.
  1547. if (Object.keys(data).length === 0) {
  1548. this.$log.warn(this.logTag, 'Trying to modify profile without any changes');
  1549. return Promise.resolve(null);
  1550. }
  1551. // Send update, get back promise
  1552. return this._sendUpdatePromise(WebClientService.SUB_TYPE_PROFILE, true, null, data);
  1553. }
  1554. /**
  1555. * Return whether the specified contact is currently typing.
  1556. */
  1557. public isTyping(contact: threema.ContactReceiver): boolean {
  1558. return this.typing.isTyping(contact);
  1559. }
  1560. /**
  1561. * Return the curring quoted message model
  1562. */
  1563. public getQuote(receiver: threema.Receiver): threema.Quote {
  1564. return this.drafts.getQuote(receiver);
  1565. }
  1566. /**
  1567. * Set or remove (if message is null) a quoted message model.
  1568. */
  1569. public setQuote(receiver: threema.Receiver, message: threema.Message = null): void {
  1570. // Remove current quote
  1571. this.drafts.removeQuote(receiver);
  1572. if (message !== null) {
  1573. const quoteText = this.messageService.getQuoteText(message);
  1574. if (quoteText !== undefined && quoteText !== null) {
  1575. const quote = {
  1576. identity: message.isOutbox ? this.me.id : message.partnerId,
  1577. text: quoteText,
  1578. } as threema.Quote;
  1579. this.drafts.setQuote(receiver, quote);
  1580. this.$rootScope.$broadcast('onQuoted', {
  1581. receiver: receiver,
  1582. quote: quote,
  1583. });
  1584. }
  1585. }
  1586. }
  1587. /**
  1588. * Set or remove (if string is null) a draft message
  1589. */
  1590. public setDraft(receiver: threema.Receiver, message: string = null): void {
  1591. if (message === null || message.trim().length === 0) {
  1592. this.drafts.removeText(receiver);
  1593. } else {
  1594. this.drafts.setText(receiver, message.trim());
  1595. }
  1596. }
  1597. /**
  1598. * return draft text
  1599. */
  1600. public getDraft(receiver: threema.Receiver): string {
  1601. return this.drafts.getText(receiver);
  1602. }
  1603. /**
  1604. * Reset data related to initialization.
  1605. */
  1606. private _resetInitializationSteps(): void {
  1607. this.$log.debug(this.logTag, 'Reset initialization steps');
  1608. this.initialized.clear();
  1609. this.pendingInitializationStepRoutines = [];
  1610. }
  1611. /**
  1612. * Reset data fields.
  1613. */
  1614. private _resetFields(): void {
  1615. // Reset initialization data
  1616. this._resetInitializationSteps();
  1617. // Create container instances
  1618. this.receivers = this.container.createReceivers();
  1619. this.conversations = this.container.createConversations();
  1620. this.messages = this.container.createMessages();
  1621. this.typingInstance = this.container.createTyping();
  1622. // Add converters (pre-processors)
  1623. this.messages.converter = this.container.Converter.unicodeToEmoji;
  1624. this.conversations.setConverter(this.container.Converter.addReceiverToConversation(this.receivers));
  1625. // Add filters
  1626. this.conversations.setFilter(this.container.Filters.hasData(this.receivers));
  1627. }
  1628. private _requestInitialData(): void {
  1629. // If all conversations are reloaded, clear the message cache
  1630. // to get in sync (we don't know if a message was removed, updated etc..)
  1631. this.messages.clear(this.$rootScope);
  1632. // Request initial data
  1633. this.requestClientInfo();
  1634. this.requestProfile();
  1635. this.requestReceivers();
  1636. this.requestConversations();
  1637. this.requestBatteryStatus();
  1638. }
  1639. /**
  1640. * Return a PromiseRequestResult with success=false and the specified error code.
  1641. */
  1642. private promiseRequestError(error: string): threema.PromiseRequestResult<undefined> {
  1643. return {
  1644. success: false,
  1645. error: error,
  1646. };
  1647. }
  1648. private _receiveResponseConfirmAction(message: threema.WireMessage): threema.PromiseRequestResult<void> {
  1649. this.$log.debug('Received receiver response');
  1650. // Unpack and validate args
  1651. const args = message.args;
  1652. if (args === undefined) {
  1653. this.$log.error('Invalid confirmAction response, args missing');
  1654. return this.promiseRequestError('invalidResponse');
  1655. }
  1656. switch (args[WebClientService.ARGUMENT_SUCCESS]) {
  1657. case true:
  1658. return { success: true };
  1659. case false:
  1660. return this.promiseRequestError(args[WebClientService.ARGUMENT_ERROR]);
  1661. default:
  1662. this.$log.error('Invalid confirmAction response, success field is not a boolean');
  1663. return this.promiseRequestError('invalidResponse');
  1664. }
  1665. }
  1666. private _receiveResponseReceivers(message: threema.WireMessage): void {
  1667. this.$log.debug('Received receivers response');
  1668. // Unpack and validate data
  1669. const data = message.data;
  1670. if (data === undefined) {
  1671. this.$log.warn('Invalid receivers response, data missing');
  1672. return;
  1673. }
  1674. // Store receivers
  1675. this.sortContacts(data.contact);
  1676. this.receivers.set(data);
  1677. this.registerInitializationStep(InitializationStep.Receivers);
  1678. }
  1679. private _receiveResponseContactDetail(message: threema.WireMessage): threema.PromiseRequestResult<any> {
  1680. this.$log.debug('Received contact detail');
  1681. // Unpack and validate data
  1682. const args = message.args;
  1683. const data = message.data;
  1684. if (args === undefined || data === undefined) {
  1685. this.$log.error('Invalid contact response, args or data missing');
  1686. return this.promiseRequestError('invalidResponse');
  1687. }
  1688. switch (args[WebClientService.ARGUMENT_SUCCESS]) {
  1689. case true:
  1690. const contactReceiver = this.receivers.contacts
  1691. .get(args[WebClientService.ARGUMENT_IDENTITY]) as threema.ContactReceiver;
  1692. if (data[WebClientService.SUB_TYPE_RECEIVER]) {
  1693. contactReceiver.systemContact =
  1694. data[WebClientService.SUB_TYPE_RECEIVER][WebClientService.ARGUMENT_SYSTEM_CONTACT];
  1695. }
  1696. return {
  1697. success: true,
  1698. data: contactReceiver,
  1699. };
  1700. case false:
  1701. return this.promiseRequestError(args[WebClientService.ARGUMENT_ERROR]);
  1702. default:
  1703. this.$log.error('Invalid contact response, success field is not a boolean');
  1704. return this.promiseRequestError('invalidResponse');
  1705. }
  1706. }
  1707. private _receiveAlert(message: threema.WireMessage): void {
  1708. this.$log.debug('Received alert from device');
  1709. this.alerts.push({
  1710. source: message.args.source,
  1711. type: message.args.type,
  1712. message: message.data.message,
  1713. } as threema.Alert);
  1714. }
  1715. /**
  1716. * A connectionAck request arrived.
  1717. */
  1718. private _receiveRequestConnectionAck(message: threema.WireMessage) {
  1719. this._sendConnectionAck();
  1720. }
  1721. /**
  1722. * A connectionAck update arrived.
  1723. */
  1724. private _receiveUpdateConnectionAck(message: threema.WireMessage) {
  1725. if (!hasValue(message.data)) {
  1726. this.$log.warn(this.logTag, 'Invalid connectionAck message: data missing');
  1727. return;
  1728. }
  1729. if (!hasValue(message.data.sequenceNumber)) {
  1730. this.$log.warn(this.logTag, 'Invalid connectionAck message: sequenceNumber missing');
  1731. return;
  1732. }
  1733. const sequenceNumber = message.data.sequenceNumber;
  1734. // Acknowledge chunks
  1735. const size = this.currentChunkCache.size;
  1736. try {
  1737. this.currentChunkCache.acknowledge(sequenceNumber);
  1738. } catch (error) {
  1739. this.$log.error(this.logTag, error);
  1740. this.failSession();
  1741. return;
  1742. }
  1743. this.$log.debug(`Chunk cache size ${size} -> ${this.currentChunkCache.size}`);
  1744. // Clear pending ack requests
  1745. if (this.pendingAckRequest !== null && sequenceNumber >= this.pendingAckRequest) {
  1746. this.pendingAckRequest = null;
  1747. }
  1748. }
  1749. /**
  1750. * A connectionDisconnect message arrived.
  1751. */
  1752. private _receiveConnectionDisconnect(message: threema.WireMessage) {
  1753. this.$log.debug(this.logTag, 'Received connectionDisconnect from device');
  1754. if (!hasValue(message.data) || !hasValue(message.data.reason)) {
  1755. this.$log.warn(this.logTag, 'Invalid connectionDisconnect message: data or reason missing');
  1756. return;
  1757. }
  1758. const reason = message.data.reason;
  1759. this.$log.debug(this.logTag, `Disconnecting requested (reason: ${reason})`);
  1760. let alertMessage: string;
  1761. switch (reason) {
  1762. case DisconnectReason.SessionStopped:
  1763. alertMessage = 'connection.SESSION_STOPPED';
  1764. break;
  1765. case DisconnectReason.SessionDeleted:
  1766. alertMessage = 'connection.SESSION_DELETED';
  1767. break;
  1768. case DisconnectReason.WebclientDisabled:
  1769. alertMessage = 'connection.WEBCLIENT_DISABLED';
  1770. break;
  1771. case DisconnectReason.SessionReplaced:
  1772. alertMessage = 'connection.SESSION_REPLACED';
  1773. break;
  1774. case DisconnectReason.SessionError:
  1775. alertMessage = 'connection.SESSION_ERROR';
  1776. break;
  1777. default:
  1778. alertMessage = 'connection.SESSION_ERROR';
  1779. this.$log.error(this.logTag, 'Unknown disconnect reason:', reason);
  1780. break;
  1781. }
  1782. // Stop and show an alert on the welcome page
  1783. this.stop(reason, false, true, true);
  1784. this.showAlert(alertMessage);
  1785. }
  1786. /**
  1787. * A connectionInfo message arrived.
  1788. */
  1789. private _receiveConnectionInfo(message: threema.WireMessage) {
  1790. this.$log.debug('Received connectionInfo from device');
  1791. if (!hasValue(message.data)) {
  1792. this.connectionInfoFuture.reject('Invalid connectionInfo message: data missing');
  1793. return;
  1794. }
  1795. if (!hasValue(message.data.id)) {
  1796. this.connectionInfoFuture.reject('Invalid connectionInfo message: data.id is missing');
  1797. return;
  1798. }
  1799. if (!(message.data.id instanceof ArrayBuffer)) {
  1800. this.connectionInfoFuture.reject('Invalid connectionInfo message: data.id is of invalid type');
  1801. return;
  1802. }
  1803. const resume = message.data.resume;
  1804. if (resume !== undefined) {
  1805. if (!hasValue(resume.id)) {
  1806. this.connectionInfoFuture.reject('Invalid connectionInfo message: data.resume.id is missing');
  1807. return;
  1808. }
  1809. if (!hasValue(resume.sequenceNumber)) {
  1810. const error = 'Invalid connectionInfo message: data.resume.sequenceNumber is missing';
  1811. this.connectionInfoFuture.reject(error);
  1812. return;
  1813. }
  1814. if (!(resume.id instanceof ArrayBuffer)) {
  1815. this.connectionInfoFuture.reject('Invalid connectionInfo message: data.resume.id is of invalid type');
  1816. return;
  1817. }
  1818. if (resume.sequenceNumber < 0 || resume.sequenceNumber > WebClientService.SEQUENCE_NUMBER_MAX) {
  1819. const error = 'Invalid connectionInfo message: data.resume.sequenceNumber is invalid';
  1820. this.connectionInfoFuture.reject(error);
  1821. return;
  1822. }
  1823. this.connectionInfoFuture.resolve(message);
  1824. } else {
  1825. this.connectionInfoFuture.resolve(null);
  1826. }
  1827. }
  1828. /**
  1829. * Process an incoming contact, group or distributionList response.
  1830. */
  1831. private _receiveResponseReceiver<T extends threema.Receiver>(
  1832. message: threema.WireMessage,
  1833. receiverType: threema.ReceiverType,
  1834. ): threema.PromiseRequestResult<T> {
  1835. this.$log.debug('Received ' + receiverType + ' response');
  1836. // Unpack and validate data
  1837. const args = message.args;
  1838. const data = message.data;
  1839. if (args === undefined) {
  1840. this.$log.error('Invalid ' + receiverType + ' response, args or data missing');
  1841. return this.promiseRequestError('invalidResponse');
  1842. }
  1843. switch (args[WebClientService.ARGUMENT_SUCCESS]) {
  1844. case true:
  1845. if (data === undefined) {
  1846. this.$log.error('Invalid ' + receiverType + ' response, args or data missing');
  1847. return this.promiseRequestError('invalidResponse');
  1848. }
  1849. // Get receiver instance
  1850. const receiver = data[WebClientService.SUB_TYPE_RECEIVER] as T;
  1851. // Update receiver type if not set
  1852. if (receiver.type === undefined) {
  1853. receiver.type = receiverType;
  1854. }
  1855. // Extend models
  1856. if (isContactReceiver(receiver)) {
  1857. this.receivers.extendContact(receiver);
  1858. } else if (isGroupReceiver(receiver)) {
  1859. this.receivers.extendGroup(receiver);
  1860. } else if (isDistributionListReceiver(receiver)) {
  1861. this.receivers.extendDistributionList(receiver);
  1862. }
  1863. return {
  1864. success: true,
  1865. data: receiver,
  1866. };
  1867. case false:
  1868. return this.promiseRequestError(args[WebClientService.ARGUMENT_ERROR]);
  1869. default:
  1870. this.$log.error('Invalid ' + receiverType + ' response, success field is not a boolean');
  1871. return this.promiseRequestError('invalidResponse');
  1872. }
  1873. }
  1874. /**
  1875. * Handle new or modified contacts.
  1876. */
  1877. private _receiveUpdateContact(message: threema.WireMessage):
  1878. threema.PromiseRequestResult<threema.ContactReceiver> {
  1879. return this._receiveResponseReceiver(message, 'contact');
  1880. }
  1881. /**
  1882. * Handle new or modified groups.
  1883. */
  1884. private _receiveResponseGroup(message: threema.WireMessage):
  1885. threema.PromiseRequestResult<threema.GroupReceiver> {
  1886. return this._receiveResponseReceiver(message, 'group');
  1887. }
  1888. /**
  1889. * Handle new or modified distribution lists.
  1890. */
  1891. private _receiveResponseDistributionList(message: threema.WireMessage):
  1892. threema.PromiseRequestResult<threema.DistributionListReceiver> {
  1893. return this._receiveResponseReceiver(message, 'distributionList');
  1894. }
  1895. private _receiveResponseCreateMessage(message: threema.WireMessage): threema.PromiseRequestResult<string> {
  1896. this.$log.debug('Received create message response');
  1897. // Unpack data and arguments
  1898. const args = message.args;
  1899. const data = message.data;
  1900. if (args === undefined || data === undefined) {
  1901. this.$log.warn('Invalid create message received, arguments or data missing');
  1902. return this.promiseRequestError('invalidResponse');
  1903. }
  1904. switch (args[WebClientService.ARGUMENT_SUCCESS]) {
  1905. case true:
  1906. const receiverType: threema.ReceiverType = args[WebClientService.ARGUMENT_RECEIVER_TYPE];
  1907. const receiverId: string = args[WebClientService.ARGUMENT_RECEIVER_ID];
  1908. const temporaryId: string = args[WebClientService.ARGUMENT_TEMPORARY_ID];
  1909. const messageId: string = data[WebClientService.ARGUMENT_MESSAGE_ID];
  1910. if (receiverType === undefined || receiverId === undefined ||
  1911. temporaryId === undefined || messageId === undefined) {
  1912. this.$log.warn('Invalid create received [type, id, temporaryId arg ' +
  1913. 'or messageId in data missing]');
  1914. return this.promiseRequestError('invalidResponse');
  1915. }
  1916. this.messages.bindTemporaryToMessageId(
  1917. {
  1918. type: receiverType,
  1919. id: receiverId,
  1920. } as threema.Receiver,
  1921. temporaryId,
  1922. messageId,
  1923. );
  1924. return { success: true, data: messageId };
  1925. case false:
  1926. return this.promiseRequestError(args[WebClientService.ARGUMENT_ERROR]);
  1927. default:
  1928. this.$log.error('Invalid create message response, success field is not a boolean');
  1929. return this.promiseRequestError('invalidResponse');
  1930. }
  1931. }
  1932. private _receiveResponseConversations(message: threema.WireMessage) {
  1933. this.$log.debug('Received conversations response');
  1934. const data = message.data as threema.Conversation[];
  1935. if (data === undefined) {
  1936. this.$log.warn('Invalid conversation response, data missing');
  1937. } else {
  1938. // If a avatar was set on a conversation, convert and copy to the receiver
  1939. for (const conversation of data) {
  1940. if (conversation.avatar !== undefined && conversation.avatar !== null) {
  1941. const receiver: threema.Receiver = this.receivers.getData({
  1942. id: conversation.id,
  1943. type: conversation.type,
  1944. });
  1945. if (receiver !== undefined && receiver.avatar === undefined) {
  1946. receiver.avatar = {
  1947. low: conversation.avatar,
  1948. };
  1949. }
  1950. // Remove avatar from conversation
  1951. delete conversation.avatar;
  1952. }
  1953. }
  1954. this.conversations.set(data);
  1955. }
  1956. this.updateUnreadCount();
  1957. this.registerInitializationStep(InitializationStep.Conversations);
  1958. }
  1959. private _receiveResponseMessages(message: threema.WireMessage): void {
  1960. this.$log.debug('Received messages response');
  1961. // Unpack data and arguments
  1962. const args = message.args;
  1963. const data = message.data as threema.Message[];
  1964. if (args === undefined || data === undefined) {
  1965. this.$log.warn('Invalid messages response, data or arguments missing');
  1966. return;
  1967. }
  1968. // Unpack required argument fields
  1969. const type: string = args[WebClientService.ARGUMENT_RECEIVER_TYPE];
  1970. const id: string = args[WebClientService.ARGUMENT_RECEIVER_ID];
  1971. let more: boolean = args[WebClientService.ARGUMENT_HAS_MORE];
  1972. if (type === undefined || id === undefined || more === undefined) {
  1973. this.$log.warn('Invalid messages response, argument field missing');
  1974. return;
  1975. }
  1976. if (!isValidReceiverType(type)) {
  1977. this.$log.warn('Invalid messages response, unknown receiver type (' + type + ')');
  1978. return;
  1979. }
  1980. const receiver: threema.BaseReceiver = {type: type, id: id};
  1981. // If there's no data returned, override `more` field.
  1982. if (data.length === 0) {
  1983. more = false;
  1984. }
  1985. // Set as loaded
  1986. this.loadingMessages.delete(receiver.type + receiver.id);
  1987. if (this.messages.isRequested(receiver)) {
  1988. // Add messages
  1989. this.messages.addOlder(receiver, data);
  1990. // Clear pending request
  1991. this.messages.clearRequested(receiver);
  1992. // Set "more" flag to indicate that more (older) messages are available.
  1993. this.messages.setMore(receiver, more);
  1994. // Notify listeners
  1995. this.messages.notify(receiver, this.$rootScope);
  1996. } else {
  1997. this.$log.warn("Ignoring message response that hasn't been requested");
  1998. return;
  1999. }
  2000. }
  2001. private _receiveResponseAvatar(message: threema.WireMessage): threema.PromiseRequestResult<any> {
  2002. this.$log.debug('Received avatar response');
  2003. // Unpack data and arguments
  2004. const args = message.args;
  2005. if (args === undefined) {
  2006. this.$log.warn('Invalid message response: arguments missing');
  2007. return this.promiseRequestError('invalidResponse');
  2008. }
  2009. const avatar = message.data;
  2010. if (avatar === undefined) {
  2011. // It's ok, a receiver without a avatar
  2012. return { success: true, data: null };
  2013. }
  2014. // Unpack required argument fields
  2015. const type = args[WebClientService.ARGUMENT_RECEIVER_TYPE];
  2016. const id = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2017. const highResolution = args[WebClientService.ARGUMENT_AVATAR_HIGH_RESOLUTION];
  2018. if (type === undefined || id === undefined || highResolution === undefined) {
  2019. this.$log.warn('Invalid avatar response, argument field missing');
  2020. return this.promiseRequestError('invalidResponse');
  2021. }
  2022. // Set avatar for receiver according to resolution
  2023. const field: string = highResolution ? 'high' : 'low';
  2024. const receiverData = this.receivers.getData(args);
  2025. if (receiverData.avatar === null || receiverData.avatar === undefined) {
  2026. receiverData.avatar = {};
  2027. }
  2028. receiverData.avatar[field] = avatar;
  2029. return { success: true, data: avatar };
  2030. }
  2031. private _receiveResponseThumbnail(message: threema.WireMessage): threema.PromiseRequestResult<any> {
  2032. this.$log.debug('Received thumbnail response');
  2033. // Unpack data and arguments
  2034. const args = message.args;
  2035. if (args === undefined) {
  2036. this.$log.warn('Invalid message response: arguments missing');
  2037. return {
  2038. success: false,
  2039. data: 'invalidResponse',
  2040. };
  2041. }
  2042. const data = message.data;
  2043. if ( data === undefined) {
  2044. // It's ok, a message without a thumbnail
  2045. return {
  2046. success: true,
  2047. data: null,
  2048. };
  2049. }
  2050. // Unpack required argument fields
  2051. const type = args[WebClientService.ARGUMENT_RECEIVER_TYPE];
  2052. const id = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2053. const messageId: string = args[WebClientService.ARGUMENT_MESSAGE_ID];
  2054. if (type === undefined || id === undefined || messageId === undefined ) {
  2055. this.$log.warn('Invalid thumbnail response, argument field missing');
  2056. return {
  2057. success: false,
  2058. data: 'invalidResponse',
  2059. };
  2060. }
  2061. this.messages.setThumbnail( this.receivers.getData(args), messageId, data);
  2062. return {
  2063. success: true,
  2064. data: data,
  2065. };
  2066. }
  2067. private _receiveResponseBlob(message: threema.WireMessage): threema.PromiseRequestResult<threema.BlobInfo> {
  2068. this.$log.debug('Received blob response');
  2069. // Unpack data and arguments
  2070. const args = message.args;
  2071. const data = message.data;
  2072. if (args === undefined ) {
  2073. this.$log.warn('Invalid message response, arguments missing');
  2074. return this.promiseRequestError('invalidResponse');
  2075. }
  2076. // Unpack required argument fields
  2077. const receiverType = args[WebClientService.ARGUMENT_RECEIVER_TYPE];
  2078. const receiverId = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2079. const msgId: string = args[WebClientService.ARGUMENT_MESSAGE_ID];
  2080. const temporaryId: string = args[WebClientService.ARGUMENT_TEMPORARY_ID];
  2081. const success: boolean = args[WebClientService.ARGUMENT_SUCCESS];
  2082. if (receiverType === undefined || receiverId === undefined
  2083. || msgId === undefined || temporaryId === undefined || success === undefined) {
  2084. this.$log.warn('Invalid blob response, argument field missing');
  2085. return this.promiseRequestError('invalidResponse');
  2086. }
  2087. // Check success flag
  2088. if (success === false) {
  2089. return this.promiseRequestError(args[WebClientService.ARGUMENT_ERROR]);
  2090. }
  2091. // Unpack data
  2092. const blobInfo: threema.BlobInfo = {
  2093. buffer: data[WebClientService.DATA_FIELD_BLOB_BLOB],
  2094. mimetype: data[WebClientService.DATA_FIELD_BLOB_TYPE],
  2095. filename: data[WebClientService.DATA_FIELD_BLOB_NAME],
  2096. };
  2097. if (blobInfo.buffer === undefined || blobInfo.mimetype === undefined || blobInfo.filename === undefined) {
  2098. this.$log.warn('Invalid blob response, data field missing');
  2099. return this.promiseRequestError('invalidResponse');
  2100. }
  2101. this.blobCache.set(msgId + receiverType, blobInfo);
  2102. // Download to browser
  2103. return {
  2104. success: true,
  2105. data: blobInfo,
  2106. };
  2107. }
  2108. private _receiveUpdateMessages(message: threema.WireMessage): void {
  2109. this.$log.debug('Received messages update');
  2110. // Unpack data and arguments
  2111. const args = message.args;
  2112. const data: threema.Message[] = message.data;
  2113. if (args === undefined || data === undefined) {
  2114. this.$log.warn('Invalid message update, data or arguments missing');
  2115. return;
  2116. }
  2117. // Unpack required argument fields
  2118. const type: string = args[WebClientService.ARGUMENT_RECEIVER_TYPE];
  2119. const id: string = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2120. const mode: string = args[WebClientService.ARGUMENT_MODE];
  2121. if (type === undefined || id === undefined || mode === undefined) {
  2122. this.$log.warn('Invalid message update, argument field missing');
  2123. return;
  2124. }
  2125. if (!isValidReceiverType(type)) {
  2126. this.$log.warn(this.logTag, 'Invalid messages update, unknown receiver type (' + type + ')');
  2127. return;
  2128. }
  2129. const receiver: threema.BaseReceiver = {type: type, id: id};
  2130. // React depending on mode
  2131. let notify = false;
  2132. for (const msg of data) {
  2133. switch (mode) {
  2134. case WebClientService.ARGUMENT_MODE_NEW:
  2135. // It's possible that this message already exists (placeholder message on send).
  2136. // Try to update it first. If not, add it as a new msg.
  2137. if (!this.messages.update(receiver, msg)) {
  2138. this.messages.addNewer(receiver, [msg]);
  2139. }
  2140. notify = true;
  2141. break;
  2142. case WebClientService.ARGUMENT_MODE_MODIFIED:
  2143. this.messages.update(receiver, msg);
  2144. break;
  2145. case WebClientService.ARGUMENT_MODE_REMOVED:
  2146. this.messages.remove(receiver, msg.id);
  2147. notify = true;
  2148. break;
  2149. default:
  2150. this.$log.warn(this.logTag, 'Invalid message response, unknown mode:', mode);
  2151. }
  2152. }
  2153. if (notify) {
  2154. this.messages.notify(receiver, this.$rootScope);
  2155. }
  2156. }
  2157. private _receiveUpdateReceiver(message: threema.WireMessage): void {
  2158. this.$log.debug('Received receiver update or delete');
  2159. // Unpack data and arguments
  2160. const args = message.args;
  2161. const data = message.data;
  2162. if (args === undefined || data === undefined) {
  2163. this.$log.warn('Invalid receiver update, data or arguments missing');
  2164. return;
  2165. }
  2166. // Unpack required argument fields
  2167. const type = args[WebClientService.ARGUMENT_RECEIVER_TYPE] as threema.ReceiverType;
  2168. const id = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2169. const mode: 'new' | 'modified' | 'removed' = args[WebClientService.ARGUMENT_MODE];
  2170. if (type === undefined || mode === undefined || id === undefined) {
  2171. this.$log.warn('Invalid receiver update, argument field missing');
  2172. return;
  2173. }
  2174. // React depending on mode
  2175. switch (mode) {
  2176. case WebClientService.ARGUMENT_MODE_NEW:
  2177. case WebClientService.ARGUMENT_MODE_MODIFIED:
  2178. // Add or update a certain receiver
  2179. const updatedReceiver = this.receivers.extend(type, data);
  2180. // Remove all cached messages if the receiver was moved to "locked" state
  2181. if (updatedReceiver !== undefined && updatedReceiver.locked) {
  2182. this.messages.clearReceiverMessages(updatedReceiver);
  2183. }
  2184. break;
  2185. case WebClientService.ARGUMENT_MODE_REMOVED:
  2186. // Remove a certain receiver
  2187. (this.receivers.get(type) as Map<string, threema.Receiver>).delete(id);
  2188. break;
  2189. default:
  2190. this.$log.warn('Invalid receiver response, unknown mode:', mode);
  2191. }
  2192. }
  2193. private _receiveUpdateReceivers(message: threema.WireMessage): void {
  2194. this.$log.debug('Received receivers update');
  2195. // Unpack data and arguments
  2196. const args = message.args;
  2197. const data = message.data;
  2198. if (args === undefined || data === undefined) {
  2199. this.$log.warn('Invalid receiver update, data or arguments missing');
  2200. return;
  2201. }
  2202. // Unpack required argument fields
  2203. const type = args[WebClientService.ARGUMENT_RECEIVER_TYPE] as threema.ReceiverType;
  2204. if (type === undefined) {
  2205. this.$log.warn('Invalid receivers update, argument field missing');
  2206. return;
  2207. }
  2208. // Refresh lists of receivers
  2209. switch (type) {
  2210. case 'contact':
  2211. this.sortContacts(data);
  2212. this.receivers.setContacts(data);
  2213. break;
  2214. case 'group':
  2215. this.receivers.setGroups(data);
  2216. break;
  2217. case 'distributionList':
  2218. this.receivers.setDistributionLists(data);
  2219. break;
  2220. default:
  2221. this.$log.warn('Unknown receiver type:', type);
  2222. }
  2223. }
  2224. private _receiveUpdateTyping(message: threema.WireMessage): void {
  2225. this.$log.debug('Received typing update');
  2226. // Unpack data and arguments
  2227. const args = message.args;
  2228. const data = message.data;
  2229. if (args === undefined || data === undefined) {
  2230. this.$log.warn('Invalid typing update, data or arguments missing');
  2231. return;
  2232. }
  2233. // Unpack required argument fields
  2234. const identity: string = args[WebClientService.ARGUMENT_RECEIVER_ID];
  2235. if (identity === undefined) {
  2236. this.$log.warn('Invalid typing update, argument field missing');
  2237. return;
  2238. }
  2239. // Unpack required data fields
  2240. const isTyping: boolean = data[WebClientService.ARGUMENT_IS_TYPING];
  2241. if (isTyping === undefined) {
  2242. this.$log.warn('Invalid typing update, data field missing');
  2243. return;
  2244. }
  2245. // Store or remove typing notification.
  2246. // Note that we know that the receiver must be a contact, because
  2247. // groups and distribution lists can't type.
  2248. const receiver = {id: identity, type: 'contact'} as threema.ContactReceiver;
  2249. if (isTyping === true) {
  2250. this.typing.setTyping(receiver);
  2251. } else {
  2252. this.typing.unsetTyping(receiver);
  2253. }
  2254. }
  2255. private _receiveUpdateConversation(message: threema.WireMessage) {
  2256. this.$log.debug('Received conversation update');
  2257. const args = message.args;
  2258. const data = message.data as threema.ConversationWithPosition;
  2259. if (args === undefined || data === undefined) {
  2260. this.$log.warn('Invalid conversation update, data or arguments missing');
  2261. return;
  2262. }
  2263. // Get receiver
  2264. const receiver = this.receivers.getData({type: data.type, id: data.id});
  2265. // Unpack required argument fields
  2266. const type: string = args[WebClientService.ARGUMENT_MODE];
  2267. switch (type) {
  2268. case WebClientService.ARGUMENT_MODE_NEW:
  2269. this.conversations.add(data);
  2270. break;
  2271. case WebClientService.ARGUMENT_MODE_MODIFIED:
  2272. // A conversation update *can* mean that a new message arrived.
  2273. // To find out, we'll look at the unread count. If it has been
  2274. // incremented, it must be a new message.
  2275. if (data.unreadCount > 0) {
  2276. const oldConversation = this.conversations.updateOrAdd(data);
  2277. if (oldConversation === null) {
  2278. this.onNewMessage(data.latestMessage, data, receiver);
  2279. } else {
  2280. // Check for unread count changes
  2281. const unreadCountIncreased = data.unreadCount > oldConversation.unreadCount;
  2282. const unreadCountDecreased = data.unreadCount < oldConversation.unreadCount;
  2283. // If the unreadcount has increased, we received a new message.
  2284. // Otherwise, if it has decreased, hide the notification.
  2285. if (unreadCountIncreased) {
  2286. this.onNewMessage(data.latestMessage, data, receiver);
  2287. } else if (unreadCountDecreased) {
  2288. this.notificationService.hideNotification(data.type + '-' + data.id);
  2289. }
  2290. }
  2291. } else {
  2292. // Update the conversation and hide any notifications
  2293. this.conversations.updateOrAdd(data);
  2294. this.notificationService.hideNotification(data.type + '-' + data.id);
  2295. }
  2296. break;
  2297. case WebClientService.ARGUMENT_MODE_REMOVED:
  2298. // Remove conversation
  2299. this.conversations.remove(data);
  2300. // Remove all cached messages for the receiver
  2301. this.messages.clearReceiverMessages(receiver);
  2302. // Call on-removed listener
  2303. this.receiverListener.forEach((listener: threema.ReceiverListener) => {
  2304. this.$log.debug(this.logTag, 'Call on removed listener');
  2305. listener.onConversationRemoved(receiver);
  2306. });
  2307. break;
  2308. default:
  2309. this.$log.warn(this.logTag, 'Received conversation without a mode');
  2310. return;
  2311. }
  2312. this.updateUnreadCount();
  2313. }
  2314. private _receiveUpdateAvatar(message: threema.WireMessage) {
  2315. this.$log.debug('Received avatar update');
  2316. const args = message.args;
  2317. const data = message.data as ArrayBuffer;
  2318. if (args === undefined) {
  2319. this.$log.warn('Invalid avatar update, arguments missing');
  2320. return;
  2321. }
  2322. // Get receiver
  2323. const receiver = this.receivers.getData({type: args.type, id: args.id});
  2324. // Set low-res avatar
  2325. receiver.avatar.low = data;
  2326. // Invalidate high-res avatar
  2327. receiver.avatar.high = undefined;
  2328. }
  2329. /**
  2330. * Process an incoming battery status message.
  2331. */
  2332. private _receiveUpdateBatteryStatus(message: threema.WireMessage): void {
  2333. this.$log.debug('Received battery status');
  2334. // Unpack data and arguments
  2335. const data = message.data as threema.BatteryStatus;
  2336. if (data === undefined) {
  2337. this.$log.warn('Invalid battery status message, data missing');
  2338. return;
  2339. }
  2340. // Set battery status
  2341. this.batteryStatusService.setStatus(data);
  2342. this.$log.debug('[BatteryStatusService]', this.batteryStatusService.toString());
  2343. }
  2344. /**
  2345. * Process an incoming profile update message.
  2346. */
  2347. private _receiveUpdateProfile(message: threema.WireMessage): void {
  2348. this.$log.debug('Received profile update');
  2349. // Unpack data and arguments
  2350. const data = message.data as threema.ProfileUpdate;
  2351. if (data === undefined) {
  2352. this.$log.warn('Invalid profile update message, data missing');
  2353. return;
  2354. }
  2355. // Update public nickname
  2356. if (data.publicNickname !== undefined) {
  2357. this.me.publicNickname = data.publicNickname;
  2358. this.me.displayName = this.me.publicNickname || this.me.id;
  2359. }
  2360. // Update avatar
  2361. if (data.avatar !== undefined) {
  2362. if (data.avatar === null) {
  2363. this.me.avatar = {};
  2364. } else {
  2365. this.me.avatar = { high: data.avatar };
  2366. }
  2367. // Request new low-res avatar
  2368. this.requestAvatar(this.me, false);
  2369. }
  2370. }
  2371. /**
  2372. * The peer sends the device information string. This can be used to
  2373. * identify the active session.
  2374. */
  2375. private _receiveResponseClientInfo(message: threema.WireMessage): void {
  2376. this.$log.debug('Received client info');
  2377. const data = message.data;
  2378. if (data === undefined) {
  2379. this.$log.warn('Invalid client info, data field missing');
  2380. return;
  2381. }
  2382. /**
  2383. * Return the field if it's not undefined, otherwise return the default.
  2384. */
  2385. function getOrDefault<T>(field: T, defaultVal: T): T {
  2386. if (field === undefined) {
  2387. return defaultVal;
  2388. }
  2389. return field;
  2390. }
  2391. // Set clientInfo attribute
  2392. this.clientInfo = {
  2393. device: data.device,
  2394. os: data.os,
  2395. osVersion: data.osVersion,
  2396. isWork: hasValue(data.isWork) ? data.isWork : false, // TODO: Backwards compat hack, remove after 08/2019
  2397. pushToken: data.pushToken,
  2398. configuration: {
  2399. voipEnabled: getOrDefault<boolean>(data.configuration.voipEnabled, true),
  2400. voipForceTurn: getOrDefault<boolean>(data.configuration.voipForceTurn, false),
  2401. largeSingleEmoji: getOrDefault<boolean>(data.configuration.largeSingleEmoji, true),
  2402. showInactiveIDs: getOrDefault<boolean>(data.configuration.showInactiveIDs, true),
  2403. },
  2404. capabilities: {
  2405. maxGroupSize: getOrDefault<number>(data.capabilities.maxGroupSize, 50),
  2406. maxFileSize: getOrDefault<number>(data.capabilities.maxFileSize, 50 * 1024 * 1024),
  2407. distributionLists: getOrDefault<boolean>(data.capabilities.distributionLists, true),
  2408. imageFormat: data.capabilities.imageFormat,
  2409. mdm: data.capabilities.mdm,
  2410. },
  2411. };
  2412. this.$log.debug('Client device:', this.clientInfo.device);
  2413. // Store push token
  2414. if (this.clientInfo.pushToken) {
  2415. this.pushToken = this.clientInfo.pushToken;
  2416. switch (this.clientInfo.os) {
  2417. case threema.OperatingSystem.Android:
  2418. this.pushTokenType = threema.PushTokenType.Gcm;
  2419. break;
  2420. case threema.OperatingSystem.Ios:
  2421. this.pushTokenType = threema.PushTokenType.Apns;
  2422. break;
  2423. default:
  2424. this.$log.error(this.logTag, 'Invalid operating system in client info');
  2425. }
  2426. }
  2427. if (this.pushToken && this.pushTokenType) {
  2428. this.pushService.init(this.pushToken, this.pushTokenType);
  2429. }
  2430. this.registerInitializationStep(InitializationStep.ClientInfo);
  2431. }
  2432. /**
  2433. * The peer sends information about the current user profile.
  2434. */
  2435. private _receiveResponseProfile(message: threema.WireMessage): void {
  2436. this.$log.debug('Received profile');
  2437. const data = message.data as threema.Profile;
  2438. if (data === undefined) {
  2439. this.$log.warn('Invalid client info, data field missing');
  2440. return;
  2441. }
  2442. // Create 'me' receiver with profile + dummy data
  2443. // TODO: Send both high-res and low-res avatars
  2444. this.receivers.setMe({
  2445. type: 'me',
  2446. id: data.identity,
  2447. publicNickname: data.publicNickname,
  2448. displayName: data.publicNickname || data.identity,
  2449. publicKey: data.publicKey,
  2450. avatar: {
  2451. high: data.avatar,
  2452. },
  2453. featureMask: 0xFF,
  2454. verificationLevel: 3,
  2455. state: 'ACTIVE',
  2456. hidden: false,
  2457. access: {
  2458. canChangeAvatar: true,
  2459. canChangeFirstName: true,
  2460. canChangeLastName: true,
  2461. },
  2462. color: '#000000',
  2463. });
  2464. this.registerInitializationStep(InitializationStep.Profile);
  2465. }
  2466. public setPassword(password: string) {
  2467. // If a password has been set, store trusted key and push token
  2468. if (this._maybeTrustKeys(password)) {
  2469. // Saved trusted key, send information to client
  2470. this.sendKeyPersisted();
  2471. }
  2472. }
  2473. /**
  2474. * Reset all Fields and clear the blob cache
  2475. */
  2476. public clearCache(): void {
  2477. this._resetFields();
  2478. this.blobCache.clear();
  2479. }
  2480. /**
  2481. * Return the max text length
  2482. */
  2483. public getMaxTextLength(): number {
  2484. return WebClientService.MAX_TEXT_LENGTH;
  2485. }
  2486. /**
  2487. * Returns the max group member size
  2488. */
  2489. public getMaxGroupMemberSize(): number {
  2490. return this.clientInfo.capabilities.maxGroupSize;
  2491. }
  2492. /**
  2493. * Whether a notification should be triggered.
  2494. */
  2495. private shouldNotify(settings: threema.SimplifiedNotificationSettings, message: threema.Message): boolean {
  2496. if (settings.dnd.enabled) {
  2497. // Do not show any notifications on muted chats
  2498. if (settings.dnd.mentionOnly) {
  2499. let textToSearch = '';
  2500. if (message.type === 'text') {
  2501. textToSearch = message.body;
  2502. } else if (message.caption) {
  2503. textToSearch = message.caption;
  2504. }
  2505. let quotedMe = false;
  2506. if (message.quote) {
  2507. textToSearch += ' ' + message.quote.text;
  2508. quotedMe = message.quote.identity === this.me.id;
  2509. }
  2510. const forMe = textToSearch.indexOf('@[' + this.me.id + ']') !== -1;
  2511. const forAll = textToSearch.indexOf('@[@@@@@@@@]') !== -1;
  2512. return forMe || forAll || quotedMe;
  2513. } else {
  2514. return false;
  2515. }
  2516. } else {
  2517. return true;
  2518. }
  2519. }
  2520. /**
  2521. * Called when a new message arrives.
  2522. */
  2523. private onNewMessage(
  2524. message: threema.Message,
  2525. conversation: threema.Conversation,
  2526. sender: threema.Receiver,
  2527. ): void {
  2528. // Ignore message from active receivers (and if the browser tab is visible)
  2529. if (this.browserService.isVisible()
  2530. && this.receiverService.compare(conversation, this.receiverService.getActive())) {
  2531. return;
  2532. }
  2533. // Do not show any notifications on private chats
  2534. if (sender.locked === true) {
  2535. return;
  2536. }
  2537. // Consider conversation notification settings
  2538. const simplifiedNotification = this.notificationService.getAppNotificationSettings(conversation);
  2539. if (!this.shouldNotify(simplifiedNotification, message)) {
  2540. return;
  2541. }
  2542. // Determine sender and partner name (used for notification)
  2543. let senderName = sender.id;
  2544. if (sender.displayName) {
  2545. senderName = sender.displayName;
  2546. } else if (isContactReceiver(sender)) {
  2547. senderName = '~' + sender.publicNickname;
  2548. }
  2549. const partner = this.receivers.getData({
  2550. id: message.partnerId,
  2551. type: 'contact',
  2552. } as threema.Receiver) as threema.ContactReceiver;
  2553. const partnerName = partner.displayName || ('~' + partner.publicNickname);
  2554. // Show notification
  2555. this.$translate('messenger.MESSAGE_NOTIFICATION_SUBJECT', {messageCount: conversation.unreadCount})
  2556. .then((titlePrefix) => {
  2557. const title = `${titlePrefix} ${senderName}`;
  2558. let body = '';
  2559. const messageType = message.type;
  2560. const caption = message.caption;
  2561. let captionString = '';
  2562. if (caption !== undefined) {
  2563. captionString = captionString + ': ' + caption;
  2564. }
  2565. const messageTypeString = this.$translate.instant('messageTypes.' + messageType);
  2566. switch (messageType as threema.MessageType) {
  2567. case 'text':
  2568. body = message.body;
  2569. break;
  2570. case 'location':
  2571. body = messageTypeString + ': ' + message.location.description;
  2572. break;
  2573. case 'file':
  2574. if (message.file.type === 'image/gif') {
  2575. body = this.$translate.instant('messageTypes.' + 'gif') + captionString;
  2576. break;
  2577. }
  2578. // Display caption, if available otherwise use filename
  2579. if (captionString.length > 0) {
  2580. body = messageTypeString + captionString;
  2581. } else {
  2582. body = messageTypeString + ': ' + message.file.name;
  2583. }
  2584. break;
  2585. case 'ballot':
  2586. // TODO Show ballot title if ballot messages are implemented in the web version
  2587. body = messageTypeString;
  2588. break;
  2589. case 'voipStatus':
  2590. let translationKey: string;
  2591. switch ((message as threema.Message).voip.status) {
  2592. case 1:
  2593. translationKey = 'CALL_MISSED';
  2594. break;
  2595. case 2:
  2596. translationKey = message.isOutbox ? 'CALL_FINISHED_IN' : 'CALL_FINISHED_OUT';
  2597. break;
  2598. case 3:
  2599. translationKey = 'CALL_REJECTED';
  2600. break;
  2601. case 4:
  2602. translationKey = 'CALL_ABORTED';
  2603. break;
  2604. default:
  2605. // No default
  2606. }
  2607. if (translationKey !== undefined) {
  2608. body = this.$translate.instant('voip.' + translationKey);
  2609. }
  2610. break;
  2611. default:
  2612. // Image, video and audio
  2613. body = messageTypeString + captionString;
  2614. }
  2615. if (conversation.type === 'group') {
  2616. body = partnerName + ': ' + body;
  2617. }
  2618. const tag = conversation.type + '-' + conversation.id;
  2619. const avatar = (sender.avatar && sender.avatar.low)
  2620. ? this.$filter('bufferToUrl')(sender.avatar.low, 'image/png')
  2621. : null;
  2622. this.notificationService.showNotification(tag, title, body, avatar, () => {
  2623. this.$state.go('messenger.home.conversation', {
  2624. type: conversation.type,
  2625. id: conversation.id,
  2626. initParams: null,
  2627. });
  2628. }, undefined, undefined, simplifiedNotification.sound.muted);
  2629. });
  2630. }
  2631. /**
  2632. * If a password has been set, store own private permanent key and public
  2633. * key of the peer in the trusted key store.
  2634. */
  2635. private _maybeTrustKeys(password: string): boolean {
  2636. if (password !== undefined && password !== null && password.length > 0) {
  2637. this.trustedKeyStore.storeTrustedKey(
  2638. this.salty.keyStore.publicKeyBytes,
  2639. this.salty.keyStore.secretKeyBytes,
  2640. this.salty.peerPermanentKeyBytes,
  2641. this.pushToken,
  2642. this.pushTokenType,
  2643. password,
  2644. );
  2645. this.$log.info('Stored trusted key');
  2646. return true;
  2647. }
  2648. return false;
  2649. }
  2650. public updatePushToken(token: string, tokenType: threema.PushTokenType): void {
  2651. this.pushToken = token;
  2652. this.pushTokenType = tokenType;
  2653. }
  2654. private _sendRequest(type, retransmit: boolean, args?: object, data?: object): void {
  2655. const message: threema.WireMessage = {
  2656. type: WebClientService.TYPE_REQUEST,
  2657. subType: type,
  2658. };
  2659. if (args !== undefined) {
  2660. message.args = args;
  2661. }
  2662. if (data !== undefined) {
  2663. message.data = data;
  2664. }
  2665. this.send(message, retransmit);
  2666. }
  2667. private _sendUpdate(type, retransmit: boolean, args?: object, data?: object): void {
  2668. const message: threema.WireMessage = {
  2669. type: WebClientService.TYPE_UPDATE,
  2670. subType: type,
  2671. };
  2672. if (args !== undefined) {
  2673. message.args = args;
  2674. }
  2675. if (data !== undefined) {
  2676. message.data = data;
  2677. }
  2678. this.send(message, retransmit);
  2679. }
  2680. private _sendPromiseMessage(
  2681. message: threema.WireMessage,
  2682. retransmit: boolean,
  2683. timeout: number = null,
  2684. ): Promise<any> {
  2685. // Create arguments on wired message
  2686. if (message.args === undefined || message.args === null) {
  2687. message.args = {};
  2688. }
  2689. let promiseId = message.args[WebClientService.ARGUMENT_TEMPORARY_ID];
  2690. if (promiseId === undefined) {
  2691. // Create a random id to identity the promise
  2692. promiseId = 'p' + Math.random().toString(36).substring(7);
  2693. message.args[WebClientService.ARGUMENT_TEMPORARY_ID] = promiseId;
  2694. }
  2695. return new Promise(
  2696. (resolve, reject) => {
  2697. const p = {
  2698. resolve: resolve,
  2699. reject: reject,
  2700. } as threema.PromiseCallbacks;
  2701. this.requestPromises.set(promiseId, p);
  2702. if (timeout !== null && timeout > 0) {
  2703. this.$timeout(() => {
  2704. p.reject('timeout');
  2705. this.requestPromises.delete(promiseId);
  2706. }, timeout);
  2707. }
  2708. this.send(message, retransmit);
  2709. },
  2710. );
  2711. }
  2712. /**
  2713. * Send a request and return a promise.
  2714. *
  2715. * The promise will be resolved if a response arrives with the same temporary ID.
  2716. *
  2717. * @param timeout Optional request timeout in ms
  2718. */
  2719. private _sendRequestPromise(type, retransmit: boolean, args = null, timeout: number = null): Promise<any> {
  2720. const message: threema.WireMessage = {
  2721. type: WebClientService.TYPE_REQUEST,
  2722. subType: type,
  2723. args: args,
  2724. };
  2725. return this._sendPromiseMessage(message, retransmit, timeout);
  2726. }
  2727. private _sendCreatePromise(
  2728. type,
  2729. retransmit: boolean,
  2730. args = null,
  2731. data: any = null,
  2732. timeout: number = null,
  2733. ): Promise<any> {
  2734. const message: threema.WireMessage = {
  2735. type: WebClientService.TYPE_CREATE,
  2736. subType: type,
  2737. args: args,
  2738. data: data,
  2739. };
  2740. return this._sendPromiseMessage(message, retransmit, timeout);
  2741. }
  2742. private _sendUpdatePromise(
  2743. type,
  2744. retransmit: boolean,
  2745. args = null,
  2746. data: any = null,
  2747. timeout: number = null,
  2748. ): Promise<any> {
  2749. const message: threema.WireMessage = {
  2750. type: WebClientService.TYPE_UPDATE,
  2751. subType: type,
  2752. data: data,
  2753. args: args,
  2754. };
  2755. return this._sendPromiseMessage(message, retransmit, timeout);
  2756. }
  2757. private _sendCreate(type, retransmit: boolean, data, args = null): void {
  2758. const message: threema.WireMessage = {
  2759. type: WebClientService.TYPE_CREATE,
  2760. subType: type,
  2761. data: data,
  2762. };
  2763. if (args) {
  2764. message.args = args;
  2765. }
  2766. this.send(message, retransmit);
  2767. }
  2768. private _sendDelete(type, retransmit: boolean, args, data = null): void {
  2769. const message: threema.WireMessage = {
  2770. type: WebClientService.TYPE_DELETE,
  2771. subType: type,
  2772. data: data,
  2773. args: args,
  2774. };
  2775. this.send(message, retransmit);
  2776. }
  2777. private _sendDeletePromise(
  2778. type, retransmit: boolean,
  2779. args,
  2780. data: any = null,
  2781. timeout: number = null,
  2782. ): Promise<any> {
  2783. const message: threema.WireMessage = {
  2784. type: WebClientService.TYPE_DELETE,
  2785. subType: type,
  2786. data: data,
  2787. args: args,
  2788. };
  2789. return this._sendPromiseMessage(message, retransmit, timeout);
  2790. }
  2791. private _receiveRequest(type, message): void {
  2792. switch (type) {
  2793. case WebClientService.SUB_TYPE_CONNECTION_ACK:
  2794. this._receiveRequestConnectionAck(message);
  2795. break;
  2796. default:
  2797. this.$log.warn('Ignored update with type:', type);
  2798. break;
  2799. }
  2800. }
  2801. private _receivePromise(message: any, receiveResult: threema.PromiseRequestResult<any>) {
  2802. if (
  2803. message !== undefined
  2804. && message.args !== undefined
  2805. && message.args[WebClientService.ARGUMENT_TEMPORARY_ID] !== undefined) {
  2806. // find pending promise
  2807. const promiseId = message.args[WebClientService.ARGUMENT_TEMPORARY_ID];
  2808. if (this.requestPromises.has(promiseId)) {
  2809. const promise = this.requestPromises.get(promiseId);
  2810. if (receiveResult === null || receiveResult === undefined) {
  2811. promise.reject('unknown');
  2812. } else if (receiveResult.success) {
  2813. promise.resolve(receiveResult.data);
  2814. } else {
  2815. promise.reject(receiveResult.error);
  2816. }
  2817. // remove from map
  2818. this.requestPromises.delete(promiseId);
  2819. }
  2820. }
  2821. }
  2822. private _receiveResponse(type, message): void {
  2823. let receiveResult: threema.PromiseRequestResult<any>;
  2824. switch (type) {
  2825. case WebClientService.SUB_TYPE_CONFIRM_ACTION:
  2826. receiveResult = this._receiveResponseConfirmAction(message);
  2827. break;
  2828. case WebClientService.SUB_TYPE_RECEIVERS:
  2829. this._receiveResponseReceivers(message);
  2830. break;
  2831. case WebClientService.SUB_TYPE_CONVERSATIONS:
  2832. this.runAfterInitializationSteps([
  2833. InitializationStep.Receivers,
  2834. ], () => {
  2835. this._receiveResponseConversations(message);
  2836. });
  2837. break;
  2838. case WebClientService.SUB_TYPE_MESSAGES:
  2839. this._receiveResponseMessages(message);
  2840. break;
  2841. case WebClientService.SUB_TYPE_AVATAR:
  2842. receiveResult = this._receiveResponseAvatar(message);
  2843. break;
  2844. case WebClientService.SUB_TYPE_THUMBNAIL:
  2845. receiveResult = this._receiveResponseThumbnail(message);
  2846. break;
  2847. case WebClientService.SUB_TYPE_BLOB:
  2848. receiveResult = this._receiveResponseBlob(message);
  2849. break;
  2850. case WebClientService.SUB_TYPE_CLIENT_INFO:
  2851. this._receiveResponseClientInfo(message);
  2852. break;
  2853. case WebClientService.SUB_TYPE_PROFILE:
  2854. this._receiveResponseProfile(message);
  2855. break;
  2856. case WebClientService.SUB_TYPE_CONTACT_DETAIL:
  2857. receiveResult = this._receiveResponseContactDetail(message);
  2858. break;
  2859. default:
  2860. this.$log.warn('Ignored response with type:', type);
  2861. return;
  2862. }
  2863. this._receivePromise(message, receiveResult);
  2864. }
  2865. private _receiveUpdate(type, message): void {
  2866. let receiveResult;
  2867. switch (type) {
  2868. case WebClientService.SUB_TYPE_RECEIVER:
  2869. this._receiveUpdateReceiver(message);
  2870. break;
  2871. case WebClientService.SUB_TYPE_RECEIVERS:
  2872. this._receiveUpdateReceivers(message);
  2873. break;
  2874. case WebClientService.SUB_TYPE_MESSAGES:
  2875. this._receiveUpdateMessages(message);
  2876. break;
  2877. case WebClientService.SUB_TYPE_TYPING:
  2878. this._receiveUpdateTyping(message);
  2879. break;
  2880. case WebClientService.SUB_TYPE_CONVERSATION:
  2881. this._receiveUpdateConversation(message);
  2882. break;
  2883. case WebClientService.SUB_TYPE_AVATAR:
  2884. this._receiveUpdateAvatar(message);
  2885. break;
  2886. case WebClientService.SUB_TYPE_BATTERY_STATUS:
  2887. this._receiveUpdateBatteryStatus(message);
  2888. break;
  2889. case WebClientService.SUB_TYPE_CONTACT:
  2890. receiveResult = this._receiveUpdateContact(message);
  2891. break;
  2892. case WebClientService.SUB_TYPE_GROUP:
  2893. receiveResult = this._receiveResponseGroup(message);
  2894. break;
  2895. case WebClientService.SUB_TYPE_DISTRIBUTION_LIST:
  2896. receiveResult = this._receiveResponseDistributionList(message);
  2897. break;
  2898. case WebClientService.SUB_TYPE_PROFILE:
  2899. this._receiveUpdateProfile(message);
  2900. break;
  2901. case WebClientService.SUB_TYPE_ALERT:
  2902. this._receiveAlert(message);
  2903. break;
  2904. case WebClientService.SUB_TYPE_CONNECTION_ACK:
  2905. this._receiveUpdateConnectionAck(message);
  2906. break;
  2907. case WebClientService.SUB_TYPE_CONNECTION_DISCONNECT:
  2908. this._receiveConnectionDisconnect(message);
  2909. break;
  2910. default:
  2911. this.$log.warn('Ignored update with type:', type);
  2912. return;
  2913. }
  2914. this._receivePromise(message, receiveResult);
  2915. }
  2916. private _receiveCreate(type, message): void {
  2917. let receiveResult: threema.PromiseRequestResult<any>;
  2918. switch (type) {
  2919. case WebClientService.SUB_TYPE_CONTACT:
  2920. receiveResult = this._receiveUpdateContact(message);
  2921. break;
  2922. case WebClientService.SUB_TYPE_GROUP:
  2923. receiveResult = this._receiveResponseGroup(message);
  2924. break;
  2925. case WebClientService.SUB_TYPE_DISTRIBUTION_LIST:
  2926. receiveResult = this._receiveResponseDistributionList(message);
  2927. break;
  2928. case WebClientService.SUB_TYPE_TEXT_MESSAGE:
  2929. case WebClientService.SUB_TYPE_FILE_MESSAGE:
  2930. receiveResult = this._receiveResponseCreateMessage(message);
  2931. break;
  2932. default:
  2933. this.$log.warn('Ignored response with type:', type);
  2934. return;
  2935. }
  2936. this._receivePromise(message, receiveResult);
  2937. }
  2938. private _receiveDelete(type, message): void {
  2939. let receiveResult;
  2940. switch (type) {
  2941. case WebClientService.SUB_TYPE_CONTACT_DETAIL:
  2942. receiveResult = this._receiveUpdateReceiver(message);
  2943. break;
  2944. default:
  2945. this.$log.warn('Ignored delete with type:', type);
  2946. return;
  2947. }
  2948. this._receivePromise(message, receiveResult);
  2949. }
  2950. /**
  2951. * Encode an object using the msgpack format.
  2952. */
  2953. private msgpackEncode(data: any): Uint8Array {
  2954. return msgpack.encode(data, this.msgpackEncoderOptions);
  2955. }
  2956. /**
  2957. * Decode an object using the msgpack format.
  2958. */
  2959. private msgpackDecode(bytes: Uint8Array): any {
  2960. return msgpack.decode(bytes, this.msgpackDecoderOptions);
  2961. }
  2962. /**
  2963. * Send a message via the underlying transport.
  2964. */
  2965. private send(message: threema.WireMessage, retransmit: boolean): void {
  2966. this.$log.debug('Sending', message.type + '/' + message.subType, 'message');
  2967. if (this.config.MSG_DEBUGGING) {
  2968. this.$log.debug('[Message] Outgoing:', message.type, '/', message.subType, message);
  2969. }
  2970. switch (this.chosenTask) {
  2971. case threema.ChosenTask.WebRTC:
  2972. {
  2973. // Send bytes through WebRTC DataChannel
  2974. const bytes: Uint8Array = this.msgpackEncode(message);
  2975. this.secureDataChannel.send(bytes);
  2976. }
  2977. break;
  2978. case threema.ChosenTask.RelayedData:
  2979. {
  2980. // Send bytes through e2e encrypted WebSocket
  2981. const bytes: Uint8Array = this.msgpackEncode(message);
  2982. // Increment the outgoing message sequence number
  2983. const messageSequenceNumber = this.outgoingMessageSequenceNumber.increment();
  2984. const chunker = new chunkedDc.Chunker(messageSequenceNumber, bytes, WebClientService.CHUNK_SIZE);
  2985. for (const chunk of chunker) {
  2986. // Send (and cache)
  2987. this.sendChunk(chunk, retransmit);
  2988. }
  2989. // Check if we need to request an acknowledgement
  2990. // Note: We only request if none is pending
  2991. if (this.pendingAckRequest === null &&
  2992. this.currentChunkCache.size > WebClientService.CHUNK_CACHE_SIZE_MAX) {
  2993. this._requestConnectionAck();
  2994. this.pendingAckRequest = this.currentChunkCache.sequenceNumber.get();
  2995. }
  2996. }
  2997. break;
  2998. default:
  2999. this.$log.error(this.logTag, 'Trying to send message, but no chosen task set');
  3000. }
  3001. }
  3002. /**
  3003. * Send a chunk via the underlying transport.
  3004. */
  3005. private sendChunk(chunk: Uint8Array, retransmit: boolean): void {
  3006. // TODO: Support for sending in chunks via data channels will be added later
  3007. if (this.chosenTask !== threema.ChosenTask.RelayedData) {
  3008. throw new Error(`Cannot send chunk, not supported by task: ${this.chosenTask}`);
  3009. }
  3010. const ready = this.previousChunkCache === null;
  3011. let chunkCache;
  3012. // Currently not ready? Enqueue in the chunk cache that is pending
  3013. // to be transferred and send a wakeup push.
  3014. if (!ready) {
  3015. chunkCache = this.previousChunkCache;
  3016. this.$log.debug(this.logTag, 'Currently not connected, queueing chunk');
  3017. if (this.pushService.isAvailable()) {
  3018. this.sendPush(threema.WakeupType.Wakeup);
  3019. } else {
  3020. this.$log.warn(this.logTag, 'Push service not available, cannot wake up peer!');
  3021. }
  3022. } else {
  3023. chunkCache = this.currentChunkCache;
  3024. }
  3025. // Add to chunk cache
  3026. try {
  3027. chunkCache.append(retransmit ? null : chunk);
  3028. } catch (error) {
  3029. this.$log.error(this.logTag, error);
  3030. this.failSession();
  3031. return;
  3032. }
  3033. // Send if ready
  3034. if (ready) {
  3035. if (this.config.MSG_DEBUGGING) {
  3036. this.$log.debug('[Chunk] Sending chunk:', chunk);
  3037. }
  3038. this.relayedDataTask.sendMessage(chunk.buffer);
  3039. }
  3040. }
  3041. /**
  3042. * Handle an incoming chunk from the underlying transport.
  3043. */
  3044. private receiveChunk(chunk: Uint8Array): void {
  3045. if (this.config.MSG_DEBUGGING && this.config.DEBUG) {
  3046. this.$log.debug('[Chunk] Received chunk:', chunk);
  3047. }
  3048. // Update incoming sequence number
  3049. try {
  3050. this.currentIncomingChunkSequenceNumber.increment();
  3051. } catch (error) {
  3052. this.$log.error(this.logTag, `Unable to continue session: ${error}`);
  3053. this.failSession();
  3054. return;
  3055. }
  3056. // Process chunk
  3057. this.unchunker.add(chunk.buffer);
  3058. }
  3059. /**
  3060. * Handle incoming message bytes from the SecureDataChannel.
  3061. */
  3062. private handleIncomingMessageBytes(bytes: Uint8Array): void {
  3063. this.$log.debug('New incoming message (' + bytes.byteLength + ' bytes)');
  3064. if (this.config.MSGPACK_DEBUGGING) {
  3065. this.$log.debug('Incoming message payload: ' + msgpackVisualizer(bytes));
  3066. }
  3067. // Decode bytes
  3068. const message: threema.WireMessage = this.msgpackDecode(bytes);
  3069. return this.handleIncomingMessage(message, false);
  3070. }
  3071. /**
  3072. * Handle incoming incoming from the SecureDataChannel
  3073. * or from the relayed data WebSocket.
  3074. */
  3075. private handleIncomingMessage(message: threema.WireMessage, log: boolean): void {
  3076. if (log) {
  3077. this.$log.debug('New incoming message');
  3078. }
  3079. // Validate message to keep contract defined by `threema.WireMessage` type
  3080. if (message.type === undefined) {
  3081. this.$log.warn('Ignoring invalid message (no type attribute)');
  3082. return;
  3083. } else if (message.subType === undefined) {
  3084. this.$log.warn('Ignoring invalid message (no subType attribute)');
  3085. return;
  3086. }
  3087. // If desired, log message type / subtype
  3088. if (this.config.MSG_DEBUGGING) {
  3089. // Deep copy message to prevent issues with JS debugger
  3090. const deepcopy = JSON.parse(JSON.stringify(message));
  3091. this.$log.debug('[Message] Incoming:', message.type, '/', message.subType, deepcopy);
  3092. }
  3093. // Process data
  3094. this.$rootScope.$apply(() => {
  3095. this.receive(message);
  3096. });
  3097. }
  3098. /**
  3099. * Receive a new incoming decrypted message.
  3100. * This method runs inside the digest loop.
  3101. */
  3102. private receive(message: threema.WireMessage): void {
  3103. // Intercept handshake message
  3104. if (!this.connectionInfoFuture.done) {
  3105. // Check for unexpected messages
  3106. if (message.type !== WebClientService.TYPE_UPDATE ||
  3107. message.subType !== WebClientService.SUB_TYPE_CONNECTION_INFO) {
  3108. // TODO: Reactivate this and remove the special stop + alert
  3109. // once the iOS beta has been closed
  3110. // this.failSession();
  3111. this.stop(DisconnectReason.SessionStopped, true, true, true);
  3112. this.showAlert('Please update the Threema app to use the latest iOS beta version');
  3113. return;
  3114. }
  3115. // Dispatch and return
  3116. this._receiveConnectionInfo(message);
  3117. return;
  3118. }
  3119. // Dispatch message
  3120. switch (message.type) {
  3121. case WebClientService.TYPE_REQUEST:
  3122. this._receiveRequest(message.subType, message);
  3123. break;
  3124. case WebClientService.TYPE_RESPONSE:
  3125. this._receiveResponse(message.subType, message);
  3126. break;
  3127. case WebClientService.TYPE_CREATE:
  3128. this._receiveCreate(message.subType, message);
  3129. break;
  3130. case WebClientService.TYPE_UPDATE:
  3131. this._receiveUpdate(message.subType, message);
  3132. break;
  3133. case WebClientService.TYPE_DELETE:
  3134. this._receiveDelete(message.subType, message);
  3135. break;
  3136. default:
  3137. this.$log.warn('Ignored message with type:', message.type);
  3138. }
  3139. }
  3140. private runAfterInitializationSteps(requiredSteps: threema.InitializationStep[], callback: any): void {
  3141. for (const requiredStep of requiredSteps) {
  3142. if (!this.initialized.has(requiredStep)) {
  3143. this.$log.debug(this.logTag,
  3144. 'Required initialization step', requiredStep, 'not completed, add pending routine');
  3145. this.pendingInitializationStepRoutines.push({
  3146. requiredSteps: requiredSteps,
  3147. callback: callback,
  3148. } as threema.InitializationStepRoutine);
  3149. return;
  3150. }
  3151. }
  3152. callback();
  3153. }
  3154. private currentController: string;
  3155. public setControllerName(name: string): void {
  3156. this.currentController = name;
  3157. }
  3158. public getControllerName(): string {
  3159. return this.currentController;
  3160. }
  3161. /**
  3162. * Update the unread count in the window title.
  3163. */
  3164. private updateUnreadCount(): void {
  3165. const totalUnreadCount = this.conversations
  3166. .get()
  3167. .reduce((a: number, b: threema.Conversation) => a + b.unreadCount, 0);
  3168. this.titleService.updateUnreadCount(totalUnreadCount);
  3169. }
  3170. /**
  3171. * Reset the unread count in the window title
  3172. */
  3173. private resetUnreadCount(): void {
  3174. this.titleService.updateUnreadCount(0);
  3175. }
  3176. /**
  3177. * Return the configuration object from the client info data.
  3178. */
  3179. public get appConfig(): threema.AppConfig {
  3180. return this.clientInfo.configuration;
  3181. }
  3182. /**
  3183. * Return the capabilities object from the client info data.
  3184. */
  3185. public get appCapabilities(): threema.AppCapabilities {
  3186. return this.clientInfo.capabilities;
  3187. }
  3188. /**
  3189. * Sort a list of contacts in-place.
  3190. */
  3191. private sortContacts(contacts: threema.ContactReceiver[]): void {
  3192. const getSortableName = (name: string) => name.startsWith('~') ? name.substr(1) : name;
  3193. let options;
  3194. if (this.browserService.supportsExtendedLocaleCompare()) {
  3195. options = {
  3196. usage: 'sort',
  3197. sensitivity: 'variant',
  3198. };
  3199. }
  3200. const compareFunc = (a: threema.Receiver, b: threema.Receiver) => {
  3201. if (a.id.startsWith('*') && !b.id.startsWith('*')) { return 1; }
  3202. if (!a.id.startsWith('*') && b.id.startsWith('*')) { return -1; }
  3203. const left = getSortableName(a.displayName);
  3204. const right = getSortableName(b.displayName);
  3205. return left.localeCompare(right, undefined, options);
  3206. };
  3207. contacts.sort(compareFunc);
  3208. }
  3209. /**
  3210. * Clear all "is typing" flags.
  3211. */
  3212. public clearIsTypingFlags(): void {
  3213. this.typing.clearAll();
  3214. }
  3215. private handleGlobalConnectionStateChange(stateChange: threema.GlobalConnectionStateChange): void {
  3216. const isOk = stateChange.state === threema.GlobalConnectionState.Ok;
  3217. const wasOk = stateChange.prevState === threema.GlobalConnectionState.Ok;
  3218. if (!isOk && wasOk && this.batteryStatusService.dataAvailable) {
  3219. this.batteryStatusTimeout = this.$timeout(
  3220. () => {
  3221. this.batteryStatusService.clearStatus();
  3222. this.batteryStatusTimeout = null;
  3223. },
  3224. 60000,
  3225. );
  3226. } else if (isOk && this.batteryStatusTimeout !== null) {
  3227. this.$timeout.cancel(this.batteryStatusTimeout);
  3228. this.batteryStatusTimeout = null;
  3229. }
  3230. }
  3231. }