-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
109 lines (91 loc) · 2.8 KB
/
index.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
// ACTIONS =============================================================================
let tabId;
document
.getElementById("solveCoding")
.addEventListener("click", async function solveCoding() {
const language = document.getElementById("language").value;
await new Promise((resolve) => {
chrome.runtime.sendMessage(
{ type: "answer-coding", language },
(response) => {
resolve(response);
}
);
});
});
document
.getElementById("solveQCM")
.addEventListener("click", async function solveQCM() {
const choicesSelector = document.getElementById("choicesSelector").value;
await new Promise((resolve) => {
chrome.runtime.sendMessage(
{ type: "answer-qcm", selector: choicesSelector },
(response) => {
resolve(response);
}
);
});
});
document
.getElementById("solveGeneric")
.addEventListener("click", async function solveGeneric() {
await new Promise((resolve) => {
chrome.runtime.sendMessage({ type: "answer-generic" }, (response) => {
resolve(response);
});
});
});
const apiKeyInput = document.getElementById("apiKey");
const apiKeyStatus = document.getElementById("apiKeyStatus");
async function retrieveApiKeyFromStorage() {
const apiKey = await new Promise((resolve) => {
chrome.storage.sync.get("apiKey", (result) => {
resolve(result.apiKey);
});
});
if (!apiKey) {
return;
}
saveApiKey(apiKey);
}
retrieveApiKeyFromStorage();
apiKeyInput.addEventListener("input", () => {
const apiKey = apiKeyInput.value.trim();
saveApiKey(apiKey);
});
async function saveApiKey(apiKey) {
const apiUrl = "https://api.openai.com/v1/chat/completions";
try {
const response = await fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "gpt-4-0125-preview",
messages: [{ role: "user", content: "Tell me a joke" }],
stream: true,
}),
});
if (!response.ok) {
throw new Error("Invalid API key");
}
if (apiKeyStatus) {
apiKeyStatus.textContent = "Got valid API key";
apiKeyStatus.style.color = "green";
}
chrome.storage.sync.set({ apiKey });
} catch (error) {
if (apiKeyStatus) {
apiKeyStatus.textContent = `Invalid or no API key (${error.message})`;
apiKeyStatus.style.color = "red";
}
}
}
document.getElementById("resetApiKey").addEventListener("click", () => {
chrome.storage.sync.remove("apiKey");
apiKeyInput.value = "";
apiKeyStatus.textContent = "Invalid or no API key";
apiKeyStatus.style.color = "red";
});