forked from darktrojan/shrunked
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcompose_script.js
More file actions
244 lines (223 loc) · 7.17 KB
/
compose_script.js
File metadata and controls
244 lines (223 loc) · 7.17 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
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
let config = {
attributes: false,
childList: true,
characterData: false,
subtree: true,
};
let resizeWhenForwardReply= false;
let logenabled = false;
let utils;
async function startup(){
utils = await import(browser.runtime.getURL("/modules/utils.mjs"));
let response = await browser.runtime.sendMessage({
type: "getOptions",
})
resizeWhenForwardReply=response["resizeInReplyForward"];
logenabled = response["logenabled"];
if(resizeWhenForwardReply) {
parseInlineAtStart();
}
// Listener to evaluate context clicked elements.
document.addEventListener("contextmenu", async (e) => {
let composeContextMenuEntryStatus = {
disabled: true,
label: "context.single"
};
let target = document.elementFromPoint(
e.clientX,
e.clientY,
);
if (target?.nodeName == "IMG") {
if (logenabled) {
console.log("Context menu on an <IMG>");
}
if (utils.imageIsAccepted(target.src)) {
if (target.width > 500 || target.height > 500) {
composeContextMenuEntryStatus.disabled = false;
} else {
if (logenabled) {
console.log("Not resizing - image is too small");
}
composeContextMenuEntryStatus.label = "context.tooSmall";
}
} else {
if (logenabled) {
console.log("Not resizing - image is not JPEG / PNG");
}
composeContextMenuEntryStatus.label = "context.tooSmall"
}
}
// Create an identifier on the node, so it can be found later, but clean up
// the DOM from any earlier actions.
const selectedNodes = document.querySelectorAll('[data-currently-selected-for-shrunked]');
selectedNodes.forEach(node => {
delete node.dataset.currentlySelectedForShrunked;
});
target.dataset.currentlySelectedForShrunked = true;
let file = composeContextMenuEntryStatus.disabled ? null : await getFileFromTarget(target)
await browser.runtime.sendMessage({
type: "updateComposeContextMenuEntry",
composeContextMenuEntryStatus,
file
})
})
browser.runtime.onMessage.addListener(request => {
switch (request.type) {
case "replaceTargetWithFile": {
let target = document.querySelector('[data-currently-selected-for-shrunked]');
return replaceTargetWithFile(target, request.file);
}
}
})
}
startup();
let observer = new MutationObserver(function(mutations) {
for (let mutation of mutations) {
if (mutation.addedNodes && mutation.addedNodes.length) {
if(logenabled)
console.log("Nodes added to message: " + mutation.addedNodes.length);
for (let target of mutation.addedNodes) {
maybeResizeInline(target);
}
}
}
});
observer.observe(document.body, config);
async function parseInlineAtStart()
{
if(logenabled)
console.log(`parsing inline images at compose start`);
let existingInline=document.body.getElementsByTagName("IMG");
for(let i=0;i<existingInline.length;i++)
{
if(logenabled)
console.log(`parsing image ${i}, node ${existingInline[i].nodeName}`);
await maybeResizeInline(existingInline[i]);
}
}
async function maybeResizeInline(target) {
if (target.nodeName == "IMG") {
try {
if (logenabled)
console.log(
"<IMG> found, source is " +
target.src.substring(0, 100) +
(target.src.length <= 100 ? "" : "\u2026")
);
let parent = target.parentNode;
while (parent && "classList" in parent) {
if (parent.classList.contains("moz-signature")) {
if (logenabled)
console.log("Not resizing - image is part of signature");
return;
}
if (parent.getAttribute("type") == "cite" && resizeWhenForwardReply==false) {
if (logenabled)
console.log("Not resizing - image is part of message being replied to");
return;
}
if (parent.classList.contains("moz-forward-container") && resizeWhenForwardReply==false) {
if (logenabled)
console.log("Not resizing - image is part of forwarded message");
return;
}
parent = parent.parentNode;
}
if (!target.complete) {
target.addEventListener(
"load",
() => {
if (logenabled)
console.log("Image now loaded, calling maybeResizeInline");
maybeResizeInline(target);
},
{ once: true }
);
if (logenabled)
console.log("Image not yet loaded");
return;
}
if (target.hasAttribute("shrunked:resized")) {
if (logenabled)
console.log("Not resizing - image already has shrunked attribute");
return;
}
if (!utils.imageIsAccepted(target.src)) {
if (logenabled)
console.log("Not resizing - image is not JPEG / PNG / BMP");
return;
}
if (target.width < 500 && target.height < 500) {
if (logenabled)
console.log("Not resizing - image is too small");
return;
}
let src = target.getAttribute("src");
if (/^data:/.test(src)) {
let srcSize = ((src.length - src.indexOf(",") - 1) * 3) / 4;
if (src.endsWith("=")) {
srcSize--;
if (src.endsWith("==")) {
srcSize--;
}
}
let { fileSizeMinimum } = await browser.storage.local.get({
fileSizeMinimum: 100,
});
if (srcSize < fileSizeMinimum * 1024) {
if (logenabled)
console.log("Not resizing - image file size is too small");
return;
}
}
let srcFile = await getFileFromTarget(target);
let destFile = await browser.runtime.sendMessage({
type: "resizeFile",
file: srcFile,
}).catch((err) => {
console.error(err);
return;
});
if (!destFile) {
return;
}
await replaceTargetWithFile(target, destFile);
} catch (ex) {
if (logenabled)
console.error(ex);
}
} else if (target.nodeType == Node.ELEMENT_NODE) {
if (logenabled)
console.log("<" + target.nodeName + "> found, checking children");
for (let child of target.children) {
maybeResizeInline(child);
}
}
}
async function getFileFromTarget(target) {
let srcName = "";
let nameParts = target.src.match(/;filename=([^,;]*)[,;]/);
if (nameParts) {
srcName = decodeURIComponent(nameParts[1]);
}
let response = await fetch(target.src);
let srcBlob = await response.blob();
return new File([srcBlob], srcName);
}
async function replaceTargetWithFile(target, destFile) {
let destURL = await new Promise(resolve => {
let reader = new FileReader();
reader.onloadend = function () {
let dataURL = reader.result;
let headerIndexEnd = dataURL.indexOf(";");
dataURL =
reader.result.substring(0, headerIndexEnd) + ";filename=" + encodeURIComponent(utils.changeExtensionIfNeeded(destFile.name)) + dataURL.substring(headerIndexEnd);
resolve(dataURL);
};
reader.readAsDataURL(destFile);
});
target.setAttribute("src", destURL);
target.removeAttribute("width");
target.removeAttribute("height");
target.setAttribute("shrunked:resized", "true");
}