Bookmarks in web app (#177)

* Bookmarks api

* Lint fix

* first pass

* Lint fix

* comment

* bookmarks, loading feedSources, and pagination

* comment

* null check

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
This commit is contained in:
Brahim Hadricheandgithub-action linter authored and GitHub committed 2023-10-23 20:39:44 -04:00
1 parent 58ce2d6396
commit 57fa1c5c3f
23 files changed
+510 -192

No files matched your search

+92 -3
View File
@@ -12,6 +12,13 @@ export class InvidiousApi {
// Note: handlers for authenticated requests are not needed, since they are handled server side
this.responseHandlers = {
"DefaultHandler": (requestData, response) => this.DefaultHandler(requestData, response),
"PlaylistHandler": (requestData, response) => this.PlaylistHandler(requestData, response),
"VideoInfoHandler": (requestData, response) => this.VideoInfoHandler(requestData, response),
"PlaylistInfoHandler": (requestData, response) => this.PlaylistInfoHandler(requestData, response),
"ChannelInfoHandler": (requestData, response) => this.ChannelInfoHandler(requestData, response),
"ChannelVideosHandler": (requestData, response) => this.ChannelVideosHandler(requestData, response),
"ChannelPlaylistsHandler": (requestData, response) => this.ChannelPlaylistsHandler(requestData, response),
"ChannelRelatedChannelsHandler": (requestData, response) => this.ChannelRelatedChannelsHandler(requestData, response),
}
}
@@ -44,10 +51,39 @@ export class InvidiousApi {
return await response.json();
}
public async makeRequest(feed: any) {
// TODO:P0 handle multiple feed sources
const feedSource = feed.feedSources[0]
public async markFeedSourcePagination(feedSource: any) {
const endpoint = this.endpoints[feedSource.endpoint]
if (!endpoint || !endpoint.paginationType) {
return;
}
const feedSourceState = feedSource.state
feedSourceState.queryParams = feedSourceState.queryParams || {}
feedSourceState.paginationType = endpoint.paginationType
if (feedSourceState.paginationType === "Pages") {
if (!Number.isInteger(feedSourceState.page)) {
feedSourceState.page = 0;
}
feedSourceState.page += 1;
feedSourceState.queryParams.page = feedSourceState.page;
} else if (feedSourceState.paginationType === "Continuation") {
const continuation = feedSourceState.continuation;
if (continuation) {
feedSourceState.queryParams.continuation = continuation;
} else {
delete feedSourceState.queryParams.continuation;
}
}
}
public canMakeRequest() {
return !!(this.instance && this.endpoints && Object.keys(this.endpoints).length);
}
public async makeRequest(feedSource: any) {
// TODO:P0 implement localStorage caching
if (!feedSource || !this.instance || !this.endpoints) {
return null;
}
@@ -90,6 +126,10 @@ export class InvidiousApi {
queryParams = { ...queryParams, ...feedSource.queryParams };
}
if (feedSource.state.queryParams !== undefined) {
queryParams = { ...queryParams, ...feedSource.state.queryParams };
}
if (feedSource.pathParams !== undefined) {
for (let param in feedSource.pathParams) {
url = url.replace(`{${param}}`, feedSource.pathParams[param]);
@@ -111,6 +151,55 @@ export class InvidiousApi {
return { items };
}
private async PlaylistHandler(feedSource, response) {
const json = await response.json();
return {
items: json.videos,
};
}
private async VideoInfoHandler(feedSource, response) {
const info = await response.json();
info.type = "video";
return { items: [info] };
}
private async ChannelInfoHandler(feedSource, response) {
const info = await response.json();
info.type = "channel";
return { items: [info] };
}
private async PlaylistInfoHandler(feedSource, response) {
const info = await response.json();
info.type = "playlist";
return { items: [info] };
}
private async ChannelVideosHandler(feedSource, response) {
const json = await response.json();
return {
items: json.videos,
continuation: json.continuation
};
}
private async ChannelPlaylistsHandler(feedSource, response) {
const json = await response.json();
return {
items: json.playlists,
continuation: json.continuation
};
}
private async ChannelRelatedChannelsHandler(feedSource, response) {
const json = await response.json();
return {
items: json.relatedChannels,
continuation: json.continuation
};
}
private makeUrl(url: string, params: any) {
const encodedUrl = new URL(url);
const existingParams = new URLSearchParams(encodedUrl.search);
+7 -2
View File
@@ -23,8 +23,8 @@ export class PlayletApi {
return await response.json();
}
static async invidiousAuthenticatedRequest(requestData) {
const url = PlayletApi.host() + "/invidious/authenticated-request?request-data=" + encodeURIComponent(JSON.stringify(requestData));
static async invidiousAuthenticatedRequest(feedSource) {
const url = PlayletApi.host() + "/invidious/authenticated-request?feed-source=" + encodeURIComponent(JSON.stringify(feedSource));
const response = await fetch(url);
return await response.json();
}
@@ -128,6 +128,11 @@ export class PlayletApi {
return await fetch(`${PlayletApi.host()}/api/search-history`, { method: "DELETE" });
}
static async getBookmarkFeeds() {
const response = await fetch(`${PlayletApi.host()}/api/bookmarks/feeds`);
return await response.json();
}
static async updateInstance(instance) {
return await PlayletApi.putJson(`${PlayletApi.host()}/api/preferences`, { "invidious.instance": instance });
}
@@ -3,6 +3,8 @@
import InfoIcon from "../assets/info-icon.svg.svelte";
import SearchIcon from "../assets/search-icon.svg.svelte";
import SettingsIcon from "../assets/settings-icon.svg.svelte";
import BookmarksIcon from "../assets/star-icon.svg.svelte";
import { appStateStore } from "lib/Stores";
import type { AppState } from "lib/Types";
@@ -37,6 +39,14 @@
<HomeIcon />
</div>
</button>
<button
on:click={() => setScreen("bookmarks")}
class={$appStateStore.screen === "bookmarks" ? "active" : ""}
>
<div class="h-6">
<BookmarksIcon />
</div>
</button>
<button
on:click={() => setScreen("settings")}
class={$appStateStore.screen === "settings" ? "active" : ""}
@@ -0,0 +1,12 @@
<script lang="ts">
import VideoListRow from "./Home/VideoListRow.svelte";
import { bookmarksStore } from "lib/Stores";
export let visibility: boolean;
</script>
<div class={visibility ? "" : "hidden"}>
{#each $bookmarksStore as feed}
<VideoListRow {feed} />
{/each}
</div>
@@ -1,115 +0,0 @@
<script lang="ts">
import { InvidiousApi } from "lib/Api/InvidiousApi";
import { invidiousVideoApiStore, playletStateStore } from "lib/Stores";
import VideoCell from "lib/Screens/Home/VideoCell.svelte";
import PlaylistCell from "lib/Screens/Home/PlaylistCell.svelte";
import ChannelCell from "./ChannelCell.svelte";
export let feed: any = undefined;
export let videos = undefined;
let itemWidths = [];
let carouselElement;
let scrollStart = 0;
let scrollEnd = 0;
// w-80|w-60 p-2: 320px|240px + 16px padding on each side
const videoItemWidth = 320 + 16 * 2;
const channelItemWidth = 240 + 16 * 2;
$: {
if (carouselElement && itemWidths && itemWidths.length) {
recalculateVisibileCells();
}
}
let invidiousApi = new InvidiousApi();
playletStateStore.subscribe((value) => {
invidiousApi.instance = value?.invidious?.current_instance;
invidiousApi.userCountryCode = value?.device?.user_country_code ?? "US";
invidiousApi.isLoggedIn = value.invidious?.logged_in ?? false;
updateRow();
});
invidiousVideoApiStore.subscribe((value) => {
invidiousApi.endpoints = value;
updateRow();
});
async function updateRow() {
const result = await invidiousApi.makeRequest(feed);
if (result && result.items) {
result.items.forEach((item) => {
if (item.videoId) {
item.type = "video";
} else if (item.playlistId) {
item.type = "playlist";
}
});
videos = result.items;
itemWidths = videos.map((video) => {
if (video.type === "channel") {
return channelItemWidth;
} else {
return videoItemWidth;
}
});
}
}
function recalculateVisibileCells() {
let scrollLeft = carouselElement.scrollLeft;
const clientWidth = carouselElement.clientWidth || window.innerWidth;
scrollStart = 0;
while (
scrollStart < itemWidths.length &&
scrollLeft > itemWidths[scrollStart]
) {
scrollLeft -= itemWidths[scrollStart];
scrollStart++;
}
scrollEnd = scrollStart;
while (
scrollEnd < itemWidths.length &&
scrollLeft + clientWidth > itemWidths[scrollEnd]
) {
scrollLeft -= itemWidths[scrollEnd];
scrollEnd++;
}
scrollStart = Math.max(0, scrollStart - 1);
scrollEnd = Math.min(itemWidths.length - 1, scrollEnd + 1);
}
</script>
{#if videos}
<div class="text-lg font-semibold m-4">
{feed.title}
</div>
<div
class="carousel carousel-center rounded-box w-full space-x-4"
bind:this={carouselElement}
on:scroll={recalculateVisibileCells}
>
{#each videos as video, i}
<div
class="carousel-item {video.type === 'channel' ? 'w-60' : 'w-80'} p-2"
>
{#if i >= scrollStart && i <= scrollEnd}
{#if video.type === "video"}
<VideoCell {...video} />
{:else if video.type === "playlist"}
<PlaylistCell {...video} />
{:else if video.type === "channel"}
<ChannelCell {...video} />
{/if}
{/if}
</div>
{/each}
</div>
{/if}
@@ -0,0 +1,219 @@
<script lang="ts">
import { InvidiousApi } from "lib/Api/InvidiousApi";
import { invidiousVideoApiStore, playletStateStore } from "lib/Stores";
import VideoCell from "lib/Screens/Home/VideoCell.svelte";
import PlaylistCell from "lib/Screens/Home/PlaylistCell.svelte";
import ChannelCell from "./ChannelCell.svelte";
export let feed: any = undefined;
export let videos = undefined;
enum FeedLoadState {
None,
Loading,
Loaded,
LoadedPage,
Error,
}
let feedLoadState = FeedLoadState.None;
let feedSourcesIndex = 0;
let itemWidths = [];
let carouselElement;
let scrollStart = 0;
let scrollEnd = 0;
// w-80|w-60 p-2: 320px|240px + 16px padding on each side
const videoItemWidth = 320 + 16 * 2;
const channelItemWidth = 240 + 16 * 2;
$: {
if (carouselElement && itemWidths && itemWidths.length) {
recalculateVisibileCells();
}
}
$: {
if (videos && scrollEnd >= videos.length - 1) {
loadRow();
}
}
let invidiousApi = new InvidiousApi();
playletStateStore.subscribe((value) => {
invidiousApi.instance = value?.invidious?.current_instance;
invidiousApi.userCountryCode = value?.device?.user_country_code ?? "US";
invidiousApi.isLoggedIn = value.invidious?.logged_in ?? false;
loadRow();
});
invidiousVideoApiStore.subscribe((value) => {
invidiousApi.endpoints = value;
loadRow();
});
async function loadRow() {
if (!invidiousApi.canMakeRequest()) {
return;
}
if (
feedLoadState === FeedLoadState.Loading ||
feedLoadState === FeedLoadState.Loaded
) {
return;
}
feedLoadState = FeedLoadState.Loading;
let totalFetchedItems = 0;
while (true) {
const feedSources = feed.feedSources;
if (feedSourcesIndex >= feedSources.length) {
break;
}
const feedSource = feedSources[feedSourcesIndex];
feedSource.state = feedSource.state || {};
if (
feedSource.state.loadState === FeedLoadState.Loaded ||
feedSource.state.loadState === FeedLoadState.Error
) {
feedSourcesIndex++;
continue;
}
invidiousApi.markFeedSourcePagination(feedSource);
try {
const result = await invidiousApi.makeRequest(feedSource);
if (!result) {
return;
}
const hasContinuation = !!result.continuation;
if (hasContinuation) {
feedSource.state.continuation = result.continuation;
}
if (result.items.length > 0) {
const paginationType = feedSource.state.paginationType;
if (paginationType === "Continuation" && hasContinuation) {
feedSource.state.loadState = FeedLoadState.LoadedPage;
} else if (paginationType === "Pages") {
feedSource.state.loadState = FeedLoadState.LoadedPage;
} else {
feedSource.state.loadState = FeedLoadState.Loaded;
}
} else {
feedSource.state.loadState = FeedLoadState.Loaded;
}
if (
feedSource.state.loadState === FeedLoadState.Loaded &&
feedSourcesIndex === feedSources.length - 1
) {
feedLoadState = FeedLoadState.Loaded;
} else {
feedLoadState = FeedLoadState.LoadedPage;
}
if (result && result.items) {
const newVideos = result.items;
newVideos.forEach((item) => {
if (item.videoId) {
item.type = "video";
} else if (item.playlistId) {
item.type = "playlist";
}
});
const newItemWidths = newVideos.map((video) => {
if (video.type === "channel") {
return channelItemWidth;
} else {
return videoItemWidth;
}
});
itemWidths = [...itemWidths, ...newItemWidths];
videos = [...(videos || []), ...newVideos];
totalFetchedItems += result.items.length;
if (totalFetchedItems >= 3) {
break;
}
}
} catch (error) {
console.error(error);
feedSource.state.loadState = FeedLoadState.Error;
}
}
}
function recalculateVisibileCells() {
let scrollLeft = carouselElement.scrollLeft;
const clientWidth = carouselElement.clientWidth || window.innerWidth;
let _scrollStart = 0;
while (
_scrollStart < itemWidths.length &&
scrollLeft > itemWidths[_scrollStart]
) {
scrollLeft -= itemWidths[_scrollStart];
_scrollStart++;
}
let _scrollEnd = _scrollStart;
while (
_scrollEnd < itemWidths.length &&
scrollLeft + clientWidth > itemWidths[_scrollEnd]
) {
scrollLeft -= itemWidths[_scrollEnd];
_scrollEnd++;
}
_scrollStart = Math.max(0, _scrollStart - 1);
_scrollEnd = Math.min(itemWidths.length - 1, _scrollEnd + 1);
if (_scrollStart !== scrollStart) {
scrollStart = _scrollStart;
}
if (_scrollEnd !== scrollEnd) {
scrollEnd = _scrollEnd;
}
}
</script>
{#if videos}
<div class="text-lg font-semibold m-4">
{feed.title}
</div>
<div
class="carousel carousel-center rounded-box w-full space-x-4"
bind:this={carouselElement}
on:scroll={recalculateVisibileCells}
>
{#each videos as video, i}
<div
class="carousel-item {video.type === 'channel' ? 'w-60' : 'w-80'} p-2"
>
{#if i >= scrollStart && i <= scrollEnd}
{#if video.type === "video"}
<VideoCell {...video} />
{:else if video.type === "playlist"}
<PlaylistCell {...video} />
{:else if video.type === "channel"}
<ChannelCell {...video} />
{/if}
{/if}
</div>
{/each}
</div>
{/if}
@@ -1,5 +1,5 @@
<script lang="ts">
import ScreenHomeRow from "lib/Screens/Home/ScreenHomeRow.svelte";
import VideoListRow from "lib/Screens/Home/VideoListRow.svelte";
import { homeLayoutFileStore } from "lib/Stores";
export let visibility: boolean;
@@ -7,6 +7,6 @@
<div class={visibility ? "" : "hidden"}>
{#each $homeLayoutFileStore as feed}
<ScreenHomeRow {feed} />
<VideoListRow {feed} />
{/each}
</div>
@@ -87,6 +87,7 @@
try {
isLoading = true;
// TODO:P1: search pagination - load more results as we scroll
videos = await invidiousApi.search(searchBoxText, searchFilters);
} finally {
isLoading = false;
+2
View File
@@ -17,4 +17,6 @@ export const invidiousVideoApiStore = writable({} as any);
export const homeLayoutFileStore = writable([] as any);
export const bookmarksStore = writable([] as any);
export const searchHistoryStore = writable([] as any);
+1 -1
View File
@@ -1,5 +1,5 @@
export type AppState = {
screen: "search" | "home" | "settings" | "info"
screen: "search" | "home" | "bookmarks" | "settings" | "info"
}
export type PlayletState = {