messenger.ts 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  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 {ContactControllerModel} from '../controller_model/contact';
  18. import {supportsPassive, throttle} from '../helpers';
  19. import {ContactService} from '../services/contact';
  20. import {ControllerService} from '../services/controller';
  21. import {ControllerModelService} from '../services/controller_model';
  22. import {ExecuteService} from '../services/execute';
  23. import {FingerPrintService} from '../services/fingerprint';
  24. import {TrustedKeyStoreService} from '../services/keystore';
  25. import {MimeService} from '../services/mime';
  26. import {NotificationService} from '../services/notification';
  27. import {ReceiverService} from '../services/receiver';
  28. import {SettingsService} from '../services/settings';
  29. import {StateService} from '../services/state';
  30. import {WebClientService} from '../services/webclient';
  31. import {ControllerModelMode} from '../types/enums';
  32. abstract class DialogController {
  33. public static $inject = ['$mdDialog'];
  34. public $mdDialog: ng.material.IDialogService;
  35. public activeElement: HTMLElement | null;
  36. constructor($mdDialog: ng.material.IDialogService) {
  37. this.$mdDialog = $mdDialog;
  38. this.activeElement = document.activeElement as HTMLElement;
  39. }
  40. public cancel(): void {
  41. this.$mdDialog.cancel();
  42. this.done();
  43. }
  44. protected hide(data: any): void {
  45. this.$mdDialog.hide(data);
  46. this.done();
  47. }
  48. private done(): void {
  49. if (this.resumeFocusOnClose() === true && this.activeElement !== null) {
  50. // reset focus
  51. this.activeElement.focus();
  52. }
  53. }
  54. /**
  55. * If true, the focus on the active element (before opening the dialog)
  56. * will be restored.
  57. */
  58. protected abstract resumeFocusOnClose(): boolean;
  59. }
  60. /**
  61. * Handle sending of files.
  62. */
  63. class SendFileController extends DialogController {
  64. public caption: string;
  65. public sendAsFile: boolean = false;
  66. public send(): void {
  67. this.hide({
  68. caption: this.caption,
  69. sendAsFile: this.sendAsFile,
  70. });
  71. }
  72. public keypress($event: KeyboardEvent): void {
  73. if ($event.key === 'Enter') { // see https://developer.mozilla.org/de/docs/Web/API/KeyboardEvent/key/Key_Values
  74. this.send();
  75. }
  76. }
  77. protected resumeFocusOnClose(): boolean {
  78. return true;
  79. }
  80. }
  81. /**
  82. * Handle settings
  83. */
  84. class SettingsController {
  85. public static $inject = ['$mdDialog', '$window', 'SettingsService', 'NotificationService'];
  86. public $mdDialog: ng.material.IDialogService;
  87. public $window: ng.IWindowService;
  88. public settingsService: SettingsService;
  89. private notificationService: NotificationService;
  90. public activeElement: HTMLElement | null;
  91. private desktopNotifications: boolean;
  92. private notificationApiAvailable: boolean;
  93. private notificationPermission: boolean;
  94. private notificationPreview: boolean;
  95. constructor($mdDialog: ng.material.IDialogService,
  96. $window: ng.IWindowService,
  97. settingsService: SettingsService,
  98. notificationService: NotificationService) {
  99. this.$mdDialog = $mdDialog;
  100. this.$window = $window;
  101. this.settingsService = settingsService;
  102. this.notificationService = notificationService;
  103. this.activeElement = document.activeElement as HTMLElement;
  104. this.desktopNotifications = notificationService.getWantsNotifications();
  105. this.notificationApiAvailable = notificationService.isNotificationApiAvailable();
  106. this.notificationPermission = notificationService.getNotificationPermission();
  107. this.notificationPreview = notificationService.getWantsPreview();
  108. }
  109. public cancel(): void {
  110. this.$mdDialog.cancel();
  111. this.done();
  112. }
  113. protected hide(data: any): void {
  114. this.$mdDialog.hide(data);
  115. this.done();
  116. }
  117. private done(): void {
  118. if (this.activeElement !== null) {
  119. // Reset focus
  120. this.activeElement.focus();
  121. }
  122. }
  123. public setWantsNotifications(desktopNotifications: boolean) {
  124. this.notificationService.setWantsNotifications(desktopNotifications);
  125. }
  126. public setWantsPreview(notificationPreview: boolean) {
  127. this.notificationService.setWantsPreview(notificationPreview);
  128. }
  129. }
  130. class ConversationController {
  131. public name = 'navigation';
  132. // Angular services
  133. private $stateParams;
  134. private $timeout: ng.ITimeoutService;
  135. private $state: ng.ui.IStateService;
  136. private $log: ng.ILogService;
  137. private $scope: ng.IScope;
  138. // Own services
  139. private webClientService: WebClientService;
  140. private receiverService: ReceiverService;
  141. private stateService: StateService;
  142. private mimeService: MimeService;
  143. // Third party services
  144. private $mdDialog: ng.material.IDialogService;
  145. private $mdToast: ng.material.IToastService;
  146. // DOM Elements
  147. private domChatElement: HTMLElement;
  148. // Scrolling
  149. public showScrollJump: boolean = false;
  150. private stopTypingTimer: ng.IPromise<void> = null;
  151. public receiver: threema.Receiver;
  152. public type: threema.ReceiverType;
  153. public message: string = '';
  154. public lastReadMsgId: number = 0;
  155. public msgReadReportPending = false;
  156. private hasMore = true;
  157. private latestRefMsgId: number = null;
  158. private messages: threema.Message[];
  159. private draft: string;
  160. private $translate: ng.translate.ITranslateService;
  161. private locked = false;
  162. public maxTextLength: number;
  163. public isTyping = (): boolean => false;
  164. private uploading = {
  165. enabled: false,
  166. value1: 0,
  167. value2: 0,
  168. };
  169. public static $inject = [
  170. '$stateParams', '$state', '$timeout', '$log', '$scope', '$rootScope',
  171. '$mdDialog', '$mdToast', '$location', '$translate',
  172. 'WebClientService', 'StateService', 'ReceiverService', 'MimeService',
  173. ];
  174. constructor($stateParams,
  175. $state: ng.ui.IStateService,
  176. $timeout: ng.ITimeoutService,
  177. $log: ng.ILogService,
  178. $scope: ng.IScope,
  179. $rootScope: ng.IRootScopeService,
  180. $mdDialog: ng.material.IDialogService,
  181. $mdToast: ng.material.IToastService,
  182. $location,
  183. $translate: ng.translate.ITranslateService,
  184. webClientService: WebClientService,
  185. stateService: StateService,
  186. receiverService: ReceiverService,
  187. mimeService: MimeService) {
  188. this.$stateParams = $stateParams;
  189. this.$timeout = $timeout;
  190. this.$log = $log;
  191. this.webClientService = webClientService;
  192. this.receiverService = receiverService;
  193. this.stateService = stateService;
  194. this.mimeService = mimeService;
  195. this.$state = $state;
  196. this.$scope = $scope;
  197. this.$mdDialog = $mdDialog;
  198. this.$mdToast = $mdToast;
  199. this.$translate = $translate;
  200. // Close any showing dialogs
  201. this.$mdDialog.cancel();
  202. this.maxTextLength = this.webClientService.getMaxTextLength();
  203. // On every navigation event, close all dialogs.
  204. // Note: Deprecated. When migrating ui-router ($state),
  205. // replace with transition hooks.
  206. $rootScope.$on('$stateChangeStart', () => this.$mdDialog.cancel());
  207. // Redirect to welcome if necessary
  208. if (stateService.state === 'error') {
  209. $log.debug('ConversationController: WebClient not yet running, redirecting to welcome screen');
  210. $state.go('welcome');
  211. return;
  212. }
  213. if (!this.locked) {
  214. // Get DOM references
  215. this.domChatElement = document.querySelector('#conversation-chat') as HTMLElement;
  216. // Add custom event handlers
  217. this.domChatElement.addEventListener('scroll', throttle(() => {
  218. $rootScope.$apply(() => {
  219. this.updateScrollJump();
  220. });
  221. }, 100, this), supportsPassive() ? {passive: true} as any : false);
  222. }
  223. // Set receiver and type
  224. try {
  225. this.receiver = webClientService.receivers.getData($stateParams);
  226. this.type = $stateParams.type;
  227. if (this.receiver.type === undefined) {
  228. this.receiver.type = this.type;
  229. }
  230. // initial set locked state
  231. this.locked = this.receiver.locked;
  232. this.receiverService.setActive(this.receiver);
  233. if (!this.receiver.locked) {
  234. let latestHeight = 0;
  235. // update unread count
  236. this.webClientService.messages.updateFirstUnreadMessage(this.receiver);
  237. this.messages = this.webClientService.messages.register(
  238. this.receiver,
  239. this.$scope,
  240. (e, allMessages: threema.Message[], hasMore: boolean) => {
  241. this.messages = allMessages;
  242. this.hasMore = hasMore;
  243. if (this.latestRefMsgId !== null) {
  244. // scroll to div..
  245. this.domChatElement.scrollTop =
  246. this.domChatElement.scrollHeight - latestHeight;
  247. this.latestRefMsgId = null;
  248. }
  249. latestHeight = this.domChatElement.scrollHeight;
  250. },
  251. );
  252. this.draft = webClientService.getDraft(this.receiver);
  253. if (this.receiver.type === 'contact') {
  254. this.isTyping = () => this.webClientService.isTyping(this.receiver as threema.ContactReceiver);
  255. }
  256. }
  257. } catch (error) {
  258. $log.error('Could not set receiver and type');
  259. $log.debug(error.stack);
  260. $state.go('messenger.home');
  261. }
  262. // reload controller if locked state was changed
  263. $scope.$watch(() => {
  264. return this.receiver.locked;
  265. }, () => {
  266. if (this.locked !== this.receiver.locked) {
  267. $state.reload();
  268. }
  269. });
  270. }
  271. public isEnabled(): boolean {
  272. return this.type !== 'group'
  273. || !(this.receiver as threema.GroupReceiver).disabled;
  274. }
  275. public isQuoting(): boolean {
  276. return this.getQuote() !== undefined;
  277. }
  278. public getQuote(): threema.Quote {
  279. return this.webClientService.getQuote(this.receiver);
  280. }
  281. public cancelQuoting(): void {
  282. // clear curren quote
  283. this.webClientService.setQuote(this.receiver);
  284. }
  285. public showError(errorMessage: string, toastLength = 4000) {
  286. if (errorMessage === undefined || errorMessage.length === 0) {
  287. errorMessage = this.$translate.instant('error.ERROR_OCCURRED');
  288. }
  289. this.$mdToast.show(
  290. this.$mdToast.simple()
  291. .textContent(errorMessage)
  292. .position('bottom center'));
  293. }
  294. /**
  295. * Submit function for input field. Can contain text or file data.
  296. * Return whether sending was successful.
  297. */
  298. public submit = (type: threema.MessageContentType, contents: threema.MessageData[]): Promise<any> => {
  299. // Validate whether a connection is available
  300. return new Promise((resolve, reject) => {
  301. if (this.stateService.state !== 'ok') {
  302. // Invalid connection, show toast and abort
  303. this.showError(this.$translate.instant('error.NO_CONNECTION'));
  304. return reject();
  305. }
  306. let success = true;
  307. let nextCallback = (index: number) => {
  308. if (index === contents.length - 1) {
  309. if (success) {
  310. resolve();
  311. } else {
  312. reject();
  313. }
  314. }
  315. };
  316. switch (type) {
  317. case 'file':
  318. // Determine file type
  319. let showSendAsFileCheckbox = false;
  320. for (let msg of contents) {
  321. const mime = (msg as threema.FileMessageData).fileType;
  322. if (this.mimeService.isImage(mime)
  323. || this.mimeService.isAudio(mime)
  324. || this.mimeService.isVideo(mime)) {
  325. showSendAsFileCheckbox = true;
  326. break;
  327. }
  328. }
  329. // Eager translations
  330. const title = this.$translate.instant('messenger.CONFIRM_FILE_SEND', {
  331. senderName: this.receiver.displayName,
  332. });
  333. const placeholder = this.$translate.instant('messenger.CONFIRM_FILE_CAPTION');
  334. const confirmSendAsFile = this.$translate.instant('messenger.CONFIRM_SEND_AS_FILE');
  335. // Show confirmation dialog
  336. this.$mdDialog.show({
  337. clickOutsideToClose: false,
  338. controller: 'SendFileController',
  339. controllerAs: 'ctrl',
  340. // tslint:disable:max-line-length
  341. template: `
  342. <md-dialog class="send-file-dialog">
  343. <md-dialog-content class="md-dialog-content">
  344. <h2 class="md-title">${title}</h2>
  345. <md-input-container md-no-float class="input-caption md-prompt-input-container">
  346. <input md-autofocus ng-keypress="ctrl.keypress($event)" ng-model="ctrl.caption" placeholder="${placeholder}" aria-label="${placeholder}">
  347. </md-input-container>
  348. <md-input-container md-no-float class="input-send-as-file md-prompt-input-container" ng-show="${showSendAsFileCheckbox}">
  349. <md-checkbox ng-model="ctrl.sendAsFile" aria-label="${confirmSendAsFile}">
  350. ${confirmSendAsFile}
  351. </md-checkbox>
  352. </md-input-container>
  353. </md-dialog-content>
  354. <md-dialog-actions>
  355. <button class="md-primary md-cancel-button md-button" md-ink-ripple type="button" ng-click="ctrl.cancel()">
  356. <span translate>common.CANCEL</span>
  357. </button>
  358. <button class="md-primary md-cancel-button md-button" md-ink-ripple type="button" ng-click="ctrl.send()">
  359. <span translate>common.SEND</span>
  360. </button>
  361. </md-dialog-actions>
  362. </md-dialog>
  363. `,
  364. // tslint:enable:max-line-length
  365. }).then((data) => {
  366. const caption = data.caption;
  367. const sendAsFile = data.sendAsFile;
  368. contents.forEach((msg: threema.FileMessageData, index: number) => {
  369. if (caption !== undefined && caption.length > 0) {
  370. msg.caption = caption;
  371. }
  372. msg.sendAsFile = sendAsFile;
  373. this.webClientService.sendMessage(this.$stateParams, type, msg)
  374. .then(() => {
  375. nextCallback(index);
  376. })
  377. .catch((error) => {
  378. this.$log.error(error);
  379. this.showError(error);
  380. success = false;
  381. nextCallback(index);
  382. });
  383. });
  384. }, angular.noop);
  385. break;
  386. case 'text':
  387. // do not show confirmation, send directly
  388. contents.forEach((msg: threema.MessageData, index: number) => {
  389. msg.quote = this.webClientService.getQuote(this.receiver);
  390. // remove quote
  391. this.webClientService.setQuote(this.receiver);
  392. // send message
  393. this.webClientService.sendMessage(this.$stateParams, type, msg)
  394. .then(() => {
  395. nextCallback(index);
  396. })
  397. .catch((error) => {
  398. this.$log.error(error);
  399. this.showError(error);
  400. success = false;
  401. nextCallback(index);
  402. });
  403. });
  404. return;
  405. default:
  406. this.$log.warn('Invalid message type:', type);
  407. reject();
  408. }
  409. });
  410. }
  411. /**
  412. * Something was typed.
  413. *
  414. * In contrast to startTyping, this method is is always called, not just if
  415. * the text field is non-empty.
  416. */
  417. public onTyping = (text: string) => {
  418. // Update draft
  419. this.webClientService.setDraft(this.receiver, text);
  420. }
  421. public onUploading = (inProgress: boolean, percentCurrent: number = null, percentFull: number = null) => {
  422. this.uploading.enabled = inProgress;
  423. this.uploading.value1 = Number(percentCurrent);
  424. this.uploading.value2 = Number(percentCurrent);
  425. }
  426. /**
  427. * We started typing.
  428. */
  429. public startTyping = (text: string) => {
  430. if (this.stopTypingTimer === null) {
  431. // Notify app
  432. this.webClientService.sendMeIsTyping(this.$stateParams, true);
  433. } else {
  434. // Stop existing timer
  435. this.$timeout.cancel(this.stopTypingTimer);
  436. }
  437. // Define a timeout to send the stopTyping event
  438. this.stopTypingTimer = this.$timeout(() => {
  439. this.stopTyping();
  440. }, 10000);
  441. }
  442. /**
  443. * We stopped typing.
  444. */
  445. public stopTyping = () => {
  446. // Cancel timer if present
  447. if (this.stopTypingTimer !== null) {
  448. this.$timeout.cancel(this.stopTypingTimer);
  449. this.stopTypingTimer = null;
  450. }
  451. // Notify app
  452. this.webClientService.sendMeIsTyping(this.$stateParams, false);
  453. }
  454. /**
  455. * User scrolled to the top of the chat.
  456. */
  457. public topOfChat(): void {
  458. this.requestMessages();
  459. }
  460. public requestMessages(): void {
  461. let refMsgId = this.webClientService.requestMessages(this.$stateParams);
  462. if (refMsgId !== null
  463. && refMsgId !== undefined) {
  464. // new message are requested, scroll to refMsgId
  465. this.latestRefMsgId = refMsgId;
  466. } else {
  467. this.latestRefMsgId = null;
  468. }
  469. }
  470. public showReceiver(ev): void {
  471. this.$state.go('messenger.home.detail', this.receiver);
  472. }
  473. public hasMoreMessages(): boolean {
  474. return this.hasMore;
  475. }
  476. /**
  477. * A message has been seen. Report it to the app, with a small delay to
  478. * avoid sending too many messages at once.
  479. */
  480. public msgRead(msgId: number): void {
  481. if (msgId > this.lastReadMsgId) {
  482. this.lastReadMsgId = msgId;
  483. }
  484. if (!this.msgReadReportPending) {
  485. this.msgReadReportPending = true;
  486. const receiver = angular.copy(this.receiver);
  487. receiver.type = this.type;
  488. this.$timeout(() => {
  489. this.webClientService.requestRead(receiver, this.lastReadMsgId);
  490. this.msgReadReportPending = false;
  491. }, 500);
  492. }
  493. }
  494. public goBack(): void {
  495. this.receiverService.setActive(undefined);
  496. // redirect to messenger home
  497. this.$state.go('messenger.home');
  498. }
  499. /**
  500. * Scroll to bottom of chat.
  501. */
  502. public scrollDown(): void {
  503. this.domChatElement.scrollTop = this.domChatElement.scrollHeight;
  504. }
  505. /**
  506. * Only show the scroll to bottom button if user scrolled more than 10px
  507. * away from bottom.
  508. */
  509. private updateScrollJump(): void {
  510. const chat = this.domChatElement;
  511. this.showScrollJump = chat.scrollHeight - (chat.scrollTop + chat.offsetHeight) > 10;
  512. }
  513. }
  514. class NavigationController {
  515. public name = 'navigation';
  516. private webClientService: WebClientService;
  517. private receiverService: ReceiverService;
  518. private stateService: StateService;
  519. private trustedKeyStoreService: TrustedKeyStoreService;
  520. private activeTab: 'contacts' | 'conversations' = 'conversations';
  521. private searchVisible = false;
  522. private searchText: string = '';
  523. private $mdDialog;
  524. private $translate: ng.translate.ITranslateService;
  525. private $state: ng.ui.IStateService;
  526. public static $inject = [
  527. '$log', '$state', '$mdDialog', '$translate',
  528. 'WebClientService', 'StateService', 'ReceiverService', 'TrustedKeyStore',
  529. ];
  530. constructor($log: ng.ILogService, $state: ng.ui.IStateService,
  531. $mdDialog: ng.material.IDialogService, $translate: ng.translate.ITranslateService,
  532. webClientService: WebClientService, stateService: StateService,
  533. receiverService: ReceiverService,
  534. trustedKeyStoreService: TrustedKeyStoreService) {
  535. // Redirect to welcome if necessary
  536. if (stateService.state === 'error') {
  537. $log.debug('NavigationController: WebClient not yet running, redirecting to welcome screen');
  538. $state.go('welcome');
  539. return;
  540. }
  541. this.webClientService = webClientService;
  542. this.receiverService = receiverService;
  543. this.stateService = stateService;
  544. this.trustedKeyStoreService = trustedKeyStoreService;
  545. this.$mdDialog = $mdDialog;
  546. this.$translate = $translate;
  547. this.$state = $state;
  548. }
  549. public contacts(): threema.ContactReceiver[] {
  550. return Array.from(this.webClientService.contacts.values()) as threema.ContactReceiver[];
  551. }
  552. /**
  553. * Search for `needle` in the `haystack`. The search is case insensitive.
  554. */
  555. private matches(haystack: string, needle: string): boolean {
  556. return haystack.toLowerCase().replace('\n', ' ').indexOf(needle.trim().toLowerCase()) !== -1;
  557. }
  558. /**
  559. * Predicate function used for conversation filtering.
  560. *
  561. * Match by contact name *or* id *or* last message text.
  562. */
  563. private searchConversation = (value: threema.Conversation, index, array): boolean => {
  564. return this.searchText === ''
  565. || this.matches(value.receiver.displayName, this.searchText)
  566. || (value.latestMessage && value.latestMessage.body
  567. && this.matches(value.latestMessage.body, this.searchText))
  568. || (value.receiver.id.length === 8 && this.matches(value.receiver.id, this.searchText));
  569. }
  570. /**
  571. * Predicate function used for contact filtering.
  572. *
  573. * Match by contact name *or* id.
  574. */
  575. private searchContact = (value, index, array): boolean => {
  576. return this.searchText === ''
  577. || value.displayName.toLowerCase().indexOf(this.searchText.toLowerCase()) !== -1
  578. || value.id.toLowerCase().indexOf(this.searchText.toLowerCase()) !== -1;
  579. }
  580. public isVisible(conversation: threema.Conversation) {
  581. return conversation.receiver.visible;
  582. }
  583. public conversations(): threema.Conversation[] {
  584. return this.webClientService.conversations.get();
  585. }
  586. public isActive(value: threema.Conversation): boolean {
  587. return this.receiverService.isConversationActive(value);
  588. }
  589. /**
  590. * Show dialog.
  591. */
  592. public showDialog(name, ev) {
  593. this.$mdDialog.show({
  594. controller: DialogController,
  595. controllerAs: 'ctrl',
  596. templateUrl: 'partials/dialog.' + name + '.html',
  597. parent: angular.element(document.body),
  598. targetEvent: ev,
  599. clickOutsideToClose: true,
  600. fullscreen: true,
  601. });
  602. }
  603. /**
  604. * Show about dialog.
  605. */
  606. public about(ev): void {
  607. this.showDialog('about', ev);
  608. }
  609. /**
  610. * Show settings dialog.
  611. */
  612. public settings(ev): void {
  613. this.$mdDialog.show({
  614. controller: SettingsController,
  615. controllerAs: 'ctrl',
  616. templateUrl: 'partials/dialog.settings.html',
  617. parent: angular.element(document.body),
  618. targetEvent: ev,
  619. clickOutsideToClose: true,
  620. fullscreen: true,
  621. });
  622. }
  623. /**
  624. * Return whether a trusted key is available.
  625. */
  626. public isPersistent(): boolean {
  627. return this.trustedKeyStoreService.hasTrustedKey();
  628. }
  629. /**
  630. * Close the session.
  631. */
  632. public closeSession(ev): void {
  633. const confirm = this.$mdDialog.confirm()
  634. .title(this.$translate.instant('common.SESSION_CLOSE'))
  635. .textContent(this.$translate.instant('common.CONFIRM_CLOSE_BODY'))
  636. .targetEvent(ev)
  637. .ok(this.$translate.instant('common.YES'))
  638. .cancel(this.$translate.instant('common.CANCEL'));
  639. this.$mdDialog.show(confirm).then(() => {
  640. const deleteStoredData = false;
  641. const resetPush = true;
  642. const redirect = true;
  643. this.webClientService.stop(true, deleteStoredData, resetPush, redirect);
  644. }, () => {
  645. // do nothing
  646. });
  647. }
  648. /**
  649. * Close and delete the session.
  650. */
  651. public deleteSession(ev): void {
  652. const confirm = this.$mdDialog.confirm()
  653. .title(this.$translate.instant('common.SESSION_DELETE'))
  654. .textContent(this.$translate.instant('common.CONFIRM_DELETE_CLOSE_BODY'))
  655. .targetEvent(ev)
  656. .ok(this.$translate.instant('common.YES'))
  657. .cancel(this.$translate.instant('common.CANCEL'));
  658. this.$mdDialog.show(confirm).then(() => {
  659. const deleteStoredData = true;
  660. const resetPush = true;
  661. const redirect = true;
  662. this.webClientService.stop(true, deleteStoredData, resetPush, redirect);
  663. }, () => {
  664. // do nothing
  665. });
  666. }
  667. public addContact(ev): void {
  668. this.$state.go('messenger.home.create', {
  669. type: 'contact',
  670. });
  671. }
  672. public createGroup(ev): void {
  673. this.$state.go('messenger.home.create', {
  674. type: 'group',
  675. });
  676. }
  677. public createDistributionList(ev): void {
  678. this.$state.go('messenger.home.create', {
  679. type: 'distributionList',
  680. });
  681. }
  682. /**
  683. * Toggle search bar.
  684. */
  685. public toggleSearch(): void {
  686. this.searchVisible = !this.searchVisible;
  687. }
  688. public getMyIdentity(): threema.Identity {
  689. return this.webClientService.getMyIdentity();
  690. }
  691. public showMyIdentity(): boolean {
  692. return this.getMyIdentity() !== undefined;
  693. }
  694. }
  695. class MessengerController {
  696. public name = 'messenger';
  697. private receiverService: ReceiverService;
  698. private $state;
  699. private webClientService: WebClientService;
  700. public static $inject = [
  701. '$scope', '$state', '$log', '$mdDialog', '$translate',
  702. 'StateService', 'ReceiverService', 'WebClientService', 'ControllerService',
  703. ];
  704. constructor($scope, $state, $log: ng.ILogService, $mdDialog: ng.material.IDialogService,
  705. $translate: ng.translate.ITranslateService,
  706. stateService: StateService, receiverService: ReceiverService,
  707. webClientService: WebClientService, controllerService: ControllerService) {
  708. // Redirect to welcome if necessary
  709. if (stateService.state === 'error') {
  710. $log.debug('MessengerController: WebClient not yet running, redirecting to welcome screen');
  711. $state.go('welcome');
  712. return;
  713. }
  714. controllerService.setControllerName('messenger');
  715. this.receiverService = receiverService;
  716. this.$state = $state;
  717. this.webClientService = webClientService;
  718. // watch for alerts
  719. $scope.$watch(() => webClientService.alerts, (alerts: threema.Alert[]) => {
  720. if (alerts.length > 0) {
  721. angular.forEach(alerts, (alert: threema.Alert) => {
  722. $mdDialog.show(
  723. $mdDialog.alert()
  724. .clickOutsideToClose(true)
  725. .title(alert.type)
  726. .textContent(alert.message)
  727. .ok($translate.instant('common.OK')));
  728. });
  729. // clean array
  730. webClientService.alerts = [];
  731. }
  732. }, true);
  733. this.webClientService.setReceiverListener({
  734. onRemoved(receiver: threema.Receiver) {
  735. switch ($state.current.name) {
  736. case 'messenger.home.conversation':
  737. case 'messenger.home.detail':
  738. case 'messenger.home.edit':
  739. if ($state.params !== undefined
  740. && $state.params.type !== undefined
  741. && $state.params.id !== undefined) {
  742. if ($state.params.type === receiver.type
  743. && $state.params.id === receiver.id) {
  744. // conversation or sub form is open, redirect to home!
  745. this.$state.go('messenger.home', null, {location: 'replace'});
  746. }
  747. }
  748. break;
  749. default:
  750. $log.warn('Ignored onRemoved event for state', $state.current.name);
  751. }
  752. },
  753. });
  754. }
  755. public showDetail(): boolean {
  756. return !this.$state.is('messenger.home');
  757. }
  758. }
  759. class ReceiverDetailController {
  760. public $mdDialog: any;
  761. public $state: ng.ui.IStateService;
  762. public receiver: threema.Receiver;
  763. public title: string;
  764. public fingerPrint?: string;
  765. private fingerPrintService: FingerPrintService;
  766. private contactService: ContactService;
  767. private showGroups = false;
  768. private showDistributionLists = false;
  769. private inGroups: threema.GroupReceiver[] = [];
  770. private inDistributionLists: threema.DistributionListReceiver[] = [];
  771. private hasSystemEmails = false;
  772. private hasSystemPhones = false;
  773. private controllerModel: threema.ControllerModel;
  774. public static $inject = [
  775. '$log', '$stateParams', '$state', '$mdDialog',
  776. 'WebClientService', 'FingerPrintService', 'ContactService', 'ControllerModelService',
  777. ];
  778. constructor($log: ng.ILogService, $stateParams, $state: ng.ui.IStateService, $mdDialog: ng.material.IDialogService,
  779. webClientService: WebClientService, fingerPrintService: FingerPrintService,
  780. contactService: ContactService, controllerModelService: ControllerModelService) {
  781. this.$mdDialog = $mdDialog;
  782. this.$state = $state;
  783. this.fingerPrintService = fingerPrintService;
  784. this.contactService = contactService;
  785. this.receiver = webClientService.receivers.getData($stateParams);
  786. // append members
  787. if (this.receiver.type === 'contact') {
  788. let contactReceiver = (<threema.ContactReceiver> this.receiver);
  789. this.contactService.requiredDetails(contactReceiver)
  790. .then(() => {
  791. this.hasSystemEmails = contactReceiver.systemContact.emails.length > 0;
  792. this.hasSystemPhones = contactReceiver.systemContact.phoneNumbers.length > 0;
  793. })
  794. .catch(() => {
  795. // do nothing
  796. });
  797. this.fingerPrint = this.fingerPrintService.generate(contactReceiver.publicKey);
  798. webClientService.groups.forEach((groupReceiver: threema.GroupReceiver) => {
  799. // check if my identity is a member
  800. if (groupReceiver.members.indexOf(contactReceiver.id) !== -1) {
  801. this.inGroups.push(groupReceiver);
  802. this.showGroups = true;
  803. }
  804. });
  805. webClientService.distributionLists.forEach(
  806. (distributionListReceiver: threema.DistributionListReceiver) => {
  807. // check if my identity is a member
  808. if (distributionListReceiver.members.indexOf(contactReceiver.id) !== -1) {
  809. this.inDistributionLists.push(distributionListReceiver);
  810. this.showDistributionLists = true;
  811. }
  812. },
  813. );
  814. }
  815. switch (this.receiver.type) {
  816. case 'contact':
  817. this.controllerModel = controllerModelService
  818. .contact(this.receiver as threema.ContactReceiver, ControllerModelMode.VIEW);
  819. break;
  820. case 'group':
  821. this.controllerModel = controllerModelService
  822. .group(this.receiver as threema.GroupReceiver, ControllerModelMode.VIEW);
  823. break;
  824. case 'distributionList':
  825. this.controllerModel = controllerModelService
  826. .distributionList(this.receiver as threema.DistributionListReceiver, ControllerModelMode.VIEW);
  827. break;
  828. default:
  829. $log.warn('Invalid receiver type:', this.receiver.type);
  830. }
  831. // if this receiver was removed, navigation to "home" view
  832. this.controllerModel.setOnRemoved((receiverId: string) => {
  833. // go "home"
  834. this.$state.go('messenger.home', null, {location: 'replace'});
  835. });
  836. }
  837. public chat(): void {
  838. this.$state.go('messenger.home.conversation', this.receiver);
  839. }
  840. public edit(): void {
  841. if (!this.controllerModel.canEdit()) {
  842. return;
  843. }
  844. this.$state.go('messenger.home.edit', this.receiver);
  845. }
  846. public goBack(): void {
  847. window.history.back();
  848. }
  849. }
  850. /**
  851. * Control edit a group or a contact
  852. * fields, validate and save routines are implemented in the specific ControllerModel
  853. */
  854. class ReceiverEditController {
  855. public $mdDialog: any;
  856. public $state: ng.ui.IStateService;
  857. private $translate: ng.translate.ITranslateService;
  858. public title: string;
  859. private $timeout: ng.ITimeoutService;
  860. private execute: ExecuteService;
  861. public loading = false;
  862. private controllerModel: threema.ControllerModel;
  863. public type: string;
  864. public static $inject = [
  865. '$log', '$stateParams', '$state', '$mdDialog',
  866. '$timeout', '$translate', 'WebClientService', 'ControllerModelService',
  867. ];
  868. constructor($log: ng.ILogService, $stateParams, $state: ng.ui.IStateService,
  869. $mdDialog, $timeout: ng.ITimeoutService, $translate: ng.translate.ITranslateService,
  870. webClientService: WebClientService, controllerModelService: ControllerModelService) {
  871. this.$mdDialog = $mdDialog;
  872. this.$state = $state;
  873. this.$timeout = $timeout;
  874. this.$translate = $translate;
  875. const receiver = webClientService.receivers.getData($stateParams);
  876. switch (receiver.type) {
  877. case 'contact':
  878. this.controllerModel = controllerModelService.contact(
  879. receiver as threema.ContactReceiver,
  880. ControllerModelMode.EDIT,
  881. );
  882. break;
  883. case 'group':
  884. this.controllerModel = controllerModelService.group(
  885. receiver as threema.GroupReceiver,
  886. ControllerModelMode.EDIT,
  887. );
  888. break;
  889. case 'distributionList':
  890. this.controllerModel = controllerModelService.distributionList(
  891. receiver as threema.DistributionListReceiver,
  892. ControllerModelMode.EDIT,
  893. );
  894. break;
  895. default:
  896. $log.warn('Invalid receiver type:', receiver.type);
  897. }
  898. this.execute = new ExecuteService($log, $timeout, 1000);
  899. this.type = receiver.type;
  900. }
  901. public save(): void {
  902. // show loading
  903. this.loading = true;
  904. // validate first
  905. this.execute.execute(this.controllerModel.save())
  906. .then((receiver: threema.Receiver) => {
  907. this.goBack();
  908. })
  909. .catch((errorCode) => {
  910. this.showError(errorCode);
  911. });
  912. }
  913. public isSaving(): boolean {
  914. return this.execute.isRunning();
  915. }
  916. public showError(errorCode): void {
  917. this.$mdDialog.show(
  918. this.$mdDialog.alert()
  919. .clickOutsideToClose(true)
  920. .title(this.controllerModel.subject)
  921. .textContent(this.$translate.instant('validationError.editReceiver.' + errorCode))
  922. .ok(this.$translate.instant('common.OK')));
  923. }
  924. public goBack(): void {
  925. window.history.back();
  926. }
  927. }
  928. /**
  929. * Control creating a group or adding contact
  930. * fields, validate and save routines are implemented in the specific ControllerModel
  931. */
  932. class ReceiverCreateController {
  933. public static $inject = ['$stateParams', '$mdDialog', '$mdToast', '$translate',
  934. '$timeout', '$state', '$log', 'ControllerModelService'];
  935. public $mdDialog: any;
  936. private loading = false;
  937. private $timeout: ng.ITimeoutService;
  938. private $log: ng.ILogService;
  939. private $state: ng.ui.IStateService;
  940. private $mdToast: any;
  941. public identity = '';
  942. private $translate: any;
  943. public type: string;
  944. private execute: ExecuteService;
  945. public controllerModel: threema.ControllerModel;
  946. constructor($stateParams: threema.CreateReceiverStateParams, $mdDialog, $mdToast, $translate,
  947. $timeout: ng.ITimeoutService, $state: ng.ui.IStateService, $log: ng.ILogService,
  948. controllerModelService: ControllerModelService) {
  949. this.$mdDialog = $mdDialog;
  950. this.$timeout = $timeout;
  951. this.$state = $state;
  952. this.$log = $log;
  953. this.$mdToast = $mdToast;
  954. this.$translate = $translate;
  955. this.type = $stateParams.type;
  956. switch (this.type) {
  957. case 'contact':
  958. this.controllerModel = controllerModelService.contact(null, ControllerModelMode.NEW);
  959. if ($stateParams.initParams !== null) {
  960. (this.controllerModel as ContactControllerModel)
  961. .identity = $stateParams.initParams.identity;
  962. }
  963. break;
  964. case 'group':
  965. this.controllerModel = controllerModelService.group(null, ControllerModelMode.NEW);
  966. break;
  967. case 'distributionList':
  968. this.controllerModel = controllerModelService.distributionList(null, ControllerModelMode.NEW);
  969. break;
  970. default:
  971. this.$log.error('invalid type', this.type);
  972. }
  973. this.execute = new ExecuteService($log, $timeout, 1000);
  974. }
  975. public isSaving(): boolean {
  976. return this.execute.isRunning();
  977. }
  978. public goBack(): void {
  979. if (!this.isSaving()) {
  980. window.history.back();
  981. }
  982. }
  983. private showAddError(errorCode: String): void {
  984. if (errorCode === undefined) {
  985. errorCode = 'invalid_entry';
  986. }
  987. this.$mdDialog.show(
  988. this.$mdDialog.alert()
  989. .clickOutsideToClose(true)
  990. .title(this.controllerModel.subject)
  991. .textContent(this.$translate.instant('validationError.createReceiver.' + errorCode))
  992. .ok(this.$translate.instant('common.OK')),
  993. );
  994. }
  995. public create(): void {
  996. // show loading
  997. this.loading = true;
  998. // validate first
  999. this.execute.execute(this.controllerModel.save())
  1000. .then((receiver: threema.Receiver) => {
  1001. this.$state.go('messenger.home.detail', receiver, {location: 'replace'});
  1002. })
  1003. .catch((errorCode) => {
  1004. this.showAddError(errorCode);
  1005. });
  1006. }
  1007. }
  1008. angular.module('3ema.messenger', ['ngMaterial'])
  1009. .config(['$stateProvider', function($stateProvider: ng.ui.IStateProvider) {
  1010. $stateProvider
  1011. .state('messenger', {
  1012. abstract: true,
  1013. templateUrl: 'partials/messenger.html',
  1014. controller: 'MessengerController',
  1015. controllerAs: 'ctrl',
  1016. })
  1017. .state('messenger.home', {
  1018. url: '/messenger',
  1019. views: {
  1020. navigation: {
  1021. templateUrl: 'partials/messenger.navigation.html',
  1022. controller: 'NavigationController',
  1023. controllerAs: 'ctrl',
  1024. },
  1025. content: {
  1026. // Required because navigation should not be changed,
  1027. template: '<div ui-view></div>',
  1028. },
  1029. },
  1030. })
  1031. .state('messenger.home.conversation', {
  1032. url: '/conversation/{type}/{id}',
  1033. templateUrl: 'partials/messenger.conversation.html',
  1034. controller: 'ConversationController',
  1035. controllerAs: 'ctrl',
  1036. })
  1037. .state('messenger.home.detail', {
  1038. url: '/conversation/{type}/{id}/detail',
  1039. templateUrl: 'partials/messenger.receiver.html',
  1040. controller: 'ReceiverDetailController',
  1041. controllerAs: 'ctrl',
  1042. })
  1043. .state('messenger.home.edit', {
  1044. url: '/conversation/{type}/{id}/detail/edit',
  1045. templateUrl: 'partials/messenger.receiver.edit.html',
  1046. controller: 'ReceiverEditController',
  1047. controllerAs: 'ctrl',
  1048. })
  1049. .state('messenger.home.create', {
  1050. url: '/receiver/create/{type}',
  1051. templateUrl: 'partials/messenger.receiver.create.html',
  1052. controller: 'ReceiverCreateController',
  1053. controllerAs: 'ctrl',
  1054. params: {initParams: null},
  1055. })
  1056. ;
  1057. }])
  1058. .controller('SendFileController', SendFileController)
  1059. .controller('MessengerController', MessengerController)
  1060. .controller('ConversationController', ConversationController)
  1061. .controller('NavigationController', NavigationController)
  1062. .controller('ReceiverDetailController', ReceiverDetailController)
  1063. .controller('ReceiverEditController', ReceiverEditController)
  1064. .controller('ReceiverCreateController', ReceiverCreateController)
  1065. ;