-
Notifications
You must be signed in to change notification settings - Fork 0
/
service_worker.js
156 lines (140 loc) · 7.21 KB
/
service_worker.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
import { buildRequestOpenAI, parseResponseOpenAI } from "./modules/openai.js";
import { buildRequestGemini, parseResponseGemini } from "./modules/gemini.js";
import { GCalLink, iCalDownload, autoSelect } from "./modules/prompts.js";
import { isAllDayEvent } from "./modules/util.js";
const modelHandlers = {
"gpt-3.5-turbo": { build: buildRequestOpenAI, parse: parseResponseOpenAI },
"gpt-4o-mini": { build: buildRequestOpenAI, parse: parseResponseOpenAI },
"gpt-4o": { build: buildRequestOpenAI, parse: parseResponseOpenAI },
"gemini-pro": { build: buildRequestGemini, parse: parseResponseGemini },
"gemini-1.5-flash-latest": { build: buildRequestGemini, parse: parseResponseGemini },
};
function buildRequest(request_params, apiKey, model) {
const handler = modelHandlers[model];
if (handler) {
return handler.build(request_params, apiKey, model);
}
throw new Error(`Unsupported model: ${model}`);
}
function parseResponse(data, model) {
const handler = modelHandlers[model];
if (handler) {
return handler.parse(data);
}
throw new Error(`Unsupported model: ${model}`);
}
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "create-gcal-url",
title: "Create Google Calendar event",
contexts: ["selection"]
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId == "create-gcal-url") {
chrome.storage.sync.get(["apiKey", "defaultModel", "selectedMode"], function (result) {
chrome.scripting.insertCSS({
target: { tabId: tab.id },
css: 'body { cursor: wait; }'
});
if (result.apiKey === undefined) {
chrome.notifications.create({
type: 'basic',
iconUrl: '/icons/64.png',
title: 'Columbia GCal Scheduler',
message: "API key is not set. Please set it in the extension options..",
priority: 1
});
chrome.runtime.openOptionsPage();
} else {
const apiKey = result.apiKey;
let selectedMode = result.selectedMode;
let model = result.defaultModel;
if (model === undefined) model = "gpt-4o";
if (selectedMode === undefined) selectedMode = "newTab";
const selectedText = info.selectionText;
let request_params;
if (selectedMode === "newTab") {
request_params = GCalLink(selectedText);
} else if (selectedMode === "ical") {
request_params = iCalDownload(selectedText);
} else if (selectedMode === "auto") {
request_params = autoSelect(selectedText);
}
const request = buildRequest(request_params, apiKey, model);
fetch(request.endpoint, request.options)
.then(response => response.json())
.then(data => {
if ((data.error?.type === "invalid_request_error") ||
(data.error?.details?.[0]?.reason === 'API_KEY_INVALID') ||
(data.error?.code === 403)) {
throw new Error("Invalid API key");
}
const parsedResponse = parseResponse(data, model);
const { function_used, event } = parsedResponse;
if (function_used === "get_event_information") {
// Format the dates
const startDate = event.start_date;
// For untimed events the end date is exclusive, so the end date should be the next day.
let endDate = event.end_date;
if (isAllDayEvent(endDate)) {
endDate = new Date(endDate.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3'));
endDate.setDate(endDate.getDate() + 1);
endDate = endDate.toISOString().split('T')[0].replace(/-/g, '');
event.end_date = endDate;
} else if (!endDate) {
endDate = startDate;
}
// URL encode the event details
const title = encodeURIComponent(event.title);
const location = encodeURIComponent(event.location);
const description = encodeURIComponent(event.description);
const recurrence = encodeURIComponent(event.recurrence);
// Construct the Google Calendar URL and open a new tab
const calendarURL = `https://www.google.com/calendar/render?action=TEMPLATE&text=${title}&dates=${startDate}/${endDate}&details=${description}&location=${location}&recur=${recurrence}`;
chrome.tabs.create({
url: calendarURL
});
} else if (function_used === "generate_ical_file") {
const icsFile = event.ical;
chrome.downloads.download({
url: `data:text/calendar,${encodeURIComponent(icsFile)}`,
filename: event.filename,
saveAs: true
});
}
// CSS rule to set the cursor back to default
chrome.scripting.insertCSS({
target: { tabId: tab.id },
css: 'body { cursor: default; }'
});
})
.catch(error => {
chrome.scripting.insertCSS({
target: { tabId: tab.id },
css: 'body { cursor: default; }'
});
if (error.message === "Invalid API key") {
chrome.notifications.create({
type: 'basic',
iconUrl: '/icons/64.png',
title: 'Columbia SSOL GCal AI Agent',
message: "Invalid API key. Please set a valid API key in the extension options.",
priority: 1
});
chrome.runtime.openOptionsPage();
} else {
console.log(error);
chrome.notifications.create({
type: 'basic',
iconUrl: '/icons/64.png',
title: 'Columbia SSOL GCal AI Agent',
message: "An error occurred while creating the event. Please try again later.",
priority: 1
});
}
});
}
});
}
});