webclient.ts 118 KB

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