webclient.ts 158 KB

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