webclient.ts 109 KB

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