filters.ts 13 KB

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