filters.ts 12 KB

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