webclient.ts 140 KB

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