-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackground.js
298 lines (272 loc) · 9.01 KB
/
background.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
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
const DEZOOMIFY_URL = "https://dezoomify.ophir.dev/#";
const iiifpath = new RegExp( // IIIF API image URL
"/\\^?(full|square|(pct:)?\\d+,\\d+,\\d+,\\d+)" + // region
"/(full|max|\\d+,|,\\d+|pct:\\d+|!?\\d+,\\d+)" + // size
"/!?[1-3]?[0-9]?[0-9]" + // rotation
"/(color|gray|bitonal|default|native)" + // quality
"\\.(jpe?g|tiff?|png|gif|jp2|pdf|webp)" // format
);
const META_REGEX = new RegExp([
/\/ImageProperties.xml/, // Zoomify
/\/info.json/, // IIIF
/\?FIF=/, // IIPImage
/_files\/0\/0_0.jpg(?:\?.*)?$/, // OpenSeadragon
/\.img.\\?cmd=info/,
/getTilesInfo\?object_id/,
/\.pff(&requestType=1)?$/, // Zoomify PFF
/\.ecw(?:\?.*)?$/, // Hungaricana
/\/p.xml(?:\?.*)?$/, // Mnesys
iiifpath,
/artsandculture\.google\.com\/asset\// // Google Arts
].map(e => e.source).join('|'));
const META_REPLACE = [
{ pattern: /\.dzi(?:\?.*)?$/, replacement: '_files/0/0_0.jpg' },
{ pattern: /_files\/\d+\/\d+_\d+\.jpg(?:\?.*)?$/, replacement: '_files/0/0_0.jpg' },
{ pattern: /\/TileGroup\d+\/\d+-\d+-\d+.jpg(?:\?.*)?$/, replacement: '/ImageProperties.xml' },
{ pattern: /\/ImageProperties\.xml\?t\w+$/, replacement: '/ImageProperties.xml' },
{ pattern: /(\?FIF=[^&]*)&.*/, replacement: '$1' }, // IIPImage
{ pattern: /(http.*artsandculture\.google\.com\/asset\/.+\/.+)\?.*/, replacement: '$1' },
{ pattern: iiifpath, replacement: '/info.json' },
{ pattern: /getTilesInfo\?object_id=(.*)&callback.*/, replacement: 'getTilesInfo?object_id=$1' },
];
// @ts-ignore
const VALID_RESOURCE_TYPES = new Set(Object.values(chrome.webRequest['ResourceType']));
/**
* Selector for which requests we want to intercept
* @type chrome.webRequest.RequestFilter
*/
const REQUESTS_FILTER = {
urls: ["<all_urls>"],
// @ts-ignore
types: [
"main_frame",
"image",
"object",
"object_subrequest",
"sub_frame",
"xmlhttprequest",
"script",
"other"
].filter(t => VALID_RESOURCE_TYPES.has(t))
};
/** @type {Map<number, PageListener>} */
const page_listeners = new Map;
/**
* Handle a click on the extension's icon
* @param {chrome.tabs.Tab} unchecked_tab
*/
async function click(unchecked_tab) {
const tab = checkTab(unchecked_tab);
chrome.browserAction.setBadgeText({ text: '...', tabId: tab.id });
const listener = page_listeners.get(tab.id);
if (listener && listener.isListening()) {
// Open the images that may have been found, and stop the existing listener
listener.openFound();
listener.close();
page_listeners.delete(checkTab(listener.tab).id);
} else {
// No active listener, start the extension for this tab
if (listener) listener.close();
const newListener = new PageListener(tab);
page_listeners.set(tab.id, newListener);
}
}
chrome.browserAction.onClicked.addListener(click);
// Remove page listeners when their tab is closed
chrome.tabs.onRemoved.addListener(tabID => {
const listener = page_listeners.get(tabID);
if (listener) {
listener.stop();
page_listeners.delete(tabID);
}
});
/**
* Tracks the state of dezoomify on a given tab
*/
class PageListener {
/**
* @param {chrome.tabs.Tab} tab
*/
constructor(tab) {
this.tab = checkTab(tab);
/** @type {Set<string>} */
this.found = new Set;
this.listener = this.handleRequest.bind(this);
const filter = { tabId: this.tab.id, ...REQUESTS_FILTER };
chrome.webRequest.onBeforeRequest.addListener(this.listener, filter);
this.handleRequest(this.tab);
this.updateStatus();
this.interval = setInterval(this.updateStatus.bind(this), 1000);
}
/**
* Stop listening, free all resources used by this listener, and reset the icon
*/
close() {
this.stop();
this.found.clear();
this.updateStatus();
}
/**
* Stop listening and free all resources used by this listener.
*/
stop() {
chrome.webRequest.onBeforeRequest.removeListener(this.listener);
clearInterval(this.interval);
}
/**
* @returns {boolean}
*/
isListening() {
return chrome.webRequest.onBeforeRequest.hasListener(this.listener);
}
/**
* Returns whether the listener currently looks "activated" from the user's perspective
* @returns {Promise<boolean>}
*/
hasVisibleResults() {
return new Promise((accept) => {
chrome.browserAction.getTitle({ tabId: this.tab.id }, title => {
accept(title !== getManifest().browser_action.default_title);
});
});
}
/**
* @param {{url:string }} request
*/
handleRequest({ url }) {
for (const { pattern, replacement } of META_REPLACE) {
url = url.replace(pattern, replacement);
}
if (META_REGEX.test(url) && !url.startsWith(DEZOOMIFY_URL)) {
this.foundZoomableImage(url);
}
}
/**
* Adds a request to the cached zoomable image requests
* @param {string} url
*/
foundZoomableImage(url) {
let parsed_url = new URL(url);
// Avoid duplicated URLs. Favor the https variant
if (parsed_url.protocol === "http:") {
parsed_url.protocol = "https:";
if (this.found.has(parsed_url.toString())) return;
} else if (parsed_url.protocol === "https:") {
parsed_url.protocol = "http:";
this.found.delete(parsed_url.toString());
}
this.found.add(url);
this.updateStatus();
}
/**
* Sets the extension's icon status
*/
updateStatus() {
const manifest = getManifest();
const found = this.found.size;
let badge = (found || '').toString();
let title = '';
const { host } = new URL(this.tab.url);
if (!this.isListening()) {
badge = '';
title = '' + manifest.browser_action.default_title;
} else if (found === 0) {
title = `Listening for zoomable image requests from ${host}... ` +
'Zoom on your image and it should be detected.';
} else if (found === 1) {
title = `Found a zoomable image on ${host}. Click to open it.`;
} else {
title = `Found ${found} images on ${host}. Click to open them.`
}
const tabId = this.tab.id;
chrome.browserAction.setBadgeText({ text: badge, tabId });
chrome.browserAction.setTitle({ title, tabId });
const path = this.isListening() ? manifest.icons : manifest.browser_action.default_icon;
chrome.browserAction.setIcon({ tabId, path });
}
openFound() {
for (const url of this.found) openDezoomify(url);
}
}
/**
* Open dezoomify in a tab
* @param {string} image_url
*/
function openDezoomify(image_url) {
const url = DEZOOMIFY_URL + image_url;
return chrome.tabs.create({ url })
}
/**
* Throw an error if a tab does not have an id or an URL
* @typedef {{id:number, url:string} & chrome.tabs.Tab} GoodTab
* @param {chrome.tabs.Tab} tab
* @returns {GoodTab}
*/
function checkTab(tab) {
if (!tab.id || !tab.url) throw new Error(`bad tab: ${tab}`);
// @ts-ignore
return tab;
}
/**
* Checks whether the two tabs point to the same site
* @param {string} url1
* @param {string} url2
*/
function sameSite(url1, url2) {
return new URL(url1).origin === new URL(url2).origin;
}
/**
* @returns {{browser_action:chrome.runtime.ManifestAction} & chrome.runtime.Manifest} the extension's manifest
*/
function getManifest() {
const { browser_action, ...manifest } = chrome.runtime.getManifest();
if (!browser_action) throw new Error(`Invalid manifest: ${manifest}`);
return { browser_action, ...manifest };
}
/**
* A context menu action
* @typedef {{
* title:string,
* url?:string,
* onclick?: (info: chrome.contextMenus.OnClickData, tab: chrome.tabs.Tab) => void
* }} MenuAction
*/
/**
* @type {MenuAction[]}
*/
const DEFAULT_MENU_ACTIONS = [
{
title: "Usage instructions and information",
url: 'https://github.com/lovasoa/dezoomify-extension/#dezoomify-extension',
},
{
title: "Open the Dezoomify website",
onclick(_info, tab) { openDezoomify(checkTab(tab).url) },
},
{
title: "Deactivate dezoomify on all tabs",
onclick(_info, _tab) {
for (const l of page_listeners.values()) l.close();
page_listeners.clear();
},
},
{
title: "Report a problem with this extension",
url: 'https://github.com/lovasoa/dezoomify-extension/issues/new',
},
{
title: "Support me, the developer !",
url: "https://github.com/sponsors/lovasoa"
}
]
/**
* Add right-click menu actions
*/
chrome.contextMenus.removeAll();
DEFAULT_MENU_ACTIONS.forEach(({ title, url, onclick }) => {
chrome.contextMenus.create({
title,
contexts: ["browser_action"],
onclick: onclick || (_ => chrome.tabs.create({ url, active: true, }))
});
});