-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
84 lines (75 loc) · 2.25 KB
/
background.js
File metadata and controls
84 lines (75 loc) · 2.25 KB
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
const setUpContextMenus = () => {
chrome.contextMenus.create({
id: "Upload",
title: "EzUpload",
type: "normal",
contexts: ["image"],
});
};
chrome.runtime.onInstalled.addListener(() => {
// When the app gets installed, set up the context menus
setUpContextMenus();
});
chrome.contextMenus.onClicked.addListener((info) => {
const mimeType = getMIMEType(info.srcUrl);
const binaryData = dataURItoBlob(info.srcUrl, mimeType);
uploadImage(binaryData);
});
const uploadImage = (binaryData) => {
chrome.identity.getAuthToken({ interactive: true }, async (token) => {
const authorization = `Bearer ${token}`;
const uploadToken = await uploadRawBytes(binaryData, authorization);
const response = await createMediaItem(authorization, uploadToken);
console.log(response);
});
};
const dataURItoBlob = (dataURI, mimeType) => {
const binary = window.atob(dataURI.split(",")[1]);
const byteArray = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; ++i) {
byteArray[i] = binary.charCodeAt(i);
}
return new Blob([byteArray], { type: mimeType });
};
const getMIMEType = (dataURI) => {
return dataURI.substring(dataURI.indexOf(":") + 1, dataURI.indexOf(";"));
};
const uploadRawBytes = async (binaryData, authorization) => {
const url = "https://photoslibrary.googleapis.com/v1/uploads";
const uploadHeaders = {
Authorization: authorization,
"Content-type": "application/octet-stream",
"X-Goog-Upload-Content-Type": binaryData.type,
"X-Goog-Upload-Protocol": "raw",
};
const response = await fetch(url, {
method: "POST",
headers: uploadHeaders,
body: binaryData,
});
return response.text();
};
const createMediaItem = async (authorization, uploadToken) => {
const createURL =
"https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate";
const createHeaders = {
"Content-Type": "application/json",
Authorization: authorization,
};
const body = {
newMediaItems: [
{
description: "item-description",
simpleMediaItem: {
uploadToken: uploadToken,
},
},
],
};
const response = await fetch(createURL, {
method: "POST",
headers: createHeaders,
body: JSON.stringify(body),
});
return response.text();
};