webclient.ts 115 KB

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