Compare commits

...
18 Commits
Author SHA1 Message Date
Brahim Hadriche 2dcfabdd60 Release v0.15.0 (#188)
* Release v0.15.0

* Changelog
2023-11-05 15:21:20 -05:00
Brahim Hadriche 8f59e3648e Implement retry mechanism (#187)
* Implement retry mechanism

* Set retry count to 3

* web app cache key

* Changelog
2023-11-05 15:11:19 -05:00
Brahim Hadricheandgithub-action linter 4233f30dec Play queue notification (#186)
* Play queue notification

* Lint fix

* change binding

* Add notification preference

* Lint fix

* changelog

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
2023-11-04 20:23:02 -04:00
Brahim Hadriche 777db66bda Fix crash related to fetching subscriptions 2023-11-04 11:12:35 -04:00
Brahim Hadriche 771929d0d8 Channel links in web app 2023-11-01 08:50:55 -04:00
Brahim Hadricheandgithub-action linter 5179de5c74 Subscribe button (#185)
* Subscribe button

* changelog

* Lint fix

* Introduce disposable part

* Lint fix

* revert navigation change

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
2023-10-31 22:47:03 -04:00
Brahim Hadriche e22051014f [Shore] update dependencies 2023-10-31 19:23:27 -04:00
Brahim Hadriche 3eb45653f0 add --compressed flag to curl 2023-10-31 15:44:03 -04:00
Brahim Hadriche 5287070233 adjust loading indicator 2023-10-30 08:38:51 -04:00
Brahim Hadriche d149c20e0d Remove comment 2023-10-29 19:12:29 -04:00
Brahim Hadriche 6cf735e089 Get rid of optional chaining (Roku 11 feature) 2023-10-29 11:38:36 -04:00
Brahim Hadriche af1fa0b401 Refactor casting dialog and add thumbnails (#184) 2023-10-29 00:28:21 -04:00
Brahim Hadriche f58137b326 Fix casting timestamp 2023-10-27 20:01:18 -04:00
Brahim Hadriche 200fb68ab9 link copy/paste fix 2023-10-27 17:34:24 -04:00
Brahim Hadriche bde4523c00 Support copy pasting links in web app 2023-10-27 16:32:11 -04:00
Brahim Hadriche af020b509a Update README.md 2023-10-27 14:52:16 -04:00
Brahim Hadriche 97592f9839 Maximize video if playing on channel exit 2023-10-27 13:22:06 -04:00
Brahim Hadriche 53f8535535 search pagination in web app (#183) 2023-10-27 13:10:20 -04:00
65 changed files with 1514 additions and 647 deletions

No files matched your search

+17
View File
@@ -5,6 +5,23 @@ 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).
## [0.15.0] - 2023-11-05
### Added
- Pagination support in web app search (load more button)
- Video links pasted into the web app triggers the dialog to cast the video
- Ability to subscribe/unsubscribe from a channel screen
- This needs additional scope for the Invidious token. You will be logged out, and need to login again. Sorry for the inconvenience.
- A notification when videos are added to the queue (can be disabled from the settings)
### Fixed
- A bug where casting from web included timestamp even if the "Start at" check box is unchecked
- A leak where channel screens would reload data even when closed
- A crash when fetching subscriptions
- Fetching errors by adding a retry mechanism to web requests
## [0.14.0] - 2023-10-25
### Added
+2 -2
View File
@@ -185,11 +185,11 @@ Since Component Libraries are simply zip files hosted at some https endpoint, Gi
### Dev library hosted by VS Code Extension
When in debug mode, Playlet lib is packaged and served locally on port 8080, and Playlet app would use it instead of the Playlet lib from Github. This is an important detail, because once you stop debugging in VS Code, the dev app on your Roku TV won't function anymore, with an error:
When in debug mode, Playlet lib is packaged and served locally on port 8086, and Playlet app would use it instead of the Playlet lib from Github. This is an important detail, because once you stop debugging in VS Code, the dev app on your Roku TV won't function anymore, with an error:
> Could not load Playlet component library from any of the following urls:
>
> - \[debug\] http://192.168.1.x:8080/playlet-lib.zip <!-- markdownlint-disable-line -->
> - \[debug\] http://192.168.1.x:8086/playlet-lib.zip <!-- markdownlint-disable-line -->
> Please restart Playlet.
> If the problem persist, contact Playlet authors.
+2 -1
View File
@@ -2,7 +2,7 @@ openapi: 3.0.0
info:
title: Playlet Web API
version: 0.14.0
version: 0.15.0
description:
Playlet Web API is a RESTful API for controlling the Playlet app on
Roku devices. The API is intended to be used by the Playlet web app, but can
@@ -538,6 +538,7 @@ components:
type: boolean
sponsorblock.show_notifications:
type: boolean
# TODO:P1 add the rest of properties
PlayQueueObject:
type: object
properties:
+34 -34
View File
@@ -1,25 +1,25 @@
{
"name": "playlet",
"version": "0.14.0",
"version": "0.15.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playlet",
"version": "0.14.0",
"version": "0.15.0",
"hasInstallScript": true,
"devDependencies": {
"@rokucommunity/bslint": "^0.8.11",
"@types/crypto-js": "^4.1.2",
"@types/fs-extra": "^11.0.2",
"@types/node": "^20.8.4",
"@types/xml2js": "^0.4.12",
"@types/crypto-js": "^4.1.3",
"@types/fs-extra": "^11.0.3",
"@types/node": "^20.8.10",
"@types/xml2js": "^0.4.13",
"argparse": "^2.0.1",
"brighterscript": "^0.65.8",
"brighterscript-formatter": "^1.6.34",
"convert-svg-to-png": "^0.6.4",
"cross-fetch": "^4.0.0",
"crypto-js": "^4.1.1",
"crypto-js": "^4.2.0",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"fs-extra": "^11.1.1",
@@ -27,13 +27,13 @@
"ip": "^1.1.8",
"json5": "^2.2.3",
"roku-deploy": "^3.10.3",
"rooibos-roku": "^5.7.0",
"rooibos-roku": "^5.8.0",
"semver": "^7.5.4",
"shelljs": "^0.8.5",
"ts-node": "^10.9.1",
"typescript": "^5.2.2",
"xml2js": "^0.6.2",
"yaml": "^2.3.2"
"yaml": "^2.3.3"
},
"engines": {
"node": "18"
@@ -330,15 +330,15 @@
"dev": true
},
"node_modules/@types/crypto-js": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-4.1.2.tgz",
"integrity": "sha512-t33RNmTu5ufG/sorROIafiCVJMx3jz95bXUMoPAZcUD14fxMXnuTzqzXZoxpR0tNx2xpw11Dlmem9vGCsrSOfA==",
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-4.1.3.tgz",
"integrity": "sha512-YP1sYYayLe7Eg5oXyLLvOLfxBfZ5Fgpz6sVWkpB18wDMywCLPWmqzRz+9gyuOoLF0fzDTTFwlyNbx7koONUwqA==",
"dev": true
},
"node_modules/@types/fs-extra": {
"version": "11.0.2",
"resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-11.0.2.tgz",
"integrity": "sha512-c0hrgAOVYr21EX8J0jBMXGLMgJqVf/v6yxi0dLaJboW9aQPh16Id+z6w2Tx1hm+piJOLv8xPfVKZCLfjPw/IMQ==",
"version": "11.0.3",
"resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-11.0.3.tgz",
"integrity": "sha512-sF59BlXtUdzEAL1u0MSvuzWd7PdZvZEtnaVkzX5mjpdWTJ8brG0jUqve3jPCzSzvAKKMHTG8F8o/WMQLtleZdQ==",
"dev": true,
"dependencies": {
"@types/jsonfile": "*",
@@ -355,18 +355,18 @@
}
},
"node_modules/@types/node": {
"version": "20.8.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.4.tgz",
"integrity": "sha512-ZVPnqU58giiCjSxjVUESDtdPk4QR5WQhhINbc9UBrKLU68MX5BF6kbQzTrkwbolyr0X8ChBpXfavr5mZFKZQ5A==",
"version": "20.8.10",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.10.tgz",
"integrity": "sha512-TlgT8JntpcbmKUFzjhsyhGfP2fsiz1Mv56im6enJ905xG1DAYesxJaeSbGqQmAw8OWPdhyJGhGSQGKRNJ45u9w==",
"dev": true,
"dependencies": {
"undici-types": "~5.25.1"
"undici-types": "~5.26.4"
}
},
"node_modules/@types/xml2js": {
"version": "0.4.12",
"resolved": "https://registry.npmjs.org/@types/xml2js/-/xml2js-0.4.12.tgz",
"integrity": "sha512-CZPpQKBZ8db66EP5hCjwvYrLThgZvnyZrPXK2W+UI1oOaWezGt34iOaUCX4Jah2X8+rQqjvl9VKEIT8TR1I0rA==",
"version": "0.4.13",
"resolved": "https://registry.npmjs.org/@types/xml2js/-/xml2js-0.4.13.tgz",
"integrity": "sha512-nuT42GzgoUa4zZgBoF4d+Zqc12/FlVxXCT4xU6j3RfqTFVQWrUAClI/0sNJ5ImM9Wv6KB42KMG2xsVMn4cSBzA==",
"dev": true,
"dependencies": {
"@types/node": "*"
@@ -1519,9 +1519,9 @@
}
},
"node_modules/crypto-js": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.1.1.tgz",
"integrity": "sha512-o2JlM7ydqd3Qk9CA0L4NL6mTzU2sdx96a+oOfPu8Mkl/PK51vSyoi8/rQ8NknZtk44vq15lmhAj9CIAGwgeWKw==",
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz",
"integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
"dev": true
},
"node_modules/css-select": {
@@ -3743,9 +3743,9 @@
}
},
"node_modules/rooibos-roku": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/rooibos-roku/-/rooibos-roku-5.7.0.tgz",
"integrity": "sha512-rkEAaowZeuLbwvtBcRZ1r5ber2yeBRqjxcwya9kfYQmDJ+m2XP8pGO9j10C0eW9hx6H7ZZl+5z1oHjnjwQsmBQ==",
"version": "5.8.0",
"resolved": "https://registry.npmjs.org/rooibos-roku/-/rooibos-roku-5.8.0.tgz",
"integrity": "sha512-mPAszwOH1VdxMgSaoXQ/CgpAZ3RQ0A+d3BoxyY8axMsYS5kPO/8dL8fa7iFTGEZYA7803Ur52zlyN8GXqV5nLg==",
"dev": true,
"dependencies": {
"source-map": "^0.7.3",
@@ -4356,9 +4356,9 @@
"dev": true
},
"node_modules/undici-types": {
"version": "5.25.3",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.25.3.tgz",
"integrity": "sha512-Ga1jfYwRn7+cP9v8auvEXN1rX3sWqlayd4HP7OKk4mZWylEmu3KzXDUGrQUN6Ol7qo1gPvB2e5gX6udnyEPgdA==",
"version": "5.26.5",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
"dev": true
},
"node_modules/universalify": {
@@ -4703,9 +4703,9 @@
"dev": true
},
"node_modules/yaml": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.3.2.tgz",
"integrity": "sha512-N/lyzTPaJasoDmfV7YTrYCI0G/3ivm/9wdG0aHuheKowWQwGTsK0Eoiw6utmzAnI6pkJa0DUVygvp3spqqEKXg==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.3.3.tgz",
"integrity": "sha512-zw0VAJxgeZ6+++/su5AFoqBbZbrEakwu+X0M5HmcwUiBL7AzcuPKjj5we4xfQLp78LkEMpD0cOnUhmgOVy3KdQ==",
"dev": true,
"engines": {
"node": ">= 14"
+8 -8
View File
@@ -1,19 +1,19 @@
{
"name": "playlet",
"version": "0.14.0",
"version": "0.15.0",
"description": "Unofficial Youtube client for Roku",
"devDependencies": {
"@rokucommunity/bslint": "^0.8.11",
"@types/crypto-js": "^4.1.2",
"@types/fs-extra": "^11.0.2",
"@types/node": "^20.8.4",
"@types/xml2js": "^0.4.12",
"@types/crypto-js": "^4.1.3",
"@types/fs-extra": "^11.0.3",
"@types/node": "^20.8.10",
"@types/xml2js": "^0.4.13",
"argparse": "^2.0.1",
"brighterscript": "^0.65.8",
"brighterscript-formatter": "^1.6.34",
"convert-svg-to-png": "^0.6.4",
"cross-fetch": "^4.0.0",
"crypto-js": "^4.1.1",
"crypto-js": "^4.2.0",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"fs-extra": "^11.1.1",
@@ -21,13 +21,13 @@
"ip": "^1.1.8",
"json5": "^2.2.3",
"roku-deploy": "^3.10.3",
"rooibos-roku": "^5.7.0",
"rooibos-roku": "^5.8.0",
"semver": "^7.5.4",
"shelljs": "^0.8.5",
"ts-node": "^10.9.1",
"typescript": "^5.2.2",
"xml2js": "^0.6.2",
"yaml": "^2.3.2"
"yaml": "^2.3.3"
},
"engines": {
"node": "18"
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-app",
"version": "0.14.0",
"version": "0.15.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-app",
"version": "0.14.0"
"version": "0.15.0"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-app",
"version": "0.14.0",
"version": "0.15.0",
"description": "Unofficial Youtube client for Roku",
"scripts": {
"prebuild": "rm -rf build/playlet-app",
@@ -14,12 +14,10 @@ function PositionSpinner()
centerx = (1280 - m.busyspinner.poster.width) / 2
centery = (720 - m.busyspinner.poster.height) / 2
m.busyspinner.translation = [centerx, centery]
m.busyspinner.visible = true
end if
end function
function OnVisibleChange()
m.busyspinner.visible = m.top.visible
if m.busyspinner.visible
m.busyspinner.control = "start"
else
+1 -1
View File
@@ -2,7 +2,7 @@ title=Playlet
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=14
minor_version=15
build_version=00000
ui_resolutions=hd
+3
View File
@@ -1,4 +1,5 @@
function ShowErrorDialog(message as object, bulletText as object, bottomMessage as object)
' TODO:P2 a null check on StandardMessageDialog, only available on 10.0 and later
dialog = CreateObject("roSGNode", "StandardMessageDialog")
dialog.message = message
dialog.bulletText = bulletText
@@ -19,5 +20,7 @@ function OnButtonSelected()
end function
function OnDialogClosed()
' TODO:P1 throw an exception to cause a crash report to be generated
' Should include which playlet lib failed to load
m.top.getScene().exitChannel = true
end function
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-lib",
"version": "0.14.0",
"version": "0.15.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-lib",
"version": "0.14.0"
"version": "0.15.0"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-lib",
"version": "0.14.0",
"version": "0.15.0",
"description": "Unofficial Youtube client for Roku",
"scripts": {
"prebuild": "rm -rf build/playlet-lib",
@@ -82,23 +82,35 @@ function onKeyEvent(key as string, press as boolean) as boolean
return false
end if
if key = "options"
VideoUtils.ToggleVideoPictureInPicture()
return true
if VideoUtils.ToggleVideoPictureInPicture()
return true
end if
end if
if key = "play"
VideoUtils.TogglePause()
if VideoUtils.TogglePause()
return true
end if
end if
if key = "pause"
VideoUtils.PauseVideo()
if VideoUtils.PauseVideo()
return true
end if
end if
if key = "playonly"
VideoUtils.ResumeVideo()
if VideoUtils.ResumeVideo()
return true
end if
end if
if key = "back"
if VideoUtils.IsVideoPlayerOpen() and not VideoUtils.IsVideoPlayerFullScreen()
if VideoUtils.ToggleVideoPictureInPicture()
return true
end if
end if
dialog = DialogUtils.ShowDialogButtons("Do you want to exit Playlet?", "Exit", ["Exit", "Cancel"])
dialog.observeField("buttonSelected", FuncName(OnExitDialog), ["buttonSelected"])
return true
@@ -1,6 +1,11 @@
import "pkg:/components/Navigation/Navigation.bs"
import "pkg:/source/asyncTask/asyncTask.bs"
import "pkg:/source/utils/DisposableObserve.bs"
import "pkg:/source/utils/FocusManagement.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
import "SubscribeTask.bs"
function Init()
m.container = m.top.findNode("container")
@@ -11,10 +16,12 @@ function Init()
m.banner = m.top.findNode("banner")
m.thumbnail = m.top.findNode("thumbnail")
m.authorLabel = m.top.findNode("authorLabel")
m.subscribeButton = m.top.findNode("subscribeButton")
m.rowList = m.top.FindNode("rowList")
m.rowList.focusable = true
m.rowList.screen = m.top
m.banner.ObserveField("loadStatus", FuncName(OnBannerLoadStatus))
DisposableObserveField(m.banner, "loadStatus", FuncName(OnBannerLoadStatus))
m.author = ""
m.authorId = ""
@@ -23,6 +30,17 @@ end function
function OnNodeready()
m.rowList@.BindNode(invalid)
SetNavigation(m.rowList, "up", m.subscribeButton)
SetNavigation(m.subscribeButton, "down", m.rowList)
m.subscribeButton.text = "Subscribe"
DisposableObserveField(m.subscribeButton, "buttonSelected", FuncName(OnSubscribeButtonSelected))
SetSubscribeButtonVisibility()
DisposableObserveFieldScoped(m.invidious, "authToken", FuncName(SetSubscribeButtonVisibility))
OnSubscriptionChanged()
DisposableObserveFieldScoped(m.invidious, "subscriptions", FuncName(OnSubscriptionChanged))
end function
function OnFocusChange() as void
@@ -36,6 +54,7 @@ end function
function OnContentSet() as void
content = m.top.content
if content = invalid
m.top.authorId = ""
return
end if
@@ -55,6 +74,8 @@ function OnContentSet() as void
authorId = ValidString(content.authorId)
author = ValidString(content._author)
m.top.authorId = authorId
if (authorId <> m.authorId or author <> m.author) and IsArray(content.tabs)
m.authorId = authorId
m.author = author
@@ -78,6 +99,10 @@ function CreateChannelFeeds(authorId as string, author as string, tabs as object
end function
function OnkeyEvent(key as string, press as boolean) as boolean
if NavigationKeyHandler(key, press).handled
return true
end if
if press = false
return false
end if
@@ -91,6 +116,25 @@ end function
function Close()
m.appController@.PopScreen(invalid)
m.top.dispose = true
end function
function OnDispose()
m.rowList.dispose = true
DisposeObservers()
end function
function OnSubscribeButtonSelected()
if m.subscribeTask <> invalid
m.subscribeTask.cancel = true
end if
isSubbed = IsSubscribed()
m.subscribeTask = StartAsyncTask(SubscribeTask, {
invidious: m.invidious,
ucid: m.authorId,
subscribe: not isSubbed
})
end function
function OnBannerLoadStatus() as void
@@ -159,10 +203,51 @@ function CreateChannelFeed(title as string, endpoint as string, ucid as string,
end function
function GetContextMenuOptionsForItem(video as object) as object
content = m.top.content
if content = invalid or StringUtils.IsNullOrEmpty(content.authorId)
if StringUtils.IsNullOrEmpty(m.top.authorId)
return []
end if
return m.bookmarks@.GetMenuForChannel(m.top.content)
end function
return m.bookmarks@.GetMenuForChannel(content)
function IsLoggedIn() as boolean
return m.invidious.authToken <> invalid
end function
function IsSubscribed() as boolean
authorId = m.top.authorId
if StringUtils.IsNullOrEmpty(authorId)
return false
end if
subscriptions = m.invidious.subscriptions
if subscriptions = invalid
return false
end if
if not subscriptions.DoesExist(authorId)
return false
end if
return subscriptions[authorId]
end function
function OnAuthorIdChange()
SetSubscribeButtonVisibility()
OnSubscriptionChanged()
end function
function SetSubscribeButtonVisibility()
isLogged = IsLoggedIn()
m.subscribeButton.visible = isLogged and not StringUtils.IsNullOrEmpty(m.top.authorId)
m.subscribeButton.focusable = m.subscribeButton.visible
if not m.subscribeButton.visible and m.subscribeButton.hasFocus()
NodeSetFocus(m.rowList, true)
end if
end function
function OnSubscriptionChanged()
isSubbed = IsSubscribed()
if isSubbed
m.subscribeButton.text = "Unsubscribe"
else
m.subscribeButton.text = "Subscribe"
end if
end function
@@ -1,6 +1,7 @@
<component name="ChannelView" extends="Group" includes="AutoBind,Focus,ContextMenuProvider">
<component name="ChannelView" extends="Group" includes="AutoBind,Focus,ContextMenuProvider,Disposable">
<interface>
<field id="content" type="node" onChange="OnContentSet" />
<field id="authorId" type="string" onChange="OnAuthorIdChange" />
<field id="appController" type="node" bind="/AppController" />
<field id="invidious" type="node" bind="/Invidious" />
<field id="bookmarks" type="node" bind="/Bookmarks" />
@@ -37,6 +38,14 @@
font="font:MediumBoldSystemFont" />
</Poster>
<Button
id="subscribeButton"
iconUri=""
focusedIconUri=""
showFocusFootprint="true"
minWidth="200"
translation="[930,64]" />
<VideoRowList
itemComponentName="RowCell"
id="rowList"
@@ -0,0 +1,35 @@
import "pkg:/components/Services/Invidious/InvidiousService.bs"
@asynctask
function SubscribeTask(input as object) as object
invidiousNode = input.invidious
ucid = input.ucid
subscribe = input.subscribe
if m.top.cancel
return invalid
end if
service = new Invidious.InvidiousService(invidiousNode)
if subscribe
response = service.Subscribe(ucid)
else
response = service.Unsubscribe(ucid)
end if
if not response.IsSuccess()
error = response.ErrorMessage()
LogError("Failed to subscribe/unsubscribe to channel:", error)
return {
success: false,
error: error
}
end if
invidiousNode.refreshSubscribtions = true
return {
success: true
}
end function
@@ -5,6 +5,8 @@
<!-- index in a feed -->
<field id="feedSourcesIndex" type="integer" value="-1" />
<!--
TODO:P0 see if the existance of the field "title" has anything to do with it
For some strange reason, the "author" field can only be set once.
If you try to set it again, it will not be updated, with type mismatch warning:
+3 -1
View File
@@ -47,7 +47,9 @@
<!-- No render nodes -->
<PlayQueue id="PlayQueue"
invidious="bind:../Invidious" />
invidious="bind:../Invidious"
notifications="bind:../Notifications"
preferences="bind:../Preferences" />
<ApplicationInfo id="ApplicationInfo" />
<Preferences id="Preferences" />
<Bookmarks id="Bookmarks" />
@@ -13,7 +13,9 @@ function InitializeBindings()
"appController": "/AppController"
},
"PlayQueue": {
"invidious": "../Invidious"
"invidious": "../Invidious",
"notifications": "../Notifications",
"preferences": "../Preferences"
},
"Invidious": {
"webServer": "../WebServer",
@@ -0,0 +1,65 @@
import "pkg:/source/utils/StringUtils.bs"
import "pkg:/source/utils/Types.bs"
' TODO:P2 a lot of shared logic with the SponsorBlock notification, should be refactored into a common notification
function Init()
m.translationAnimation = m.top.findNode("translationAnimation")
m.translationAnimationInterpolator = m.top.findNode("translationAnimationInterpolator")
m.animationTimer = m.top.findNode("animationTimer")
m.top.translation = [1280, 20]
m.translationAnimation.observeField("state", FuncName(OnAnimationState))
m.animationTimer.observeField("fire", FuncName(OnAnimationTimer))
end function
function OnContentSet() as void
content = m.top.content
if content = invalid
return
end if
if not StringUtils.IsNullOrEmpty(content.thumbnail)
m.top.thumbnail = content.thumbnail
else
m.top.thumbnail = "pkg:/images/thumbnail-missing.jpg"
end if
m.top.line1 = content.title
end function
function OnShow()
AnimateIn()
end function
function OnAnimationTimer()
AnimateOut()
end function
function AnimateIn()
m.translationAnimation.unobserveField("state")
m.animationTimer.control = "stop"
m.animationTimer.control = "start"
m.translationAnimation.observeField("state", FuncName(OnAnimationState))
Animate(false)
end function
function AnimateOut()
Animate(true)
end function
function Animate(reverse as boolean) as void
' We are already animating in the requested direction
if m.translationAnimationInterpolator.reverse = reverse and m.translationAnimation.control <> "none"
return
end if
m.translationAnimationInterpolator.reverse = reverse
m.translationAnimation.control = "start"
end function
function OnAnimationState()
if m.translationAnimation.state = "stopped" and m.translationAnimationInterpolator.reverse = true
m.top.getParent().removeChild(m.top)
end if
end function
@@ -0,0 +1,58 @@
<component name="PlayQueueNotification" extends="Group">
<interface>
<field id="content" type="node" onChange="OnContentSet" />
<field id="thumbnail" type="uri" alias="thumbnailPoster.uri" />
<field id="line1" type="string" alias="line1Label.text" />
<field id="show" type="boolean" alwaysNotify="true" onChange="OnShow" />
</interface>
<children>
<Poster
width="500"
height="126"
opacity="0.9"
uri="pkg:/images/white.9.png">
<Poster
id="thumbnailPoster"
loadDisplayMode="scaleToZoom"
width="170"
height="106"
failedBitmapUri="pkg:/images/thumbnail-missing.jpg"
translation="[10,10]">
</Poster>
<LayoutGroup
itemSpacings="[10]"
translation="[190,10]">
<Label
width="300"
font="font:SmallestBoldSystemFont"
horizAlign="center"
color="0x262626ff"
text="Added to queue">
<Font role="font" uri="font:BoldSystemFontFile" size="22" />
</Label>
<Label
id="line1Label"
width="300"
font="font:SmallestSystemFont"
maxLines="3"
color="0x262626ff"
wrap="true" />
</LayoutGroup>
</Poster>
<Animation
id="translationAnimation"
duration="0.3"
optional="true">
<Vector2DFieldInterpolator
id="translationAnimationInterpolator"
key="[0.0, 0.5, 1.0]"
keyValue="[ [1280.0, 20.0], [1020.0, 20.0], [760.0, 20.0] ]"
fieldToInterp="PlayQueueNotification.translation" />
</Animation>
<Timer
id="animationTimer"
duration="3" />
</children>
</component>
@@ -0,0 +1,28 @@
namespace PlayQueue
const NOTIFICATION_NODE_ID = "PlayQueueNotification"
function ShowNotifcation(notifications as object, contentNode as object) as void
notification = notifications.findNode(NOTIFICATION_NODE_ID)
if notification = invalid
notification = notifications.createChild("PlayQueueNotification")
notification.id = NOTIFICATION_NODE_ID
end if
notification.content = contentNode
notification.show = true
end function
function RemoveNotifcation(notifications as object) as void
notification = notifications.findNode(NOTIFICATION_NODE_ID)
if notification <> invalid
notifications.RemoveChild(notification)
end if
end function
function SetVisible(notifications as object, visible as boolean)
notification = notifications.findNode(NOTIFICATION_NODE_ID)
if notification <> invalid
notification.visible = visible
end if
end function
end namespace
@@ -1,5 +1,6 @@
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/PlaylistView/PlaylistContentTask.bs"
import "pkg:/components/PlayQueue/Notifications/PlayQueueNotificationUtils.bs"
import "pkg:/components/VideoFeed/FeedLoadState.bs"
import "pkg:/components/VideoPlayer/VideoUtils.bs"
import "pkg:/source/asyncTask/asyncTask.bs"
@@ -30,6 +31,10 @@ end function
function AddToQueue(node as object)
m.queue.push(node)
queueNotifications = m.top.preferences["misc.queue_notifications"]
if queueNotifications
PlayQueue.ShowNotifcation(m.top.notifications, node)
end if
end function
' TODO:P1 better model of the queue (Now playing, etc)
@@ -4,6 +4,8 @@
<field id="index" type="integer" value="-1" />
<field id="playlistIndex" type="integer" value="-1" />
<field id="invidious" type="node" />
<field id="notifications" type="node" />
<field id="preferences" type="node" />
<function name="Play" />
<function name="AddToQueue" />
<function name="GetQueue" />
@@ -137,6 +137,9 @@ function OnItemLongPressed(index as integer) as void
LogInfo("Long press: playlist:", playlistId, "video:", videoId)
' TODO:P1 handle case of opening the channel
' - Owner of a video
' - Owner of a playlist
contextMenuProviders = [m.top]
ContextMenuUtils.Open(contextMenuProviders, m.appController, video)
end function
@@ -105,14 +105,21 @@ function IsReachable(instance as string, testNode as object) as void
return
end if
name = json.software?.name
if not IsString(name)
software = json.software
if software = invalid
testNode.state = "failed"
testNode.details = `Invalid json from ${url} (couldn't read software.name)`
testNode.details = `Invalid json from ${url} (couldn't read $.software)`
return
end if
version = json.software?.version
name = software.name
if not IsString(name)
testNode.state = "failed"
testNode.details = `Invalid json from ${url} (couldn't read $.software.name)`
return
end if
version = software.version
if not IsString(version)
testNode.state = "failed"
testNode.details = `Invalid json from ${url} (couldn't read software.version)`
@@ -1,4 +1,6 @@
import "InvidiousService.bs"
import "InvidiousSubscriptionsTask.bs"
import "pkg:/source/asyncTask/asyncTask.bs"
function Init()
m.top.apiDefinitions = ParseJson(ReadAsciiFile("libpkg:/config/invidious_video_api.yaml"))
@@ -17,3 +19,18 @@ end function
function SetAuthToken(token as string, instance as string, username as dynamic)
m.service.SetAuthToken(token, instance, username)
end function
function OnAuthTokenChange() as void
m.top.refreshSubscribtions = true
end function
function GetSubscriptions() as void
if m.subscriptionsTask <> invalid
m.subscriptionsTask.cancel = true
end if
if m.top.authToken = invalid
m.top.subscriptions = invalid
return
end if
m.subscriptionsTask = StartAsyncTask(InvidiousSubscriptionsTask, { invidious: m.top })
end function
@@ -4,8 +4,10 @@
<field id="preferences" type="node" />
<field id="webServer" type="node" />
<field id="authToken" type="assocarray" />
<field id="authToken" type="assocarray" onChange="OnAuthTokenChange" />
<field id="apiDefinitions" type="assocarray" />
<field id="refreshSubscribtions" type="boolean" alwaysNotify="true" onChange="GetSubscriptions" />
<field id="subscriptions" type="assocarray" />
<function name="GetCurrentInstance" />
<function name="GetAuthorizeTokenLink" />
@@ -22,8 +22,10 @@ namespace Invidious
const SEARCH_SUGGEST_ENDPOINT = "/api/v1/search/suggestions"
const AUTH_SCOPES = "GET:feed,GET:playlists*,POST:tokens/register,POST:tokens/unregister,POST:history*"
const AUTH_SCOPES = "GET:feed,GET:playlists*,POST:tokens/*,POST:history*,:subscriptions*"
const AUTH_PLAYLISTS = "/api/v1/auth/playlists"
const AUTH_SUBSCRIPTIONS = "/api/v1/auth/subscriptions"
const AUTH_TOKENS_UNREGISTER = "/api/v1/auth/tokens/unregister"
const AUTH_TOKENS_REGISTER = "/api/v1/auth/tokens/register"
@@ -86,7 +88,7 @@ namespace Invidious
url = `${authToken.instance}${Invidious.HISTORY_ENDPOINT}/${videoId}`
request = HttpClient.Post(url, "")
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.SendAndForget()
request.Send()
end function
function SearchSuggestions(q as string, cancellation = invalid as object) as object
@@ -147,6 +149,7 @@ namespace Invidious
request.QueryParams(m.DefaultQueryParams())
request.Cancellation(cancellation)
request.CacheSeconds(60 * 60 * 24)' 24 hours
request.TryCount(3)
return request.Await()
end function
@@ -248,6 +251,12 @@ namespace Invidious
request.CacheSeconds(endpoint.cacheSeconds)
end if
if feedSource.tryCount <> invalid
request.TryCount(feedSource.tryCount)
else if endpoint.tryCount <> invalid
request.TryCount(endpoint.tryCount)
end if
if feedSource.queryParams <> invalid
request.QueryParams(feedSource.queryParams)
end if
@@ -370,16 +379,28 @@ namespace Invidious
function AuthFeedHandler(m as object, feedSource as object, response as object) as object
m.DeleteExpiredToken(response)
if response.StatusCode() = 200
json = response.Json()
videos = []
videos.Append(json.notifications)
videos.Append(json.videos)
return {
items: videos
}
if response.StatusCode() <> 200
return invalid
end if
return invalid
json = response.Json()
if json = invalid
return invalid
end if
videos = []
if IsArray(json.notifications)
videos.Append(json.notifications)
end if
if IsArray(json.videos)
videos.Append(json.videos)
end if
return {
items: videos
}
end function
function DeleteExpiredToken(response as object)
@@ -461,7 +482,7 @@ namespace Invidious
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Header("Content-Type", "application/json")
request.SendAndForget()
request.Send()
end function
function GetAuthorizeTokenLink() as dynamic
@@ -481,6 +502,47 @@ namespace Invidious
return `${invidiousHost}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}`
end function
function GetSubscriptions(cancellation = invalid as object) as object
authToken = m.node.authToken
if authToken = invalid
return invalid
end if
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}`
request = HttpClient.Get(url)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Cancellation(cancellation)
return request.Await()
end function
function Subscribe(channelId as string, cancellation = invalid as object) as object
authToken = m.node.authToken
if authToken = invalid
return invalid
end if
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
request = HttpClient.Post(url, "")
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Cancellation(cancellation)
return request.Await()
end function
function Unsubscribe(channelId as string, cancellation = invalid as object) as object
authToken = m.node.authToken
if authToken = invalid
return invalid
end if
url = `${authToken.instance}${Invidious.AUTH_SUBSCRIPTIONS}/${channelId}`
request = HttpClient.Delete(url)
request.Headers(m.GetAuthenticationHeaders(authToken.token))
request.Cancellation(cancellation)
return request.Await()
end function
end class
end namespace
@@ -0,0 +1,42 @@
import "InvidiousService.bs"
import "pkg:/source/utils/Logging.bs"
@asynctask
function InvidiousSubscriptionsTask(input as object) as object
invidiousNode = input.invidious
service = new Invidious.InvidiousService(invidiousNode)
response = service.GetSubscriptions(m.top.cancellation)
if m.top.cancel
return invalid
end if
subscriptions = response.Json()
if not response.IsSuccess() or subscriptions = invalid
error = response.ErrorMessage()
LogError("Error getting subscriptions:", error)
return {
success: false,
error: response.ErrorMessage()
}
end if
if m.top.cancel
return invalid
end if
subscriptionsDict = {}
for each subscription in subscriptions
subscriptionsDict[subscription.authorId] = true
end for
invidiousNode.subscriptions = subscriptionsDict
return {
success: true
}
end function
@@ -41,9 +41,7 @@ namespace InvidiousContent
node.liveNow = VideoIsLive(item)
VideoSetPremiereTimestampText(node, item)
SetIfExists(node, "publishedText", item, "publishedText")
if not StringUtils.IsNullOrEmpty(instance)
node.thumbnail = VideoGetThumbnail(item, instance) ?? "pkg:/images/thumbnail-missing.jpg"
end if
VideoSetThumbnail(node, item, instance)
SetIfExists(node, "title", item, "title")
SetIfExists(node, "timestamp", item, "timestamp")
SetIfExists(node, "videoId", item, "videoId")
@@ -128,10 +126,11 @@ namespace InvidiousContent
end if
end function
function VideoGetThumbnail(videoItem as object, instance as dynamic, quality = "medium" as string) as dynamic
function VideoSetThumbnail(node as object, videoItem as object, instance as dynamic, quality = "medium" as string) as boolean
videoThumbnails = videoItem.videoThumbnails
if videoThumbnails = invalid or videoThumbnails.Count() = 0
return invalid
node.thumbnail = "pkg:/images/thumbnail-missing.jpg"
return false
end if
url = invalid
for each thumbnail in videoThumbnails
@@ -143,10 +142,14 @@ namespace InvidiousContent
if url = invalid
url = videoThumbnails[0].url
end if
if url.startsWith("/") and not StringUtils.IsNullOrEmpty(instance)
if url.startsWith("/")
if StringUtils.IsNullOrEmpty(instance)
return false
end if
url = instance + url
end if
return url
node.thumbnail = url
return true
end function
function VideoIsLive(videoItem as object) as boolean
@@ -208,7 +211,9 @@ namespace InvidiousContent
end if
thumbnail = thumbnailUrl
else if playlistItem.videos <> invalid and playlistItem.videos.Count() > 0 and playlistItem.videos[0].index = 0
thumbnail = VideoGetThumbnail(playlistItem.videos[0], instance, quality)
if VideoSetThumbnail(node, playlistItem.videos[0], instance, quality)
return
end if
else if node.getChildCount() > 0
thumbnail = node.getChild(0).thumbnail
end if
@@ -84,7 +84,7 @@ namespace SponsorBlock
end if
url = `${m.sponsorBlockConfig.serverAddress}${SponsorBlock.VIEWED_SEGMENT_ENDPOINT}?UUID=${segmentId}`
HttpClient.Post(url, "").SendAndForget()
HttpClient.Post(url, "").Send()
end function
function GenerateProgressBarBackground(segments as object, lengthSeconds as integer, path as string)
@@ -17,8 +17,6 @@ function FindChildren()
m.thumbnail = m.top.FindNode("thumbnail")
end function
' TODO:P1 premeres in x hours is not displayed correctly, and ends up failing with an error
' Need to try not a live event, but a video
function OnContentSet() as void
content = m.top.itemContent
@@ -7,6 +7,7 @@ import "pkg:/components/VideoFeed/VideoRowListContentTask.bs"
import "pkg:/components/VideoFeed/VideoRowListRowContentTask.bs"
import "pkg:/components/VideoPlayer/VideoUtils.bs"
import "pkg:/source/asyncTask/asyncTask.bs"
import "pkg:/source/utils/DisposableObserve.bs"
import "pkg:/source/utils/ErrorUtils.bs"
import "pkg:/source/utils/Logging.bs"
import "pkg:/source/utils/Types.bs"
@@ -18,12 +19,13 @@ function Init()
end function
function OnNodeReady()
m.top.ObserveField("itemFocused", FuncName(OnItemFocused))
m.top.ObserveField("rowItemFocused", FuncName(OnRowItemFocused))
m.top.observeField("focusedChild", FuncName(OnFocusedChildChange))
m.top.ObserveField("visible", FuncName(OnVisibilityChange))
DisposableObserveField(m.top, "itemFocused", FuncName(OnItemFocused))
DisposableObserveField(m.top, "rowItemFocused", FuncName(OnRowItemFocused))
DisposableObserveField(m.top, "focusedChild", FuncName(OnFocusedChildChange))
DisposableObserveField(m.top, "visible", FuncName(OnVisibilityChange))
m.invidious.ObserveFieldScoped("authToken", FuncName(OnAuthTokenChange))
' TODO:P1 Reload when subscriptions change
DisposableObserveFieldScoped(m.invidious, "authToken", FuncName(OnAuthTokenChange))
InitializeLongPressTimer()
end function
@@ -311,3 +313,7 @@ function OnkeyEvent(key as string, press as boolean) as boolean
end if
return false
end function
function OnDispose()
DisposeObservers()
end function
@@ -1,4 +1,4 @@
<component name="VideoRowList" extends="RowList" includes="AutoBind,ContextMenuProvider">
<component name="VideoRowList" extends="RowList" includes="AutoBind,ContextMenuProvider,Disposable">
<interface>
<field id="appController" type="node" bind="/AppController" />
<field id="invidious" type="node" bind="/Invidious" />
@@ -185,8 +185,8 @@ function OnVideoPlayerStateChange() as void
end if
if state = "finished"
metadata = content?.metadata
if not PlayNext(metadata?.recommendedVideos)
metadata = content.metadata
if metadata <> invalid and not PlayNext(metadata.recommendedVideos)
m.container@.watchedVideosClear(invalid)
VideoUtils.CloseVideo()
end if
@@ -231,7 +231,10 @@ function PlayNextRecommendedVideo(recommendedVideos as object) as boolean
end if
for each metadata in recommendedVideos
videoId = metadata?.videoId
if metadata = invalid
continue for
end if
videoId = metadata.videoId
if videoId = invalid
continue for
end if
@@ -85,32 +85,37 @@ namespace VideoUtils
return GetVideoPlayer() <> invalid
end function
function PauseVideo() as void
function PauseVideo() as boolean
player = GetVideoPlayer()
if player = invalid
return
return false
end if
player.control = "pause"
return true
end function
function ResumeVideo() as void
function ResumeVideo() as boolean
player = GetVideoPlayer()
if player = invalid
return
return false
end if
player.control = "resume"
return true
end function
function TogglePause() as void
function TogglePause() as boolean
player = GetVideoPlayer()
if player = invalid
return
return false
end if
if player.state = "playing"
player.control = "pause"
return true
else if player.state = "paused"
player.control = "resume"
return true
end if
return false
end function
end namespace
@@ -53,26 +53,37 @@ namespace Http
response = context.response
invidiousNode = context.server.task.invidious
feedSource = request.query["feed-source"]
if feedSource = invalid
response.Default(400, "Expected feed-source")
return true
end if
token = invidiousNode.authToken
if token = invalid
response.Default(403, "No token, not logged in")
return true
end if
feedSource = request.query["feed-source"]
if feedSource = invalid
response.Default(400, "Expected feed-source")
return true
end if
feedSource = ParseJson(feedSource)
if feedSource = invalid
response.Default(400, "Expected valid JSON for feed-source")
return true
end if
invService = new Invidious.InvidiousService(invidiousNode)
invResponse = invService.MakeRequest(feedSource, feedSource.state?.queryParams)
additionalQueryParams = invalid
if feedSource.state <> invalid and feedSource.state.queryParams <> invalid
additionalQueryParams = feedSource.state.queryParams
end if
invResponse = invService.MakeRequest(feedSource, additionalQueryParams)
if not invResponse.success
response.Default(500, `Failed to make request: ${invResponse.error}`)
return true
end if
response.Json(invResponse.result)
return true
end function)
@@ -0,0 +1,5 @@
<component name="Disposable" extends="Group">
<interface>
<field id="dispose" type="boolean" alwaysNotify="true" onChange="OnDispose" />
</interface>
</component>
@@ -142,6 +142,7 @@ channel_info:
url: /api/v1/channels/{ucid}
responseHandler: ChannelInfoHandler
cacheSeconds: 259200 # 3 days
tryCount: 3
# Channel endpoints
channel_videos:
@@ -149,6 +150,7 @@ channel_videos:
url: /api/v1/channels/{ucid}/videos
responseHandler: ChannelVideosHandler
paginationType: Continuation
tryCount: 3
queryParams:
sort_by:
# defaults to newest
@@ -162,6 +164,7 @@ channel_playlists:
url: /api/v1/channels/{ucid}/playlists
responseHandler: ChannelPlaylistsHandler
paginationType: Continuation
tryCount: 3
queryParams:
sort_by:
required: false
@@ -175,21 +178,25 @@ channel_shorts:
url: /api/v1/channels/{ucid}/shorts
responseHandler: ChannelVideosHandler
paginationType: Continuation
tryCount: 3
channel_streams:
title: Channel streams
url: /api/v1/channels/{ucid}/streams
responseHandler: ChannelVideosHandler
paginationType: Continuation
tryCount: 3
channel_podcasts:
title: Channel podcasts
url: /api/v1/channels/{ucid}/podcasts
responseHandler: ChannelPlaylistsHandler
paginationType: Continuation
tryCount: 3
channel_channels:
title: Related channels
url: /api/v1/channels/{ucid}/channels
responseHandler: ChannelRelatedChannelsHandler
paginationType: Continuation
tryCount: 3
+14
View File
@@ -114,4 +114,18 @@
},
],
},
{
displayText: "Miscellaneous",
key: "misc",
description: "Misc. preferences",
children: [
{
displayText: "Queue notifications",
key: "misc.queue_notifications",
description: "Show a notification when a video is added to the queue",
type: "boolean",
defaultValue: true,
},
],
},
]
+1 -1
View File
@@ -2,7 +2,7 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=14
minor_version=15
build_version=00000
ui_resolutions=hd
+51 -13
View File
@@ -46,6 +46,7 @@ namespace HttpClient
function new()
m._timeoutSeconds = 30
m._tryCount = 1
end function
function Method(method as string) as HttpRequest
@@ -141,6 +142,14 @@ namespace HttpClient
return m
end function
function TryCount(tryCount as integer) as HttpRequest
m._tryCount = ValidInt(tryCount)
if m._tryCount < 1
m._tryCount = 1
end if
return m
end function
function NoCache() as HttpRequest
m._noCache = true
return m
@@ -163,6 +172,7 @@ namespace HttpClient
command = `curl "${m.BuildUrl()}"`
command += ` \\\n -X ${m._method}`
command += ` \\\n --max-time ${m._timeoutSeconds}`
command += ` \\\n --compressed`
if m._headers <> invalid
for each key in m._headers
@@ -178,14 +188,6 @@ namespace HttpClient
end function
function Send() as HttpRequest
return m.DoSend(false)
end function
function SendAndForget() as HttpRequest
return m.DoSend(true)
end function
private function DoSend(forget as boolean) as HttpRequest
if m.urlTransfer <> invalid or m._cache <> invalid
return m
end if
@@ -214,9 +216,7 @@ namespace HttpClient
m.urlTransfer.SetHeaders(m._headers)
end if
if not forget
m.urlTransfer.SetMessagePort(CreateObject("roMessagePort"))
end if
m.urlTransfer.SetMessagePort(CreateObject("roMessagePort"))
LogInfo("Sending", m._method, m.urlTransfer.GetURL(), "ID:", m.urlTransfer.GetIdentity())
@@ -225,14 +225,22 @@ namespace HttpClient
#end if
if m._method = "POST"
m._sent = m.urlTransfer.AsyncPostFromString(m._body)
body = m._body
if body = invalid
body = ""
end if
m._sent = m.urlTransfer.AsyncPostFromString(body)
else if m._method = "GET"
m._sent = m.urlTransfer.AsyncGetToString()
else if m._method = "HEAD"
m._sent = m.urlTransfer.AsyncHead()
else
m.urlTransfer.SetRequest(m._method)
m._sent = m.urlTransfer.AsyncPostFromString(m._body)
body = m._body
if body = invalid
body = ""
end if
m._sent = m.urlTransfer.AsyncPostFromString(body)
end if
if m._sent <> true
@@ -259,6 +267,36 @@ namespace HttpClient
end function
function Await() as HttpResponse
tryCount = m._tryCount
response = invalid
response = m.AwaitInternal()
if response.IsSuccess() or response.TimedOut() or response.IsCancelled() or response.StatusCode() < 500
return response
end if
tryCount -= 1
while tryCount > 0
backoffMs = 1000 + Rnd(2000)
LogInfo("Request failed with status code:", response.StatusCode(), "ID:", m.urlTransfer.GetIdentity(), `\nRetrying:`, m._tryCount - tryCount, "in", backoffMs, "ms")
m.urlTransfer = invalid
m._cache = invalid
m._sent = invalid
sleep(backoffMs)
response = m.AwaitInternal()
if response.IsSuccess() or response.TimedOut() or response.IsCancelled() or response.StatusCode() < 500
return response
end if
tryCount -= 1
end while
return response
end function
private function AwaitInternal() as HttpResponse
if m.urlTransfer = invalid and m._cache = invalid
m.Send()
end if
@@ -0,0 +1,39 @@
function DisposableObserveField(node as object, field as string, callback as string)
node.ObserveField(field, callback)
if m._disposableObserveFields = invalid
m._disposableObserveFields = []
end if
m._disposableObserveFields.push({
node: node,
field: field
})
end function
function DisposableObserveFieldScoped(node as object, field as string, callback as string)
node.ObserveFieldScoped(field, callback)
if m._disposableObserveFieldsScoped = invalid
m._disposableObserveFieldsScoped = []
end if
m._disposableObserveFieldsScoped.push({
node: node,
field: field
})
end function
function DisposeObservers()
if m._disposableObserveFields <> invalid
for each item in m._disposableObserveFields
item.node.UnobserveField(item.field)
next
m._disposableObserveFields = invalid
end if
if m._disposableObserveFieldsScoped <> invalid
for each item in m._disposableObserveFieldsScoped
item.node.UnobserveFieldScoped(item.field)
next
m._disposableObserveFieldsScoped = invalid
end if
end function
+30 -30
View File
@@ -1,28 +1,28 @@
{
"name": "playlet-web",
"version": "0.14.0",
"version": "0.15.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playlet-web",
"version": "0.14.0",
"version": "0.15.0",
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^2.4.6",
"@tailwindcss/typography": "^0.5.10",
"@tsconfig/svelte": "^5.0.2",
"autoprefixer": "^10.4.16",
"daisyui": "^3.9.2",
"daisyui": "^3.9.4",
"dotenv": "^16.3.1",
"ip": "^1.1.8",
"postcss": "^8.4.31",
"svelte": "^4.2.1",
"svelte": "^4.2.2",
"svelte-check": "^3.5.2",
"svelte-preprocess": "^5.0.4",
"tailwindcss": "^3.3.3",
"tailwindcss": "^3.3.5",
"tslib": "^2.6.2",
"typescript": "^5.2.2",
"vite": "^4.4.11",
"vite": "^4.5.0",
"vite-tsconfig-paths": "^4.2.1"
}
},
@@ -876,9 +876,9 @@
}
},
"node_modules/daisyui": {
"version": "3.9.2",
"resolved": "https://registry.npmjs.org/daisyui/-/daisyui-3.9.2.tgz",
"integrity": "sha512-yJZ1QjHUaL+r9BkquTdzNHb7KIgAJVFh0zbOXql2Wu0r7zx5qZNLxclhjN0WLoIpY+o2h/8lqXg7ijj8oTigOw==",
"version": "3.9.4",
"resolved": "https://registry.npmjs.org/daisyui/-/daisyui-3.9.4.tgz",
"integrity": "sha512-fvi2RGH4YV617/6DntOVGcOugOPym9jTGWW2XySb5ZpvdWO4L7bEG77VHirrnbRUEWvIEVXkBpxUz2KFj0rVnA==",
"dev": true,
"dependencies": {
"colord": "^2.9",
@@ -1031,9 +1031,9 @@
}
},
"node_modules/fast-glob": {
"version": "3.2.12",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.12.tgz",
"integrity": "sha512-DVj4CQIYYow0BlaelwK1pHl5n5cRSJfM60UA0zK891sVInoPri2Ekj7+e1CT3/3qxXenpI+nBBmQAcJPJgaj4w==",
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz",
"integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==",
"dev": true,
"dependencies": {
"@nodelib/fs.stat": "^2.0.2",
@@ -1278,9 +1278,9 @@
}
},
"node_modules/jiti": {
"version": "1.18.2",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-1.18.2.tgz",
"integrity": "sha512-QAdOptna2NYiSSpv0O/BwoHBSmz4YhpzJHyi+fnMRTXFjp7B8i/YG5Z8IfusxB1ufjcD2Sre1F3R+nX3fvy7gg==",
"version": "1.21.0",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.0.tgz",
"integrity": "sha512-gFqAIbuKyyso/3G2qhiO2OM6shY6EPP/R0+mkDbyspxKazh8BXDC5FiFsUjlczgdNz/vfra0da2y+aHrusLG/Q==",
"dev": true,
"bin": {
"jiti": "bin/jiti.js"
@@ -1335,9 +1335,9 @@
"dev": true
},
"node_modules/magic-string": {
"version": "0.30.3",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.3.tgz",
"integrity": "sha512-B7xGbll2fG/VjP+SWg4sX3JynwIU0mjoTc6MPpKNuIvftk6u6vqhDnk1R80b8C2GBR6ywqy+1DcKBrevBg+bmw==",
"version": "0.30.5",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.5.tgz",
"integrity": "sha512-7xlpfBaQaP/T6Vh8MO/EqXSW5En6INHEvEXQiuff7Gku0PWjU3uf6w/j9o7O+SpB5fOAkrI5HeoNgwjEO0pFsA==",
"dev": true,
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.4.15"
@@ -1984,9 +1984,9 @@
}
},
"node_modules/svelte": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/svelte/-/svelte-4.2.1.tgz",
"integrity": "sha512-LpLqY2Jr7cRxkrTc796/AaaoMLF/1ax7cto8Ot76wrvKQhrPmZ0JgajiWPmg9mTSDqO16SSLiD17r9MsvAPTmw==",
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/svelte/-/svelte-4.2.2.tgz",
"integrity": "sha512-My2tytF2e2NnHSpn2M7/3VdXT4JdTglYVUuSuK/mXL2XtulPYbeBfl8Dm1QiaKRn0zoULRnL+EtfZHHP0k4H3A==",
"dev": true,
"dependencies": {
"@ampproject/remapping": "^2.2.1",
@@ -2000,7 +2000,7 @@
"estree-walker": "^3.0.3",
"is-reference": "^3.0.1",
"locate-character": "^3.0.0",
"magic-string": "^0.30.0",
"magic-string": "^0.30.4",
"periscopic": "^3.1.0"
},
"engines": {
@@ -2122,9 +2122,9 @@
"dev": true
},
"node_modules/tailwindcss": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.3.3.tgz",
"integrity": "sha512-A0KgSkef7eE4Mf+nKJ83i75TMyq8HqY3qmFIJSWy8bNt0v1lG7jUcpGpoTFxAwYcWOphcTBLPPJg+bDfhDf52w==",
"version": "3.3.5",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.3.5.tgz",
"integrity": "sha512-5SEZU4J7pxZgSkv7FP1zY8i2TIAOooNZ1e/OGtxIEv6GltpoiXUqWvLy89+a10qYTB1N5Ifkuw9lqQkN9sscvA==",
"dev": true,
"dependencies": {
"@alloc/quick-lru": "^5.2.0",
@@ -2132,10 +2132,10 @@
"chokidar": "^3.5.3",
"didyoumean": "^1.2.2",
"dlv": "^1.1.3",
"fast-glob": "^3.2.12",
"fast-glob": "^3.3.0",
"glob-parent": "^6.0.2",
"is-glob": "^4.0.3",
"jiti": "^1.18.2",
"jiti": "^1.19.1",
"lilconfig": "^2.1.0",
"micromatch": "^4.0.5",
"normalize-path": "^3.0.0",
@@ -2285,9 +2285,9 @@
"dev": true
},
"node_modules/vite": {
"version": "4.4.11",
"resolved": "https://registry.npmjs.org/vite/-/vite-4.4.11.tgz",
"integrity": "sha512-ksNZJlkcU9b0lBwAGZGGaZHCMqHsc8OpgtoYhsQ4/I2v5cnpmmmqe5pM4nv/4Hn6G/2GhTdj0DhZh2e+Er1q5A==",
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/vite/-/vite-4.5.0.tgz",
"integrity": "sha512-ulr8rNLA6rkyFAlVWw2q5YJ91v098AFQ2R0PRFwPzREXOUJQPtFUG0t+/ZikhaOCDqFoDhN6/v8Sq0o4araFAw==",
"dev": true,
"dependencies": {
"esbuild": "^0.18.10",
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-web",
"version": "0.14.0",
"version": "0.15.0",
"type": "module",
"scripts": {
"dev": "vite",
@@ -13,17 +13,17 @@
"@tailwindcss/typography": "^0.5.10",
"@tsconfig/svelte": "^5.0.2",
"autoprefixer": "^10.4.16",
"daisyui": "^3.9.2",
"daisyui": "^3.9.4",
"dotenv": "^16.3.1",
"ip": "^1.1.8",
"postcss": "^8.4.31",
"svelte": "^4.2.1",
"svelte": "^4.2.2",
"svelte-check": "^3.5.2",
"svelte-preprocess": "^5.0.4",
"tailwindcss": "^3.3.3",
"tailwindcss": "^3.3.5",
"tslib": "^2.6.2",
"typescript": "^5.2.2",
"vite": "^4.4.11",
"vite": "^4.5.0",
"vite-tsconfig-paths": "^4.2.1"
}
}
+55 -15
View File
@@ -27,7 +27,7 @@ export class InvidiousApi {
return await response.json();
}
public async search(query: string, filters: any) {
public async search(query: string, filters: any, page: number = 1) {
let url = `${this.instance}/api/v1/search?q=${encodeURIComponent(query)}&region=${this.userCountryCode}`;
for (let filter in filters) {
if (typeof filters[filter] === 'string') {
@@ -42,6 +42,7 @@ export class InvidiousApi {
url += `&${filter}=${filters[filter].join(',')}`;
}
}
url += `&page=${page}`;
const response = await fetch(url);
return await response.json();
}
@@ -153,7 +154,14 @@ export class InvidiousApi {
cacheSeconds = endpoint.cacheSeconds
}
const responseJson = await this.cachedFetch(url, cacheSeconds);
let tryCount = 1;
if (feedSource.tryCount !== undefined) {
tryCount = feedSource.tryCount
} else if (endpoint.tryCount !== undefined) {
tryCount = endpoint.tryCount
}
const responseJson = await this.cachedFetch(url, cacheSeconds, tryCount);
let responseHandler = endpoint.responseHandler !== undefined ? this.responseHandlers[endpoint.responseHandler] : this.responseHandlers["DefaultHandler"];
if (!responseHandler) {
@@ -221,26 +229,53 @@ export class InvidiousApi {
return encodedUrl.toString();
}
private async cachedFetch(url: string, cacheSeconds?: number) {
if (!cacheSeconds) {
private async cachedFetch(url: string, cacheSeconds?: number, tryCount: number = 1) {
if (cacheSeconds) {
const cache = this.getCache(url, cacheSeconds);
if (cache) {
return cache;
}
}
try {
tryCount -= 1;
const response = await fetch(url);
return await response.json();
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
this.setCache(url, data);
return data;
} catch (error) {
console.error(error);
}
const cache = this.getCache(url, cacheSeconds);
if (cache) {
return cache;
}
while (tryCount > 0) {
tryCount -= 1;
let backOffMs = 1000 + Math.floor(Math.random() * (3000 - 1000));
console.log(`Retrying ${url} in ${backOffMs}ms`);
await new Promise(resolve => setTimeout(resolve, backOffMs));
const response = await fetch(url);
const data = await response.json();
this.setCache(url, data);
return data;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
this.setCache(url, data);
return data;
} catch (error) {
console.error(error);
}
}
}
// TODO:P2 use more appropriate cache storage
private getCache(url: string, cacheSeconds: number) {
const cache = localStorage.getItem(url);
const cacheKey = this.getCacheKey(url);
const cache = localStorage.getItem(cacheKey);
if (!cache) {
return null;
}
@@ -259,12 +294,17 @@ export class InvidiousApi {
}
private setCache(url: string, data: any) {
const cacheKey = this.getCacheKey(url);
const cacheData = {
__version: 1,
timestamp: Date.now(),
data
};
localStorage.setItem(url, JSON.stringify(cacheData));
localStorage.setItem(cacheKey, JSON.stringify(cacheData));
}
private getCacheKey(url: string) {
return `v1:${url}`;
}
}
+19 -47
View File
@@ -43,73 +43,45 @@ export class PlayletApi {
await fetch(`${PlayletApi.host()}/invidious/logout`);
}
static async playVideo(videoId, timestamp, title, author) {
if (!videoId) {
static async playVideo(args) {
if (!args.videoId) {
return;
}
const args = { videoId };
if (timestamp !== undefined) {
if (typeof timestamp === "string") {
timestamp = parseInt(timestamp);
if (args.timestamp !== undefined) {
if (typeof args.timestamp === "string") {
args.timestamp = parseInt(args.timestamp);
}
args["timestamp"] = timestamp;
}
if (title !== undefined) {
args["title"] = title;
}
if (author !== undefined) {
args["author"] = author;
await PlayletApi.postJson(`${PlayletApi.host()}/api/queue/play`, args);
}
static async playPlaylist(args) {
if (!args.playlistId) {
return;
}
await PlayletApi.postJson(`${PlayletApi.host()}/api/queue/play`, args);
}
static async playPlaylist(playlistId, title, videoCount) {
if (!playlistId) {
static async queueVideo(args) {
if (!args.videoId) {
return;
}
const args = { playlistId };
if (title !== undefined) {
args["title"] = title;
}
if (videoCount !== undefined) {
args["author"] = videoCount;
}
await PlayletApi.postJson(`${PlayletApi.host()}/api/queue/play`, args);
}
static async queueVideo(videoId, timestamp, title, author) {
if (!videoId) {
return;
}
const args = { videoId };
if (timestamp !== undefined) {
if (typeof timestamp === "string") {
timestamp = parseInt(timestamp);
if (args.timestamp !== undefined) {
if (typeof args.timestamp === "string") {
args.timestamp = parseInt(args.timestamp);
}
args["timestamp"] = timestamp;
}
if (title !== undefined) {
args["title"] = title;
}
if (author !== undefined) {
args["author"] = author;
}
const response = await PlayletApi.postJson(`${PlayletApi.host()}/api/queue`, args);
return await response.json();
}
static async queuePlaylist(playlistId, title, videoCount) {
if (!playlistId) {
static async queuePlaylist(args) {
if (!args.playlistId) {
return;
}
const args = { playlistId };
if (title !== undefined) {
args["title"] = title;
}
if (videoCount !== undefined) {
args["author"] = videoCount;
}
const response = await PlayletApi.postJson(`${PlayletApi.host()}/api/queue`, args);
return await response.json();
}
+66 -95
View File
@@ -1,11 +1,12 @@
<script lang="ts">
import { onDestroy, onMount } from "svelte";
import { PlayletApi } from "lib/Api/PlayletApi";
import { playletStateStore } from "lib/Stores";
import { InvidiousApi } from "lib/Api/InvidiousApi";
import VideoStartAt from "lib/VideoStartAt.svelte";
import VideoCastDialog from "./VideoFeed/VideoCastDialog.svelte";
import ChannelCastDialog from "./VideoFeed/ChannelCastDialog.svelte";
let modal;
let videoModal;
let channelModal;
let isDragging;
let isLoading;
let dragEndTimeout;
@@ -30,16 +31,25 @@
onMount(async () => {
document.body.addEventListener("drop", onDrop);
document.body.addEventListener("dragover", onDragOver);
document.body.addEventListener("paste", onPaste);
});
onDestroy(() => {
document.body.removeEventListener("drop", onDrop);
document.body.removeEventListener("dragover", onDragOver);
document.body.removeEventListener("paste", onPaste);
});
async function onPaste(event) {
closeModal();
const dataString = event.clipboardData.getData("text/plain");
await processUrlText(dataString);
}
async function onDrop(event) {
event.preventDefault();
modal.close();
closeModal();
isDragging = false;
for (var i in event.dataTransfer.items) {
@@ -48,20 +58,24 @@
let dataString = (await new Promise((resolve) =>
item.getAsString(resolve)
)) as string;
if (isValidHttpUrl(dataString)) {
const videoInfo = parseYouTubeUrl(dataString);
if (videoInfo.videoId) {
searchForVideoById(videoInfo.videoId, videoInfo.timestamp);
return;
} else {
// TODO:P2 make a HEAD request and check for a redirect, then
// resolve the redirect url.
const urlInfo: any = await invidiousApi.resolveUrl(dataString);
if (urlInfo && urlInfo.pageType === "WEB_PAGE_TYPE_CHANNEL") {
searchForChannelById(urlInfo.ucid);
return;
}
}
await processUrlText(dataString);
}
}
}
async function processUrlText(dataString: string) {
if (isValidHttpUrl(dataString)) {
const videoInfo = parseYouTubeUrl(dataString);
if (videoInfo.videoId) {
searchForVideoById(videoInfo.videoId, videoInfo.timestamp);
return;
} else {
// TODO:P2 make a HEAD request and check for a redirect, then
// resolve the redirect url.
const urlInfo: any = await invidiousApi.resolveUrl(dataString);
if (urlInfo && urlInfo.pageType === "WEB_PAGE_TYPE_CHANNEL") {
searchForChannelById(urlInfo.ucid);
return;
}
}
}
@@ -75,7 +89,7 @@
if (videoStartAtChecked) {
videoStartAtTimestamp = timestamp;
}
modal.showModal();
videoModal.show();
} finally {
isLoading = false;
}
@@ -85,14 +99,14 @@
try {
isLoading = true;
channelMetadata = await invidiousApi.getChannelMetadata(channelId);
modal.showModal();
channelModal.show();
} finally {
isLoading = false;
}
}
function onDragOver(event) {
modal.close();
closeModal();
clearTimeout(dragEndTimeout);
dragEndTimeout = setTimeout(() => {
isDragging = false;
@@ -101,14 +115,17 @@
event.preventDefault();
}
function isValidHttpUrl(string) {
let url;
function isValidHttpUrl(url) {
if (!url) {
return false;
}
let urlObj;
try {
url = new URL(string);
urlObj = new URL(url);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
return urlObj.protocol === "http:" || urlObj.protocol === "https:";
}
function parseYouTubeUrl(url) {
@@ -164,38 +181,11 @@
return result;
}
async function playVideoOnTv() {
await PlayletApi.playVideo(
videoMetadata?.videoId,
videoStartAtTimestamp,
videoMetadata?.title,
videoMetadata?.author
);
}
async function queueVideoOnTv() {
await PlayletApi.queueVideo(
videoMetadata?.videoId,
videoStartAtTimestamp,
videoMetadata?.title,
videoMetadata?.author
);
}
async function openChannelOnTv() {
await PlayletApi.openChannel(channelMetadata?.authorId);
}
function openVideoInvidiousInNewTab() {
let url = `${invidiousInstance}/watch?v=${videoMetadata?.videoId}`;
if (videoStartAtChecked && videoStartAtTimestamp) {
url += `&t=${videoStartAtTimestamp}`;
}
window.open(url);
}
function openChannelInvidiousInNewTab() {
let url = `${invidiousInstance}/channel/${channelMetadata?.authorId}`;
window.open(url);
function closeModal() {
videoModal?.close();
channelModal?.close();
videoMetadata = undefined;
channelMetadata = undefined;
}
</script>
@@ -211,41 +201,22 @@
{/if}
</div>
<dialog bind:this={modal} id="modal_video_drag_drop" class="modal">
<form method="dialog" class="modal-box bg-base-100">
{#if videoMetadata}
<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={queueVideoOnTv}>
Queue on {tvName}
</button>
<button class="btn m-2" on:click={openVideoInvidiousInNewTab}>
Open in Invidious
</button>
</div>
{:else if channelMetadata}
<h3 class="text-lg m-5">{channelMetadata.author}</h3>
<div class="text-sm m-5 line-clamp-3">{channelMetadata.description}</div>
<button class="btn m-2" on:click={openChannelOnTv}>
Open on {tvName}
</button>
<button class="btn m-2" on:click={openChannelInvidiousInNewTab}>
Open in Invidious
</button>
{:else}
<span class="loading loading-spinner loading-md" />
{/if}
<button class="btn m-2">Cancel</button>
</form>
<form method="dialog" class="modal-backdrop">
<button>close</button>
</form>
</dialog>
<VideoCastDialog
bind:this={videoModal}
videoId={videoMetadata?.videoId}
title={videoMetadata?.title}
videoThumbnails={videoMetadata?.videoThumbnails}
author={videoMetadata?.author}
lengthSeconds={videoMetadata?.lengthSeconds}
liveNow={videoMetadata?.liveNow}
viewCount={videoMetadata?.viewCount}
bind:videoStartAtChecked
bind:videoStartAtTimestamp
/>
<ChannelCastDialog
bind:this={channelModal}
author={channelMetadata?.author}
authorId={channelMetadata?.authorId}
authorThumbnails={channelMetadata?.authorThumbnails}
/>
@@ -1,5 +1,5 @@
<script lang="ts">
import VideoListRow from "./Home/VideoListRow.svelte";
import VideoListRow from "lib/VideoFeed/VideoListRow.svelte";
import { bookmarksStore } from "lib/Stores";
export let visibility: boolean;
@@ -1,81 +0,0 @@
<script lang="ts">
import { PlayletApi } from "lib/Api/PlayletApi";
import { playletStateStore } from "lib/Stores";
export let author: string | undefined = undefined;
export let authorId: string | undefined = undefined;
export let authorThumbnails: any[] | undefined = undefined;
export let channelHandle: string | undefined = undefined;
export let subCount: number | undefined = undefined;
// svelte-ignore unused-export-let
export let type: string = undefined;
let modal;
let tvName = "Roku TV";
let invidiousInstance;
playletStateStore.subscribe((value) => {
tvName = value?.device?.friendly_name ?? "Roku TV";
invidiousInstance = value?.invidious?.current_instance;
});
function getThumbnailUrl() {
if (!authorThumbnails || authorThumbnails.length === 0) {
return "";
}
const authorThumbnail = authorThumbnails[authorThumbnails.length - 1];
let url = authorThumbnail.url;
if (url.startsWith("//")) {
url = "https:" + url;
}
return url;
}
async function openChannelOnTv() {
await PlayletApi.openChannel(authorId);
}
function openInvidiousInNewTab() {
let url = `${invidiousInstance}/channel/${authorId}`;
window.open(url);
}
</script>
<button class="w-60 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-44 rounded-full aspect-square object-cover"
loading="lazy"
width="176"
height="176"
src={getThumbnailUrl()}
alt={author}
/>
</figure>
<div class="card-body">
<h3 class="card-title text-base line-clamp-1 min-h-8">{author}</h3>
<div>{subCount} subscribers</div>
<div>{channelHandle || ""}</div>
</div>
</div>
</button>
<!-- TODO:P2 a dialog for every video is very slow. Need to reuse the same one -->
<dialog bind:this={modal} id="modal_{authorId}" class="modal">
<form method="dialog" class="modal-box bg-base-100">
<h3 class="text-lg m-5">{author}</h3>
<div class="flex flex-col">
<button class="btn m-2" on:click={openChannelOnTv}>
Open on {tvName}
</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>
@@ -1,114 +0,0 @@
<script lang="ts">
import { PlayletApi } from "lib/Api/PlayletApi";
import { playletStateStore } from "lib/Stores";
export let title: string | undefined = undefined;
export let author: string | undefined = undefined;
export let playlistId: string | undefined = undefined;
export let playlistThumbnail: string | undefined = undefined;
export let videoCount: number | undefined = undefined;
export let videos: any[] | undefined = undefined;
// svelte-ignore unused-export-let
export let type: string = undefined;
let modal;
let tvName = "Roku TV";
let invidiousInstance;
playletStateStore.subscribe((value) => {
tvName = value?.device?.friendly_name ?? "Roku TV";
invidiousInstance = value?.invidious?.current_instance;
});
function getThumbnailUrl(quality: string = "medium") {
let url = "";
if (playlistThumbnail) {
url = playlistThumbnail;
if (url.startsWith("/") && invidiousInstance) {
url = invidiousInstance + url;
}
} else if (videos && videos.length) {
const video = videos[0];
if (video.videoThumbnails) {
const videoThumbnail =
video.videoThumbnails.find(
(thumbnail) => thumbnail.quality === quality
) || video.videoThumbnails[0];
url = videoThumbnail.url;
}
if (url.startsWith("/") && invidiousInstance) {
url = invidiousInstance + url;
}
}
if (url === "") {
url = `${invidiousInstance}/vi/-----------/mqdefault.jpg`;
}
return url;
}
async function playPlaylistOnTv() {
await PlayletApi.playPlaylist(playlistId, title, videoCount);
}
async function queuePlaylistOnTv() {
await PlayletApi.queuePlaylist(playlistId, title, videoCount);
}
async function openPlaylistOnTv() {
await PlayletApi.openPlaylist(playlistId);
}
function openInvidiousInNewTab() {
let url = `${invidiousInstance}/playlist?list=${playlistId}`;
window.open(url);
}
</script>
<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 aspect-video object-cover"
loading="lazy"
width="320"
height="180"
src={getThumbnailUrl()}
alt={title}
/>
<div
class="absolute bottom-2 right-0 bg-black/70 text-white text-sm rounded-sm pt-1 pb-1 pr-2 pl-2"
>
{videoCount} videos
</div>
</figure>
<div class="card-body">
<h3 class="card-title text-base line-clamp-2 min-h-12">{title}</h3>
<div class="font-semibold">{author}</div>
</div>
</div>
</button>
<!-- TODO:P2 a dialog for every video is very slow. Need to reuse the same one -->
<dialog bind:this={modal} id="modal_{playlistId}" class="modal">
<form method="dialog" class="modal-box bg-base-100">
<h3 class="text-lg m-5">{title}</h3>
<div class="flex flex-col">
<button class="btn m-2" on:click={playPlaylistOnTv}>
Play on {tvName}
</button>
<button class="btn m-2" on:click={queuePlaylistOnTv}>
Queue on {tvName}
</button>
<button class="btn m-2" on:click={openPlaylistOnTv}>
Open on {tvName}
</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>
@@ -1,5 +1,5 @@
<script lang="ts">
import VideoListRow from "lib/Screens/Home/VideoListRow.svelte";
import VideoListRow from "lib/VideoFeed/VideoListRow.svelte";
import { homeLayoutFileStore } from "lib/Stores";
export let visibility: boolean;
+46 -15
View File
@@ -2,11 +2,11 @@
import { InvidiousApi } from "lib/Api/InvidiousApi";
import { PlayletApi } from "lib/Api/PlayletApi";
import { playletStateStore, searchHistoryStore } from "lib/Stores";
import VideoCell from "lib/Screens/Home/VideoCell.svelte";
import PlaylistCell from "lib/Screens/Home/PlaylistCell.svelte";
import VideoCell from "lib/VideoFeed/VideoCell.svelte";
import PlaylistCell from "lib/VideoFeed/PlaylistCell.svelte";
import ChannelCell from "lib/VideoFeed/ChannelCell.svelte";
import SearchThinIcon from "assets/search-thin-icon.svg.svelte";
import FiltersIcon from "assets/filters.svg.svelte";
import ChannelCell from "./Home/ChannelCell.svelte";
import SearchFilters from "./Search/SearchFilters.svelte";
export let visibility: boolean;
@@ -16,6 +16,7 @@
let searchBox;
let searchBoxText = "";
let suggestions: { suggestions: any[] } = { suggestions: [] };
let page = 1;
let videos = [];
let searchHistory = [];
let isLoading = false;
@@ -75,26 +76,33 @@
async function suggestionClicked(query) {
searchBoxText = query;
page = 1;
videos = [];
await searchVideos();
}
async function searchVideos() {
suggestions = { suggestions: [] };
videos = [];
if (searchBoxText.length === 0) {
return;
}
try {
isLoading = true;
// TODO:P1: search pagination - load more results as we scroll
videos = await invidiousApi.search(searchBoxText, searchFilters);
const newVideos = await invidiousApi.search(
searchBoxText,
searchFilters,
page
);
videos = [...videos, ...newVideos];
} finally {
isLoading = false;
}
const newSearchHistory = await PlayletApi.putSearchHistory(searchBoxText);
searchHistoryStore.set(newSearchHistory);
if (page === 1) {
const newSearchHistory = await PlayletApi.putSearchHistory(searchBoxText);
searchHistoryStore.set(newSearchHistory);
}
}
</script>
@@ -103,6 +111,8 @@
<form
on:submit={async (e) => {
e.preventDefault();
page = 1;
videos = [];
await searchVideos();
}}
>
@@ -124,7 +134,14 @@
}, 200);
}}
/>
<button class="join-item btn" on:click={searchVideos}>
<button
class="join-item btn"
on:click={async () => {
page = 1;
videos = [];
await searchVideos();
}}
>
<div class="h-6">
<SearchThinIcon />
</div>
@@ -160,12 +177,6 @@
</div>
<div>
{#if isLoading}
<div class="fixed w-full h-1/2 z-50 flex justify-center items-center">
<span class="loading loading-spinner loading-md" />
</div>
{/if}
<div
class="grid grid-flow-row-dense gap-4 items-center justify-center sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 m-4"
>
@@ -179,6 +190,26 @@
{/if}
{/each}
</div>
{#if !isLoading && videos.length > 0 && searchBoxText}
<div class="flex justify-center items-center">
<button
class="btn w-1/2"
on:click={async () => {
page++;
await searchVideos();
}}
>
Load more
</button>
</div>
{/if}
{#if isLoading}
<div class="w-full h-1/2 z-50 flex justify-center items-center">
<span class="loading loading-spinner loading-md" />
</div>
{/if}
</div>
<SearchFilters
@@ -0,0 +1,62 @@
<script lang="ts">
import { PlayletApi } from "lib/Api/PlayletApi";
import { playletStateStore } from "lib/Stores";
import ChannelThumbnail from "./ChannelThumbnail.svelte";
export let author: string | undefined = undefined;
export let authorId: string | undefined = undefined;
export let authorThumbnails: any[] | undefined = undefined;
export function show() {
modal.showModal();
}
export function close() {
modal.close();
}
let modal;
let tvName = "Roku TV";
let invidiousInstance;
playletStateStore.subscribe((value) => {
tvName = value?.device?.friendly_name ?? "Roku TV";
invidiousInstance = value?.invidious?.current_instance;
});
async function openOnTv() {
await PlayletApi.openChannel(authorId);
}
function openInvidious() {
let url = `${invidiousInstance}/channel/${authorId}`;
window.open(url);
}
</script>
<dialog bind:this={modal} class="modal">
<form method="dialog" class="modal-box bg-base-100">
<div class="flex flex-col items-center">
{#if authorThumbnails}
<div class="w-32">
<ChannelThumbnail bind:author bind:authorThumbnails />
</div>
{/if}
<div class="m-4">{author}</div>
</div>
<div class="flex flex-col">
<div class="join join-vertical m-2">
<button class="btn join-item hover:btn-accent" on:click={openOnTv}>
Open on {tvName}
</button>
<button class="btn join-item hover:btn-accent" on:click={openInvidious}>
Open in Invidious
</button>
<button class="btn join-item hover:btn-accent">Cancel</button>
</div>
</div>
</form>
<form method="dialog" class="modal-backdrop">
<button>Close</button>
</form>
</dialog>
@@ -0,0 +1,32 @@
<script lang="ts">
import ChannelCastDialog from "./ChannelCastDialog.svelte";
import ChannelThumbnail from "./ChannelThumbnail.svelte";
export let author: string | undefined = undefined;
export let authorId: string | undefined = undefined;
export let authorThumbnails: any[] | undefined = undefined;
export let channelHandle: string | undefined = undefined;
export let subCount: number | undefined = undefined;
// svelte-ignore unused-export-let
export let type: string = undefined;
let modal;
</script>
<button class="w-60 p-2" on:click={modal.show()}>
<div class="card card-compact bg-base-100 shadow-xl border border-neutral">
<ChannelThumbnail bind:author bind:authorThumbnails />
<div class="card-body">
<h3 class="card-title text-base line-clamp-1 min-h-8">{author}</h3>
<div>{subCount} subscribers</div>
<div>{channelHandle || ""}</div>
</div>
</div>
</button>
<ChannelCastDialog
bind:this={modal}
bind:author
bind:authorId
bind:authorThumbnails
/>
@@ -0,0 +1,28 @@
<script lang="ts">
export let author: string | undefined = undefined;
export let authorThumbnails: any[] | undefined = undefined;
let thumbnailUrl;
$: {
if (authorThumbnails && authorThumbnails.length > 0) {
const authorThumbnail = authorThumbnails[authorThumbnails.length - 1];
let url = authorThumbnail.url;
if (url.startsWith("//")) {
url = "https:" + url;
}
thumbnailUrl = url;
}
}
</script>
<figure class="relative">
<img
class="w-44 rounded-full aspect-square object-cover"
loading="lazy"
width="176"
height="176"
src={thumbnailUrl}
alt={author}
/>
</figure>
@@ -0,0 +1,120 @@
<script lang="ts">
import { PlayletApi } from "lib/Api/PlayletApi";
import { playletStateStore } from "lib/Stores";
import PlaylistThumbnail from "./PlaylistThumbnail.svelte";
export let title: string | undefined = undefined;
export let playlistId: string | undefined = undefined;
export let videoCount: number | undefined = undefined;
export let playlistThumbnail: string | undefined = undefined;
export let videos: any[] | undefined = undefined;
export function show() {
modal.showModal();
}
export function close() {
modal.close();
}
let modal;
let tvName = "Roku TV";
let invidiousInstance;
playletStateStore.subscribe((value) => {
tvName = value?.device?.friendly_name ?? "Roku TV";
invidiousInstance = value?.invidious?.current_instance;
});
async function playOnTv() {
await PlayletApi.playPlaylist(getPlaylistInfo());
}
async function queueOnTv() {
await PlayletApi.queuePlaylist(getPlaylistInfo());
}
async function openOnTv() {
await PlayletApi.openPlaylist(playlistId);
}
function openInvidious() {
let url = `${invidiousInstance}/playlist?list=${playlistId}`;
window.open(url);
}
function getPlaylistInfo() {
return {
type: "playlist",
playlistId,
title,
playlistThumbnail: getPlaylistThumbnail(),
videoCount,
videos,
};
}
function getPlaylistThumbnail() {
let url = "";
if (playlistThumbnail) {
url = playlistThumbnail;
if (url.startsWith("/") && invidiousInstance) {
url = invidiousInstance + url;
}
} else if (videos && videos.length) {
const video = videos[0];
if (video.videoThumbnails) {
const videoThumbnail =
video.videoThumbnails.find(
(thumbnail) => thumbnail.quality === "medium"
) || video.videoThumbnails[0];
url = videoThumbnail.url;
}
if (url.startsWith("/") && invidiousInstance) {
url = invidiousInstance + url;
}
}
if (url === "") {
url = `${invidiousInstance}/vi/-----------/mqdefault.jpg`;
}
return url;
}
</script>
<dialog bind:this={modal} class="modal">
<form method="dialog" class="modal-box bg-base-100">
<div class="flex flex-col items-center">
<div class="w-64">
<PlaylistThumbnail
bind:title
bind:playlistThumbnail
bind:videoCount
bind:videos
bind:invidiousInstance
/>
</div>
<div class="m-4">{title}</div>
</div>
<div class="flex flex-col">
<div class="join join-vertical m-2">
<button class="btn join-item hover:btn-accent" on:click={playOnTv}>
Play on {tvName}
</button>
<button class="btn join-item hover:btn-accent" on:click={queueOnTv}>
Queue on {tvName}
</button>
<button class="btn join-item hover:btn-accent" on:click={openOnTv}>
Open on {tvName}
</button>
<button class="btn join-item hover:btn-accent" on:click={openInvidious}>
Open in Invidious
</button>
<button class="btn join-item hover:btn-accent">Cancel</button>
</div>
</div>
</form>
<form method="dialog" class="modal-backdrop">
<button>Close</button>
</form>
</dialog>
@@ -0,0 +1,46 @@
<script lang="ts">
import { playletStateStore } from "lib/Stores";
import PlaylistCastDialog from "./PlaylistCastDialog.svelte";
import PlaylistThumbnail from "./PlaylistThumbnail.svelte";
export let title: string | undefined = undefined;
export let author: string | undefined = undefined;
export let playlistId: string | undefined = undefined;
export let playlistThumbnail: string | undefined = undefined;
export let videoCount: number | undefined = undefined;
export let videos: any[] | undefined = undefined;
// svelte-ignore unused-export-let
export let type: string = undefined;
let modal;
let invidiousInstance;
playletStateStore.subscribe((value) => {
invidiousInstance = value?.invidious?.current_instance;
});
</script>
<button class="w-80 p-2" on:click={modal.show()}>
<div class="card card-compact bg-base-100 shadow-xl border border-neutral">
<PlaylistThumbnail
bind:title
bind:playlistThumbnail
bind:videoCount
bind:videos
bind:invidiousInstance
/>
<div class="card-body">
<h3 class="card-title text-base line-clamp-2 min-h-12">{title}</h3>
<div class="font-semibold">{author}</div>
</div>
</div>
</button>
<PlaylistCastDialog
bind:this={modal}
bind:title
bind:playlistId
bind:playlistThumbnail
bind:videoCount
bind:videos
/>
@@ -0,0 +1,52 @@
<script lang="ts">
export let title: string | undefined = undefined;
export let videoCount: number | undefined = undefined;
export let playlistThumbnail: string | undefined = undefined;
export let videos: any[] | undefined = undefined;
export let invidiousInstance;
let thumbnailUrl;
$: {
let url = "";
if (playlistThumbnail) {
url = playlistThumbnail;
if (url.startsWith("/") && invidiousInstance) {
url = invidiousInstance + url;
}
} else if (videos && videos.length) {
const video = videos[0];
if (video.videoThumbnails) {
const videoThumbnail =
video.videoThumbnails.find(
(thumbnail) => thumbnail.quality === "medium"
) || video.videoThumbnails[0];
url = videoThumbnail.url;
}
if (url.startsWith("/") && invidiousInstance) {
url = invidiousInstance + url;
}
}
if (url === "") {
url = `${invidiousInstance}/vi/-----------/mqdefault.jpg`;
}
thumbnailUrl = url;
}
</script>
<figure class="relative">
<img
class="w-full rounded-box aspect-video object-cover"
loading="lazy"
width="320"
height="180"
src={thumbnailUrl}
alt={title}
/>
<div
class="absolute bottom-2 right-0 bg-black/70 text-white text-sm rounded-sm pt-1 pb-1 pr-2 pl-2"
>
{videoCount} videos
</div>
</figure>
@@ -0,0 +1,122 @@
<script lang="ts">
import { PlayletApi } from "lib/Api/PlayletApi";
import { playletStateStore } from "lib/Stores";
import VideoStartAt from "./VideoStartAt.svelte";
import VideoThumbnail from "./VideoThumbnail.svelte";
export let videoId: string | undefined = undefined;
export let title: string | undefined = undefined;
export let videoThumbnails: any[] | undefined = undefined;
export let author: string | undefined = undefined;
export let lengthSeconds: number = undefined;
export let liveNow: boolean = undefined;
export let viewCount: number | undefined = undefined;
export let videoStartAtChecked;
export let videoStartAtTimestamp;
export function show() {
modal.showModal();
}
export function close() {
modal.close();
videoStartAtChecked = false;
videoStartAtTimestamp = 0;
}
let modal;
let tvName = "Roku TV";
let invidiousInstance;
playletStateStore.subscribe((value) => {
tvName = value?.device?.friendly_name ?? "Roku TV";
invidiousInstance = value?.invidious?.current_instance;
});
async function playOnTv() {
await PlayletApi.playVideo(getVideoInfo());
}
async function queueOnTv() {
await PlayletApi.queueVideo(getVideoInfo());
}
function openInvidious() {
let url = `${invidiousInstance}/watch?v=${videoId}`;
if (videoStartAtChecked && videoStartAtTimestamp) {
url += `&t=${videoStartAtTimestamp}`;
}
window.open(url);
}
function getVideoInfo() {
const timestamp = videoStartAtChecked ? videoStartAtTimestamp : undefined;
return {
type: "video",
videoId,
title,
videoThumbnails: getVideoThumbnails(),
author,
lengthSeconds,
liveNow,
viewCount,
timestamp,
};
}
function getVideoThumbnails() {
if (!invidiousInstance || !videoThumbnails || !videoThumbnails.length) {
return videoThumbnails;
}
return videoThumbnails.map((thumbnail) => {
let url = thumbnail.url;
if (url.startsWith("/")) {
url = invidiousInstance + url;
thumbnail.url = url;
}
return thumbnail;
});
}
</script>
<dialog bind:this={modal} class="modal">
<form method="dialog" class="modal-box bg-base-100">
<div class="flex flex-col items-center">
<div class="w-64">
<VideoThumbnail
bind:title
bind:videoThumbnails
bind:liveNow
bind:lengthSeconds
bind:viewCount
bind:invidiousInstance
/>
</div>
<div class="m-4">{title}</div>
</div>
<div class="flex flex-col">
<VideoStartAt
bind:checked={videoStartAtChecked}
bind:timestamp={videoStartAtTimestamp}
{lengthSeconds}
/>
<div class="join join-vertical m-2">
<button class="btn join-item hover:btn-accent" on:click={playOnTv}>
Play on {tvName}
</button>
<button class="btn join-item hover:btn-accent" on:click={queueOnTv}>
Queue on {tvName}
</button>
<button class="btn join-item hover:btn-accent" on:click={openInvidious}>
Open in Invidious
</button>
<button class="btn join-item hover:btn-accent">Cancel</button>
</div>
</div>
</form>
<form method="dialog" class="modal-backdrop">
<button>Close</button>
</form>
</dialog>
@@ -1,7 +1,8 @@
<script lang="ts">
import { PlayletApi } from "lib/Api/PlayletApi";
import { playletStateStore } from "lib/Stores";
import VideoStartAt from "lib/VideoStartAt.svelte";
import VideoCastDialog from "./VideoCastDialog.svelte";
import VideoThumbnail from "./VideoThumbnail.svelte";
import ChannelCastDialog from "./ChannelCastDialog.svelte";
export let title: string | undefined = undefined;
export let videoId: string | undefined = undefined;
@@ -37,14 +38,11 @@
// svelte-ignore unused-export-let
export let indexId: string = undefined;
let modal;
let tvName = "Roku TV";
let videoModal;
let channelModal;
let invidiousInstance;
let videoStartAtChecked;
let videoStartAtTimestamp;
playletStateStore.subscribe((value) => {
tvName = value?.device?.friendly_name ?? "Roku TV";
invidiousInstance = value?.invidious?.current_instance;
});
@@ -110,20 +108,6 @@
}
}
function getThumbnailUrl(quality: string = "medium") {
if (!videoThumbnails || videoThumbnails.length === 0) {
return "";
}
const videoThumbnail =
videoThumbnails.find((thumbnail) => thumbnail.quality === quality) ||
videoThumbnails[0];
let url = videoThumbnail.url;
if (url.startsWith("/") && invidiousInstance) {
url = invidiousInstance + url;
}
return url;
}
function formatViewCount(viewCount) {
if (isNaN(viewCount)) {
return "";
@@ -153,102 +137,43 @@
X = X / 10;
return X;
}
function getFormattedTime(length) {
const hours = Math.floor(length / 3600);
const minutes = Math.floor((length / 60) % 60);
const seconds = length % 60;
const secondsString = seconds < 10 ? `0${seconds}` : seconds.toString();
const minutesString =
minutes < 10 && hours > 0 ? `0${minutes}` : minutes.toString();
let formattedTime = minutesString + ":" + secondsString;
if (hours > 0) {
formattedTime = hours.toString() + ":" + formattedTime;
}
return formattedTime;
}
function isVideoLive() {
if (liveNow) {
return true;
}
return lengthSeconds === 0 && viewCount === 0;
}
async function playVideoOnTv() {
await PlayletApi.playVideo(videoId, videoStartAtTimestamp, title, author);
}
async function queueVideoOnTv() {
await PlayletApi.queueVideo(videoId, videoStartAtTimestamp, title, author);
}
function openInvidiousInNewTab() {
let url = `${invidiousInstance}/watch?v=${videoId}`;
if (videoStartAtChecked && videoStartAtTimestamp) {
url += `&t=${videoStartAtTimestamp}`;
}
window.open(url);
}
</script>
<button class="w-80 p-2" on:click={modal.showModal()}>
<button class="w-80 p-2" on:click={videoModal.show()}>
<div class="card card-compact bg-base-100 shadow-xl border border-neutral">
<figure class="relative">
<img
class="w-full rounded-box aspect-video object-cover"
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}
</figure>
<VideoThumbnail
bind:title
bind:videoThumbnails
bind:liveNow
bind:lengthSeconds
bind:viewCount
bind:invidiousInstance
/>
<div class="card-body">
<h3 class="card-title text-base line-clamp-2 min-h-12">{title}</h3>
<div class="font-semibold">{author}</div>
<button
class="font-semibold link"
on:click={(e) => {
e.stopPropagation();
channelModal.show();
}}
>
{author}
</button>
<div>{getViewCountDateText()}</div>
</div>
</div>
</button>
<!-- TODO:P2 a dialog for every video is very slow. Need to reuse the same one -->
<dialog bind:this={modal} id="modal_{videoId}" class="modal">
<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={queueVideoOnTv}
>Queue on {tvName}
</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>
<VideoCastDialog
bind:this={videoModal}
bind:videoId
bind:title
bind:author
bind:lengthSeconds
bind:videoThumbnails
bind:liveNow
bind:viewCount
videoStartAtChecked={false}
videoStartAtTimestamp={0}
/>
<ChannelCastDialog bind:this={channelModal} bind:author bind:authorId />
@@ -1,8 +1,8 @@
<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 VideoCell from "./VideoCell.svelte";
import PlaylistCell from "./PlaylistCell.svelte";
import ChannelCell from "./ChannelCell.svelte";
// TODO:P1 figure out why some uncached feeds (e.g. channels/ucid/videos) get hit twice
@@ -0,0 +1,73 @@
<script lang="ts">
export let title: string | undefined = undefined;
export let videoThumbnails: any[] | undefined = undefined;
export let liveNow: boolean = undefined;
export let lengthSeconds: number = undefined;
export let viewCount: number | undefined = undefined;
export let invidiousInstance;
let thumbnailUrl;
$: {
if (videoThumbnails && videoThumbnails.length > 0) {
const videoThumbnail =
videoThumbnails.find((thumbnail) => thumbnail.quality === "medium") ||
videoThumbnails[0];
let url = videoThumbnail.url;
if (url.startsWith("/") && invidiousInstance) {
url = invidiousInstance + url;
}
thumbnailUrl = url;
}
}
function getFormattedTime(length) {
const hours = Math.floor(length / 3600);
const minutes = Math.floor((length / 60) % 60);
const seconds = length % 60;
const secondsString = seconds < 10 ? `0${seconds}` : seconds.toString();
const minutesString =
minutes < 10 && hours > 0 ? `0${minutes}` : minutes.toString();
let formattedTime = minutesString + ":" + secondsString;
if (hours > 0) {
formattedTime = hours.toString() + ":" + formattedTime;
}
return formattedTime;
}
function isVideoLive() {
if (liveNow) {
return true;
}
return lengthSeconds === 0 && viewCount === 0;
}
</script>
<figure class="relative">
<img
class="w-full rounded-box aspect-video object-cover"
loading="lazy"
width="320"
height="180"
src={thumbnailUrl}
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}
</figure>