webclient.ts 122 KB

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