webclient.ts 145 KB

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