webclient.ts 99 KB

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