webclient.ts 158 KB

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