messenger.ts 63 KB

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