-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
276 lines (250 loc) · 7.71 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
// Initialize storage on install
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.local.set({ savedSubreddits: [] });
});
let joinInProgress = false;
let activeTabId = null;
let currentJoinOperation = null;
// Listen for messages from popup or content script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'startJoining') {
// Store the active tab ID
activeTabId = message.tabId;
// Forward the join request to content script
chrome.tabs.sendMessage(message.tabId, {
action: 'joinSubreddits',
subreddits: message.subreddits
}).then(response => {
if (response.success) {
joinInProgress = true;
currentJoinOperation = {
tabId: message.tabId,
subreddits: message.subreddits
};
// Initialize progress state
chrome.storage.local.set({
joinProgress: {
current: 0,
total: message.subreddits ? message.subreddits.length : 0,
status: 'Starting...',
timestamp: Date.now(),
inProgress: true
}
});
}
sendResponse(response);
}).catch(error => {
sendResponse({ success: false, error: error.message });
});
return true;
}
else if (message.action === 'joinProgress') {
// Store progress state
chrome.storage.local.set({
joinProgress: {
current: message.current,
total: message.total,
status: message.status,
timestamp: Date.now(),
inProgress: true
}
});
// Forward progress updates to any open popup
chrome.runtime.sendMessage(message).catch(() => {
// Popup might be closed, ignore the error
});
// Check if joining is complete
if (message.current === message.total) {
joinInProgress = false;
currentJoinOperation = null;
// Show completion notification
chrome.notifications.create({
type: 'basic',
iconUrl: 'images/icon128.png',
title: 'Reddit Copycat',
message: `Successfully joined ${message.current} subreddits!`
});
// Clear progress after a delay
setTimeout(() => {
chrome.storage.local.set({
joinProgress: {
inProgress: false
}
});
}, 2000);
}
}
else if (message.action === 'checkJoinStatus') {
// Send back both the status and the active tab ID
sendResponse({
isJoining: joinInProgress,
activeTabId: activeTabId,
currentOperation: currentJoinOperation
});
return true;
}
else if (message.action === 'processImport') {
processImport(message.data)
.then(result => sendResponse(result))
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
}
else if (message.action === 'startLeaving') {
// Store the active tab ID
activeTabId = message.tabId;
// Forward the leave request to content script
chrome.tabs.sendMessage(message.tabId, {
action: 'leaveSubreddits',
subreddits: message.subreddits
}).then(response => {
if (response.success) {
joinInProgress = true;
currentJoinOperation = {
tabId: message.tabId,
subreddits: message.subreddits,
isLeaving: true
};
// Initialize progress state
chrome.storage.local.set({
joinProgress: {
current: 0,
total: message.subreddits ? message.subreddits.length : 0,
status: 'Starting to leave...',
timestamp: Date.now(),
inProgress: true,
isLeaving: true
}
});
}
sendResponse(response);
}).catch(error => {
sendResponse({ success: false, error: error.message });
});
return true;
}
else if (message.action === 'leaveProgress') {
// Store progress state
chrome.storage.local.set({
joinProgress: {
current: message.current,
total: message.total,
status: message.status,
timestamp: Date.now(),
inProgress: true,
isLeaving: true
}
});
// Forward progress updates to any open popup
chrome.runtime.sendMessage(message).catch(() => {
// Popup might be closed, ignore the error
});
// Check if leaving is complete
if (message.current === message.total) {
joinInProgress = false;
currentJoinOperation = null;
// Show completion notification
chrome.notifications.create({
type: 'basic',
iconUrl: 'images/icon128.png',
title: 'Reddit Copycat',
message: `Successfully left ${message.current} subreddits!`
});
// Clear progress after a delay
setTimeout(() => {
chrome.storage.local.set({
joinProgress: {
inProgress: false,
isLeaving: true
}
});
}, 2000);
}
}
});
// Handle import processing in the background
async function processImport(importedSubs) {
try {
// Get current subreddits and merge
const storage = await chrome.storage.local.get(['savedSubreddits']);
const currentSubs = storage.savedSubreddits || [];
const newSubs = importedSubs.filter(sub => !currentSubs.includes(sub));
const allSubs = [...new Set([...currentSubs, ...importedSubs])];
// Save the merged list
await chrome.storage.local.set({
savedSubreddits: allSubs,
lastImport: {
success: true,
newCount: newSubs.length,
totalCount: allSubs.length,
timestamp: Date.now()
}
});
// Show notification
await chrome.notifications.create({
type: 'basic',
iconUrl: 'images/icon128.png',
title: 'Reddit Copycat',
message: `Successfully imported ${newSubs.length} new subreddits! (${allSubs.length} total)`
});
return {
success: true,
newCount: newSubs.length,
totalCount: allSubs.length
};
} catch (error) {
console.error('[Reddit Copycat] Import processing error:', error);
await chrome.storage.local.set({
lastImport: {
success: false,
error: error.message,
timestamp: Date.now()
}
});
await chrome.notifications.create({
type: 'basic',
iconUrl: 'images/icon128.png',
title: 'Reddit Copycat',
message: 'Failed to process import: ' + error.message
});
throw error;
}
}
// Listen for tab updates to handle Reddit page refreshes
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && tab.url?.includes('reddit.com') && joinInProgress && tabId === activeTabId) {
console.log('[Reddit Copycat] Reddit page refreshed, reinjecting content script');
// Reinject content script if needed
chrome.scripting.executeScript({
target: { tabId },
files: ['content.js']
}).then(() => {
// Small delay to ensure content script is initialized
setTimeout(() => {
// Try to resume the join operation
if (currentJoinOperation) {
chrome.tabs.sendMessage(tabId, {
action: 'joinSubreddits',
subreddits: currentJoinOperation.subreddits
}).catch(() => {
console.log('[Reddit Copycat] Failed to resume join operation');
});
}
}, 1000);
});
}
});
// Listen for tab removal
chrome.tabs.onRemoved.addListener((tabId) => {
if (tabId === activeTabId) {
// The Reddit tab was closed
joinInProgress = false;
currentJoinOperation = null;
activeTabId = null;
chrome.storage.local.set({
joinProgress: {
inProgress: false,
error: 'The Reddit tab was closed. Please reopen Reddit and try again.'
}
});
}
});