filters.ts 14 KB

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