webclient.ts 90 KB

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