-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
266 lines (231 loc) · 8.39 KB
/
script.js
File metadata and controls
266 lines (231 loc) · 8.39 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
// Utility Functions
function normalizeName(string) {
function truncateSpecialCharacters(string) {
const specialCharIndex = string.search(/[^a-zA-Z0-9\s]/);
if (specialCharIndex !== -1) {
return string.substring(0, specialCharIndex);
};
return string
};
function splitSecondWhiteSpace(string) {
const secondWhiteSpace = string.match(/(?:\S*\s){2}/)
if (secondWhiteSpace) {
return string.substring(0, secondWhiteSpace[0].length - 1);
};
return string
};
return truncateSpecialCharacters(splitSecondWhiteSpace(string));
};
function truncateText(string, len) {
if (string.length > len) {
const whitespaceIndex = string.indexOf(" ", len);
if (whitespaceIndex !== -1) {
return string.slice(0, whitespaceIndex);
};
};
return string
};
function normalizeDescription(string) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = string;
return tempDiv.textContent
.trim()
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/\(/g, "(")
.replace(/\)/g, ")");
}
// DUMB helper classes
class Article {
constructor(feed, title, date, url, description, image_url) {
this.feed = feed;
this.title = title;
this.date = date;
this.url = url;
this.description = description;
this.image_url = image_url;
}
}
class feedFetcher {
constructor() {
this.CORSProxy = "https://corsproxy.io/?url=";
};
async fetchRSSFeed(url) {
url = this.CORSProxy + encodeURIComponent(url);
try {
const response = await fetch(url);
const xmlDocument = new DOMParser().parseFromString(await response.text(), "application/xml");
const items = Array.from(xmlDocument.getElementsByTagName("item"));
const feedDomain = normalizeName(xmlDocument.getElementsByTagName("title")[0].textContent);
// Array of Article objects.
return items.map(item => {
let title = truncateText(item.getElementsByTagName("title")[0].textContent, 140);
let feed = feedDomain;
let date = item.getElementsByTagName("pubDate")[0]?.textContent;
let url = item.getElementsByTagName("link")[0].textContent;
let description = truncateText(normalizeDescription(item.getElementsByTagName("description")[0]?.textContent), 180);
let image_url = Array.from(item.getElementsByTagName("*")).find(element => element.hasAttribute("url"))?.getAttribute("url");
if (!feed || !date || !description || description.includes("undefined") || description.includes("null")) {
return null
};
if (!image_url) {
image_url = "./static/default-image.png "
};
return new Article(feed, title, date, url, description, image_url);
}).filter(article => article !== null);
} catch (error) {
console.error("Error fetching RSS feed:", error);
return [];
}
};
async validateFeed(url) {
url = this.CORSProxy + encodeURIComponent(url);
try {
const response = await fetch(url);
if (!response.ok || !response.headers.get('Content-Type')?.includes('xml')) {
return false;
}
return true;
} catch (error) {
console.error(`Error validating RSS URL: ${url}`, error);
return false;
}
};
};
// DOM Manipulation
const newsFeed = document.getElementById("feed");
const newsReader = document.getElementById("reader");
const addButton = document.getElementById("add-icon");
const modal = document.getElementById("modal");
const closeModalButton = document.getElementById("closeModal");
const saveTextButton = document.getElementById("save-text");
const inputText = document.getElementById("input-text");
const tableBody = document.querySelector("#urls-table tbody");
const feedTable = document.querySelector("main > table");
const pollingInterval = document.querySelector("#polling-interval");
const feed = new feedFetcher();
let feedURLs = [];
let intervalID;
async function validateRSSURL(url) {
const domainPattern = /^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?$/;
if (domainPattern.test(url) && (url.toLowerCase().includes("rss") || url.toLowerCase().includes("feed"))) {
return await feed.validateFeed(url);
}
return false;
};
async function renderArticles() {
const fetchAllArticles = feedURLs.map(url => feed.fetchRSSFeed(url));
const arrays = await Promise.all(fetchAllArticles);
const articles = arrays
.flat()
.sort((a, b) => new Date(b.date) - new Date(a.date))
.map((article, index) => {
return createArticle(
article.feed,
article.title,
article.date,
article.url,
article.description,
article.image_url,
index
);
}).join("");
feedTable.innerHTML = articles
};
function createArticle(feedName, title, date, url, description, image_url, index) {
return `
<tr class="article ${index % 2 === 0 ? "alternate-color" : ""}">
<td class="cell left-col">
<div class="icon">
<i class="fa fa-newspaper" aria-hidden="true"></i>
</div>
<div class="text-container">
<h1 class="title">${feedName}</h1>
<h2>${title}</h2>
<p class="date">${date}</p>
</div>
</td>
<td class="cell right-col">
<img class="image" src="${image_url}" alt="Article Image">
<p class="description">${description}... <a class="hyperlink" href="${url}" target="_blank"> Read more</a></p>
</td>
</tr>
`;
}
function populateTable() {
tableBody.innerHTML = feedURLs.map((url, index) => `
<tr>
<td>${url}</td>
<td><button onclick="deleteURL(${index})">×</button></td>
</tr>
`).join('');
};
function deleteURL(index) {
feedURLs.splice(index, 1);
saveURLs();
};
function saveURLs(url = null) {
if (url) {
feedURLs.push(url);
};
localStorage.setItem("feedURLs", JSON.stringify(feedURLs));
populateTable();
};
function loadURLs() {
const stored = localStorage.getItem("feedURLs");
feedURLs = stored ? JSON.parse(stored) : [];
};
// Event Listeners
saveTextButton.addEventListener("click", async () => {
const text = inputText.value;
if (text) {
try {
const isValid = await validateRSSURL(text);
if (isValid) {
saveURLs(text);
inputText.value = "";
} else {
alert("Please, enter a valid RSS feed URL!");
inputText.value = "";
}
} catch (error) {
console.error("Error during validation:", error);
alert("An error occurred while validating the URL.");
inputText.value = "";
}
}
});
addButton.addEventListener("click", () => {
modal.classList.toggle("toggle-modal");
});
window.addEventListener("click", (event) => {
if (event.target === modal) {
modal.classList.toggle("toggle-modal");
}
});
pollingInterval.addEventListener('change', function() {
const interval = parseInt(this.value, 10);
clearInterval(intervalID);
intervalID = setInterval(renderArticles, interval);
localStorage.setItem("interval", JSON.stringify(interval));
});
const callback = function(mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
renderArticles();
};
};
};
const observer = new MutationObserver(callback);
observer.observe(tableBody, { childList: true, subtree: true });
// Initial Render
if (!localStorage.getItem("firstRun")) {
localStorage.setItem("firstRun", "dummy");
saveURLs("https://www.newscientist.com/feed/home/");
};
intervalID = setInterval(renderArticles, (localStorage.getItem("interval") || 300000));
loadURLs();
populateTable();