webclient.ts 133 KB

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