webclient.ts 123 KB

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