blob: 7b6cb9428e6c7cbd57e5ac85a770dd6ac3e8fdbf [file] [log] [blame]
Akrona0ea3c32018-12-14 18:33:48 +01001/**
2 * Parse Data URI scheme for attachement fields
3 * Afterwards the object has the parameters
4 * - contentType (defaults to text/plain)
5 * - base64 (if the data was base64 encoded)
6 * - isLink (if the contentType is application/x.korap-link)
7 * - param (as a map of arbitrary parameters)
8 * - payload (the URI decoded data)
9 *
10 * @author Nils Diewald
11 */
12define(function () {
Akrond3bb85b2019-02-08 10:15:13 +010013 const uriRE = new RegExp("^data: *([^;,]*?(?: *; *[^,;]+?)*) *, *(.+)$");
Akrona0ea3c32018-12-14 18:33:48 +010014 const mapRE = new RegExp("^ *([^=]+?) *= *(.+?) *$");
15
16 return {
17
18 /**
19 * Constructor
20 */
21 create : function (url) {
22 return Object.create(this)._init(url);
23 },
24
25 // Parse URI scheme
26 _init : function (url) {
27
28 // Decode
29 url = decodeURIComponent(url);
30
31 if (!uriRE.exec(url))
32 return;
33
34 this.payload = RegExp.$2;
35
36 let map = {};
37 let start = 0;
38 this.base64 = false;
39 this.isLink = false;
40 this.contentType = "text/plain";
41
42 // Split parameter map
43 RegExp.$1.split(/ *; */).map(function (item) {
44
45 // Check first parameter
46 if (!start++ && item.match(/^[-a-z0-9]+?\/.+$/)) {
47 this.contentType = item;
48
49 if (item === "application/x.korap-link")
50 this.isLink = true;
51 }
52
53 // Decode b64
54 else if (item.toLowerCase() == "base64") {
55 this.base64 = true;
56 this.payload = window.atob(this.payload);
57 }
58
59 // Parse arbitrary metadata
60 else if (mapRE.exec(item)) {
61 map[RegExp.$1] = RegExp.$2;
62 };
63 }.bind(this));
64
65 this.param = map;
66 return this;
67 },
68
69 /**
70 * Inline the attachement
71 * This should optimally be plugin-treatable
72 */
73 inline : function () {
74 if (this.isLink) {
75 let title = this.param["title"] || this.payload;
76 let a = document.createElement('a');
77 a.setAttribute('href', this.payload);
78 a.setAttribute('rel', 'noopener noreferrer');
79 a.addT(title);
80 return a;
81 };
82
83 return document.createTextNode(this.payload);
84 }
85 }
86});