-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackground.js
235 lines (207 loc) · 8.42 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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Tempted to just use `var { calendar } = messenger;`?
// You will find yourself naming function arguments `calendar` way too often.
var { calendar: lightning } = messenger;
lightning.calendars.onCreated.addListener((calendar) => {
console.log("Created calendar", calendar);
});
lightning.calendars.onUpdated.addListener((calendar, changeInfo) => {
console.log("Updated calendar", calendar, changeInfo);
});
lightning.calendars.onRemoved.addListener((id) => {
console.log("Removed calendar", id);
});
lightning.items.onCreated.addListener((item) => {
console.log("Created item", item);
}, { returnFormat: "ical" });
lightning.items.onUpdated.addListener((item, changeInfo) => {
console.log("Updated item", item, changeInfo);
}, { returnFormat: "ical" });
lightning.items.onRemoved.addListener((calendarId, id) => {
console.log("Deleted item", id);
});
lightning.items.onAlarm.addListener((item, alarm) => {
console.log("Alarm item", item, alarm);
}, { returnFormat: "ical" });
function icalDate(date) {
return date.toISOString().replace(/\.\d+Z$/, "").replace(/[:-]/g, "");
}
lightning.provider.onItemCreated.addListener(async (calendar, item) => {
console.log("Provider add to calendar", item);
item.metadata = { created: true };
return item;
}, { returnFormat: "ical" });
lightning.provider.onItemUpdated.addListener(async (calendar, item, oldItem) => {
console.log("Provider modify in calendar", item, oldItem);
item.metadata = { updated: true };
return item;
}, { returnFormat: "ical" });
lightning.provider.onItemRemoved.addListener(async (calendar, item) => {
console.log("Provider remove from calendar", item);
});
let ticks = {};
lightning.provider.onInit.addListener(async (calendar) => {
console.log("Initializing", calendar);
});
lightning.provider.onSync.addListener(async (calendar) => {
console.log("Synchronizing", calendar, "tick", ticks[calendar.id]);
if (!ticks[calendar.id]) {
ticks[calendar.id] = 0;
await lightning.items.create(calendar.cacheId, {
id: "findme",
type: "event",
title: "New Event",
startDate: icalDate(new Date()),
endDate: icalDate(new Date()),
metadata: { etag: 123 }
});
} else if (ticks[calendar.id] == 1) {
await lightning.items.update(calendar.cacheId, "findme", {
title: "Updated",
startDate: icalDate(new Date()),
endDate: icalDate(new Date()),
metadata: { etag: 234 }
});
} else if (ticks[calendar.id] == 2) {
await lightning.calendars.clear(calendar.cacheId);
} else {
ticks[calendar.id] = -1;
}
ticks[calendar.id]++;
});
lightning.provider.onResetSync.addListener(async (calendar) => {
console.log("Reset sync for", calendar);
delete ticks[calendar.id];
});
setTimeout(async () => {
let calendars = await lightning.calendars.query({ type: "ext-" + messenger.runtime.id });
await Promise.all(calendars.map((calendar) => lightning.calendars.remove(calendar.id)));
await lightning.calendars.synchronize();
await new Promise(resolve => setTimeout(resolve, 500));
await new Promise(resolve => setTimeout(resolve, 2000));
}, 2000);
browser.browserAction.onClicked.addListener(() => {
browser.tabs.create({
url: "sidebar/yearView.html"
});
});
let messageQueue = [];
let contentScriptReady = false;
function queueOrSendMessage(message) {
if (!contentScriptReady) {
console.log("Content script not ready, queuing message:", message);
messageQueue.push(message);
} else {
console.log("Content script ready, sending message:", message);
messenger.runtime.sendMessage(message);
}
}
function onContentScriptReady() {
console.log("Content script reported ready, sending the calendar data...");
contentScriptReady = true;
// Combine fetching of calendar details, events, and user storage
let calendarDetailsPromise = messenger.calendar.calendars.query({});
let now = new Date();
let startOfYear = new Date(now.getFullYear(), 0, 1); // January 1st of the current year
let endOfYear = new Date(now.getFullYear(), 11, 31); // December 31st of the current year
let rangeStart = icalDate(startOfYear);
let rangeEnd = icalDate(endOfYear);
let eventsPromise = lightning.items.query({
rangeStart: rangeStart,
rangeEnd: rangeEnd,
expand: true // Include recurring events
});
let userStoragePromise = browser.storage.local.get('UserStorage');
Promise.all([calendarDetailsPromise, eventsPromise, userStoragePromise]).then(([calendarDetails, events, userStorageResult]) => {
let userStorage = userStorageResult.UserStorage || {};
messenger.runtime.sendMessage({
action: "getCalendarDataCombined",
calendarDetails: calendarDetails,
events: events,
userStorage: userStorage
});
}).catch(error => {
console.error("Error fetching combined calendar data:", error);
});
}
messenger.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
if (message.action === "contentScriptReady") {
onContentScriptReady();
} else if (message.action === "saveMonthRange") {
saveMonthRange(message.monthRange);
} else if (message.action === "saveCalendarVisibilityState") {
saveCalendarVisibilityState(message.calendarId, message.isVisible);
} else if (message.action == "saveFirstMonthYear") {
saveFirstMonthYear(message.firstMonthYear);
} else if (message.action == "fetchEventsForYear") {
const year = message.year;
try {
const events = await fetchEventsForYearFromSource(year);
// After fetching events successfully, send them to the content script
messenger.runtime.sendMessage({
action: "eventsForYearFetched",
year: year, // The year for which events were fetched
events: events // The fetched events
});
} catch (error) {
console.error("Error fetching events for year:", year, error);
sendResponse({error: "Failed to fetch events"});
}
return true; // Indicates you wish to send a response asynchronously
}
});
async function fetchEventsForYearFromSource(year) {
// Calculate the start and end dates of the year
let rangeStart = new Date(year, 0, 1); // January 1st of the year
let rangeEnd = new Date(year, 11, 31, 23, 59, 59, 999); // December 31st of the year
// Convert dates to the required format for querying
let formattedRangeStart = icalDate(rangeStart);
let formattedRangeEnd = icalDate(rangeEnd);
try {
// Query the events within the specified date range
let events = await lightning.items.query({
rangeStart: formattedRangeStart,
rangeEnd: formattedRangeEnd,
expand: true // Include recurring events
});
return events; // Return the fetched events
} catch (error) {
console.error("Error fetching events for year:", year, error);
throw error; // Rethrow the error to be handled by the caller
}
}
function saveFirstMonthYear(firstMonthYear) {
console.log("Saving first month and year:", firstMonthYear);
browser.storage.local.set({UserStorage: {firstMonthYear: firstMonthYear}}).then(() => {
}).catch((error) => {
console.error('Error saving first month and year:', error);
});
}
function saveMonthRange(monthRange) {
console.log("Saving month range:", monthRange);
browser.storage.local.set({UserStorage: {monthRange: monthRange}}).then(() => {
}).catch((error) => {
console.error('Error saving month range:', error);
});
}
// Helper function to save the visibility state of a calendar
function saveCalendarVisibilityState(calendarId, isVisible) {
// Retrieve the current state object, or initialize it if it doesn't exist
browser.storage.local.get('UserStorage').then((result) => {
let userStorage = result.UserStorage || {};
let states = userStorage.calendarVisibilityStates || {};
// Update the state for the specific calendarId
states[calendarId] = isVisible;
// Save the updated states object back to storage
userStorage.calendarVisibilityStates = states;
browser.storage.local.set({UserStorage: userStorage}).then(() => {
console.log('visibility State saved successfully:', userStorage.calendarVisibilityStates);
}).catch((error) => {
console.error('Error saving state:', error);
});
}).catch((error) => {
console.error('Error retrieving states:', error);
});
}