-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
168 lines (149 loc) · 6.58 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
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'searchMastodon') {
console.log('Searching Mastodon for:', message.searchTerm);
// Load saved settings from browser.storage.local
browser.storage.local.get(['client_id', 'client_secret', 'access_token', 'apiKey', 'domain', 'dateType', 'dropWords', 'numPosts'])
.then(({ client_id, client_secret, access_token, apiKey, domain, dateType, dropWords, numPosts = 5 }) => {
console.log('Loaded settings:', client_id, client_secret, access_token, apiKey, domain, dateType, dropWords, numPosts);
if ((!access_token && !apiKey) || !domain) {
sendResponse({ success: false, error: 'Missing access token, API key, or domain.' });
return;
}
const searchTerm = message.searchTerm;
const authorization = access_token ? `Bearer ${access_token}` : `Bearer ${apiKey}`;
console.log(authorization);
fetch(`https://${domain}/api/v2/search?q=${encodeURIComponent(searchTerm)}&resolve=true&limit=${numPosts}`, {
headers: {
'Authorization': authorization
}
})
.then(response => response.json())
.then(data => {
console.log(data.statuses); //TODO: For some reason this sendResponse does not work unless I log data.statuses. I have no idea why. Best guess is there's some sort of race condition going on? Though I'm not familiar enough with javascript to know if that's true
sendResponse({ success: true, results: data.statuses });
})
.catch(error => {
sendResponse({ success: false, error: error.message });
});
return true;
})
.catch(error => {
sendResponse({ success: false, error: 'Failed to retrieve saved settings.' });
});
return true;
} else if (message.action === 'getSettings') {
browser.storage.local.get(['domain', 'numPosts', 'dropWords', 'dateType'])
.then(({ domain, numPosts = 5, dropWords, dateType }) => {
sendResponse({ domain, numPosts, dropWords, dateType });
})
.catch(error => {
sendResponse({ success: false, error: 'Failed to retrieve settings.' });
});
return true;
} else if (message.action === 'authorize') {
const domain = message.domain;
let appRegistrate = null;
// Register the app and start the OAuth flow
registerApp(domain).then(appRegistration => {
console.log('App registration successful');
appRegistrate = appRegistration;
return launchOAuthFlow(appRegistration, domain);
}).then(redirectUrl => {
return validate(redirectUrl, domain, appRegistrate); // Pass appRegistration here
}).then(() => {
sendResponse({ success: true });
}).catch(error => {
console.error('Error during OAuth process:', error);
sendResponse({ success: false, error: error.message });
});
return true;
}
});
// Registers the app with a mastodon server
async function registerApp(domain) {
try {
const response = await fetch(`https://${domain}/api/v1/apps`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_name: 'DuckDuckSocial',
redirect_uris: browser.identity.getRedirectURL(), // Use the add-on's redirect URL
scopes: 'read write',
website: 'https://tomcasavant.com'
})
});
if (!response.ok) {
const errorText = await response.text();
console.error('Error registering app:', errorText);
throw new Error('Failed to register app');
}
const appData = await response.json();
await browser.storage.local.set({
client_id: appData.client_id,
client_secret: appData.client_secret,
redirect_uri: appData.redirect_uri
});
return appData;
} catch (error) {
console.error('Error during app registration:', error);
throw error;
}
}
// Launches OAuth flow
function launchOAuthFlow(appRegistration, domain) {
const authorizationUrl = `https://${domain}/oauth/authorize?client_id=${appRegistration.client_id}&redirect_uri=${encodeURIComponent(appRegistration.redirect_uri)}&response_type=code&scope=read`;
return browser.identity.launchWebAuthFlow({
interactive: true,
url: authorizationUrl
});
}
// Get access token from Authorization
async function exchangeCodeForToken(code, domain, appRegistration) {
try {
const response = await fetch(`https://${domain}/oauth/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: appRegistration.client_id,
client_secret: appRegistration.client_secret,
redirect_uri: appRegistration.redirect_uri,
grant_type: 'authorization_code',
code: code
})
});
if (!response.ok) {
const errorText = await response.text();
console.error('Error exchanging code for token:', errorText);
throw new Error('Failed to exchange authorization code for access token');
}
const tokenData = await response.json();
await browser.storage.local.set({ access_token: tokenData.access_token });
} catch (error) {
console.error('Error during token exchange:', error);
throw error;
}
}
// Validates the redirect URL
async function validate(redirectUrl, domain, appRegistration) {
try {
if (redirectUrl) {
console.log('Generated Redirect URL');
const code = new URL(redirectUrl).searchParams.get('code');
if (code) {
await exchangeCodeForToken(code, domain, appRegistration);
console.log('Access token saved successfully.');
} else {
throw new Error('Authorization code not found in redirect URL.');
}
} else {
throw new Error('No redirect URL returned.');
}
} catch (error) {
console.error('Validation error:', error);
throw error;
}
}