-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
267 lines (224 loc) · 7.48 KB
/
api.js
File metadata and controls
267 lines (224 loc) · 7.48 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// API Configuration
// Note: config.js must be loaded before this file to get API_URL
const API_CONFIG = {
get baseURL() {
// Use environment-aware API_URL from config.js if available
return typeof API_URL !== 'undefined' ? API_URL : 'https://focus-backend-g1zg.onrender.com/api';
},
endpoints: {
register: '/auth/register',
login: '/auth/login',
profile: '/auth/profile',
updateStats: '/users/stats',
updateSettings: '/users/settings',
updateActivity: '/users/activity',
updateProfileEffect: '/users/profile-effect',
updateNameBanner: '/users/name-banner',
updateAvatarDecoration: '/users/avatar-decoration',
updateProfileDecoration: '/users/profile-decoration',
getUser: '/users', // + /:username
leaderboard: '/users/leaderboard',
addFriend: '/friends/add',
removeFriend: '/friends', // + /:friendUserId
getFriends: '/friends',
getFriendsActivity: '/friends/activity'
}
};
// API Helper Functions
class API {
static async request(endpoint, options = {}) {
const token = await this.getToken();
const config = {
headers: {
'Content-Type': 'application/json',
...(token && { 'Authorization': `Bearer ${token}` }),
...options.headers
},
...options
};
const url = API_CONFIG.baseURL + endpoint;
console.log('API Request:', options.method || 'GET', url);
try {
const response = await fetch(url, config);
console.log('API Response status:', response.status);
const data = await response.json();
console.log('API Response data:', data);
if (!response.ok) {
// Check for device conflict (logged in on another device)
if (response.status === 401 && data.code === 'DEVICE_CONFLICT') {
console.error('🚨 Device conflict detected - user logged in elsewhere');
await this.handleDeviceConflict(data.message);
}
throw new Error(data.error || 'API request failed');
}
return data;
} catch (error) {
console.error('API Error:', error);
throw error;
}
}
static async handleDeviceConflict(message) {
// Show notification to user
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon48.png',
title: '🔒 Logged Out',
message: message || 'You have been logged in from another device.',
priority: 2,
requireInteraction: true
});
// Clear all auth data
await chrome.storage.local.clear();
// Redirect to login if on extension pages
chrome.tabs.query({}, (tabs) => {
tabs.forEach(tab => {
if (tab.url && tab.url.includes('chrome-extension://')) {
chrome.tabs.update(tab.id, { url: chrome.runtime.getURL('pages/login.html') });
}
});
});
}
static async getToken() {
const result = await chrome.storage.local.get(['authToken']);
return result.authToken;
}
static async setToken(token) {
await chrome.storage.local.set({ authToken: token });
}
static async clearToken() {
await chrome.storage.local.remove(['authToken']);
}
static async getDeviceId() {
const result = await chrome.storage.local.get(['deviceId']);
if (result.deviceId) {
return result.deviceId;
}
// Generate new device ID
const newDeviceId = crypto.randomUUID ? crypto.randomUUID() : `device_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
await chrome.storage.local.set({ deviceId: newDeviceId });
return newDeviceId;
}
static getBrowserInfo() {
return navigator.userAgent;
}
// Auth endpoints
static async register(username, displayName, password) {
const deviceId = await this.getDeviceId();
const browserInfo = this.getBrowserInfo();
const data = await this.request(API_CONFIG.endpoints.register, {
method: 'POST',
body: JSON.stringify({ username, displayName, password, deviceId, browserInfo })
});
if (data.token) {
await this.setToken(data.token);
}
if (data.deviceId) {
await chrome.storage.local.set({ deviceId: data.deviceId });
}
return data;
}
static async login(username, password) {
const deviceId = await this.getDeviceId();
const browserInfo = this.getBrowserInfo();
const data = await this.request(API_CONFIG.endpoints.login, {
method: 'POST',
body: JSON.stringify({ username, password, deviceId, browserInfo })
});
if (data.token) {
await this.setToken(data.token);
}
if (data.deviceId) {
await chrome.storage.local.set({ deviceId: data.deviceId });
}
return data;
}
static async getProfile() {
return await this.request(API_CONFIG.endpoints.profile);
}
// User endpoints
static async updateStats(stats) {
return await this.request(API_CONFIG.endpoints.updateStats, {
method: 'PUT',
body: JSON.stringify(stats)
});
}
static async updateSettings(settings) {
return await this.request(API_CONFIG.endpoints.updateSettings, {
method: 'PUT',
body: JSON.stringify(settings)
});
}
static async updateActivity(status, startTime) {
return await this.request(API_CONFIG.endpoints.updateActivity, {
method: 'PUT',
body: JSON.stringify({ status, startTime })
});
}
static async updateProfileEffect(effectId) {
return await this.request(API_CONFIG.endpoints.updateProfileEffect, {
method: 'PUT',
body: JSON.stringify({ effectId })
});
}
static async updateNameBanner(bannerId) {
return await this.request(API_CONFIG.endpoints.updateNameBanner, {
method: 'PUT',
body: JSON.stringify({ bannerId })
});
}
static async updateAvatarDecoration(decorationId) {
return await this.request(API_CONFIG.endpoints.updateAvatarDecoration, {
method: 'PUT',
body: JSON.stringify({ decorationId })
});
}
static async updateProfileDecoration(decorationId) {
return await this.request(API_CONFIG.endpoints.updateProfileDecoration, {
method: 'PUT',
body: JSON.stringify({ decorationId })
});
}
static async getUserByUsername(username) {
return await this.request(`${API_CONFIG.endpoints.getUser}/${username}`);
}
static async getLeaderboard(limit = 50) {
return await this.request(`${API_CONFIG.endpoints.leaderboard}?limit=${limit}`);
}
// Friends endpoints
static async addFriend(friendUsername) {
return await this.request(API_CONFIG.endpoints.addFriend, {
method: 'POST',
body: JSON.stringify({ friendUsername })
});
}
static async acceptFriendRequest(friendUsername) {
return await this.request('/friends/accept', {
method: 'POST',
body: JSON.stringify({ friendUsername })
});
}
static async rejectFriendRequest(friendUsername, withdraw = false) {
return await this.request('/friends/reject', {
method: 'POST',
body: JSON.stringify({ friendUsername, withdraw })
});
}
static async getFriendRequests() {
return await this.request('/friends/requests');
}
static async removeFriend(friendUserId) {
return await this.request(`${API_CONFIG.endpoints.removeFriend}/${friendUserId}`, {
method: 'DELETE'
});
}
static async getFriends() {
return await this.request(API_CONFIG.endpoints.getFriends);
}
static async getFriendsActivity() {
return await this.request(API_CONFIG.endpoints.getFriendsActivity);
}
}
// Export for use in other files
if (typeof module !== 'undefined' && module.exports) {
module.exports = { API, API_CONFIG };
}