webclient.ts 123 KB

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