webclient.ts 113 KB

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