webclient.ts 168 KB

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