webclient.ts 133 KB

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