Bookmarks web app part 2 (#178)

* Message for no bookmarks

* feed lazy loading

* cached fetch

* Versioned cache

* comment
This commit is contained in:
Brahim Hadriche authored and GitHub committed 2023-10-24 13:41:13 -04:00
1 parent 57fa1c5c3f
commit 072b93728a
3 files changed
+150 -64

No files matched your search

+79 -34
View File
@@ -83,7 +83,6 @@ export class InvidiousApi {
} }
public async makeRequest(feedSource: any) { public async makeRequest(feedSource: any) {
// TODO:P0 implement localStorage caching
if (!feedSource || !this.instance || !this.endpoints) { if (!feedSource || !this.instance || !this.endpoints) {
return null; return null;
} }
@@ -95,7 +94,6 @@ export class InvidiousApi {
let url = this.instance + endpoint.url let url = this.instance + endpoint.url
let queryParams = {} let queryParams = {}
let headers = {}
if (endpoint.authenticated) { if (endpoint.authenticated) {
// Authenticated requests on the web app would be blocked by CORS, so we use the Playlet API as a proxy // Authenticated requests on the web app would be blocked by CORS, so we use the Playlet API as a proxy
@@ -137,66 +135,66 @@ export class InvidiousApi {
} }
url = this.makeUrl(url, queryParams); url = this.makeUrl(url, queryParams);
const response = await fetch(url, { headers: headers });
let cacheSeconds = undefined
if (feedSource.cacheSeconds !== undefined) {
cacheSeconds = feedSource.cacheSeconds
} else if (endpoint.cacheSeconds !== undefined) {
cacheSeconds = endpoint.cacheSeconds
}
const responseJson = await this.cachedFetch(url, cacheSeconds);
let responseHandler = endpoint.responseHandler !== undefined ? this.responseHandlers[endpoint.responseHandler] : this.responseHandlers["DefaultHandler"]; let responseHandler = endpoint.responseHandler !== undefined ? this.responseHandlers[endpoint.responseHandler] : this.responseHandlers["DefaultHandler"];
if (!responseHandler) { if (!responseHandler) {
return null; return null;
} }
return await responseHandler(feedSource, response); return await responseHandler(feedSource, responseJson);
} }
private async DefaultHandler(feedSource, response) { private async DefaultHandler(feedSource, responseJson) {
const items = await response.json(); return { items: responseJson };
return { items };
} }
private async PlaylistHandler(feedSource, response) { private async PlaylistHandler(feedSource, responseJson) {
const json = await response.json();
return { return {
items: json.videos, items: responseJson.videos,
}; };
} }
private async VideoInfoHandler(feedSource, response) { private async VideoInfoHandler(feedSource, responseJson) {
const info = await response.json(); responseJson.type = "video";
info.type = "video"; return { items: [responseJson] };
return { items: [info] };
} }
private async ChannelInfoHandler(feedSource, response) { private async ChannelInfoHandler(feedSource, responseJson) {
const info = await response.json(); responseJson.type = "channel";
info.type = "channel"; return { items: [responseJson] };
return { items: [info] };
} }
private async PlaylistInfoHandler(feedSource, response) { private async PlaylistInfoHandler(feedSource, responseJson) {
const info = await response.json(); responseJson.type = "playlist";
info.type = "playlist"; return { items: [responseJson] };
return { items: [info] };
} }
private async ChannelVideosHandler(feedSource, response) { private async ChannelVideosHandler(feedSource, responseJson) {
const json = await response.json();
return { return {
items: json.videos, items: responseJson.videos,
continuation: json.continuation continuation: responseJson.continuation
}; };
} }
private async ChannelPlaylistsHandler(feedSource, response) { private async ChannelPlaylistsHandler(feedSource, responseJson) {
const json = await response.json();
return { return {
items: json.playlists, items: responseJson.playlists,
continuation: json.continuation continuation: responseJson.continuation
}; };
} }
private async ChannelRelatedChannelsHandler(feedSource, response) { private async ChannelRelatedChannelsHandler(feedSource, responseJson) {
const json = await response.json();
return { return {
items: json.relatedChannels, items: responseJson.relatedChannels,
continuation: json.continuation continuation: responseJson.continuation
}; };
} }
@@ -212,4 +210,51 @@ export class InvidiousApi {
encodedUrl.search = mergedParams.toString(); encodedUrl.search = mergedParams.toString();
return encodedUrl.toString(); return encodedUrl.toString();
} }
private async cachedFetch(url: string, cacheSeconds?: number) {
if (!cacheSeconds) {
const response = await fetch(url);
return await response.json();
}
const cache = this.getCache(url, cacheSeconds);
if (cache) {
return cache;
}
const response = await fetch(url);
const data = await response.json();
this.setCache(url, data);
return data;
}
// TODO:P2 use more appropriate cache storage
private getCache(url: string, cacheSeconds: number) {
const cache = localStorage.getItem(url);
if (!cache) {
return null;
}
try {
const cacheData = JSON.parse(cache);
if (cacheData.timestamp + cacheSeconds * 1000 < Date.now()) {
return null;
}
console.log(`Cache hit for ${url}`);
return cacheData.data;
} catch (error) {
console.error(error);
return null;
}
}
private setCache(url: string, data: any) {
const cacheData = {
__version: 1,
timestamp: Date.now(),
data
};
localStorage.setItem(url, JSON.stringify(cacheData));
}
} }
@@ -6,7 +6,21 @@
</script> </script>
<div class={visibility ? "" : "hidden"}> <div class={visibility ? "" : "hidden"}>
{#each $bookmarksStore as feed} {#if $bookmarksStore.length === 0}
<VideoListRow {feed} /> <div
{/each} class="flex flex-col items-center justify-start h-screen w-2/3 mx-auto"
>
<div class="text-2xl font-bold text-gray-500">No Bookmarks</div>
<div class="text-gray-500 text-center">
You currently have no bookmarks.<br />
To add bookmarks, select a video, playlist or channel, and add a bookmark.<br
/>
Please note that Bookmarks is an experimental feature.
</div>
</div>
{:else}
{#each $bookmarksStore as feed}
<VideoListRow {feed} />
{/each}
{/if}
</div> </div>
@@ -6,7 +6,7 @@
import ChannelCell from "./ChannelCell.svelte"; import ChannelCell from "./ChannelCell.svelte";
export let feed: any = undefined; export let feed: any = undefined;
export let videos = undefined; export let videos = [];
enum FeedLoadState { enum FeedLoadState {
None, None,
@@ -22,6 +22,7 @@
let itemWidths = []; let itemWidths = [];
let carouselElement; let carouselElement;
let carouselElementIntersecting = false;
let scrollStart = 0; let scrollStart = 0;
let scrollEnd = 0; let scrollEnd = 0;
@@ -30,8 +31,23 @@
const videoItemWidth = 320 + 16 * 2; const videoItemWidth = 320 + 16 * 2;
const channelItemWidth = 240 + 16 * 2; const channelItemWidth = 240 + 16 * 2;
const intersectionObserver = new IntersectionObserver(
function (entries) {
carouselElementIntersecting = entries[0].isIntersecting;
if (carouselElementIntersecting) {
loadRow();
}
},
{ threshold: [0] }
);
$: { $: {
if (carouselElement && itemWidths && itemWidths.length) { if (
carouselElement &&
carouselElementIntersecting &&
itemWidths &&
itemWidths.length
) {
recalculateVisibileCells(); recalculateVisibileCells();
} }
} }
@@ -42,6 +58,12 @@
} }
} }
$: {
if (carouselElement) {
intersectionObserver.observe(carouselElement);
}
}
let invidiousApi = new InvidiousApi(); let invidiousApi = new InvidiousApi();
playletStateStore.subscribe((value) => { playletStateStore.subscribe((value) => {
@@ -61,6 +83,14 @@
return; return;
} }
if (!carouselElementIntersecting) {
return;
}
if (scrollEnd < videos.length - 3) {
return;
}
if ( if (
feedLoadState === FeedLoadState.Loading || feedLoadState === FeedLoadState.Loading ||
feedLoadState === FeedLoadState.Loaded feedLoadState === FeedLoadState.Loaded
@@ -191,29 +221,26 @@
} }
</script> </script>
{#if videos} <div class="text-lg font-semibold m-4">
<div class="text-lg font-semibold m-4"> {feed.title}
{feed.title} </div>
</div> <div
<div class="carousel carousel-center rounded-box w-full space-x-4"
class="carousel carousel-center rounded-box w-full space-x-4" style="min-height: 16rem;"
bind:this={carouselElement} bind:this={carouselElement}
on:scroll={recalculateVisibileCells} on:scroll={recalculateVisibileCells}
> >
{#each videos as video, i} {#each videos as video, i}
<div <div class="carousel-item {video.type === 'channel' ? 'w-60' : 'w-80'} p-2">
class="carousel-item {video.type === 'channel' ? 'w-60' : 'w-80'} p-2" {#if i >= scrollStart && i <= scrollEnd}
> {#if video.type === "video"}
{#if i >= scrollStart && i <= scrollEnd} <VideoCell {...video} />
{#if video.type === "video"} {:else if video.type === "playlist"}
<VideoCell {...video} /> <PlaylistCell {...video} />
{:else if video.type === "playlist"} {:else if video.type === "channel"}
<PlaylistCell {...video} /> <ChannelCell {...video} />
{:else if video.type === "channel"}
<ChannelCell {...video} />
{/if}
{/if} {/if}
</div> {/if}
{/each} </div>
</div> {/each}
{/if} </div>