webclient.ts 107 KB

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