messenger.ts 59 KB

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