mastowall/script.js

381 lines
14 KiB
JavaScript
Raw Normal View History

// The existingPosts array is used to track already displayed posts
let existingPosts = [];
2023-05-17 02:13:01 +02:00
// getUrlParameter helps to fetch URL parameters
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
console.log(results)
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
// secondsAgo calculates how many seconds have passed since the provided date
const secondsAgo = date => Math.floor((new Date() - date) / 1000);
// timeAgo formats the time elapsed in a human readable format
const timeAgo = function(seconds) {
// An array of intervals for years, months, days, hours, and minutes.
const intervals = [
2023-11-23 20:44:42 +01:00
{ limit: 31536000, singular: 'Jahre', plural: 'Jahren' },
{ limit: 2592000, singular: 'Monat', plural: 'Monaten' },
{ limit: 86400, singular: 'Tag', plural: 'Tagen' },
{ limit: 3600, singular: 'Stunde', plural: 'Stunden' },
{ limit: 60, singular: 'Minute', plural: 'Minuten' }
];
// Loop through the intervals to find which one is the best fit.
for (let interval of intervals) {
if (seconds >= interval.limit) {
2023-11-23 20:44:42 +01:00
let amount = Math.floor(seconds / interval.limit);
let text;
if (amount !== 1) {
text = interval.plural;
} else {
text = interval.singular;
}
return `Vor ${amount} ${text}`;
}
}
2023-11-23 20:44:42 +01:00
let text = "Sekunde";
let amount = Math.floor(seconds);
if (amount !== 1) {
text += "n";
}
return `Vor ${amount} ${text}`;
};
2023-05-17 02:13:01 +02:00
let includeReplies;
// max post age in seconds
let maxAge;
// below times are in milliseconds
// duration for slide animations
let duration;
// refresh rate
let refresh;
// extra cards text
let extraCards;
// fetchConfig fetches the configuration from the config.json file
const fetchConfig = async function() {
try {
const config = await $.getJSON('config.json');
$('#navbar-brand').text(config.navbarBrandText);
$('.navbar').css('background-color', config.navbarColor);
includeReplies = config.includeReplies;
maxAge = config.maxAge;
duration = config.duration * 1000;
refresh = config.refreshDuration * 1000;
extraCards = config.extraCards;
return config.defaultServerUrl;
} catch (error) {
console.log("Error loading config.json:", error);
2023-11-23 20:48:46 +01:00
$('#navbar-brand').text("Netzbegrünung Mastowall - gruene.social");
$('.navbar').css('background-color', "#008939");
includeReplies = true;
maxAge = 60 * 60 * 24 * 7;
duration = 10000;
refresh = 30000;
extraCards = [
"<div><img src='sharepic.png' style='max-width: 100%;max-height: 100%'></div>"
];
return "https://gruene.social";
}
}
// fetchPosts fetches posts from the server using the given hashtag
const fetchPosts = async function(serverUrl, hashtag) {
try {
const posts = await $.get(`${serverUrl}/api/v1/timelines/tag/${hashtag}?limit=20`);
return posts;
} catch (error) {
console.error(`Error loading posts for hashtag #${hashtag}:`, error);
}
};
// updateTimesOnPage updates the time information displayed for each post
const updateTimesOnPage = function() {
$('.card-text a.time').each(function() {
const timeValue = $(this).attr('data-time');
if (timeValue === '') return;
const date = new Date(timeValue);
const newTimeAgo = timeAgo(secondsAgo(date));
$(this).text(newTimeAgo);
});
};
2023-11-25 02:18:39 +01:00
// replace certain emojies in some text with images
const replaceEmojies = (text, emojis) => {
emojis.forEach(emoji => {
text = text.replaceAll(`:${emoji.shortcode}:`, `<img class="emoji" src="${emoji.static_url}">`);
});
return text;
};
// displayPost creates and displays a post
const displayPost = function(post) {
2023-11-10 19:42:57 +01:00
if (existingPosts.includes(post.id) || (!includeReplies && post.in_reply_to_id !== null)) return 0;
existingPosts.push(post.id);
let cardHTML = `
<div class="col-sm-3">
<div class="card m-2 p-2">
<div class="d-flex align-items-center mb-2">
<img src="${post.account.avatar}" class="avatar-img rounded-circle mr-2">
2023-11-25 02:18:39 +01:00
<p class="m-0">${replaceEmojies(DOMPurify.sanitize(post.account.display_name), post.account.emojis)} <span class="user-name">@${DOMPurify.sanitize(post.account.acct)}</span></p>
</div>
${post.media_attachments[0] ?
(post.media_attachments[0].url.endsWith('.mp4') ?
`<video src="${post.media_attachments[0].url}" controls autoplay muted loop></video>` :
`<img src="${post.media_attachments[0].url}" class="card-img-top mb-2">`) :
''}
2023-11-25 02:18:39 +01:00
<p class="card-text">${replaceEmojies(DOMPurify.sanitize(post.content), post.emojis)}</p>
${post.spoiler_text ? `<p class="card-text text-muted spoiler">${DOMPurify.sanitize(post.spoiler_text)}</p>` : ''}
<p class="card-text text-right"><small class="text-muted"><a class="time" href="${post.url}" target="_blank" data-time="${post.created_at}">${timeAgo(secondsAgo(new Date(post.created_at)))}</a></small></p>
</div>
</div>
`;
let $card = $(cardHTML);
$('#wall').prepend($card);
$('.masonry-grid').masonry('prepended', $card);
2023-11-10 19:42:57 +01:00
return 1;
};
const processPosts = function(posts) {
2023-11-23 21:57:58 +01:00
posts = posts.filter((post) => {
return secondsAgo(new Date(post.created_at)) < maxAge && post.content.indexOf("nitter.") === -1
});
return posts;
};
// updateWall displays all posts
const updateWall = function(posts) {
if (!posts || posts.length === 0) return;
posts = processPosts(posts);
2023-11-23 20:57:33 +01:00
posts.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
2023-11-10 19:42:57 +01:00
let ret = 0
posts.forEach(post => ret += displayPost(post));
$('.masonry-grid').masonry('layout');
return ret;
2023-11-10 17:16:31 +01:00
};
// updateCarousel
const updateCarousel = function(slides, posts) {
if (!posts || posts.length === 0) return;
posts = processPosts(posts);
2023-11-23 20:57:33 +01:00
posts.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
2023-11-10 17:16:31 +01:00
// remove slides in carousel
slides.innerHTML = "";
2023-11-10 19:42:57 +01:00
var newHTML = ` <!-- No Indicators -->`
2023-11-10 17:16:31 +01:00
newHTML += `<!-- the slides -->
<div class="carousel-inner">
`;
let existingCards = [];
2023-11-10 17:16:31 +01:00
for( let i = 0; i < posts.length; i++ ) {
let post = posts[i];
if (existingCards.includes(post.id) || (!includeReplies && post.in_reply_to_id !== null)) continue;
existingCards.push(post.id);
2023-11-16 14:45:16 +01:00
/*console.log( post.content )*/
2023-11-10 17:16:31 +01:00
if ( i == 0 ) {
newHTML += `<div class="carousel-item active" data-interval="${duration}" data-pause="false">`;
2023-11-10 17:16:31 +01:00
}
else {
newHTML += `<div class="carousel-item" data-interval="${duration}" data-pause="false">`;
2023-11-10 17:16:31 +01:00
}
2023-11-25 02:18:39 +01:00
const postContent = replaceEmojies(DOMPurify.sanitize(post.content), post.emojis);
2023-11-10 17:16:31 +01:00
newHTML += `
2023-11-10 19:42:57 +01:00
<div class="card-big">
<div class="d-flex align-items-center mb-4">
<img src="${post.account.avatar}" class="avatar-img-big rounded-circle mr-4">
2023-11-25 02:18:39 +01:00
<p class="avatar-name">${replaceEmojies(DOMPurify.sanitize(post.account.display_name), post.account.emojis)} <span class="user-name">@${DOMPurify.sanitize(post.account.acct)}</span></p>
2023-11-10 17:16:31 +01:00
</div>
2023-11-10 19:42:57 +01:00
<hr>
2023-11-16 14:45:16 +01:00
<div class="row align-items-center vertical-align-center">
2023-11-25 01:48:53 +01:00
<div class="${post.media_attachments[0] ? `col-md-6` : `col-md-12`}"><div class="card-text" ${strip(postContent).length > 700 ? `style="font-size: ${strip(postContent).length > 1000 ? `0.5`:`0.9`}em;"`: ``}>${postContent}</div></div>
${post.media_attachments[0] ?
(post.media_attachments[0].url.endsWith('.mp4') ?
`<div class="col-md-6"><video src="${post.media_attachments[0].url}" controls autoplay muted loop class="card-img-bottom" align="center"></video></div>` :
`<div class="col-md-6"><img src="${post.media_attachments[0].url}" class="card-img-bottom" align="center"> </div>`) :
''}
2023-11-10 17:16:31 +01:00
</div>
2023-11-10 19:42:57 +01:00
<hr>
2023-11-16 14:45:16 +01:00
<p class="card-text text-right">
<small class="text-muted"><a class="time" href="${post.url}" target="_blank" data-time="${post.created_at}">${timeAgo(secondsAgo(new Date(post.created_at)))}</a>
2023-11-16 14:45:16 +01:00
${post.favourites_count ? `, <b>${post.favourites_count}</b> mal favorisiert` : '' }
2023-11-16 14:51:31 +01:00
${post.replies_count ? `, <b>${post.replies_count}</b> mal kommentiert` : '' }
2023-11-16 14:45:16 +01:00
${post.reblogs_count ? `, <b>${post.reblogs_count}</b> mal geteilt` : '' }
</small>
</p>
2023-11-10 19:42:57 +01:00
</div>
2023-11-10 17:16:31 +01:00
`;
newHTML += '</div>';
}
for( let i = 0; i < extraCards.length; i++ ) {
2023-11-25 02:21:55 +01:00
newHTML += `<div class="carousel-item" data-interval="${duration * 2}" data-pause="false">
<div className="card-big">
<div class="d-flex align-items-center mb-4">
${extraCards[i]}
</div>
</div>
</div>`;
}
2023-11-10 17:16:31 +01:00
newHTML += '</div>'
document.getElementById("myCarousel").innerHTML = newHTML;
};
2023-11-10 19:42:57 +01:00
const showCarousel = function() {
// show popover
document.getElementById('popover').style.opacity = '1';
2023-11-10 19:42:57 +01:00
// Activate Carousel
$('#myCarousel').carousel("cycle");
}
const strip = function(html) {
let doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || "";
}
2023-11-10 19:42:57 +01:00
const hideCarousel = function() {
// show popover
document.getElementById('popover').style.opacity = '0';
// Activate Carousel
}
2023-11-10 17:16:31 +01:00
2023-06-05 12:23:01 +02:00
// hashtagsString returns a single string based on the given array of hashtags
const hashtagsString = function(hashtagsArray) {
return `${hashtagsArray.map(hashtag => `#${hashtag}`).join(' ')}`;
}
// updateHashtagsOnPage updates the displayed hashtags
const updateHashtagsOnPage = function(hashtagsArray) {
2023-06-05 12:23:01 +02:00
$('#hashtag-display').text(hashtagsArray.length > 0 ? hashtagsString(hashtagsArray) : 'No hashtags set');
};
2023-05-17 02:13:01 +02:00
2023-06-05 12:23:01 +02:00
// updateHashtagsOnPage updates the document title by appending the given array of hashtags
const updateHashtagsInTitle = function(hashtagsArray) {
const baseTitle = document.title;
document.title = `${baseTitle} | ${hashtagsString(hashtagsArray)}`;
}
// handleHashtagDisplayClick handles the event when the hashtag display is clicked
const handleHashtagDisplayClick = function(serverUrl) {
$('#app-content').addClass('d-none');
$('#zero-state').removeClass('d-none');
const currentHashtags = getUrlParameter('hashtags').split(',');
if ( currentHashtags = null ) {
currentHasttags = "netzbegruenung,ldk24,wasjetztzählt".split(',')
}
for (let i = 0; i < currentHashtags.length; i++) {
$(`#hashtag${i+1}`).val(currentHashtags[i]);
}
$('#serverUrl').val(serverUrl);
};
2023-05-17 02:13:01 +02:00
// handleHashtagFormSubmit handles the submission of the hashtag form
const handleHashtagFormSubmit = function(e, hashtagsArray) {
e.preventDefault();
2023-05-17 02:13:01 +02:00
let hashtags = [
$('#hashtag1').val(),
$('#hashtag2').val(),
$('#hashtag3').val()
];
2023-05-17 02:13:01 +02:00
hashtags = hashtags.filter(function(hashtag) {
return hashtag !== '' && /^[\w]+$/.test(hashtag);
});
let serverUrl = $('#serverUrl').val();
if (!/^https:\/\/[\w.\-]+\/?$/.test(serverUrl)) {
alert('Invalid server URL.');
return;
}
const newUrl = window.location.origin + window.location.pathname + `?hashtags=${hashtags.join(',')}&server=${serverUrl}`;
window.location.href = newUrl;
};
2023-05-17 02:13:01 +02:00
// On document ready, the script configures Masonry, handles events, fetches and displays posts
$(document).ready(async function() {
const defaultServerUrl = await fetchConfig();
$('.masonry-grid').masonry({
itemSelector: '.col-sm-3',
columnWidth: '.col-sm-3',
percentPosition: true
2023-05-17 02:13:01 +02:00
});
setInterval(function() {
$('.masonry-grid').masonry('layout');
}, refresh);
2023-11-10 17:16:31 +01:00
let hashtags = getUrlParameter('hashtags');
if ( hashtags == '' ) {
2024-05-05 09:10:49 +02:00
hashtags = "netzbegruenung,lptsh,wasjetztzählt";
}
const hashtagsArray = hashtags ? hashtags.split(',') : [];
const serverUrl = getUrlParameter('server') || defaultServerUrl;
$('#hashtag-display').on('click', function() {
handleHashtagDisplayClick(serverUrl);
});
2023-11-10 17:16:31 +01:00
const slides = $('#myCarousel');
2023-11-10 19:42:57 +01:00
const popover = $('#popover');
2023-11-10 17:16:31 +01:00
if (hashtagsArray.length > 0 && hashtagsArray[0] !== '') {
let allPosts = await Promise.all(hashtagsArray.map(hashtag => fetchPosts(serverUrl, hashtag)));
updateWall(allPosts.flat());
setTimeout(function() {
$('.masonry-grid').masonry('layout');
2023-11-16 16:22:59 +01:00
}, 2000);
2023-11-10 19:59:46 +01:00
updateCarousel(slides, allPosts.flat());
2023-11-10 19:42:57 +01:00
setTimeout(async function() { showCarousel(); }, duration)
setInterval(async function() {
const newPosts = await Promise.all(hashtagsArray.map(hashtag => fetchPosts(serverUrl, hashtag)));
2023-11-10 19:42:57 +01:00
let updated = updateWall(newPosts.flat());
if ( updated > 0 ) {
2023-11-10 19:59:46 +01:00
updateCarousel(slides, newPosts.flat());
2023-11-10 19:42:57 +01:00
}
}, refresh);
} else {
$('#zero-state').removeClass('d-none');
$('#popover').removeClass('popover');
$('#app-content').addClass('d-none');
}
updateHashtagsOnPage(hashtagsArray);
2023-06-05 12:23:01 +02:00
updateHashtagsInTitle(hashtagsArray);
$('#hashtag-form').on('submit', function(e) {
handleHashtagFormSubmit(e, hashtagsArray);
});
2023-11-10 17:16:31 +01:00
updateTimesOnPage();
setInterval(updateTimesOnPage, 60000);
2023-05-17 02:13:01 +02:00
});