webclient.ts 106 KB

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