filters.ts 13 KB

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