messenger.ts 44 KB

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