-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
235 lines (201 loc) · 6.92 KB
/
Copy pathbackground.js
File metadata and controls
235 lines (201 loc) · 6.92 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
importScripts("config.js");
const API_BASE = "https://api.ticktick.com/open/v1";
const MENU_ID = "send-to-ticktick";
// --- Context Menu Setup ---
chrome.runtime.onInstalled.addListener(async () => {
const { project_name } = await chrome.storage.local.get("project_name");
chrome.contextMenus.create({
id: MENU_ID,
title: project_name ? `Send to ${project_name}` : "Send to TickTick",
contexts: ["page", "link"],
});
});
chrome.storage.onChanged.addListener((changes) => {
if (changes.project_name) {
const name = changes.project_name.newValue;
chrome.contextMenus.update(MENU_ID, {
title: name ? `Send to ${name}` : "Send to TickTick",
});
}
});
// --- URL Resolver ---
function decodeEntities(str) {
return str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/�?39;/g, "'")
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(///g, "/")
.replace(/\s+/g, " ")
.trim();
}
async function resolveUrl(url) {
try {
const res = await fetch(url, { redirect: "follow" });
const finalUrl = res.url;
let title = null;
const contentType = res.headers.get("content-type") || "";
if (contentType.includes("text/html")) {
const html = await res.text();
// Try <title> tag first
const titleMatch = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
if (titleMatch) {
const decoded = decodeEntities(titleMatch[1]);
if (decoded && decoded !== finalUrl) title = decoded;
}
// Fall back to og:title / twitter:title meta tags (works for JS-rendered sites like x.com)
if (!title) {
const ogMatch = html.match(/<meta[^>]+(?:property|name)=["']og:title["'][^>]+content=["']([^"']*?)["']/i)
|| html.match(/<meta[^>]+content=["']([^"']*?)["'][^>]+(?:property|name)=["']og:title["']/i);
if (ogMatch) title = decodeEntities(ogMatch[1]);
}
if (!title) {
const twMatch = html.match(/<meta[^>]+(?:property|name)=["']twitter:title["'][^>]+content=["']([^"']*?)["']/i)
|| html.match(/<meta[^>]+content=["']([^"']*?)["'][^>]+(?:property|name)=["']twitter:title["']/i);
if (twMatch) title = decodeEntities(twMatch[1]);
}
}
return { url: finalUrl, title: title || finalUrl };
} catch {
return { url, title: url };
}
}
// --- Toast Notification ---
function showToast(tabId, message, isError = false) {
chrome.scripting.executeScript({
target: { tabId },
func: (msg, err) => {
const existing = document.getElementById("ticktick-toast");
if (existing) existing.remove();
const toast = document.createElement("div");
toast.id = "ticktick-toast";
toast.textContent = msg;
Object.assign(toast.style, {
position: "fixed",
bottom: "24px",
right: "24px",
zIndex: "2147483647",
padding: "10px 18px",
borderRadius: "8px",
fontSize: "14px",
fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
color: "#fff",
background: err ? "#d32f2f" : "#388e3c",
boxShadow: "0 4px 12px rgba(0,0,0,0.25)",
opacity: "0",
transition: "opacity 0.3s ease",
pointerEvents: "none",
});
document.body.appendChild(toast);
requestAnimationFrame(() => { toast.style.opacity = "1"; });
setTimeout(() => {
toast.style.opacity = "0";
setTimeout(() => toast.remove(), 300);
}, 2500);
},
args: [message, isError],
}).catch(() => {});
}
// --- Context Menu Click Handler ---
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId !== MENU_ID) return;
const { access_token, project_id } = await chrome.storage.local.get([
"access_token",
"project_id",
]);
if (!access_token || !project_id) return;
let title, content;
if (info.linkUrl) {
// Get anchor text from the content script in the frame that was right-clicked
let linkText;
try {
const linkData = await chrome.tabs.sendMessage(
tab.id,
{ action: "getLinkText" },
{ frameId: info.frameId }
);
linkText = linkData?.text;
} catch {}
// Resolve redirect chain for the final URL
const resolved = await resolveUrl(info.linkUrl);
title = linkText || resolved.title;
content = resolved.url;
} else {
// Right-clicked on the page
title = tab.title || "Untitled";
content = tab.url || "";
}
try {
const res = await fetch(`${API_BASE}/task`, {
method: "POST",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ title, content, projectId: project_id }),
});
if (!res.ok) {
console.error("TickTick API error:", res.status, await res.text());
showToast(tab.id, "Failed to add task", true);
} else {
showToast(tab.id, "Task added to TickTick!");
}
} catch (err) {
console.error("Failed to create task:", err);
showToast(tab.id, "Failed to add task", true);
}
});
// --- OAuth Message Handler ---
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "authenticate") {
handleAuth().then(sendResponse).catch(err => sendResponse({ error: err.message }));
return true; // keep message channel open for async response
}
});
async function handleAuth() {
const redirectUri = chrome.identity.getRedirectURL();
const state = crypto.randomUUID();
const authUrl =
"https://ticktick.com/oauth/authorize" +
`?client_id=${encodeURIComponent(CLIENT_ID)}` +
`&scope=${encodeURIComponent("tasks:write tasks:read")}` +
`&state=${encodeURIComponent(state)}` +
`&redirect_uri=${encodeURIComponent(redirectUri)}` +
`&response_type=code`;
const responseUrl = await chrome.identity.launchWebAuthFlow({
url: authUrl,
interactive: true,
});
const url = new URL(responseUrl);
const code = url.searchParams.get("code");
const returnedState = url.searchParams.get("state");
if (returnedState !== state) {
throw new Error("OAuth state mismatch");
}
if (!code) {
throw new Error("No authorization code received");
}
// Exchange code for access token
const tokenResponse = await fetch("https://ticktick.com/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Basic " + btoa(CLIENT_ID + ":" + CLIENT_SECRET),
},
body: new URLSearchParams({
code,
grant_type: "authorization_code",
scope: "tasks:write tasks:read",
redirect_uri: redirectUri,
}),
});
if (!tokenResponse.ok) {
const text = await tokenResponse.text();
throw new Error(`Token exchange failed: ${tokenResponse.status} ${text}`);
}
const tokenData = await tokenResponse.json();
await chrome.storage.local.set({ access_token: tokenData.access_token });
return { success: true };
}