Support playing a video from a specific time (cast from phone, drag a… (#88)

* Support playing a video from a specific time (cast from phone, drag and drop, open in Invidious)

* Remove a console log
This commit is contained in:
Brahim Hadriche authored and GitHub committed 2023-06-25 16:17:12 -04:00
1 parent 6c84630cec
commit 3acf733eec
14 files changed
+220 -45

No files matched your search

+6
View File
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- Support playing a video from a specific time (cast from phone, drag and drop, open in Invidious)
## [0.10.0] - 2023-06-25
### Added
+2
View File
@@ -1,3 +1,5 @@
<!-- markdownlint-disable MD036 -->
# Releasing
These are mostly the steps when releasing a new version:
+3 -1
View File
@@ -1,3 +1,5 @@
<!-- markdownlint-disable MD041 -->
This is an automated release. It is generated when new code is pushed to the main branch.
To test this release:
@@ -6,4 +8,4 @@ To test this release:
- Go to settings, and scroll down to `Developer settings`
- Set `Playlet Library version` to `unstable` and click `Apply`
- Restart Playlet
- You can verify that you're testing the `unstable` release in the `Info` tab in Playlet or the web app
- You can verify that you're testing the `unstable` release in the `Info` tab in Playlet or the web app
+7 -4
View File
@@ -113,8 +113,11 @@ function OnWebServerLogin()
m.homeGridScreen.refresh = true
end function
function OnWebServerCommand()
if m.serverTask.command.StartsWith("play:")
function OnWebServerCommand() as void
if m.serverTask.command = invalid or m.serverTask.command.command = invalid
return
end if
if m.serverTask.command.command = "play"
sender = m.videoContainer.sender ?? m.currentFocued
if m.videoContainer.fullscreen
dialog = m.top.getScene().dialog
@@ -122,7 +125,7 @@ function OnWebServerCommand()
dialog.close = true
end if
end if
PlayVideo(m.serverTask.command.Mid(5), { sender: sender })
PlayVideo(m.serverTask.command.videoId, { sender: sender, timestamp: m.serverTask.command.timestamp })
end if
end function
@@ -146,5 +149,5 @@ function PlayVideoFromArgs(args as object) as void
end if
sender = m.videoContainer.sender ?? m.currentFocued
PlayVideo(args.contentId, { sender: sender })
PlayVideo(args.contentId, { sender: sender, timestamp: args.timestamp })
end function
@@ -7,11 +7,16 @@ import "pkg:/components/VideoPlayer/MarkVideoWatchedTask.bs"
function PlayVideo(videoId as string, args = invalid as object)
sender = args?.sender
metadata = args?.metadata
timestamp = args?.timestamp
if metadata <> invalid and GetInterface(metadata, "ifSGNodeField") <> invalid
metadata = args.metadata.getFields()
end if
if timestamp = invalid
timestamp = 0
end if
width = 1280
height = 720
translation = [0.0, 0.0]
@@ -29,6 +34,7 @@ function PlayVideo(videoId as string, args = invalid as object)
videoContainer.insertChild(videoContainer.videoPlayer, 0)
videoContainer.videoPlayer.id = "VideoPlayer"
videoContainer.videoPlayer.metadata = metadata
videoContainer.videoPlayer.timestamp = timestamp
videoContainer.videoPlayer.videoId = videoId
videoContainer.videoPlayer.width = width
videoContainer.videoPlayer.height = height
@@ -286,8 +286,11 @@ function OnVideoPlayerStateChange() as void
' If we successfully played the video, then any error that comes later is not due to a 403 (FORBIDDEN).
' This is to reduce false positives, as we do not want retry another link if the first link is working fine.
if state = "playing"
if state = "playing" and not m.videoPlayingSuccess
m.videoPlayingSuccess = true
if m.top.timestamp <> 0
m.top.seek = m.top.timestamp
end if
end if
if state = "error"
@@ -7,6 +7,7 @@
<field id="chapter" type="string" alias="chapterLabel.text" />
<field id="videoId" type="string" />
<field id="metadata" type="assocarray" />
<field id="timestamp" type="integer" />
</interface>
<children>
<Label
@@ -23,8 +23,7 @@ namespace Http
response.Default(204, "OK")
return true
else if payload.command = "play"
videoId = payload.videoId
server.task.top.command = `play:${videoId}`
server.task.top.command = payload
response.Default(204, "OK")
return true
else if payload.command = "set-playlet-lib-urls"
@@ -3,6 +3,6 @@
<component name="WebServerTask" extends="Task">
<interface>
<field id="login" type="boolean" alwaysNotify="true" />
<field id="command" type="string" alwaysNotify="true" />
<field id="command" type="assocarray" alwaysNotify="true" />
</interface>
</component>
+58 -17
View File
@@ -3,12 +3,16 @@
import { PlayletApi } from "./PlayletApi";
import { playletStateStore } from "./Stores";
import { InvidiousApi } from "./InvidiousApi";
import VideoStartAt from "./VideoStartAt.svelte";
let modal;
let isDragging;
let isLoading;
let dragEndTimeout;
let videoStartAtChecked;
let videoStartAtTimestamp;
let videoMetadata;
let tvName = "Roku TV";
@@ -43,10 +47,10 @@
let dataString = await new Promise((resolve) =>
item.getAsString(resolve)
);
if (IsValidHttpUrl(dataString)) {
const videoId = GetVideoId(dataString);
if (videoId) {
searchForVideoById(videoId);
if (isValidHttpUrl(dataString)) {
const videoInfo = parseYouTubeUrl(dataString);
if (videoInfo.videoId) {
searchForVideoById(videoInfo.videoId, videoInfo.timestamp);
return;
}
}
@@ -54,10 +58,12 @@
}
}
async function searchForVideoById(videoId) {
async function searchForVideoById(videoId, timestamp) {
try {
isLoading = true;
videoMetadata = await invidiousApi.getVideoMetadata(videoId);
videoStartAtTimestamp = timestamp;
videoStartAtChecked = videoStartAtTimestamp !== undefined;
modal.showModal();
} finally {
isLoading = false;
@@ -74,7 +80,7 @@
event.preventDefault();
}
function IsValidHttpUrl(string) {
function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
@@ -84,7 +90,18 @@
return url.protocol === "http:" || url.protocol === "https:";
}
function GetVideoId(url) {
function parseYouTubeUrl(url) {
const urlSearchParams = new URLSearchParams(new URL(url).search);
function getTimestamp(){
const timestamp = urlSearchParams.get("t");
if (timestamp) {
return timestamp.endsWith("s")
? timestamp.slice(0, -1)
: timestamp;
}
}
// Share/Short url
// TODO: use regex, and support timestamped videos
const YoutubeUrls = [
@@ -100,33 +117,52 @@
for (var i in YoutubeUrls) {
let youtubeUrl = YoutubeUrls[i];
if (url.startsWith(youtubeUrl)) {
url = url.replace(youtubeUrl, "");
if (url.includes("?")) {
url = url.substring(0, url.indexOf("?"));
let videoId = url.replace(youtubeUrl, "");
if (videoId.includes("?")) {
videoId = videoId.substring(0, videoId.indexOf("?"));
}
return url;
const result: any = {
videoId,
};
const timestamp = getTimestamp();
if (timestamp) {
result.timestamp = timestamp;
}
return result;
}
}
// regular url
url = new URL(url);
const urlSearchParams = new URLSearchParams(url.search);
return urlSearchParams.get("v");
const result: any = {
videoId: urlSearchParams.get("v"),
};
const timestamp = getTimestamp();
if (timestamp) {
result.timestamp = timestamp
}
return result;
}
async function playVideoOnTv() {
await PlayletApi.playVideo(videoMetadata?.videoId);
await PlayletApi.playVideo(videoMetadata?.videoId, videoStartAtTimestamp);
}
function openInvidiousInNewTab() {
window.open(`${invidiousInstance}/watch?v=${videoMetadata?.videoId}`);
let url = `${invidiousInstance}/watch?v=${videoMetadata?.videoId}`;
if (videoStartAtChecked && videoStartAtTimestamp) {
url += `&t=${videoStartAtTimestamp}`;
}
window.open(url);
}
</script>
<div
class="{isDragging || isLoading
? ''
: 'hidden'} absolute w-full h-full bg-base-100/80 z-50 flex justify-center items-center"
: 'hidden'} fixed w-full h-full bg-base-100/80 z-50 flex justify-center items-center"
>
{#if isDragging}
<div class="text-2xl font-bold">Drop a Youtube link here</div>
@@ -139,6 +175,11 @@
<form method="dialog" class="modal-box bg-base-100">
<h3 class="text-lg m-5">{videoMetadata?.title}</h3>
<div class="flex flex-col">
<VideoStartAt
bind:checked={videoStartAtChecked}
bind:timestamp={videoStartAtTimestamp}
lengthSeconds={videoMetadata?.lengthSeconds}
/>
<button class="btn m-2" on:click={playVideoOnTv}>Play on {tvName}</button>
<button class="btn m-2" on:click={openInvidiousInNewTab}
>Open in Invidious</button
+6 -2
View File
@@ -43,11 +43,15 @@ export class PlayletApi {
return await PlayletApi.postJson(`${PlayletApi.host()}/api/command`, { command: "logout" });
}
static async playVideo(videoId) {
static async playVideo(videoId, timestamp) {
if (!videoId) {
return;
}
return await PlayletApi.postJson(`${PlayletApi.host()}/api/command`, { command: "play", videoId: videoId });
const payload = { command: "play", videoId: videoId };
if (timestamp !== undefined) {
payload["timestamp"] = timestamp;
}
return await PlayletApi.postJson(`${PlayletApi.host()}/api/command`, payload);
}
static async getSearchHistory() {
+2
View File
@@ -18,6 +18,8 @@
// svelte-ignore unused-export-let
export let defaultValue: any = undefined;
// svelte-ignore unused-export-let
export let rokuComponent: any = undefined;
const customComponents = {
ClearSearchHistoryControl
+40 -17
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { PlayletApi } from "./PlayletApi";
import { playletStateStore } from "./Stores";
import VideoStartAt from "./VideoStartAt.svelte";
export let title: string | undefined = undefined;
export let videoId: string | undefined = undefined;
@@ -39,6 +40,8 @@
let modal;
let tvName = "Roku TV";
let invidiousInstance;
let videoStartAtChecked;
let videoStartAtTimestamp;
playletStateStore.subscribe((value) => {
tvName = value?.device?.friendly_name ?? "Roku TV";
@@ -49,14 +52,14 @@
if (isUpcoming) {
return `Premeres in ${getFormattedTimeLeft(premiereTimestamp)}`;
}
const pubText = publishedText || '';
const pubText = publishedText || "";
const viewCountText = formatViewCount(viewCount);
if (pubText === '' && viewCountText === '') {
return '';
if (pubText === "" && viewCountText === "") {
return "";
}
return `${pubText} • ${viewCountText}`;
return `${pubText} • ${viewCountText}`;
}
function getFormattedTimeLeft(unixTimestamp) {
@@ -149,7 +152,7 @@
function getFormattedTime(length) {
const minutes = Math.floor(length / 60).toString();
const seconds = (length % 60);
const seconds = length % 60;
const secondsString = seconds < 10 ? `0${seconds}` : seconds.toString();
return minutes + ":" + secondsString;
}
@@ -162,24 +165,37 @@
}
async function playVideoOnTv() {
await PlayletApi.playVideo(videoId);
await PlayletApi.playVideo(videoId, videoStartAtTimestamp);
}
function openInvidiousInNewTab() {
window.open(`${invidiousInstance}/watch?v=${videoId}`)
window.open(`${invidiousInstance}/watch?v=${videoId}`);
}
</script>
<button class="w-80 p-2" on:click="{modal.showModal()}">
<button class="w-80 p-2" on:click={modal.showModal()}>
<div class="card card-compact bg-base-100 shadow-xl border border-neutral">
<figure class="relative">
<img class="w-full rounded-box" loading="lazy" width="320" height="180" src={getThumbnailUrl()} alt={title} />
<img
class="w-full rounded-box"
loading="lazy"
width="320"
height="180"
src={getThumbnailUrl()}
alt={title}
/>
{#if isVideoLive()}
<div class="absolute bottom-2 right-0 bg-red-500 text-white text-sm rounded-sm font-bold pt-1 pb-1 pr-2 pl-2">LIVE</div>
{:else}
{#if lengthSeconds}
<div class="absolute bottom-2 right-0 bg-black/70 text-white text-sm rounded-sm pt-1 pb-1 pr-2 pl-2">{getFormattedTime(lengthSeconds)}</div>
{/if}
<div
class="absolute bottom-2 right-0 bg-red-500 text-white text-sm rounded-sm font-bold pt-1 pb-1 pr-2 pl-2"
>
LIVE
</div>
{:else if lengthSeconds}
<div
class="absolute bottom-2 right-0 bg-black/70 text-white text-sm rounded-sm pt-1 pb-1 pr-2 pl-2"
>
{getFormattedTime(lengthSeconds)}
</div>
{/if}
</figure>
<div class="card-body">
@@ -194,12 +210,19 @@
<form method="dialog" class="modal-box bg-base-100">
<h3 class="text-lg m-5">{title}</h3>
<div class="flex flex-col">
<VideoStartAt
bind:checked={videoStartAtChecked}
bind:timestamp={videoStartAtTimestamp}
{lengthSeconds}
/>
<button class="btn m-2" on:click={playVideoOnTv}>Play on {tvName}</button>
<button class="btn m-2" on:click={openInvidiousInNewTab}>Open in Invidious</button>
<button class="btn m-2" on:click={openInvidiousInNewTab}
>Open in Invidious</button
>
<button class="btn m-2">Cancel</button>
</div>
</form>
<form method="dialog" class="modal-backdrop">
<button>close</button>
</form>
</dialog>
</dialog>
+83
View File
@@ -0,0 +1,83 @@
<script lang="ts">
export let checked = false;
export let lengthSeconds = undefined;
export let timestamp = 0;
let textInputElemet;
let timestampText = "";
let timestampRange = 0;
$: {
if (document.activeElement !== textInputElemet) {
timestampText = getTimeStampText(timestamp);
}
}
$: timestampRange = timestamp !== undefined ? timestamp : 0;
function getTimeStamp(timestampText) {
if (timestampText === "") {
return 0;
}
const match = /^(\d{1,3}):(\d{1,2})$/.exec(timestampText);
if (match) {
const minutes = parseInt(match[1]);
const seconds = parseInt(match[2]);
if (seconds < 60) {
return minutes * 60 + seconds;
}
}
}
function getTimeStampText(timestamp) {
if (timestamp === undefined) {
return "";
}
const minutes = Math.floor(timestamp / 60);
const remainingSeconds = timestamp % 60;
const formattedMinutes = String(minutes);
const formattedSeconds = String(remainingSeconds).padStart(2, "0");
return `${formattedMinutes}:${formattedSeconds}`;
}
</script>
<div class="form-control">
<div class="flex flex-row items-center">
<label class="label justify-start cursor-pointer">
<input type="checkbox" bind:checked class="checkbox" />
<span class="label-text m-2">Start at</span>
</label>
<input
bind:this={textInputElemet}
disabled={!checked}
class="input w-24"
placeholder="0:00"
bind:value={timestampText}
on:input={(e) => {
timestamp = getTimeStamp(e.currentTarget.value);
}}
/>
{#if checked}
{#if timestamp !== undefined}
<span class="label-text m-2">({timestamp}s)</span>
{:else}
<span class="label-text m-2 text-error">(Invalid time)</span>
{/if}
{/if}
</div>
{#if lengthSeconds && checked}
<input
type="range"
min="0"
max={lengthSeconds}
bind:value={timestampRange}
on:input={(e) => {
// @ts-ignore
timestamp = e.currentTarget.value;
}}
class="range range-xs range-primary"
/>
{/if}
</div>