webclient.ts 157 KB

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