webclient.ts 172 KB

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