webclient.ts 105 KB

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