-
peter_rabbit authoredpeter_rabbit authored
article-utils.js 2.48 KiB
"use strict";
const { fetchjson, fetchtext } = require("./fetch");
function getArticleBody(text) {
return text
.split(" ")
.map(word => {
if (word.includes("http://") || word.includes("https://")) {
const splitword = word.split("||");
const href = splitword[0].match(/http.+/);
const text = splitword.length > 1 ? splitword[1].replaceAll("_", " ") : href;
return word.replace(/http.*/, `<a href=${href} target="_blank">${text}</a>`);
} else return word;
})
.join(" ")
.replaceAll("\n", "<br/>");
}
function getArticleDate(date) {
return `${date.getDate()}-${date.getMonth() + 1}-${date.getFullYear()}`;
}
function loadArticles(dir_url) {
return new Promise((resolve, reject) => {
fetchjson(`${dir_url}/index.json`)
.then(json => {
Promise.all(
json.articles.map(async articlePath => {
const art = await fetchjson(`${dir_url}/${articlePath}`);
const tmpSplit = articlePath.split("/");
tmpSplit.pop();
const absArtPath = `${dir_url}/${tmpSplit.join("/")}`;
return Object.assign(art, { path: absArtPath });
})
)
.then(articles => {
populateArticles(articles)
.then(completeArticles => resolve(completeArticles))
.catch(e => reject(e));
})
.catch(e => reject(e));
})
.catch(e => console.log(e));
});
}
function populateArticles(articles) {
return new Promise((resolve, reject) => {
Promise.all(
articles.map(async article => {
if (article.body.indexOf("<file>") !== -1) {
const txtPath = article.body.replace("<file>", "");
const textValue = await fetchtext(`${article.path}/${txtPath}`);
article.body = textValue;
article.date = article.date ? new Date(article.date) : undefined;
}
return article;
})
)
.then(completeArticles => resolve(completeArticles.sort((a, b) => a.date - b.date)))
.catch(e => reject(e));
});
}
module.exports = {
loadArticles,
getArticleBody,
getArticleDate,
populateArticles,
};