messenger.ts 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622
  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. import {
  18. StateParams as UiStateParams,
  19. StateProvider as UiStateProvider,
  20. StateService as UiStateService,
  21. Transition as UiTransition,
  22. TransitionService as UiTransitionService,
  23. } from '@uirouter/angularjs';
  24. import {ContactControllerModel} from '../controller_model/contact';
  25. import {bufferToUrl, logAdapter, supportsPassive, throttle, u8aToHex} from '../helpers';
  26. import {ContactService} from '../services/contact';
  27. import {ControllerService} from '../services/controller';
  28. import {ControllerModelService} from '../services/controller_model';
  29. import {ExecuteService} from '../services/execute';
  30. import {FingerPrintService} from '../services/fingerprint';
  31. import {TrustedKeyStoreService} from '../services/keystore';
  32. import {MimeService} from '../services/mime';
  33. import {NotificationService} from '../services/notification';
  34. import {ReceiverService} from '../services/receiver';
  35. import {SettingsService} from '../services/settings';
  36. import {StateService} from '../services/state';
  37. import {VersionService} from '../services/version';
  38. import {WebClientService} from '../services/webclient';
  39. import {isContactReceiver} from '../typeguards';
  40. // Type aliases
  41. import ControllerModelMode = threema.ControllerModelMode;
  42. class DialogController {
  43. public $mdDialog: ng.material.IDialogService;
  44. public activeElement: HTMLElement | null;
  45. public config: threema.Config;
  46. public static $inject = ['$mdDialog', 'CONFIG'];
  47. constructor($mdDialog: ng.material.IDialogService, CONFIG: threema.Config) {
  48. this.$mdDialog = $mdDialog;
  49. this.activeElement = document.activeElement as HTMLElement;
  50. this.config = CONFIG;
  51. }
  52. public cancel(): void {
  53. this.$mdDialog.cancel();
  54. this.done();
  55. }
  56. protected hide(data: any): void {
  57. this.$mdDialog.hide(data);
  58. this.done();
  59. }
  60. private done(): void {
  61. if (this.resumeFocusOnClose() === true && this.activeElement !== null) {
  62. // reset focus
  63. this.activeElement.focus();
  64. }
  65. }
  66. /**
  67. * If true, the focus on the active element (before opening the dialog)
  68. * will be restored. Default `true`, override if desired.
  69. */
  70. protected resumeFocusOnClose(): boolean {
  71. return true;
  72. }
  73. }
  74. /**
  75. * Handle sending of files.
  76. */
  77. class SendFileController extends DialogController {
  78. public static $inject = ['$mdDialog', '$log', 'CONFIG', 'preview'];
  79. private logTag: string = '[SendFileController]';
  80. public caption: string;
  81. public sendAsFile: boolean = false;
  82. private preview: threema.FileMessageData | null = null;
  83. public previewDataUrl: string | null = null;
  84. constructor($mdDialog: ng.material.IDialogService,
  85. $log: ng.ILogService,
  86. CONFIG: threema.Config,
  87. preview: threema.FileMessageData) {
  88. super($mdDialog, CONFIG);
  89. this.preview = preview;
  90. if (preview !== null) {
  91. this.previewDataUrl = bufferToUrl(
  92. this.preview.data,
  93. this.preview.fileType,
  94. logAdapter($log.warn, this.logTag),
  95. );
  96. }
  97. }
  98. public send(): void {
  99. this.hide({
  100. caption: this.caption,
  101. sendAsFile: this.sendAsFile,
  102. });
  103. }
  104. public keypress($event: KeyboardEvent): void {
  105. if ($event.key === 'Enter') { // see https://developer.mozilla.org/de/docs/Web/API/KeyboardEvent/key/Key_Values
  106. this.send();
  107. }
  108. }
  109. public hasPreview(): boolean {
  110. return this.previewDataUrl !== null && this.previewDataUrl !== undefined;
  111. }
  112. }
  113. /**
  114. * Handle settings
  115. */
  116. class SettingsController {
  117. public static $inject = ['$mdDialog', '$window', 'SettingsService', 'NotificationService'];
  118. public $mdDialog: ng.material.IDialogService;
  119. public $window: ng.IWindowService;
  120. public settingsService: SettingsService;
  121. private notificationService: NotificationService;
  122. public activeElement: HTMLElement | null;
  123. private desktopNotifications: boolean;
  124. private notificationApiAvailable: boolean;
  125. private notificationPermission: boolean;
  126. private notificationPreview: boolean;
  127. private notificationSound: boolean;
  128. constructor($mdDialog: ng.material.IDialogService,
  129. $window: ng.IWindowService,
  130. settingsService: SettingsService,
  131. notificationService: NotificationService) {
  132. this.$mdDialog = $mdDialog;
  133. this.$window = $window;
  134. this.settingsService = settingsService;
  135. this.notificationService = notificationService;
  136. this.activeElement = document.activeElement as HTMLElement;
  137. this.desktopNotifications = notificationService.getWantsNotifications();
  138. this.notificationApiAvailable = notificationService.isNotificationApiAvailable();
  139. this.notificationPermission = notificationService.getNotificationPermission();
  140. this.notificationPreview = notificationService.getWantsPreview();
  141. this.notificationSound = notificationService.getWantsSound();
  142. }
  143. public cancel(): void {
  144. this.$mdDialog.cancel();
  145. this.done();
  146. }
  147. protected hide(data: any): void {
  148. this.$mdDialog.hide(data);
  149. this.done();
  150. }
  151. private done(): void {
  152. if (this.activeElement !== null) {
  153. // Reset focus
  154. this.activeElement.focus();
  155. }
  156. }
  157. public setWantsNotifications(desktopNotifications: boolean) {
  158. this.notificationService.setWantsNotifications(desktopNotifications);
  159. }
  160. public setWantsPreview(notificationPreview: boolean) {
  161. this.notificationService.setWantsPreview(notificationPreview);
  162. }
  163. public setWantsSound(notificationSound: boolean) {
  164. this.notificationService.setWantsSound(notificationSound);
  165. }
  166. }
  167. interface ConversationStateParams extends UiStateParams {
  168. type: threema.ReceiverType;
  169. id: string;
  170. initParams: null | {text: string | null};
  171. }
  172. class ConversationController {
  173. public name = 'navigation';
  174. private logTag: string = '[ConversationController]';
  175. // Angular services
  176. private $stateParams;
  177. private $timeout: ng.ITimeoutService;
  178. private $state: UiStateService;
  179. private $log: ng.ILogService;
  180. private $scope: ng.IScope;
  181. private $rootScope: ng.IRootScopeService;
  182. private $filter: ng.IFilterService;
  183. private $translate: ng.translate.ITranslateService;
  184. // Own services
  185. private webClientService: WebClientService;
  186. private receiverService: ReceiverService;
  187. private stateService: StateService;
  188. private mimeService: MimeService;
  189. // Third party services
  190. private $mdDialog: ng.material.IDialogService;
  191. private $mdToast: ng.material.IToastService;
  192. // Controller model
  193. private controllerModel: threema.ControllerModel<threema.Receiver>;
  194. // DOM Elements
  195. private domChatElement: HTMLElement;
  196. // Scrolling
  197. public showScrollJump: boolean = false;
  198. // The conversation receiver
  199. public receiver: threema.Receiver;
  200. public type: threema.ReceiverType;
  201. // The conversation messages
  202. private messages: threema.Message[];
  203. // This will be set to true as soon as the initial messages have been loaded
  204. private initialized = false;
  205. // Mentions
  206. public allMentions: threema.Mention[] = [];
  207. public currentMentions: threema.Mention[] = [];
  208. public currentMentionFilterWord = null;
  209. public selectedMention: number = null;
  210. public message: string = '';
  211. public lastReadMsg: threema.Message | null = null;
  212. public msgReadReportPending = false;
  213. private hasMore = true;
  214. private latestRefMsgId: string | null = null;
  215. private allText: string;
  216. public initialData: threema.InitialConversationData = {
  217. draft: '',
  218. initialText: '',
  219. };
  220. private locked = false;
  221. public maxTextLength: number;
  222. public isTyping = (): boolean => false;
  223. private uploading = {
  224. enabled: false,
  225. value1: 0,
  226. value2: 0,
  227. };
  228. public static $inject = [
  229. '$stateParams', '$timeout', '$log', '$scope', '$rootScope',
  230. '$mdDialog', '$mdToast', '$translate', '$filter',
  231. '$state', '$transitions',
  232. 'WebClientService', 'StateService', 'ReceiverService', 'MimeService', 'VersionService',
  233. 'ControllerModelService',
  234. ];
  235. constructor($stateParams: ConversationStateParams,
  236. $timeout: ng.ITimeoutService,
  237. $log: ng.ILogService,
  238. $scope: ng.IScope,
  239. $rootScope: ng.IRootScopeService,
  240. $mdDialog: ng.material.IDialogService,
  241. $mdToast: ng.material.IToastService,
  242. $translate: ng.translate.ITranslateService,
  243. $filter: ng.IFilterService,
  244. $state: UiStateService,
  245. $transitions: UiTransitionService,
  246. webClientService: WebClientService,
  247. stateService: StateService,
  248. receiverService: ReceiverService,
  249. mimeService: MimeService,
  250. versionService: VersionService,
  251. controllerModelService: ControllerModelService) {
  252. this.$stateParams = $stateParams;
  253. this.$timeout = $timeout;
  254. this.$log = $log;
  255. this.webClientService = webClientService;
  256. this.receiverService = receiverService;
  257. this.stateService = stateService;
  258. this.mimeService = mimeService;
  259. this.$state = $state;
  260. this.$scope = $scope;
  261. this.$filter = $filter;
  262. this.$rootScope = $rootScope;
  263. this.$mdDialog = $mdDialog;
  264. this.$mdToast = $mdToast;
  265. this.$translate = $translate;
  266. // Close any showing dialogs
  267. this.$mdDialog.cancel();
  268. this.maxTextLength = this.webClientService.getMaxTextLength();
  269. this.allText = this.$translate.instant('messenger.ALL');
  270. // On every navigation event, close all dialogs using ui-router transition hooks.
  271. $transitions.onStart({}, function(trans: UiTransition) {
  272. const $mdDialogInner: ng.material.IDialogService = trans.injector().get('$mdDialog');
  273. $mdDialogInner.cancel();
  274. });
  275. // Check for version updates
  276. versionService.checkForUpdate();
  277. // Redirect to welcome if necessary
  278. if (stateService.state === 'error') {
  279. $log.debug('ConversationController: WebClient not yet running, redirecting to welcome screen');
  280. $state.go('welcome');
  281. return;
  282. }
  283. if (!this.locked) {
  284. // Get DOM references
  285. this.domChatElement = document.querySelector('#conversation-chat') as HTMLElement;
  286. // Add custom event handlers
  287. this.domChatElement.addEventListener('scroll', throttle(() => {
  288. $rootScope.$apply(() => {
  289. this.updateScrollJump();
  290. });
  291. }, 100, this), supportsPassive() ? {passive: true} : false);
  292. }
  293. // Set receiver and type
  294. try {
  295. this.receiver = webClientService.receivers.getData({type: $stateParams.type, id: $stateParams.id});
  296. this.type = $stateParams.type;
  297. if (this.receiver.type === undefined) {
  298. this.receiver.type = this.type;
  299. }
  300. // Initialize controller model
  301. const mode = ControllerModelMode.CHAT;
  302. switch (this.receiver.type) {
  303. case 'me':
  304. this.controllerModel = controllerModelService.me(
  305. this.receiver as threema.MeReceiver, mode);
  306. break;
  307. case 'contact':
  308. this.controllerModel = controllerModelService.contact(
  309. this.receiver as threema.ContactReceiver, mode);
  310. break;
  311. case 'group':
  312. this.controllerModel = controllerModelService.group(
  313. this.receiver as threema.GroupReceiver, mode);
  314. break;
  315. case 'distributionList':
  316. this.controllerModel = controllerModelService.distributionList(
  317. this.receiver as threema.DistributionListReceiver, mode);
  318. break;
  319. default:
  320. $log.error(this.logTag, 'Cannot initialize controller model:',
  321. 'Invalid receiver type "' + this.receiver.type + '"');
  322. $state.go('messenger.home');
  323. return;
  324. }
  325. // Check if this receiver may be chatted with
  326. if (this.controllerModel.canChat() === false) {
  327. $log.warn(this.logTag, 'Cannot chat with this receiver, redirecting to home');
  328. $state.go('messenger.home');
  329. return;
  330. }
  331. // initial set locked state
  332. this.locked = this.receiver.locked;
  333. this.receiverService.setActive(this.receiver);
  334. if (!this.receiver.locked) {
  335. let latestHeight = 0;
  336. // Subscribe to messages
  337. this.messages = this.webClientService.messages.register(
  338. this.receiver,
  339. this.$scope,
  340. (e, allMessages: threema.Message[], hasMore: boolean) => {
  341. // This function is called every time there are new or removed messages.
  342. // Update data
  343. this.messages = allMessages;
  344. const wasInitialized = this.initialized;
  345. this.initialized = true;
  346. this.hasMore = hasMore;
  347. // Update "first unread" divider
  348. if (!wasInitialized) {
  349. this.webClientService.messages.updateFirstUnreadMessage(this.receiver);
  350. }
  351. // Autoscroll
  352. if (this.latestRefMsgId !== null) {
  353. // scroll to div..
  354. this.domChatElement.scrollTop = this.domChatElement.scrollHeight - latestHeight;
  355. this.latestRefMsgId = null;
  356. }
  357. latestHeight = this.domChatElement.scrollHeight;
  358. },
  359. );
  360. // Update "first unread" divider
  361. this.webClientService.messages.updateFirstUnreadMessage(this.receiver);
  362. // Enable mentions only in group chats
  363. if (this.type === 'group') {
  364. this.allMentions.push({
  365. identity: null,
  366. query: this.$translate.instant('messenger.ALL').toLowerCase(),
  367. isAll: true,
  368. });
  369. this.controllerModel.getMembers().forEach((identity: string) => {
  370. const contactReceiver = this.webClientService.contacts.get(identity);
  371. if (contactReceiver) {
  372. this.allMentions.push({
  373. identity: identity,
  374. query: (contactReceiver.displayName + ' ' + identity).toLowerCase(),
  375. isAll: false,
  376. });
  377. }
  378. });
  379. }
  380. this.initialData = {
  381. draft: webClientService.getDraft(this.receiver),
  382. initialText: $stateParams.initParams ? $stateParams.initParams.text : '',
  383. };
  384. if (isContactReceiver(this.receiver)) {
  385. this.isTyping = () => this.webClientService.isTyping(this.receiver as threema.ContactReceiver);
  386. }
  387. }
  388. } catch (error) {
  389. $log.error('Could not set receiver and type');
  390. $log.debug(error.stack);
  391. $state.go('messenger.home');
  392. }
  393. // reload controller if locked state was changed
  394. $scope.$watch(() => {
  395. return this.receiver.locked;
  396. }, () => {
  397. if (this.locked !== this.receiver.locked) {
  398. $state.reload();
  399. }
  400. });
  401. }
  402. public isEnabled(): boolean {
  403. return this.type !== 'group'
  404. || !(this.receiver as threema.GroupReceiver).disabled;
  405. }
  406. public isQuoting(): boolean {
  407. return this.getQuote() !== undefined;
  408. }
  409. public getQuote(): threema.Quote {
  410. return this.webClientService.getQuote(this.receiver);
  411. }
  412. public cancelQuoting(): void {
  413. // Clear current quote
  414. this.webClientService.setQuote(this.receiver);
  415. }
  416. public showError(errorMessage: string, toastLength = 4000) {
  417. if (errorMessage === undefined || errorMessage.length === 0) {
  418. errorMessage = this.$translate.instant('error.ERROR_OCCURRED');
  419. }
  420. this.$mdToast.show(
  421. this.$mdToast.simple()
  422. .textContent(errorMessage)
  423. .position('bottom center'));
  424. }
  425. /**
  426. * Submit function for input field. Can contain text or file data.
  427. * Return whether sending was successful.
  428. */
  429. public submit = (type: threema.MessageContentType, contents: threema.MessageData[]): Promise<any> => {
  430. // Validate whether a connection is available
  431. return new Promise((resolve, reject) => {
  432. if (!this.stateService.readyToSubmit(this.webClientService.chosenTask)) {
  433. // Invalid connection, show toast and abort
  434. this.showError(this.$translate.instant('error.NO_CONNECTION'));
  435. return reject();
  436. }
  437. let success = true;
  438. const nextCallback = (index: number) => {
  439. if (index === contents.length - 1) {
  440. if (success) {
  441. resolve();
  442. } else {
  443. reject('Message sending unsuccessful');
  444. }
  445. }
  446. };
  447. switch (type) {
  448. case 'file':
  449. // Determine file type
  450. let showSendAsFileCheckbox = false;
  451. let captionSupported = false;
  452. for (const msg of contents as threema.FileMessageData[]) {
  453. if (!msg.fileType) {
  454. msg.fileType = 'application/octet-stream';
  455. }
  456. captionSupported = this.mimeService.isImage(msg.fileType);
  457. if (this.mimeService.isImage(msg.fileType)
  458. || this.mimeService.isAudio(msg.fileType)
  459. || this.mimeService.isVideo(msg.fileType)) {
  460. showSendAsFileCheckbox = true;
  461. break;
  462. }
  463. }
  464. // Prepare preview
  465. let preview: threema.FileMessageData | null = null;
  466. if (contents.length === 1) {
  467. const msg = contents[0] as threema.FileMessageData;
  468. if (this.mimeService.isImage(msg.fileType)) {
  469. preview = msg;
  470. }
  471. }
  472. // Eager translations
  473. const title = this.$translate.instant('messenger.CONFIRM_FILE_SEND', {
  474. senderName: (this.$filter('emojify') as any)
  475. ((this.$filter('emptyToPlaceholder') as any)(this.receiver.displayName, '-')),
  476. });
  477. const placeholder = this.$translate.instant('messenger.CONFIRM_FILE_CAPTION');
  478. const confirmSendAsFile = this.$translate.instant('messenger.CONFIRM_SEND_AS_FILE');
  479. // Show confirmation dialog
  480. this.$mdDialog.show({
  481. clickOutsideToClose: false,
  482. locals: { preview: preview },
  483. controller: 'SendFileController',
  484. controllerAs: 'ctrl',
  485. // tslint:disable:max-line-length
  486. template: `
  487. <md-dialog class="send-file-dialog">
  488. <md-dialog-content class="md-dialog-content">
  489. <h2 class="md-title">${title}</h2>
  490. <img class="preview" ng-if="ctrl.hasPreview()" ng-src="{{ ctrl.previewDataUrl }}" />
  491. <md-input-container md-no-float class="input-caption md-prompt-input-container" ng-show="!${showSendAsFileCheckbox} || ctrl.sendAsFile || ${captionSupported}">
  492. <input maxlength="1000" md-autofocus ng-keypress="ctrl.keypress($event)" ng-model="ctrl.caption" placeholder="${placeholder}" aria-label="${placeholder}">
  493. </md-input-container>
  494. <md-input-container md-no-float class="input-send-as-file md-prompt-input-container" ng-show="${showSendAsFileCheckbox}">
  495. <md-checkbox ng-model="ctrl.sendAsFile" aria-label="${confirmSendAsFile}">
  496. ${confirmSendAsFile}
  497. </md-checkbox>
  498. </md-input-container>
  499. </md-dialog-content>
  500. <md-dialog-actions>
  501. <button class="md-primary md-cancel-button md-button" md-ink-ripple type="button" ng-click="ctrl.cancel()">
  502. <span translate>common.CANCEL</span>
  503. </button>
  504. <button class="md-primary md-cancel-button md-button" md-ink-ripple type="button" ng-click="ctrl.send()">
  505. <span translate>common.SEND</span>
  506. </button>
  507. </md-dialog-actions>
  508. </md-dialog>
  509. `,
  510. // tslint:enable:max-line-length
  511. }).then((data) => {
  512. const caption = data.caption;
  513. const sendAsFile = data.sendAsFile;
  514. contents.forEach((msg: threema.FileMessageData, index: number) => {
  515. if (caption !== undefined && caption.length > 0) {
  516. msg.caption = caption;
  517. }
  518. msg.sendAsFile = sendAsFile;
  519. this.webClientService.sendMessage(this.$stateParams, type, msg)
  520. .then(() => {
  521. nextCallback(index);
  522. })
  523. .catch((error) => {
  524. this.$log.error(error);
  525. this.showError(error);
  526. success = false;
  527. nextCallback(index);
  528. });
  529. });
  530. }, angular.noop);
  531. break;
  532. case 'text':
  533. // do not show confirmation, send directly
  534. contents.forEach((msg: threema.MessageData, index: number) => {
  535. msg.quote = this.webClientService.getQuote(this.receiver);
  536. // remove quote
  537. this.webClientService.setQuote(this.receiver);
  538. // send message
  539. this.webClientService.sendMessage(this.$stateParams, type, msg)
  540. .then(() => {
  541. nextCallback(index);
  542. })
  543. .catch((error) => {
  544. this.$log.error(error);
  545. this.showError(error);
  546. success = false;
  547. nextCallback(index);
  548. });
  549. });
  550. return;
  551. default:
  552. this.$log.warn('Invalid message type:', type);
  553. reject();
  554. }
  555. });
  556. }
  557. /**
  558. * Something was typed.
  559. *
  560. * In contrast to startTyping, this method is is always called, not just if
  561. * the text field is non-empty.
  562. */
  563. public onTyping = (text: string, currentWord: threema.WordResult = null) => {
  564. // Update draft
  565. this.webClientService.setDraft(this.receiver, text);
  566. /* Make mentions readonly for now
  567. if (currentWord && currentWord.substr(0, 1) === '@') {
  568. this.currentMentionFilterWord = currentWord.substr(1);
  569. const query = this.currentMentionFilterWord.toLowerCase().trim();
  570. const selectedMentionObject = this.getSelectedMention();
  571. this.currentMentions = this.allMentions.filter((i) => {
  572. if (query.length === 0) {
  573. return true;
  574. }
  575. return i.query.indexOf(query) >= 0;
  576. });
  577. // If only one mention is filtered, select them
  578. if (this.currentMentions.length === 1) {
  579. this.selectedMention = 0;
  580. } else if (selectedMentionObject !== null) {
  581. // Get the new position of the latest selected mention object
  582. this.selectedMention = null;
  583. this.selectedMention = this.currentMentions.findIndex((m) => {
  584. return m.identity === selectedMentionObject.identity;
  585. });
  586. }
  587. } else {
  588. this.currentMentionFilterWord = null;
  589. }
  590. */
  591. }
  592. public getSelectedMention = (): threema.Mention => {
  593. if (this.selectedMention === null
  594. || this.selectedMention < 0
  595. || this.selectedMention > this.currentMentions.length - 1) {
  596. return null;
  597. }
  598. return this.currentMentions[this.selectedMention];
  599. }
  600. public showMentionSelector = (): boolean => {
  601. return this.type === 'group'
  602. && this.currentMentionFilterWord != null
  603. && this.currentMentions.length > 0;
  604. }
  605. /**
  606. * Handle mention selector navigation
  607. */
  608. public onComposeKeyDown = (ev: KeyboardEvent): boolean => {
  609. /* Make mentions readonly for now
  610. if (this.showMentionSelector() && !ev.shiftKey) {
  611. let move = ev.key === 'ArrowDown' ? 1 : (ev.key === 'ArrowUp' ? - 1 : 0);
  612. if (move !== 0) {
  613. // Move cursors position in mention selector
  614. if (this.selectedMention !== null) {
  615. this.selectedMention += move;
  616. // Fix positions
  617. if (this.selectedMention > this.currentMentions.length - 1) {
  618. this.selectedMention = 0;
  619. } else if (this.selectedMention < 0) {
  620. this.selectedMention = this.currentMentions.length - 1;
  621. }
  622. } else {
  623. this.selectedMention = 0;
  624. }
  625. return false;
  626. }
  627. if (ev.key === 'Enter') {
  628. // Enter, select current mention
  629. const selectedMentionObject = this.getSelectedMention();
  630. if (selectedMentionObject === null) {
  631. // If no (or a invalid) mention is selected, select the first mention
  632. this.selectedMention = 0;
  633. } else {
  634. this.onMentionSelected(selectedMentionObject.identity);
  635. }
  636. return false;
  637. }
  638. }
  639. */
  640. return true;
  641. }
  642. public onMentionSelected(identity: string = null): void {
  643. this.$rootScope.$broadcast('onMentionSelected', {
  644. query: '@' + this.currentMentionFilterWord,
  645. mention: '@[' + (identity === null ? '@@@@@@@@' : identity.toUpperCase()) + ']',
  646. });
  647. }
  648. public onUploading = (inProgress: boolean, percentCurrent: number = null, percentFull: number = null) => {
  649. this.uploading.enabled = inProgress;
  650. this.uploading.value1 = Number(percentCurrent);
  651. this.uploading.value2 = Number(percentCurrent);
  652. }
  653. /**
  654. * We started typing.
  655. */
  656. public startTyping = () => {
  657. // Notify app
  658. this.webClientService.sendMeIsTyping(this.$stateParams, true);
  659. }
  660. /**
  661. * We stopped typing.
  662. */
  663. public stopTyping = () => {
  664. // Notify app
  665. this.webClientService.sendMeIsTyping(this.$stateParams, false);
  666. }
  667. /**
  668. * User scrolled to the top of the chat.
  669. */
  670. public topOfChat(): void {
  671. this.requestMessages();
  672. }
  673. public requestMessages(): void {
  674. const refMsgId = this.webClientService.requestMessages(this.$stateParams);
  675. if (refMsgId !== null
  676. && refMsgId !== undefined) {
  677. // new message are requested, scroll to refMsgId
  678. this.latestRefMsgId = refMsgId;
  679. } else {
  680. this.latestRefMsgId = null;
  681. }
  682. }
  683. public showReceiver(ev): void {
  684. this.$state.go('messenger.home.detail', this.receiver);
  685. }
  686. public hasMoreMessages(): boolean {
  687. return this.hasMore;
  688. }
  689. /**
  690. * A message has been seen. Report it to the app, with a small delay to
  691. * avoid sending too many messages at once.
  692. */
  693. public msgRead(message: threema.Message): void {
  694. // Ignore status messages
  695. if (message.type === 'status') {
  696. return;
  697. }
  698. // Update lastReadMsg
  699. if (this.lastReadMsg === null || message.sortKey > this.lastReadMsg.sortKey) {
  700. this.lastReadMsg = message;
  701. }
  702. if (!this.msgReadReportPending) {
  703. // Don't send a read message for messages that are already read.
  704. // (Note: Ignore own messages since those are always read.)
  705. if (!message.isOutbox && !message.unread) {
  706. return;
  707. }
  708. // Don't send a read message for conversations that have no unread messages.
  709. const conversation = this.webClientService.conversations.find(this.receiver);
  710. if (conversation !== null && conversation.unreadCount === 0) {
  711. return;
  712. }
  713. this.msgReadReportPending = true;
  714. const receiver = angular.copy(this.receiver);
  715. receiver.type = this.type;
  716. this.$timeout(() => {
  717. this.webClientService.requestRead(receiver, this.lastReadMsg);
  718. this.msgReadReportPending = false;
  719. }, 300);
  720. }
  721. }
  722. public goBack(): void {
  723. this.receiverService.setActive(undefined);
  724. // redirect to messenger home
  725. this.$state.go('messenger.home');
  726. }
  727. /**
  728. * Scroll to bottom of chat.
  729. */
  730. public scrollDown(): void {
  731. this.domChatElement.scrollTop = this.domChatElement.scrollHeight;
  732. }
  733. /**
  734. * Only show the scroll to bottom button if user scrolled more than 10px
  735. * away from bottom.
  736. */
  737. private updateScrollJump(): void {
  738. const chat = this.domChatElement;
  739. this.showScrollJump = chat.scrollHeight - (chat.scrollTop + chat.offsetHeight) > 10;
  740. }
  741. }
  742. class NavigationController {
  743. public name = 'navigation';
  744. private webClientService: WebClientService;
  745. private receiverService: ReceiverService;
  746. private stateService: StateService;
  747. private trustedKeyStoreService: TrustedKeyStoreService;
  748. private activeTab: 'contacts' | 'conversations' = 'conversations';
  749. private searchVisible = false;
  750. private searchText: string = '';
  751. private $mdDialog;
  752. private $translate: ng.translate.ITranslateService;
  753. private $state: UiStateService;
  754. public static $inject = [
  755. '$log', '$state', '$mdDialog', '$translate',
  756. 'WebClientService', 'StateService', 'ReceiverService', 'TrustedKeyStore',
  757. ];
  758. constructor($log: ng.ILogService, $state: UiStateService,
  759. $mdDialog: ng.material.IDialogService, $translate: ng.translate.ITranslateService,
  760. webClientService: WebClientService, stateService: StateService,
  761. receiverService: ReceiverService,
  762. trustedKeyStoreService: TrustedKeyStoreService) {
  763. // Redirect to welcome if necessary
  764. if (stateService.state === 'error') {
  765. $log.debug('NavigationController: WebClient not yet running, redirecting to welcome screen');
  766. $state.go('welcome');
  767. return;
  768. }
  769. this.webClientService = webClientService;
  770. this.receiverService = receiverService;
  771. this.stateService = stateService;
  772. this.trustedKeyStoreService = trustedKeyStoreService;
  773. this.$mdDialog = $mdDialog;
  774. this.$translate = $translate;
  775. this.$state = $state;
  776. }
  777. public contacts(): threema.ContactReceiver[] {
  778. return Array.from(this.webClientService.contacts.values()) as threema.ContactReceiver[];
  779. }
  780. /**
  781. * Search for `needle` in the `haystack`. The search is case insensitive.
  782. */
  783. private matches(haystack: string, needle: string): boolean {
  784. return haystack.toLowerCase().replace('\n', ' ').indexOf(needle.trim().toLowerCase()) !== -1;
  785. }
  786. /**
  787. * Predicate function used for conversation filtering.
  788. *
  789. * Match by contact name *or* id *or* last message text.
  790. */
  791. private searchConversation = (value: threema.Conversation, index, array): boolean => {
  792. return this.searchText === ''
  793. || this.matches(value.receiver.displayName, this.searchText)
  794. || (value.latestMessage && value.latestMessage.body
  795. && this.matches(value.latestMessage.body, this.searchText))
  796. || (value.receiver.id.length === 8 && this.matches(value.receiver.id, this.searchText));
  797. }
  798. /**
  799. * Predicate function used for contact filtering.
  800. *
  801. * Match by contact name *or* id.
  802. */
  803. private searchContact = (value, index, array): boolean => {
  804. return this.searchText === ''
  805. || value.displayName.toLowerCase().indexOf(this.searchText.toLowerCase()) !== -1
  806. || value.id.toLowerCase().indexOf(this.searchText.toLowerCase()) !== -1;
  807. }
  808. public isVisible(conversation: threema.Conversation) {
  809. return conversation.receiver.visible;
  810. }
  811. public conversations(): threema.Conversation[] {
  812. return this.webClientService.conversations.get();
  813. }
  814. public isActive(value: threema.Conversation): boolean {
  815. return this.receiverService.isConversationActive(value);
  816. }
  817. /**
  818. * Return true if the app wants to hide inactive contacts.
  819. */
  820. public hideInactiveContacts(): boolean {
  821. return !this.webClientService.appConfig.showInactiveIDs;
  822. }
  823. /**
  824. * Show dialog.
  825. */
  826. public showDialog(name, ev) {
  827. this.$mdDialog.show({
  828. controller: DialogController,
  829. controllerAs: 'ctrl',
  830. templateUrl: 'partials/dialog.' + name + '.html',
  831. parent: angular.element(document.body),
  832. targetEvent: ev,
  833. clickOutsideToClose: true,
  834. fullscreen: true,
  835. });
  836. }
  837. /**
  838. * Show about dialog.
  839. */
  840. public about(ev): void {
  841. this.showDialog('about', ev);
  842. }
  843. /**
  844. * Show settings dialog.
  845. */
  846. public settings(ev): void {
  847. this.$mdDialog.show({
  848. controller: SettingsController,
  849. controllerAs: 'ctrl',
  850. templateUrl: 'partials/dialog.settings.html',
  851. parent: angular.element(document.body),
  852. targetEvent: ev,
  853. clickOutsideToClose: true,
  854. fullscreen: true,
  855. });
  856. }
  857. /**
  858. * Show profile.
  859. */
  860. public showProfile(ev): void {
  861. this.receiverService.setActive(undefined);
  862. this.$state.go('messenger.home.detail', this.webClientService.me);
  863. }
  864. /**
  865. * Return whether a trusted key is available.
  866. */
  867. public isPersistent(): boolean {
  868. return this.trustedKeyStoreService.hasTrustedKey();
  869. }
  870. /**
  871. * Close the session.
  872. */
  873. public closeSession(ev): void {
  874. const confirm = this.$mdDialog.confirm()
  875. .title(this.$translate.instant('common.SESSION_CLOSE'))
  876. .textContent(this.$translate.instant('common.CONFIRM_CLOSE_BODY'))
  877. .targetEvent(ev)
  878. .ok(this.$translate.instant('common.YES'))
  879. .cancel(this.$translate.instant('common.CANCEL'));
  880. this.$mdDialog.show(confirm).then(() => {
  881. const deleteStoredData = false;
  882. const resetPush = true;
  883. const redirect = true;
  884. this.webClientService.stop(true, deleteStoredData, resetPush, redirect);
  885. this.receiverService.setActive(undefined);
  886. }, () => {
  887. // do nothing
  888. });
  889. }
  890. /**
  891. * Close and delete the session.
  892. */
  893. public deleteSession(ev): void {
  894. const confirm = this.$mdDialog.confirm()
  895. .title(this.$translate.instant('common.SESSION_DELETE'))
  896. .textContent(this.$translate.instant('common.CONFIRM_DELETE_CLOSE_BODY'))
  897. .targetEvent(ev)
  898. .ok(this.$translate.instant('common.YES'))
  899. .cancel(this.$translate.instant('common.CANCEL'));
  900. this.$mdDialog.show(confirm).then(() => {
  901. const deleteStoredData = true;
  902. const resetPush = true;
  903. const redirect = true;
  904. this.webClientService.stop(true, deleteStoredData, resetPush, redirect);
  905. this.receiverService.setActive(undefined);
  906. }, () => {
  907. // do nothing
  908. });
  909. }
  910. public addContact(ev): void {
  911. this.$state.go('messenger.home.create', {
  912. type: 'contact',
  913. });
  914. }
  915. public createGroup(ev): void {
  916. this.$state.go('messenger.home.create', {
  917. type: 'group',
  918. });
  919. }
  920. public createDistributionList(ev): void {
  921. this.$state.go('messenger.home.create', {
  922. type: 'distributionList',
  923. });
  924. }
  925. /**
  926. * Toggle search bar.
  927. */
  928. public toggleSearch(): void {
  929. this.searchVisible = !this.searchVisible;
  930. }
  931. /**
  932. * Return the user profile.
  933. */
  934. public getMe(): threema.MeReceiver {
  935. return this.webClientService.me;
  936. }
  937. /**
  938. * Only show the "create distribution list" button if the app supports it.
  939. */
  940. public showCreateDistributionListButton(): boolean {
  941. return this.webClientService.appCapabilities.distributionLists;
  942. }
  943. }
  944. class MessengerController {
  945. private logTag: string = '[MessengerController]';
  946. public name = 'messenger';
  947. private receiverService: ReceiverService;
  948. private $state;
  949. private webClientService: WebClientService;
  950. public static $inject = [
  951. '$scope', '$state', '$log', '$mdDialog', '$translate',
  952. 'StateService', 'ReceiverService', 'WebClientService', 'ControllerService',
  953. ];
  954. constructor($scope, $state, $log: ng.ILogService, $mdDialog: ng.material.IDialogService,
  955. $translate: ng.translate.ITranslateService,
  956. stateService: StateService, receiverService: ReceiverService,
  957. webClientService: WebClientService, controllerService: ControllerService) {
  958. // Redirect to welcome if necessary
  959. if (stateService.state === 'error') {
  960. $log.debug(this.logTag, 'MessengerController: WebClient not yet running, redirecting to welcome screen');
  961. $state.go('welcome');
  962. return;
  963. }
  964. controllerService.setControllerName('messenger');
  965. this.receiverService = receiverService;
  966. this.$state = $state;
  967. this.webClientService = webClientService;
  968. // watch for alerts
  969. $scope.$watch(() => webClientService.alerts, (alerts: threema.Alert[]) => {
  970. if (alerts.length > 0) {
  971. angular.forEach(alerts, (alert: threema.Alert) => {
  972. $mdDialog.show(
  973. $mdDialog.alert()
  974. .clickOutsideToClose(true)
  975. .title(alert.type)
  976. .textContent(alert.message)
  977. .ok($translate.instant('common.OK')));
  978. });
  979. // clean array
  980. webClientService.alerts = [];
  981. }
  982. }, true);
  983. this.webClientService.setReceiverListener({
  984. onConversationRemoved(receiver: threema.Receiver) {
  985. switch ($state.current.name) {
  986. case 'messenger.home.conversation':
  987. case 'messenger.home.detail':
  988. case 'messenger.home.edit':
  989. if ($state.params !== undefined
  990. && $state.params.type !== undefined
  991. && $state.params.id !== undefined) {
  992. if ($state.params.type === receiver.type
  993. && $state.params.id === receiver.id) {
  994. // conversation or sub form is open, redirect to home!
  995. $state.go('messenger.home');
  996. }
  997. }
  998. break;
  999. default:
  1000. $log.debug(this.logTag, 'Ignored onRemoved event for state', $state.current.name);
  1001. }
  1002. },
  1003. });
  1004. }
  1005. public showDetail(): boolean {
  1006. return !this.$state.is('messenger.home');
  1007. }
  1008. }
  1009. class ReceiverDetailController {
  1010. private logTag: string = '[ReceiverDetailController]';
  1011. // Angular services
  1012. private $mdDialog: any;
  1013. private $scope: ng.IScope;
  1014. private $state: UiStateService;
  1015. // Own services
  1016. private fingerPrintService: FingerPrintService;
  1017. private contactService: ContactService;
  1018. private webClientService: WebClientService;
  1019. public receiver: threema.Receiver;
  1020. public me: threema.MeReceiver;
  1021. public title: string;
  1022. public fingerPrint = { value: null }; // Object, so that data binding works
  1023. private showGroups = false;
  1024. private showDistributionLists = false;
  1025. private inGroups: threema.GroupReceiver[] = [];
  1026. private inDistributionLists: threema.DistributionListReceiver[] = [];
  1027. private hasSystemEmails = false;
  1028. private hasSystemPhones = false;
  1029. private isWorkReceiver = false;
  1030. private showBlocked = () => false;
  1031. private controllerModel: threema.ControllerModel<threema.Receiver>;
  1032. public static $inject = [
  1033. '$scope', '$log', '$stateParams', '$state', '$mdDialog', '$translate',
  1034. 'WebClientService', 'FingerPrintService', 'ContactService', 'ControllerModelService',
  1035. ];
  1036. constructor($scope: ng.IScope, $log: ng.ILogService, $stateParams, $state: UiStateService,
  1037. $mdDialog: ng.material.IDialogService, $translate: ng.translate.ITranslateService,
  1038. webClientService: WebClientService, fingerPrintService: FingerPrintService,
  1039. contactService: ContactService, controllerModelService: ControllerModelService) {
  1040. this.$mdDialog = $mdDialog;
  1041. this.$scope = $scope;
  1042. this.$state = $state;
  1043. this.fingerPrintService = fingerPrintService;
  1044. this.contactService = contactService;
  1045. this.webClientService = webClientService;
  1046. this.receiver = webClientService.receivers.getData($stateParams);
  1047. this.me = webClientService.me;
  1048. // Append group membership
  1049. if (isContactReceiver(this.receiver)) {
  1050. const contactReceiver = this.receiver;
  1051. this.contactService.requiredDetails(contactReceiver)
  1052. .then(() => {
  1053. this.hasSystemEmails = contactReceiver.systemContact.emails.length > 0;
  1054. this.hasSystemPhones = contactReceiver.systemContact.phoneNumbers.length > 0;
  1055. })
  1056. .catch(() => {
  1057. // do nothing
  1058. });
  1059. this.isWorkReceiver = contactReceiver.identityType === threema.IdentityType.Work;
  1060. this.fingerPrintService
  1061. .generate(contactReceiver.publicKey)
  1062. .then(this.setFingerPrint.bind(this));
  1063. webClientService.groups.forEach((groupReceiver: threema.GroupReceiver) => {
  1064. // check if my identity is a member
  1065. if (groupReceiver.members.indexOf(contactReceiver.id) !== -1) {
  1066. this.inGroups.push(groupReceiver);
  1067. this.showGroups = true;
  1068. }
  1069. });
  1070. webClientService.distributionLists.forEach(
  1071. (distributionListReceiver: threema.DistributionListReceiver) => {
  1072. // check if my identity is a member
  1073. if (distributionListReceiver.members.indexOf(contactReceiver.id) !== -1) {
  1074. this.inDistributionLists.push(distributionListReceiver);
  1075. this.showDistributionLists = true;
  1076. }
  1077. },
  1078. );
  1079. this.showBlocked = () => contactReceiver.isBlocked;
  1080. }
  1081. switch (this.receiver.type) {
  1082. case 'me':
  1083. const meReceiver = this.receiver as threema.MeReceiver;
  1084. this.fingerPrintService
  1085. .generate(meReceiver.publicKey)
  1086. .then(this.setFingerPrint.bind(this));
  1087. this.controllerModel = controllerModelService.me(meReceiver, ControllerModelMode.VIEW);
  1088. break;
  1089. case 'contact':
  1090. const contactReceiver = this.receiver as threema.ContactReceiver;
  1091. this.fingerPrintService
  1092. .generate(contactReceiver.publicKey)
  1093. .then(this.setFingerPrint.bind(this));
  1094. this.controllerModel = controllerModelService
  1095. .contact(contactReceiver, ControllerModelMode.VIEW);
  1096. break;
  1097. case 'group':
  1098. this.controllerModel = controllerModelService
  1099. .group(this.receiver as threema.GroupReceiver, ControllerModelMode.VIEW);
  1100. break;
  1101. case 'distributionList':
  1102. this.controllerModel = controllerModelService
  1103. .distributionList(this.receiver as threema.DistributionListReceiver, ControllerModelMode.VIEW);
  1104. break;
  1105. default:
  1106. $log.error(this.logTag, 'Cannot initialize controller model:',
  1107. 'Invalid receiver type "' + this.receiver.type + '"');
  1108. $state.go('messenger.home');
  1109. return;
  1110. }
  1111. // If this receiver was removed, navigate to "home" view
  1112. this.controllerModel.setOnRemoved((receiverId: string) => {
  1113. $log.warn(this.logTag, 'Receiver removed, redirecting to home');
  1114. this.$state.go('messenger.home');
  1115. });
  1116. }
  1117. /**
  1118. * Set the fingerprint value and run $digest.
  1119. *
  1120. * This may only be called from outside the $digest loop
  1121. * (e.g. from a plain promise callback).
  1122. */
  1123. private setFingerPrint(fingerPrint: string): void {
  1124. this.fingerPrint.value = fingerPrint;
  1125. this.$scope.$digest();
  1126. }
  1127. public chat(): void {
  1128. this.$state.go('messenger.home.conversation', {
  1129. type: this.receiver.type,
  1130. id: this.receiver.id,
  1131. initParams: null,
  1132. });
  1133. }
  1134. public edit(): void {
  1135. if (!this.controllerModel.canEdit()) {
  1136. return;
  1137. }
  1138. this.$state.go('messenger.home.edit', {
  1139. type: this.receiver.type,
  1140. id: this.receiver.id,
  1141. initParams: null,
  1142. });
  1143. }
  1144. /**
  1145. * Show the QR code of the public key.
  1146. */
  1147. public showQr(): void {
  1148. const profile = this.webClientService.me;
  1149. const $mdDialog = this.$mdDialog;
  1150. $mdDialog.show({
  1151. controllerAs: 'ctrl',
  1152. controller: [function() {
  1153. this.cancel = () => {
  1154. $mdDialog.cancel();
  1155. };
  1156. this.profile = profile;
  1157. this.qrCode = {
  1158. errorCorrectionLevel: 'L',
  1159. size: '400px',
  1160. data: '3mid:'
  1161. + profile.id
  1162. + ','
  1163. + u8aToHex(new Uint8Array(profile.publicKey)),
  1164. };
  1165. }],
  1166. templateUrl: 'partials/dialog.qr.html',
  1167. parent: angular.element(document.body),
  1168. clickOutsideToClose: true,
  1169. fullscreen: true,
  1170. });
  1171. }
  1172. public goBack(): void {
  1173. window.history.back();
  1174. }
  1175. }
  1176. /**
  1177. * Control edit a group or a contact
  1178. * fields, validate and save routines are implemented in the specific ControllerModel
  1179. */
  1180. class ReceiverEditController {
  1181. private logTag: string = '[ReceiverEditController]';
  1182. public $mdDialog: any;
  1183. public $state: UiStateService;
  1184. private $translate: ng.translate.ITranslateService;
  1185. public title: string;
  1186. private $timeout: ng.ITimeoutService;
  1187. private execute: ExecuteService;
  1188. public loading = false;
  1189. private controllerModel: threema.ControllerModel<threema.Receiver>;
  1190. public type: string;
  1191. public static $inject = [
  1192. '$log', '$stateParams', '$state', '$mdDialog',
  1193. '$timeout', '$translate', 'WebClientService', 'ControllerModelService',
  1194. ];
  1195. constructor($log: ng.ILogService, $stateParams, $state: UiStateService,
  1196. $mdDialog, $timeout: ng.ITimeoutService, $translate: ng.translate.ITranslateService,
  1197. webClientService: WebClientService, controllerModelService: ControllerModelService) {
  1198. this.$mdDialog = $mdDialog;
  1199. this.$state = $state;
  1200. this.$timeout = $timeout;
  1201. this.$translate = $translate;
  1202. const receiver = webClientService.receivers.getData($stateParams);
  1203. switch (receiver.type) {
  1204. case 'me':
  1205. this.controllerModel = controllerModelService.me(
  1206. receiver as threema.MeReceiver,
  1207. ControllerModelMode.EDIT,
  1208. );
  1209. break;
  1210. case 'contact':
  1211. this.controllerModel = controllerModelService.contact(
  1212. receiver as threema.ContactReceiver,
  1213. ControllerModelMode.EDIT,
  1214. );
  1215. break;
  1216. case 'group':
  1217. this.controllerModel = controllerModelService.group(
  1218. receiver as threema.GroupReceiver,
  1219. ControllerModelMode.EDIT,
  1220. );
  1221. break;
  1222. case 'distributionList':
  1223. this.controllerModel = controllerModelService.distributionList(
  1224. receiver as threema.DistributionListReceiver,
  1225. ControllerModelMode.EDIT,
  1226. );
  1227. break;
  1228. default:
  1229. $log.error(this.logTag, 'Cannot initialize controller model:',
  1230. 'Invalid receiver type "' + receiver.type + '"');
  1231. $state.go('messenger.home');
  1232. return;
  1233. }
  1234. this.type = receiver.type;
  1235. this.execute = new ExecuteService($log, $timeout, 1000);
  1236. }
  1237. public keypress($event: KeyboardEvent): void {
  1238. if ($event.key === 'Enter' && this.controllerModel.isValid()) {
  1239. this.save();
  1240. }
  1241. }
  1242. public save(): void {
  1243. // show loading
  1244. this.loading = true;
  1245. // validate first
  1246. this.execute.execute(this.controllerModel.save())
  1247. .then((receiver: threema.Receiver) => {
  1248. this.goBack();
  1249. })
  1250. .catch((errorCode) => {
  1251. this.showEditError(errorCode);
  1252. });
  1253. }
  1254. public isSaving(): boolean {
  1255. return this.execute !== undefined
  1256. && this.execute.isRunning();
  1257. }
  1258. private showEditError(errorCode: string): void {
  1259. if (errorCode === undefined) {
  1260. errorCode = 'unknown';
  1261. }
  1262. this.$mdDialog.show(
  1263. this.$mdDialog.alert()
  1264. .clickOutsideToClose(true)
  1265. .title(this.controllerModel.subject)
  1266. .textContent(this.$translate.instant('validationError.modifyReceiver.' + errorCode))
  1267. .ok(this.$translate.instant('common.OK')),
  1268. );
  1269. }
  1270. public goBack(): void {
  1271. window.history.back();
  1272. }
  1273. }
  1274. interface CreateReceiverStateParams extends UiStateParams {
  1275. type: threema.ReceiverType;
  1276. initParams: null | {identity: string | null};
  1277. }
  1278. /**
  1279. * Control creating a group or adding contact
  1280. * fields, validate and save routines are implemented in the specific ControllerModel
  1281. */
  1282. class ReceiverCreateController {
  1283. private logTag: string = '[ReceiverEditController]';
  1284. public $mdDialog: any;
  1285. private loading = false;
  1286. private $timeout: ng.ITimeoutService;
  1287. private $log: ng.ILogService;
  1288. private $state: UiStateService;
  1289. private $mdToast: any;
  1290. public identity = '';
  1291. private $translate: any;
  1292. public type: string;
  1293. private execute: ExecuteService;
  1294. public controllerModel: threema.ControllerModel<threema.Receiver>;
  1295. public static $inject = ['$stateParams', '$mdDialog', '$mdToast', '$translate',
  1296. '$timeout', '$state', '$log', 'ControllerModelService'];
  1297. constructor($stateParams: CreateReceiverStateParams, $mdDialog, $mdToast, $translate,
  1298. $timeout: ng.ITimeoutService, $state: UiStateService, $log: ng.ILogService,
  1299. controllerModelService: ControllerModelService) {
  1300. this.$mdDialog = $mdDialog;
  1301. this.$timeout = $timeout;
  1302. this.$state = $state;
  1303. this.$log = $log;
  1304. this.$mdToast = $mdToast;
  1305. this.$translate = $translate;
  1306. this.type = $stateParams.type;
  1307. switch (this.type) {
  1308. case 'me':
  1309. $log.warn(this.logTag, 'Cannot create own contact');
  1310. $state.go('messenger.home');
  1311. return;
  1312. case 'contact':
  1313. this.controllerModel = controllerModelService.contact(null, ControllerModelMode.NEW);
  1314. if ($stateParams.initParams !== null) {
  1315. (this.controllerModel as ContactControllerModel)
  1316. .identity = $stateParams.initParams.identity;
  1317. }
  1318. break;
  1319. case 'group':
  1320. this.controllerModel = controllerModelService.group(null, ControllerModelMode.NEW);
  1321. break;
  1322. case 'distributionList':
  1323. this.controllerModel = controllerModelService.distributionList(null, ControllerModelMode.NEW);
  1324. break;
  1325. default:
  1326. this.$log.error('invalid type', this.type);
  1327. }
  1328. this.execute = new ExecuteService($log, $timeout, 1000);
  1329. }
  1330. public isSaving(): boolean {
  1331. return this.execute.isRunning();
  1332. }
  1333. public goBack(): void {
  1334. if (!this.isSaving()) {
  1335. window.history.back();
  1336. }
  1337. }
  1338. private showAddError(errorCode: string): void {
  1339. if (errorCode === undefined) {
  1340. errorCode = 'unknown';
  1341. }
  1342. this.$mdDialog.show(
  1343. this.$mdDialog.alert()
  1344. .clickOutsideToClose(true)
  1345. .title(this.controllerModel.subject)
  1346. .textContent(this.$translate.instant('validationError.modifyReceiver.' + errorCode))
  1347. .ok(this.$translate.instant('common.OK')),
  1348. );
  1349. }
  1350. public keypress($event: KeyboardEvent): void {
  1351. if ($event.key === 'Enter' && this.controllerModel.isValid()) {
  1352. this.create();
  1353. }
  1354. }
  1355. public create(): void {
  1356. // Show loading indicator
  1357. this.loading = true;
  1358. // Save, then go to receiver detail page
  1359. this.execute.execute(this.controllerModel.save())
  1360. .then((receiver: threema.Receiver) => {
  1361. this.$state.go('messenger.home.detail', receiver, {location: 'replace'});
  1362. })
  1363. .catch(this.showAddError.bind(this));
  1364. }
  1365. }
  1366. angular.module('3ema.messenger', ['ngMaterial'])
  1367. .config(['$stateProvider', function($stateProvider: UiStateProvider) {
  1368. $stateProvider
  1369. .state('messenger', {
  1370. abstract: true,
  1371. templateUrl: 'partials/messenger.html',
  1372. controller: 'MessengerController',
  1373. controllerAs: 'ctrl',
  1374. })
  1375. .state('messenger.home', {
  1376. url: '/messenger',
  1377. views: {
  1378. navigation: {
  1379. templateUrl: 'partials/messenger.navigation.html',
  1380. controller: 'NavigationController',
  1381. controllerAs: 'ctrl',
  1382. },
  1383. content: {
  1384. // Required because navigation should not be changed,
  1385. template: '<div ui-view></div>',
  1386. },
  1387. },
  1388. })
  1389. .state('messenger.home.conversation', {
  1390. url: '/conversation/{type}/{id}',
  1391. templateUrl: 'partials/messenger.conversation.html',
  1392. controller: 'ConversationController',
  1393. controllerAs: 'ctrl',
  1394. params: {initParams: null},
  1395. })
  1396. .state('messenger.home.detail', {
  1397. url: '/conversation/{type}/{id}/detail',
  1398. templateUrl: 'partials/messenger.receiver.html',
  1399. controller: 'ReceiverDetailController',
  1400. controllerAs: 'ctrl',
  1401. })
  1402. .state('messenger.home.edit', {
  1403. url: '/conversation/{type}/{id}/detail/edit',
  1404. templateUrl: 'partials/messenger.receiver.edit.html',
  1405. controller: 'ReceiverEditController',
  1406. controllerAs: 'ctrl',
  1407. })
  1408. .state('messenger.home.create', {
  1409. url: '/receiver/create/{type}',
  1410. templateUrl: 'partials/messenger.receiver.create.html',
  1411. controller: 'ReceiverCreateController',
  1412. controllerAs: 'ctrl',
  1413. params: {initParams: null},
  1414. })
  1415. ;
  1416. }])
  1417. .controller('SendFileController', SendFileController)
  1418. .controller('MessengerController', MessengerController)
  1419. .controller('ConversationController', ConversationController)
  1420. .controller('NavigationController', NavigationController)
  1421. .controller('ReceiverDetailController', ReceiverDetailController)
  1422. .controller('ReceiverEditController', ReceiverEditController)
  1423. .controller('ReceiverCreateController', ReceiverCreateController)
  1424. ;