filters.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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 {escapeRegExp, filter} from './helpers';
  18. import {MimeService} from './services/mime';
  19. import {NotificationService} from './services/notification';
  20. import {WebClientService} from './services/webclient';
  21. angular.module('3ema.filters', [])
  22. /**
  23. * Escape HTML by replacing special characters with HTML entities.
  24. */
  25. .filter('escapeHtml', function() {
  26. const map = {
  27. '&': '&amp;',
  28. '<': '&lt;',
  29. '>': '&gt;',
  30. '"': '&quot;',
  31. "'": '&#039;',
  32. };
  33. return (text: string) => {
  34. if (text === undefined || text === null) {
  35. text = '';
  36. }
  37. return text.replace(/[&<>"']/g, (m) => map[m]);
  38. };
  39. })
  40. /**
  41. * Replace newline characters with a <br> tag.
  42. */
  43. .filter('nlToBr', function() {
  44. return (text, enabled: boolean) => {
  45. if (enabled || enabled === undefined) {
  46. text = text.replace(/\n/g, '<br>');
  47. }
  48. return text;
  49. };
  50. })
  51. /**
  52. * Replace a undefined/null or empty string with a placeholder
  53. */
  54. .filter('emptyToPlaceholder', function() {
  55. return (text, placeholder: string = '-') => {
  56. if (text === null || text === undefined || text.trim().length === 0) {
  57. return placeholder;
  58. }
  59. return text;
  60. };
  61. })
  62. /**
  63. * Convert links in text to <a> tags.
  64. */
  65. .filter('linkify', function() {
  66. const autolinker = new Autolinker({
  67. // Open links in new window
  68. newWindow: true,
  69. // Don't strip protocol prefix
  70. stripPrefix: false,
  71. // Don't truncate links
  72. truncate: 99999,
  73. // Add class name to linked links
  74. className: 'autolinked',
  75. // Link urls
  76. urls: true,
  77. // Link e-mails
  78. email: true,
  79. // Don't link phone numbers (doesn't work reliably)
  80. phone: false,
  81. // Don't link twitter handles
  82. twitter: false,
  83. // Don't link hashtags
  84. hashtag: false,
  85. });
  86. return (text) => autolinker.link(text);
  87. })
  88. /**
  89. * Convert emoji unicode characters to images.
  90. * Reference: http://git.emojione.com/demos/latest/index.html#js
  91. *
  92. * Set the `imgTag` parameter to `true` to use inline PNGs instead of sprites.
  93. */
  94. .filter('emojify', function() {
  95. return function(text, imgTag = false, greedyMatch = false) {
  96. if (text !== null) {
  97. emojione.sprites = imgTag !== true;
  98. emojione.emojiSize = '32';
  99. emojione.imagePathPNG = 'img/e1/';
  100. emojione.greedyMatch = greedyMatch;
  101. return emojione.unicodeToImage(text);
  102. } else {
  103. return text;
  104. }
  105. };
  106. })
  107. /**
  108. * Enlarge 1-3 emoji.
  109. */
  110. .filter('enlargeSingleEmoji', function() {
  111. const pattern = /<span class="e1 ([^>]*>[^<]*)<\/span>/g;
  112. const singleEmojiThreshold = 3;
  113. const singleEmojiClassName = 'large-emoji';
  114. return function(text, enlarge = false) {
  115. if (!enlarge) {
  116. return text;
  117. }
  118. const matches = text.match(pattern);
  119. if (matches != null && matches.length >= 1 && matches.length <= singleEmojiThreshold) {
  120. if (text.replace(pattern, '').length === 0) {
  121. text = text.replace(pattern, '<span class="e1 ' + singleEmojiClassName + ' $1</span>');
  122. }
  123. }
  124. return text;
  125. };
  126. })
  127. /**
  128. * Convert markdown elements to html elements
  129. */
  130. .filter('markify', function() {
  131. return function(text) {
  132. if (text !== null) {
  133. text = text.replace(/\B\*([^\r\n]+?)\*\B/g, '<span class="text-bold">$1</span>');
  134. text = text.replace(/\b_([^\r\n]+?)_\b/g, '<span class="text-italic">$1</span>');
  135. text = text.replace(/\B~([^\r\n]+?)~\B/g, '<span class="text-strike">$1</span>');
  136. return text;
  137. }
  138. return text;
  139. };
  140. })
  141. /**
  142. * Convert mention elements to html elements
  143. */
  144. .filter('mentionify', [
  145. 'WebClientService',
  146. '$translate',
  147. 'escapeHtmlFilter',
  148. function(webClientService: WebClientService, $translate: ng.translate.ITranslateService, escapeHtmlFilter) {
  149. return(text) => {
  150. if (text !== null && text.length > 10) {
  151. let result = text.match(/@\[([\*\@a-zA-Z0-9][\@a-zA-Z0-9]{7})\]/g);
  152. if (result !== null) {
  153. result = ([...new Set(result)]);
  154. // Unique
  155. for (const possibleMention of result) {
  156. const identity = possibleMention.substr(2, 8);
  157. let mentionName;
  158. let cssClass;
  159. if (identity === '@@@@@@@@') {
  160. mentionName = $translate.instant('messenger.ALL');
  161. cssClass = 'all';
  162. } else if (identity === webClientService.me.id) {
  163. mentionName = webClientService.me.displayName;
  164. cssClass = 'me';
  165. } else {
  166. const contact = webClientService.contacts.get(possibleMention.substr(2, 8));
  167. if (contact !== null && contact !== undefined) {
  168. // Add identity to class for a simpler parsing
  169. cssClass = 'id ' + identity;
  170. mentionName = contact.displayName;
  171. }
  172. }
  173. if (mentionName !== undefined) {
  174. text = text.replace(
  175. new RegExp(escapeRegExp(possibleMention), 'g'),
  176. '<span class="mention ' + cssClass + '"'
  177. + ' text="@[' + identity + ']">' + escapeHtmlFilter(mentionName) + '</span>',
  178. );
  179. }
  180. }
  181. }
  182. }
  183. return text;
  184. };
  185. },
  186. ])
  187. /**
  188. * Reverse an array.
  189. */
  190. .filter('reverse', function() {
  191. return (list) => list.slice().reverse();
  192. })
  193. /**
  194. * Return whether receiver has corresponding data.
  195. */
  196. .filter('hasData', function() {
  197. return function(obj, receivers) {
  198. const valid = (receiver) => receivers.get(receiver.type).has(receiver.id);
  199. return filter(obj, valid);
  200. };
  201. })
  202. /**
  203. * Return whether item has a corresponding contact.
  204. */
  205. .filter('hasContact', function() {
  206. return function(obj, contacts) {
  207. const valid = (item) => contacts.has(item.id);
  208. return filter(obj, valid);
  209. };
  210. })
  211. /**
  212. * Return whether contact is not me.
  213. */
  214. .filter('isNotMe', ['WebClientService', function(webClientService: WebClientService) {
  215. return function(obj: threema.Receiver) {
  216. const valid = (contact: threema.Receiver) => contact.id !== webClientService.receivers.me.id;
  217. return filter(obj, valid);
  218. };
  219. }])
  220. /**
  221. * Filter for duration formatting.
  222. */
  223. .filter('duration', function() {
  224. return function(seconds) {
  225. const left = Math.floor(seconds / 60);
  226. const right = seconds % 60;
  227. const padLeft = left < 10 ? '0' : '';
  228. const padRight = right < 10 ? '0' : '';
  229. return padLeft + left + ':' + padRight + right;
  230. };
  231. })
  232. .filter('bufferToUrl', ['$sce', '$log', function($sce, $log) {
  233. const logTag = '[filters.bufferToUrl]';
  234. return function(buffer: ArrayBuffer, mimeType: string, trust: boolean = true) {
  235. if (!buffer) {
  236. $log.error(logTag, 'Could not apply bufferToUrl filter: buffer is', buffer);
  237. return '';
  238. }
  239. let binary = '';
  240. const bytes = new Uint8Array(buffer);
  241. const len = bytes.byteLength;
  242. for (let i = 0; i < len; i++) {
  243. binary += String.fromCharCode(bytes[i]);
  244. }
  245. switch (mimeType) {
  246. case 'image/jpeg':
  247. case 'image/png':
  248. case 'image/webp':
  249. // OK
  250. break;
  251. default:
  252. $log.warn(logTag, 'Unknown mimeType: ' + mimeType);
  253. mimeType = 'image/jpeg';
  254. break;
  255. }
  256. const uri = 'data:' + mimeType + ';base64,' + btoa(binary);
  257. if (trust) {
  258. return $sce.trustAsResourceUrl(uri);
  259. } else {
  260. return uri;
  261. }
  262. };
  263. }])
  264. .filter('mapLink', function() {
  265. return function(location: threema.LocationInfo) {
  266. return 'https://www.openstreetmap.org/?mlat='
  267. + location.lat + '&mlon='
  268. + location.lon;
  269. };
  270. })
  271. /**
  272. * Convert message state to material icon class.
  273. */
  274. .filter('messageStateIcon', function() {
  275. return (message: threema.Message) => {
  276. if (!message) {
  277. return '';
  278. }
  279. if (!message.isOutbox) {
  280. switch (message.state) {
  281. case 'user-ack':
  282. return 'thumb_up';
  283. case 'user-dec':
  284. return 'thumb_down';
  285. default:
  286. return 'reply';
  287. }
  288. }
  289. switch (message.state) {
  290. case 'pending':
  291. case 'sending':
  292. return 'file_upload';
  293. case 'sent':
  294. return 'email';
  295. case 'delivered':
  296. return 'move_to_inbox';
  297. case 'read':
  298. return 'visibility';
  299. case 'send-failed':
  300. return 'report_problem';
  301. case 'user-ack':
  302. return 'thumb_up';
  303. case 'user-dec':
  304. return 'thumb_down';
  305. default:
  306. return '';
  307. }
  308. };
  309. })
  310. .filter('fileSize', function() {
  311. return (size: number) => {
  312. if (!size) {
  313. return '';
  314. }
  315. const i = Math.floor( Math.log(size) / Math.log(1024) );
  316. const x = (size / Math.pow(1024, i)).toFixed(2);
  317. return (x + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i]);
  318. };
  319. })
  320. /**
  321. * Return the MIME type label.
  322. */
  323. .filter('mimeTypeLabel', ['MimeService', function(mimeService: MimeService) {
  324. return (mimeType: string) => mimeService.getLabel(mimeType);
  325. }])
  326. /**
  327. * Return the MIME type icon URL.
  328. */
  329. .filter('mimeTypeIcon', ['MimeService', function(mimeService: MimeService) {
  330. return (mimeType: string) => mimeService.getIconUrl(mimeType);
  331. }])
  332. /**
  333. * Convert ID-Array to (Display-)Name-String, separated by ','
  334. */
  335. .filter('idsToNames', ['WebClientService', function(webClientService: WebClientService) {
  336. return(ids: string[]) => {
  337. const names: string[] = [];
  338. for (const id of ids) {
  339. this.contactReceiver = webClientService.contacts.get(id);
  340. names.push(this.contactReceiver.displayName);
  341. }
  342. return names.join(', ');
  343. };
  344. }])
  345. /**
  346. * Format a unix timestamp as a date.
  347. */
  348. .filter('unixToTimestring', ['$translate', function($translate) {
  349. function formatTime(date) {
  350. return ('00' + date.getHours()).slice(-2) + ':' +
  351. ('00' + date.getMinutes()).slice(-2);
  352. }
  353. function formatMonth(num) {
  354. switch (num) {
  355. case 0x0:
  356. return 'date.month_short.JAN';
  357. case 0x1:
  358. return 'date.month_short.FEB';
  359. case 0x2:
  360. return 'date.month_short.MAR';
  361. case 0x3:
  362. return 'date.month_short.APR';
  363. case 0x4:
  364. return 'date.month_short.MAY';
  365. case 0x5:
  366. return 'date.month_short.JUN';
  367. case 0x6:
  368. return 'date.month_short.JUL';
  369. case 0x7:
  370. return 'date.month_short.AUG';
  371. case 0x8:
  372. return 'date.month_short.SEP';
  373. case 0x9:
  374. return 'date.month_short.OCT';
  375. case 0xa:
  376. return 'date.month_short.NOV';
  377. case 0xb:
  378. return 'date.month_short.DEC';
  379. }
  380. }
  381. function isSameDay(date1, date2) {
  382. return date1.getFullYear() === date2.getFullYear()
  383. && date1.getMonth() === date2.getMonth()
  384. && date1.getDate() === date2.getDate();
  385. }
  386. return (timestamp: number, forceFull: boolean = false) => {
  387. const date = new Date(timestamp * 1000);
  388. const now = new Date();
  389. if (!forceFull && isSameDay(date, now)) {
  390. return formatTime(date);
  391. }
  392. const yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
  393. if (!forceFull && isSameDay(date, yesterday)) {
  394. return $translate.instant('date.YESTERDAY') + ', ' + formatTime(date);
  395. }
  396. let year = '';
  397. if (forceFull || date.getFullYear() !== now.getFullYear()) {
  398. year = ' ' + date.getFullYear();
  399. }
  400. return date.getDate() + '. '
  401. + $translate.instant(formatMonth(date.getMonth()))
  402. + year + ', '
  403. + formatTime(date);
  404. };
  405. }])
  406. /**
  407. * Return a simplified DND mode.
  408. *
  409. * This will return either 'on', 'off' or 'mention'.
  410. * The 'until' mode will be processed depending on the expiration timestamp.
  411. */
  412. .filter('dndModeSimplified', ['NotificationService', function(notificationService: NotificationService) {
  413. return (conversation: threema.Conversation) => {
  414. const simplified = notificationService.getAppNotificationSettings(conversation);
  415. if (simplified.dnd.enabled) {
  416. return simplified.dnd.mentionOnly ? 'mention' : 'on';
  417. }
  418. return 'off';
  419. };
  420. }])
  421. ;