-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
262 lines (230 loc) · 9.94 KB
/
Copy pathbackground.js
File metadata and controls
262 lines (230 loc) · 9.94 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// background.js
/**
* Creates a dynamic browser action icon.
* @param {string} color - The background color of the icon.
* @param {number} size - The width and height of the icon in pixels.
* @returns {ImageData} The generated icon data.
*/
function createIcon(color, size) {
const canvas = new OffscreenCanvas(size, size);
const context = canvas.getContext('2d');
context.fillStyle = color;
context.fillRect(0, 0, size, size);
context.font = `bold ${size * 0.6}px Arial`;
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillStyle = 'white';
context.fillText('SC', size / 2, size / 2);
return context.getImageData(0, 0, size, size);
}
/**
* A reusable callback function to gracefully handle Chrome API errors.
* This is expected when a tab is closed before an API call completes.
*/
const handleTabApiError = () => {
if (chrome.runtime.lastError) {
// Log the error for debugging purposes, but prevent it from being "uncaught".
console.log(`Ignored an error: ${chrome.runtime.lastError.message}`);
}
};
/**
* Updates the browser action icon's state (enabled/disabled) based on whether the URL
* in the given tab matches any of the user-configured and enabled sites.
* @param {number} tabId - The ID of the tab to update.
* @param {string} url - The URL of the tab.
*/
function updateActionIconState(tabId, url) {
if (!url || !tabId) return;
chrome.storage.local.get({ sites: [] }, (result) => {
if (chrome.runtime.lastError) {
console.warn("Could not get sites from storage:", chrome.runtime.lastError.message);
return;
};
const sites = result.sites;
let matchFound = false;
for (const site of sites) {
// Skip disabled sites
if (site.enabled === false) continue;
if (site.host && url.includes(site.host)) {
if (site.urlRegex) {
try {
if (new RegExp(site.urlRegex, 'i').test(url)) matchFound = true;
} catch (e) { /* Ignore invalid regex */ }
} else {
matchFound = true;
}
}
if (matchFound) break;
}
const iconColor = matchFound ? '#1E90FF' : '#808080';
// Set the icon and enabled/disabled state for the specific tab.
chrome.action.setIcon({
tabId: tabId,
imageData: {
'48': createIcon(iconColor, 48),
'128': createIcon(iconColor, 128)
}
}, handleTabApiError);
if (matchFound) {
chrome.action.enable(tabId, handleTabApiError);
} else {
chrome.action.disable(tabId, handleTabApiError);
}
});
}
/**
* Tries to connect to the internal and external SickChill addresses to find one that is active.
* Assumes https:// for external and http:// for internal if no protocol is specified.
* @param {object} settings - The plugin settings containing address and API key.
* @returns {Promise<string|null>} The base URL of the active SickChill instance or null if none are reachable.
*/
async function getActiveAddress(settings) {
// Create an array specifying which address is which
const addressesToTry = [
{ address: settings.internalAddress, isExternal: false },
{ address: settings.externalAddress, isExternal: true }
].filter(a => a.address); // Filter out any empty addresses
for (const { address, isExternal } of addressesToTry) {
let addressWithProtocol = address;
// If no protocol is specified, apply default based on type
if (!address.startsWith('http://') && !address.startsWith('https://')) {
addressWithProtocol = isExternal
? `https://${address}` // Default to HTTPS for external
: `http://${address}`; // Default to HTTP for internal
}
let cleanBaseUrl;
console.log(`SickChill Plugin: Attempting to connect to ${addressWithProtocol}`);
try {
const urlObject = new URL(addressWithProtocol);
// Remove any trailing slash from the path to create a clean base URL.
const cleanPath = urlObject.pathname.replace(/\/+$/, '');
cleanBaseUrl = `${urlObject.protocol}//${urlObject.host}${cleanPath}`;
await fetch(`${cleanBaseUrl}/api/${settings.apiKey}/?cmd=ping`, { signal: AbortSignal.timeout(3000) });
console.log(`SickChill Plugin: Successfully connected to ${cleanBaseUrl}`);
return cleanBaseUrl;
} catch (e) {
console.warn(`SickChill Plugin: Connection to ${cleanBaseUrl || addressWithProtocol} failed.`);
}
}
return null;
}
/**
* Handles the main user action: opening the SickChill "Add Show" page and preparing it for automation.
* @param {string} name - The name of the TV show to add.
*/
async function handleDirectToAddShow(name) {
if (!name || name.trim() === '') return; // Don't proceed if name is empty
const settings = await chrome.storage.local.get(['internalAddress', 'externalAddress', 'apiKey']);
const activeAddress = await getActiveAddress(settings);
if (!activeAddress) {
console.error("Could not connect to any configured SickChill address.");
// If connection fails, open the options page for the user to check their settings.
chrome.runtime.openOptionsPage();
return;
}
// Store the show name in session storage, which is temporary and ideal for this task.
await chrome.storage.session.set({ showNameToAdd: name.trim() });
const addShowUrl = `${activeAddress}/addShows/newShow/`;
chrome.tabs.create({ url: addShowUrl });
}
/**
* This function is injected into the SickChill tab to perform the search automatically.
* @param {string} showName - The name of the show to search for.
* @param {boolean} useExactMatch - Whether to check the 'exact match' checkbox.
*/
function automateSearch(showName, useExactMatch) {
const searchInput = document.getElementById('show-name');
const searchButton = document.getElementById('search-button');
const exactMatchCheckbox = document.getElementById('exact-match');
if (searchInput && searchButton) {
if (exactMatchCheckbox) {
exactMatchCheckbox.checked = useExactMatch;
}
searchInput.value = showName;
searchButton.click();
} else {
console.error('SickChill Plugin: Could not find search input or button on the page.');
}
}
// Listens for tab updates to know when the SickChill page has loaded.
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
// Check if the tab has finished loading and is the correct "Add Show" page.
if (changeInfo.status === 'complete' && tab.url && tab.url.includes('/addShows/newShow/')) {
const data = await chrome.storage.session.get('showNameToAdd');
const settings = await chrome.storage.local.get({ enableExactSearch: false });
// If a show name is stored, inject the automation script.
if (data.showNameToAdd) {
console.log(`Injecting search script for "${data.showNameToAdd}" into tab ${tabId}`);
try {
await chrome.scripting.executeScript({
target: { tabId: tabId },
func: automateSearch,
args: [data.showNameToAdd, settings.enableExactSearch]
});
// Clean up by removing the show name from session storage.
await chrome.storage.session.remove('showNameToAdd');
} catch (error) {
handleTabApiError();
}
}
}
});
// Primary message listener for actions triggered from content scripts or the popup.
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "directToAddShowPage") {
handleDirectToAddShow(request.name);
}
return true;
});
// --- Event Listeners for Browser Action Icon ---
function checkActiveTab() {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (chrome.runtime.lastError) {
handleTabApiError();
return;
}
if (tabs[0]) {
updateActionIconState(tabs[0].id, tabs[0].url);
}
});
}
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && tab.url) {
updateActionIconState(tabId, tab.url);
}
});
chrome.tabs.onActivated.addListener(async (activeInfo) => {
try {
const tab = await chrome.tabs.get(activeInfo.tabId);
if (tab && tab.url) {
updateActionIconState(tab.id, tab.url);
}
} catch (error) {
// This error is expected if the tab was closed before the API call completed.
handleTabApiError();
}
});
chrome.storage.onChanged.addListener((changes) => {
if (changes.sites) {
checkActiveTab();
}
});
// --- Context Menu (Right-Click) Setup ---
chrome.runtime.onInstalled.addListener(() => {
// Initial check of the active tab
checkActiveTab();
// Create the context menu item
chrome.contextMenus.create({
id: "search-sickchill",
title: "Search SickChill for \"%s\"", // %s is a placeholder for the selected text
contexts: ["selection"]
});
});
// Listener for when the context menu item is clicked
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "search-sickchill") {
// The selected text is in info.selectionText
handleDirectToAddShow(info.selectionText);
}
});
console.log("SickChill Plugin: Background script loaded.");