messenger.ts 64 KB

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