-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpopup.js
192 lines (171 loc) · 5.93 KB
/
popup.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
var signin = function (callback) {
chrome.identity.getAuthToken({interactive: true}, callback);
};
function onGoogleLibraryLoaded() {
signin(authorizationCallback);
}
var authorizationCallback = function (data) {
gapi.auth.setToken({access_token: data});
gapi.client.load('gmail', 'v1', function () {
gapi.client.load('drive', 'v2', processThread);
});
};
function getHashFromUrl(url) {
return url.substr(url.lastIndexOf("#") + 1);
}
var getMessageIdFromUrl = function (url) {
var hash = getHashFromUrl(url);
return hash.substr(hash.lastIndexOf("/") + 1);
};
function parseBase64(contentInBase64) {
return atob(contentInBase64.replace(/\-/g, "+").replace(/_/g, "/"));
}
function arrayBufferToBase64(buffer) {
var binary = ''
var bytes = new Uint8Array(buffer)
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[ i ])
}
return window.btoa(binary);
}
function getContentFromMessage(message) {
//Take the first part with text/html type, or text/plain
var firstHtmlContent, firstPlainTextContent;
for (var i = 0; i < message.payload.parts.length; i++) {
var part = message.payload.parts[i];
if (part.mimeType == "text/html") {
firstHtmlContent = part.body.data;
break;
} else if (part.mimeType == "text/plain") {
firstPlainTextContent = part.body.data;
}
}
var contentInBase64 = firstHtmlContent ? firstHtmlContent : firstPlainTextContent;
return parseBase64(contentInBase64);
}
function deleteFile(id) {
gapi.client.drive.files.delete({ 'fileId': id}).execute(function (data) {
console.log(data)
});
}
function createDraftEmail(attachment) {
return 'Subject:\n' +
'MIME-Version: 1.0\n' +
'Content-Type: multipart/mixed; boundary="----=_Part_0_1557435007.1403835997405"\n' +
'\n' +
'------=_Part_0_1557435007.1403835997405\n' +
'Content-Type: text/html; charset="UTF-8"\n' +
'\n' +
'Here is your file\n' +
'------=_Part_0_1557435007.1403835997405\n' +
'Content-Type: application/pdf; name="email.pdf"\n' +
'Content-Transfer-Encoding: base64\n' +
'Content-Disposition: attachment; filename=email.pdf\n' +
'\n' +
attachment +
'\n' +
'------=_Part_0_1557435007.1403835997405--'
}
function createDraftWithAttachment(linkToPDF, callback) {
//Download the PDF
var oReq = new XMLHttpRequest();
oReq.open("GET", linkToPDF, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
//Create the draft and call the callback
var email = createDraftEmail(arrayBufferToBase64(oReq.response));
uploadDraft(email, function (data) {
console.log(data);
callback(data);
})
};
oReq.send();
}
/**
* Create Draft email.
*
* @param {String} userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* @param {String} email RFC 5322 formatted String.
* @param {Function} callback Function to call when the request is complete.
*/
function uploadDraft(email, callback) {
var base64EncodedEmail = btoa(email);
var payload = {
userId: "me",
'message': {
'raw': base64EncodedEmail
}
};
console.log(JSON.stringify(payload));
var request = gapi.client.gmail.users.drafts.create(payload);
request.execute(callback);
}
function processThread() {
chrome.tabs.query({active: true, currentWindow: true}, function (data) {
var tab = data[0];
//get current email
var messageId = getMessageIdFromUrl(tab.url);
gapi.client.gmail.users.threads.get({userId: "me", id: messageId}).execute(function (thread) {
var totalHtml = "";
//export to pdf
for (var i = 0; i < thread.messages.length; i++) {
if (i > 0) {
totalHtml = totalHtml + "<hr>\n";
}
totalHtml = totalHtml + getContentFromMessage(thread.messages[i]);
}
insertFile("Extracted from GMail " + messageId, totalHtml, function (result) {
console.log(result);
createDraftWithAttachment(result.exportLinks["application/pdf"], function (draft) {
//open the draft in gmail window
console.log("new url : "+tab.url+"?compose="+draft.message.id);
chrome.tabs.update(tab.id, {url:tab.url+"?compose="+draft.message.id});
deleteFile(result.id);
});
});
});
})
}
/**
* Insert new file.
*
* @param {File} fileData File object to read data from.
* @param {Function} callback Function to call when the request is complete.
*/
function insertFile(title, htmlData, callback) {
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
var contentType = 'text/html';
var metadata = {
'title': title,
'mimeType': contentType
};
var base64Data = btoa(htmlData);
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + contentType + '\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v2/files?convert=true',
'method': 'POST',
'params': {'uploadType': 'multipart'},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody});
if (!callback) {
callback = function (file) {
console.log(file)
};
}
request.execute(callback);
}