-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
298 lines (281 loc) · 9.23 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
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/*
** Description: This file is the background script of the extension.
** It contains the main logic of the extension.
** Author: Bastien Boymond
*/
const baseUrl = "https://www.japscan.lol/"
/*
** Description: Request GET for REST API that return a boolean
** Parameters: [url] {string}: the url to request
** Return: bool: a promise that will be resolved with the value
*/
async function requestGet(url){
let data;
try {
const res = await fetch(url, {
method: 'GET',
credentials: 'include',
});
console.log(res);
if ((await res.text()) === 'true') {
return true
} else {
return false
}
} catch (e) {
console.log(e);
return false
}
};
/*
** Description: Request GET for REST API that return content of request
** Parameters: [url] {string}: the url to request
** Return: {Promise}: a promise that will be resolved with the value
*/
async function requestGetData(url){
try {
const res = await fetch(url, {
method: 'GET',
credentials: 'include',
});
return(res.text());
} catch (e) {
return (e);
}
};
/*
** Description: Request POST for API
** Parameters: [url] {string}: the url to request
** [data] {object}: the data to send
** [token] {string}: the token to use for the request (optional)
** Return: {Promise}: a promise that will be resolved with the value
*/
async function requestPost(url, data, token=null) {
try {
console.log(token, data, url);
console.log(JSON.stringify(data));
if (!token) {
const res = await fetch(url, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(data)
});
console.log("request without token");
return await res.json();
}
const res = await fetch(url, {
method: 'POST',
credentials: 'include',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(data)
});
console.log("request with token");
return await res.json();
} catch (e) {
console.log(e);
return false
}
}
/*
** Description: Request POST for Anilist API
** Parameters: [token] {string}: the token to use for the request
** [query] {string}: the query to send
** [variables] {object}: the variables to send
** Return: {Promise}: a promise that will be resolved with the value
*/
async function graphqlRequest(token, query, variables) {
const url = 'https://graphql.anilist.co';
const res = await fetch(url, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query: query,
variables: variables
})
});
if (res.status === 200) {
const json = await res.json();
return json.data
} else {
console.log(await res.json());
return false
}
}
/*
** Description: Get MediaList from Anilist API
** Parameters: [token] {string}: the token to use for the request
** [id] {int}: the id of the MediaList
** Return: {Promise}: a promise that will be resolved with the value
*/
async function getMediaListById(token, id) {
return await graphqlRequest(token, `
query ($id: Int) {
MediaList(id: $id) {
id
mediaId
status
score
progress
repeat
media {
id
title {
userPreferred
}
}
}
}`, {id: id});
}
/*
** Description: Get Stored value from chrome storage
** Parameters: [key] {string}: the key of the value to get
** Return: {Promise}: a promise that will be resolved with the value
*/
function get_stored_value(key) {
return new Promise((resolve) => {
chrome.storage.sync.get(key, function(value) {
resolve(value[key]);
});
});
}
/*
** Description: Store value in chrome storage
** Parameters: [key] {string}: the key of the value to store
** [value] {string}: the value to store
** Return: None
*/
function store_value(key, value)
{
chrome.storage.sync.set({
[key]: value,
})
}
/*
** Description: update the progress of the manga in anilist
** Parameters: [ids] {object}: the ids of the manga
** [chapter] {int}: the chapter to update
** [type] {string}: the type of the manga
** [page] {int}: the page of the manga
** [mangaName] {string}: the name of the manga
** Return: None
*/
async function anilist_update(ids, chapter, type, page, mangaName) {
console.log(ids, chapter, type, page, mangaName);
const token = await get_stored_value('anilist_code');
if (!token) return;
let progress = await get_stored_value('anilist_progress_' + ids.idManga);
if (!progress) {
const MediaList = await getMediaListById(token, ids.idList);
progress = MediaList.MediaList.progress;
store_value('anilist_progress_' + ids.idManga, progress);
}
if (progress != parseInt(chapter)) {
const res = await graphqlRequest(token, `
mutation ($id: Int, $progress: Int) {
SaveMediaListEntry (id: $id, progress: $progress) {
id
progress
}
}`, {id: ids.idList, progress: chapter});
store_value('anilist_progress_' + ids.idManga, chapter);
} else {
console.log('no update');
}
console.log('anilist updated');
}
/*
** Description: Parse the message received from the content script
** Parameters: [msg] {string}: the message received
** Return: {array}: the data of the message
*/
function createData(msg) {
data = msg.split('/');
data.shift();
return data
}
/*
** Description: get the stored value of the mangas and update the progress in anilist if we got api key
** Parameters: [data] {array}: the data of the manga
** Return: None
*/
async function anilist_save(data) {
const anilist_id = await get_stored_value('anilist_id_' + data[0]);
const anilist_data = await get_stored_value('anilist_data');
console.log(anilist_data);
if (!anilist_id) return;
if (!anilist_data) return;
anilist_data.forEach(element => {
if (element.idManga == anilist_id) {
anilist_update(element, data[1], data[2], data[3], data[0]);
}
});
}
/*
** Description: Every Page we save the stats of the manga in the local storage and on the server
** Parameters: [data] {array}: the data of the manga
** Return: None
*/
async function save_stats(data) {
const userId = await get_stored_value('user_id');
const tokenJapscan = await get_stored_value('token_stats');
const saved = await get_stored_value('saved_stats_' + data[0]);
if (!userId || !tokenJapscan) return;
if (saved) {
if (saved.chapter == data[1] && saved.type == data[2] && saved.page == data[3]) return;
store_value('saved_stats_' + data[0], {chapter: data[1], type: data[2], page: data[3]});
console.log(saved.page, data[3], saved.page === data[3], 'page');
const new_chapter_read = saved.chapter === data[1] ? 0 : 1;
let new_page_read = 0;
if (new_chapter_read == 1) {
new_page_read = 1;
} else if (saved.page !== data[3]) {
new_page_read = 1;
}
await requestPost('http://141.94.68.137:3900/savestats', {userid: userId, manga: data[0], chapter_read: new_chapter_read, type: data[2], page_read: new_page_read, chapter: data[1], page: data[3]}, tokenJapscan);
}
store_value('saved_stats_' + data[0], {chapter: data[1], type: data[2], page: data[3]});
}
/*
** Description: Get the message from the content script and doing something depending on the message
** Parameters: [msg] {string}: the message receive
** [sender] {object}: the sender of the message
** [sendResponse] {function}: the function to send the response
** Return: {boolean}: true if we need to send a response
*/
chrome.runtime.onMessage.addListener(async (msg, sender, sendResponse) => {
if (msg.text.includes('update/')) {
data = createData(msg.text);
await anilist_save(data);
await save_stats(data);
} else {
doSomethingWith(msg).then(sendResponse);
}
return true;
});
async function doSomethingWith(msg) {
let data = await requestGetData(`${msg.text}`);
return data;
}
/*
** Description: When the extension is installed or updated we open the welcome page
*/
chrome.runtime.onInstalled.addListener(function(details){
let internalUrl = chrome.runtime.getURL("website/welcome/welcome.html");
if(details.reason == "install"){
chrome.tabs.create({ url: internalUrl });
}else if(details.reason == "update"){
//call a function to handle an update
}
});