-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrack.js
458 lines (395 loc) · 15.7 KB
/
track.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
// Your initial projects list
let globalProjects = [
"EdgeTX/edgetx",
"ExpressLRS/ExpressLRS",
"iNavFlight/inav",
"betaflight/betaflight",
"BossHobby/QUICKSILVER",
"hd-zero/hdzero-goggle",
"hd-zero/hdzero-vtx"
];
// Save projects to localStorage
function saveProjectsToLocalStorage(projects) {
try {
localStorage.setItem('projects', JSON.stringify(projects));
} catch (error) {
console.error('Check Your projects list');
}
}
function updateRateLimitDiv(remainingLimit = "-", totalLimit = 60, resetTime = "-") {
const currentTime = Math.floor(Date.now() / 1000); // Current time in UTC epoch (seconds)
const timeDiffInMinutes = isNaN(resetTime) ? "-" : Math.ceil(Math.abs(resetTime - currentTime) / 60);
const rateLimitMessage = `Rate limit: ${remainingLimit}/${totalLimit}`;
const rateResetMessage = `Limit reset in ${timeDiffInMinutes} mins`;
const nodeAPIInfo = 'Github API requests are limited.';
const rateLimitDiv = document.getElementById('rate-limit');
rateLimitDiv.innerHTML = `
${nodeAPIInfo}<br>
${rateLimitMessage}<br>
${rateResetMessage}`;
}
// Load projects from localStorage
function loadProjectsFromLocalStorage() {
const savedProjects = localStorage.getItem('projects');
updateRateLimitDiv();
if (savedProjects) {
try {
return JSON.parse(savedProjects);
} catch (error) {
// Clear the localStorage
localStorage.removeItem('projects');
console.error("Error parsing projects from localStorage");
}
}
return [];
}
// Load projects from localStorage
let savedProjects = loadProjectsFromLocalStorage();
if (savedProjects.length > 0) {
globalProjects = savedProjects;
}
function fetchWithTimeout(url, options, timeout = 10000) {
return Promise.race([
fetch(url, options),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Unable to get data')), timeout)
)
]);
}
let displayLimit = [60];
async function getReleaseInfo(project) {
const url = "https://api.github.com/repos/" + project + "/releases";
try {
const cachedData = localStorage.getItem(`releaseInfo_${project}`);
if (cachedData) {
const parsedData = JSON.parse(cachedData);
if (parsedData.expiresAt > Date.now()) {
console.log("Using cache");
return parsedData.data; // Use cached data
} else {
// Cache expired, delete
localStorage.removeItem(`releaseInfo_${project}`);
console.log("Cache expired");
}
}
const response = await fetchWithTimeout(url);
// Log Github API rate limits
displayLimit.push(Number(response.headers.get('X-Ratelimit-Remaining')));
updateRateLimitDiv(
Math.min(...displayLimit),
response.headers.get('X-RateLimit-Limit'),
response.headers.get('X-RateLimit-Reset'));
if (!response.ok) {
console.log('Project ' + project + ' not found');
alert('Project ' + project + ' not found');
return;
}
const data = await response.json();
let latestRelease, previousRelease;
// read checkbox value
const stableOnly = stableCheckbox.checked;
for (let i = 0; i < data.length; i++) {
// not nightly and not prerelease
if (!data[i].tag_name.includes('nightly')
&& (stableOnly ? !data[i].prerelease : true) // stableOnly checkbox disables prereleases
) {
if (!latestRelease) {
latestRelease = data[i];
} else if (!previousRelease) {
previousRelease = data[i];
break;
}
}
}
const latestTag = latestRelease?.tag_name;
const tempDate = new Date(latestRelease?.published_at);
const latestDate = isNaN(tempDate.getTime()) ? null : tempDate;
const previousTag = previousRelease?.tag_name;
const tempDate2 = new Date(previousRelease?.published_at);
const previousDate = isNaN(tempDate2.getTime()) ? null : tempDate2;
const diff = latestDate && previousDate ?
Math.floor((latestDate - previousDate) / (1000 * 60 * 60 * 24)) : null;
// Save to cache
const info = [latestTag, latestDate, previousTag, diff];
const expirationTime = Date.now() + 24 * 60 * 60 * 1000; //+1 day
const cachedData2 = {
data: info, // fetched data
expiresAt: expirationTime
};
localStorage.setItem(`releaseInfo_${project}`, JSON.stringify(cachedData2));
return info;
} catch (error) {
console.error("Error", error);
return;
}
}
function setCellColor(cellDate) {
// Highlight cell in green where the date is no older than 1 month and in red if older than half a year
if (!cellDate) { return }
const today = new Date();
const oneMonthAgo = new Date();
const halfYearAgo = new Date();
oneMonthAgo.setMonth(today.getMonth() - 1);
halfYearAgo.setMonth(today.getMonth() - 6);
const date = new Date(cellDate);
if (date.getTime() > oneMonthAgo.getTime()) {
return "#00BB0033"; //green
} else if (date.getTime() < halfYearAgo.getTime()) {
return "#BB000033"; //red
}
}
function createTableRow(project) {
const tr = document.createElement("tr");
const tdProject = document.createElement("td");
tdProject.textContent = project.replace("/", "/\u200B");
tr.appendChild(tdProject);
const tdLatest = document.createElement("td");
tdLatest.textContent = "loading...";
tr.appendChild(tdLatest);
const tdDate = document.createElement("td");
tdDate.textContent = "loading...";
tr.appendChild(tdDate);
const tdPrevious = document.createElement("td");
tdPrevious.textContent = "loading...";
tr.appendChild(tdPrevious);
const tdDiff = document.createElement("td");
tdDiff.textContent = "loading...";
tr.appendChild(tdDiff);
const tdAction = document.createElement("td");
const removeButton = document.createElement("button");
removeButton.textContent = " X ";
removeButton.className = "remove-button";
removeButton.addEventListener("click", function () {
projectBody.removeChild(tr);
// remove from cache
globalProjects.splice(globalProjects.indexOf(project), 1);
saveProjectsToLocalStorage(globalProjects);
localStorage.removeItem(`releaseInfo_${project}`);
});
tdAction.appendChild(removeButton);
tr.appendChild(tdAction);
getReleaseInfo(project)
.then(info => {
if (!info) {
tdLatest.textContent = "-";
tdDate.textContent = "-";
tdPrevious.textContent = "-";
tdDiff.textContent = "-";
} else {
tdProject.innerHTML = `<a href="https://github.com/${project}" target="_blank">${project}</a>`; // link to the project
tdLatest.textContent = info[0] ? info[0] : "-"; // latest Release
tdDate.textContent = info[1] ? new Date(info[1]).toISOString().split('T')[0] : "-"; // release Date
tdDate.style.backgroundColor = setCellColor(info[1]); // cell color
tdPrevious.textContent = info[2] ? info[2] : "-"; // previous Release
tdDiff.textContent = info[3] ? info[3] + " days" : "-"; // delta in days
}
})
.catch(error => console.error(error));
return tr;
}
// Get elements
const projectInput = document.getElementById("project-input");
const projectBody = document.getElementById("project-body");
const addButton = document.getElementById("add-button");
const exportButton = document.getElementById("export-button");
const importButton = document.getElementById("import-button");
const importInput = document.getElementById("import-input");
const stableCheckbox = document.getElementById("stable-option");
const table = document.getElementById("project-table");
const projectName = document.getElementById("project-name");
const projectDate = document.getElementById("project-date");
startApp();
// Use projects list
function startApp() {
// set checkbox value
const storedValue = localStorage.getItem("stableOnly");
stableCheckbox.checked = storedValue === "true";
importInput.value = '';
// create project list in a local storage
saveProjectsToLocalStorage(globalProjects);
// load projects
for (const project of globalProjects) {
const tr = createTableRow(project);
if (tr) {
projectBody.appendChild(tr);
}
displayLimit = [60];
}
}
function parseRepoName(input) {
let repoName;
if (input.startsWith('http')) {
const urlObj = new URL(input);
const pathSegments = urlObj.pathname.split('/');
repoName = pathSegments[1] + '/' + pathSegments[2];
} else {
repoName = input;
}
return repoName;
}
function handleInput() {
// read input value
const regex = /[^\x20-\x7E]+/g; // not visible ASCII characters
const project = parseRepoName(projectInput.value.trim().replace(regex, ''));
// Check url for alphanumeric or hyphen, slash, alphanumeric or hyphen
const pattern = /^[a-zA-Z]+[a-zA-Z\d\-_]*\/[a-zA-Z]+[a-zA-Z\d\-_]*$/;
if (project && pattern.test(project)) {
const tr = createTableRow(project);
if (tr) {
projectBody.appendChild(tr);
globalProjects.push(project);
saveProjectsToLocalStorage(globalProjects);
projectInput.value = "";
} else {
return;
}
} else {
const msg = `Invalid project name (${project}), it should be in the format 'project/repository'.`;
console.error(msg);
alert(msg);
}
}
addButton.addEventListener("click", function () {
handleInput();
});
projectInput.addEventListener("keypress", function (event) {
if (event.key === 'Enter' || event.code === 'Enter') {
handleInput();
}
});
stableCheckbox.addEventListener("change", (e) => {
// save checkbox value
localStorage.setItem('stableOnly', e.target.checked);
// clear cache
deleteItemsWithPrefix("releaseInfo_");
// clear table
projectBody.innerHTML = '';
// reload app
startApp();
});
function deleteItemsWithPrefix(prefix) {
Object.keys(localStorage)
.filter(key => key.startsWith(prefix))
.forEach(key => localStorage.removeItem(key));
}
function sortRowsByName(rows, ascending) {
return rows.sort(function (rowA, rowB) {
const tdProjectA = rowA.getElementsByTagName("td")[0].textContent;
const tdProjectB = rowB.getElementsByTagName("td")[0].textContent;
return ascending ? tdProjectA.localeCompare(tdProjectB) : tdProjectB.localeCompare(tdProjectA);
});
}
function sortRowsByDate(rows, ascending) {
return rows.sort(function (rowA, rowB) {
const dateA = new Date(rowA.getElementsByTagName("td")[2].textContent);
const dateB = new Date(rowB.getElementsByTagName("td")[2].textContent);
return ascending ? dateA - dateB : dateB - dateA;
});
}
let sortOrder = false;
function sortTable(criteria) {
// Get the rows in the table
const rows = Array.from(table.getElementsByTagName("tr")).slice(1); // slice(1) to exclude the header row
const tbody = table.getElementsByTagName("tbody")[0];
// reorder the table
let sortedRows;
rows.forEach(row => row.remove());
if (criteria === "byName") {
sortedRows = sortRowsByName(rows, sortOrder);
}
if (criteria === "byDate") {
sortedRows = sortRowsByDate(rows, sortOrder);
}
sortedRows.forEach(row => tbody.appendChild(row));
// Toggle sorting
sortOrder = !sortOrder;
}
function exportToJSON() {
// read local storage
const localProjects = localStorage.getItem('projects');
if (localProjects === null) {
return;
}
const existingProjects = JSON.parse(localStorage.getItem('projects'));
// convert array to json string
const jsonContent = JSON.stringify(existingProjects, null, 2);
// create blob from json string
const blob = new Blob([jsonContent], { type: 'application/json;charset=utf-8;' });
// create link
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', 'projects.json');
// append link and click it
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
function importJSON() {
const file = importInput.files[0];
const allowedMimeTypes = ['application/json'];
if (!file?.type || !allowedMimeTypes.includes(file.type)) {
alert('Please select a JSON file');
importInput.value = '';
if (file?.type) {
console.log("file type", file.type);
}
return;
} else {
console.log("loading json file", file.name);
}
const reader = new FileReader();
reader.onload = function (event) {
try {
const jsonContent = JSON.parse(event.target.result);
console.log('new projects:', jsonContent);
// validate each project for "projectName/repoName" format
const validFormat = /^[^\/]+\/[^\/]+$/;
const validProjects = jsonContent.filter(project => validFormat.test(project));
if (validProjects.length === 0) {
alert('Please select a valid JSON file');
importInput.value = '';
return;
}
// Retrieve existing projects from local storage
const localProjects = localStorage.getItem('projects');
const existingProjects = localProjects === null ? [] : JSON.parse(localProjects);
// Append new entries if they don't exist
validProjects.forEach(project => {
if (!existingProjects.includes(project)) {
existingProjects.push(project);
console.log('append:', project);
}
});
// Save the updated projects back to local storage
globalProjects = existingProjects;
importInput.value = '';
console.log('json imported');
// clear table
projectBody.innerHTML = '';
// and reload app
startApp();
} catch (error) {
alert('Error parsing JSON file');
console.error('Error parsing JSON:', error);
importInput.value = '';
}
};
reader.readAsText(file);
}
// export and download project list to json file
exportButton.addEventListener("click", function () {
exportToJSON();
});
// import json file with projects' list
importButton.addEventListener("click", function () {
importJSON();
});
// Sort by name after clicking "Project" header
projectName.addEventListener("click", function () {
sortTable("byName");
});
// Sort by date after clicking "Date" header
projectDate.addEventListener("click", function () {
sortTable("byDate");
});