Basic post display
This commit is contained in:
74
src/lib/server/timeline.ts
Normal file
74
src/lib/server/timeline.ts
Normal file
@ -0,0 +1,74 @@
|
||||
import { HASHTAG_FILTER, URL_FILTER } from '$env/static/private';
|
||||
import type { Post, Tag, TimelineEvent } from '$lib/mastodon/response';
|
||||
import { savePost } from '$lib/server/db';
|
||||
import { WebSocket } from "ws";
|
||||
/*
|
||||
Filter youtube: /v3/videos (part: snippet), /v3/videoCategories (part: snippet). Category 10 is Music
|
||||
*/
|
||||
|
||||
const YOUTUBE_REGEX = new RegExp('https?:\/\/(www\.)?youtu((be.com\/.*v=)|(\.be\/))(?<videoId>[a-zA-Z_0-9-]+)');
|
||||
|
||||
export class TimelineReader {
|
||||
private static _instance: TimelineReader;
|
||||
private constructor() {
|
||||
//const socket = new WebSocket("wss://metalhead.club/api/v1/streaming/public/local")
|
||||
const socket = new WebSocket("wss://metalhead.club/api/v1/streaming")
|
||||
socket.onopen = (_event) => {
|
||||
socket.send('{ "type": "subscribe", "stream": "public:local"}');
|
||||
};
|
||||
socket.onmessage = (event) => {
|
||||
try {
|
||||
const data: TimelineEvent = JSON.parse(event.data.toString());
|
||||
if (data.event !== 'update') {
|
||||
return;
|
||||
}
|
||||
const post: Post = JSON.parse(data.payload);
|
||||
const hashttags: string[] = HASHTAG_FILTER.split(',');
|
||||
const found_tags: Tag[] = post.tags.filter((t: Tag) => hashttags.includes(t.name));
|
||||
|
||||
const urls: string[] = URL_FILTER.split(',');
|
||||
const found_urls = urls.filter(t => post.content.includes(t));
|
||||
|
||||
if (found_urls.length === 0 && found_tags.length === 0) {
|
||||
//return;
|
||||
}
|
||||
|
||||
const youtubeMatches = found_urls.map(u => u.match(YOUTUBE_REGEX)).filter(i => i !== null);
|
||||
if (found_urls.length > 0 && youtubeMatches.length === found_urls.length) {
|
||||
// TODO: Check with YouTube API if it is in YT music or labeled as music
|
||||
console.info('Found youtube urls', youtubeMatches);
|
||||
}
|
||||
console.log(
|
||||
"message",
|
||||
`Update by @${post.account?.username}: ${post.content}`,
|
||||
'tags',
|
||||
post.tags,
|
||||
found_tags,
|
||||
found_urls);
|
||||
savePost(post);
|
||||
|
||||
} catch (e) {
|
||||
console.error("error message", event, event.data, e)
|
||||
}
|
||||
|
||||
};
|
||||
socket.onclose = (event) => {
|
||||
console.log("Closed", event, event.code, event.reason)
|
||||
};
|
||||
socket.onerror = (event) => {
|
||||
console.log("error", event, event.message, event.error)
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
public static init() {
|
||||
if (this._instance === undefined) {
|
||||
this._instance = new TimelineReader();
|
||||
}
|
||||
}
|
||||
|
||||
public static get instance(): TimelineReader {
|
||||
TimelineReader.init();
|
||||
return this._instance;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user