webclient.ts 87 KB

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