Compare commits

..
26 Commits
Author SHA1 Message Date
Brahim Hadriche 6adbe94a1e Release 0.8.0 (#54) 2023-03-02 16:36:12 -05:00
Brahim Hadriche aaea507fde Use format streams by default instead of DASH (#53) 2023-03-02 16:26:15 -05:00
Brahim Hadriche 52b4feb130 Fix return type 2023-03-01 18:01:32 -05:00
Brahim Hadriche 0d79c4975e Feature/cherrypick ws (#52)
* int to hex

* Websocket frame size

* Hash methods refactor

* Uri components fix
2023-02-27 20:10:21 -05:00
Brahim Hadriche 0e2be8d5bb Decode username https://github.com/iv-org/invidious/pull/3656 2023-02-22 09:00:41 -05:00
Brahim Hadriche 71453237c4 Add username to web app and state api (#50) 2023-02-21 13:54:13 -05:00
Brahim Hadriche 5baab67bb4 [PoC] Invidious import export (#45)
* Invidious import export

* Delete duplicate profiles

* Subscription cleanup

* No need for export

* Load user playlists

* Write profile to file

* playlist limit
2023-02-19 10:35:54 -05:00
Brahim Hadriche ece50b547e Update README.md 2023-02-17 09:07:52 -05:00
Brahim Hadriche 7a27bc673e Update README.md 2023-02-16 16:49:32 -05:00
Brahim Hadriche 822f95bb9d Update CHANGELOG.md 2023-02-14 19:14:28 -05:00
Brahim Hadriche 57f4c7a4a2 Add benchmark video 2023-02-14 19:08:38 -05:00
Brahim Hadriche d1cb877784 Format views for billions 2023-02-14 16:28:32 -05:00
Brahim Hadriche 0de521c525 Add git commit to the state api 2023-02-12 10:27:37 -05:00
Brahim Hadriche 447e58c336 Update release.yml 2023-02-12 10:09:40 -05:00
Brahim Hadriche 66cf61059b Update release.yml 2023-02-12 09:39:39 -05:00
Brahim Hadriche f1f1e550bc Update ci (#49)
* Update lint.yml

* Update release.yml

* Update release.yml

* Update release.yml

* Update release.yml
2023-02-12 09:34:36 -05:00
Brahim Hadriche fb7a898cfa Fix web build on ci 2023-02-12 08:57:25 -05:00
Brahim Hadriche f40e0b7471 Remove image generation from ci command 2023-02-11 22:11:41 -05:00
Brahim Hadriche 43f0159510 Update lint.yml 2023-02-10 21:02:21 -05:00
Brahim Hadriche 80d67cf417 Update release.yml 2023-02-10 20:59:50 -05:00
Brahim Hadriche b0bbb97626 Update release.yml 2023-02-10 20:58:08 -05:00
Brahim Hadriche beb607a2d0 Create release.yml 2023-02-10 20:56:36 -05:00
Brahim Hadriche 043a0e5301 [part 1] Feature/ci release (#48)
* Git status check

* Add git hash to manifest
2023-02-10 20:31:25 -05:00
Brahim Hadricheandgithub-action linter e0020ffa66 SponsorBlock Notification (#47)
* SponsorBlock Notification

* Lint fix

* Reuse animation for multiple skips

* Small change

* Rename color utils

* Lint fix

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
2023-02-10 15:20:08 -05:00
Brahim Hadriche 9697ac58d0 Fix crash in case GetLocalIpAddress returns invalid 2023-02-07 20:40:25 -05:00
Brahim Hadriche 97921aab6e Add comment 2023-02-05 17:42:25 -05:00
38 changed files with 936 additions and 199 deletions

No files matched your search

-2
View File
@@ -1,8 +1,6 @@
name: Linter
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
+35
View File
@@ -0,0 +1,35 @@
name: Release
on:
push:
branches: [ "main" ]
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Use Node.js 18.x
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build Playlet
run: npm run build:release:ci
- name: Delete unstable release
run: gh release delete unstable --cleanup-tag --yes || echo "unstable release was not deleted"
env:
GH_TOKEN: ${{ secrets.GH_TOKEN }}
- name: Create unstable release
run: gh release create unstable ./release/playlet.zip ./playlet/src/lib/playlet-lib.zip --notes "This is an automated release." --prerelease --title unstable
env:
GH_TOKEN: ${{ secrets.GH_TOKEN }}
+10 -1
View File
@@ -4,6 +4,15 @@ 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.8.0] - 2023-03-02
### Added
- SponsorBlock notification
- Invidious username to web app v1
### Fixed
- Crash in case GetLocalIpAddress() returns invalid
- Use Format Stream (720p) instead of DASH (https://github.com/iv-org/invidious/issues/3666)
## [0.7.0] - 2023-02-04
### Added
- A script to sync between Youtube profile and and Invidious profile
@@ -34,7 +43,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Bug where DASH stream is not compatible. Play format stream as a fallback
- Showing upcoming videos correctly
# Removed
### Removed
- Dependency on [roku-promise](https://github.com/rokucommunity/roku-promise)
## [0.5.0] - 2022-12-02
+13 -5
View File
@@ -1,10 +1,18 @@
# Playlet
<p align="center">
<img src="banner.png" style="display:block;text-align:center" alt="Playlet Logo" width="800"/>
<br/><br/>
<a href="https://github.com/iBicha/playlet">
<img alt="AGPL-3.0 license" src="https://img.shields.io/github/license/iBicha/playlet.svg"/>
</a>
<a href="https://github.com/iBicha/playlet/releases">
<img alt="Current Release" src="https://img.shields.io/github/release/iBicha/playlet.svg"/>
<img alt="Total Downloads" src="https://img.shields.io/github/downloads/iBicha/playlet/latest/playlet-lib.zip.svg"/>
</a>
</p>
# Playlet
Unofficial Youtube client for Roku 📺
Playlet is an unofficial Youtube client for Roku 📺
## Features
- 🔥 No Ads (Not now, not ever)
@@ -13,6 +21,7 @@ Unofficial Youtube client for Roku 📺
- ⚔️ SponsorBlock integration (skips undesirable sections in videos)
- 📱 Cast from phone
- 🔮 Picture-in-picture mode
- ⚡ Fast! [Check out how we compare with the official Youtube app](https://youtu.be/qmSvA-QQW20)
### Cast from phone
1. Open settings in Playlet
@@ -30,9 +39,8 @@ Unofficial Youtube client for Roku 📺
1. Change the Invidious instance
## Screenshots
<img src="screenshot1.jpg" alt="Screenshot of Playlet" width="350"/>
<img src="screenshot2.jpg" alt="Screenshot of Playlet" width="350"/>
<img src="screenshot3.jpg" alt="Screenshot of Playlet" width="350"/>
| ![](screenshot1.jpg) | ![](screenshot2.jpg) | ![](screenshot3.jpg) |
|----------------------|----------------------|----------------------|
## Installation
### Roku Store (Published app)
+108 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet",
"version": "0.6.0",
"version": "0.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "playlet",
"version": "0.6.0",
"version": "0.8.0",
"hasInstallScript": true,
"dependencies": {
"bslib": "npm:@rokucommunity/bslib@^0.1.1",
@@ -26,6 +26,7 @@
"roku-log-bsc-plugin": "^0.7.0",
"ropm": "^0.10.11",
"semver": "^7.3.8",
"shelljs": "^0.8.5",
"ts-node": "^10.9.1",
"typescript": "^4.9.5"
},
@@ -2263,6 +2264,15 @@
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"dev": true
},
"node_modules/interpret": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/interpret/-/interpret-1.4.0.tgz",
"integrity": "sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==",
"dev": true,
"engines": {
"node": ">= 0.10"
}
},
"node_modules/ip": {
"version": "1.1.8",
"resolved": "https://registry.npmjs.org/ip/-/ip-1.1.8.tgz",
@@ -2290,6 +2300,18 @@
"node": ">=8"
}
},
"node_modules/is-core-module": {
"version": "2.11.0",
"resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz",
"integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==",
"dev": true,
"dependencies": {
"has": "^1.0.3"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
@@ -2957,6 +2979,12 @@
"node": ">=0.10.0"
}
},
"node_modules/path-parse": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
"integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
"dev": true
},
"node_modules/path-to-regexp": {
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
@@ -3213,6 +3241,18 @@
"node": ">=8.10.0"
}
},
"node_modules/rechoir": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz",
"integrity": "sha512-HFM8rkZ+i3zrV+4LQjwQ0W+ez98pApMGM3HUrN04j3CqzPOzl9nmP15Y8YXNm8QHGv/eacOVEjqhmWpkRV0NAw==",
"dev": true,
"dependencies": {
"resolve": "^1.1.6"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/regexp-to-ast": {
"version": "0.5.0",
"resolved": "https://registry.npmjs.org/regexp-to-ast/-/regexp-to-ast-0.5.0.tgz",
@@ -3281,6 +3321,23 @@
"integrity": "sha512-AKGr4qvHiryxRb19m3PsLRGuKVAbJLUD7E6eOaHkfKhwc+vSgVOCY5xNvm9EkolBKTOf0GrQAZKLimOCz81Khg==",
"dev": true
},
"node_modules/resolve": {
"version": "1.22.1",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz",
"integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==",
"dev": true,
"dependencies": {
"is-core-module": "^2.9.0",
"path-parse": "^1.0.7",
"supports-preserve-symlinks-flag": "^1.0.0"
},
"bin": {
"resolve": "bin/resolve"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/reusify": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz",
@@ -3819,6 +3876,43 @@
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"dev": true
},
"node_modules/shelljs": {
"version": "0.8.5",
"resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.8.5.tgz",
"integrity": "sha512-TiwcRcrkhHvbrZbnRcFYMLl30Dfov3HKqzp5tO5b4pt6G/SezKcYhmDg15zXVBswHmctSAQKznqNW2LO5tTDow==",
"dev": true,
"dependencies": {
"glob": "^7.0.0",
"interpret": "^1.0.0",
"rechoir": "^0.6.2"
},
"bin": {
"shjs": "bin/shjs"
},
"engines": {
"node": ">=4"
}
},
"node_modules/shelljs/node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
"dev": true,
"dependencies": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^3.1.1",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
},
"engines": {
"node": "*"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/side-channel": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz",
@@ -3952,6 +4046,18 @@
"node": ">=4"
}
},
"node_modules/supports-preserve-symlinks-flag": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
"integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
"dev": true,
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/tar-fs": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
+6 -2
View File
@@ -1,6 +1,6 @@
{
"name": "playlet",
"version": "0.7.0",
"version": "0.8.0",
"description": "Unofficial Youtube client for Roku",
"dependencies": {
"bslib": "npm:@rokucommunity/bslib@^0.1.1",
@@ -20,6 +20,7 @@
"roku-log-bsc-plugin": "^0.7.0",
"ropm": "^0.10.11",
"semver": "^7.3.8",
"shelljs": "^0.8.5",
"ts-node": "^10.9.1",
"typescript": "^4.9.5"
},
@@ -37,7 +38,8 @@
"prebuild": "rm -rf dist",
"build:dev": "npm run build:web && npm run build:lib:dev && npm run build:app:dev",
"build:prod": "npm run build:web && npm run build:lib:prod && npm run build:app:prod",
"build:release": "npm run format:fix && npm run lint:fix && npm run manifest-version && npm run generate-images && npm run build:prod && npm run sign-package",
"build:release": "npm run build:release:ci && npm run sign-package",
"build:release:ci": "npm run format:fix && npm run lint:fix && npm run manifest-version && npm run manifest-git-hash && npm run build:prod",
"build:app": "cd playlet && bsc --create-package --lintConfig ../config/bslint.jsonc",
"build:app:dev": "npm run build:app -- --debug=true",
"build:app:prod": "npm run build:app -- --debug=false --sourceMap=false",
@@ -52,9 +54,11 @@
"format:fix": "npm run format:base -- --write",
"generate-images": "node tools/generate-images.js",
"manifest-version": "node tools/update-manifest-version.js",
"manifest-git-hash": "node tools/update-manifest-git-hash.js",
"sign-package": "node tools/sign-package.js",
"screenshot": "node tools/screenshot.js",
"profile-sync": "node tools/profile-sync.js",
"generate-sponsorblock-config": "node tools/generate-sponsorblock-config.js",
"postinstall": "npx ropm copy && cd playlet-web && npm install"
}
}
@@ -0,0 +1,65 @@
import "pkg:/source/services/SponsorBlock.bs"
function Init()
m.categoryLabel = m.top.findNode("categoryLabel")
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", "OnAnimationState")
m.animationTimer.observeField("fire", "OnAnimationTimer")
end function
function OnSegmentSet()
category = m.top.segment.category
categoryTitle = SponsorBlock.SegmentShortTitle(category)
m.categoryLabel.text = "Skipped" + chr(10) + categoryTitle
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", "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.state = "running"
return
end if
' Check if we are already at the destination
if m.translationAnimation.state = "stopped"
if reverse
destination = m.translationAnimationInterpolator.keyValue[0][0]
else
destination = m.translationAnimationInterpolator.keyValue[1][0]
end if
current = m.top.translation[0]
if current = destination
return
end if
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,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<component name="SponsorBlockNotification" extends="Group">
<interface>
<field id="segment" type="assocarray" onChange="OnSegmentSet" />
</interface>
<children>
<Rectangle
width="250"
height="70"
color="#414141"
opacity="0.8">
<Poster
uri="libpkg:/images/LogoSponsorBlockSimple256px.png"
width="50"
height="50"
translation="[10,10]">
</Poster>
<Label
id="categoryLabel"
text="..."
font="font:SmallestBoldSystemFont"
lineSpacing="5"
horizAlign="center"
vertAlign="center"
wrap="true"
width="170"
height="70"
translation="[70,0]">
</Label>
</Rectangle>
<Animation
id="translationAnimation"
duration="0.3"
optional="true">
<Vector2DFieldInterpolator
id="translationAnimationInterpolator"
key="[0.0, 0.5, 1.0]"
keyValue="[ [1280.0, 20.0], [1140.0, 20.0], [1000.0, 20.0] ]"
fieldToInterp="SponsorBlockNotification.translation" />
</Animation>
<Timer
id="animationTimer"
duration="3"
/>
</children>
</component>
@@ -0,0 +1,27 @@
import "pkg:/components/VideoPlayer/Video.bs"
function ShowSponsorBlockNotifcation(segment as object)
videoContainer = GetVideoContainer()
notification = videoContainer.findNode("sponsorBlockNotification")
if notification = invalid
notification = videoContainer.createChild("SponsorBlockNotification")
notification.id = "sponsorBlockNotification"
end if
notification.segment = segment
end function
function RemoveSponsorBlockNotifcation()
videoContainer = GetVideoContainer()
notification = videoContainer.findNode("sponsorBlockNotification")
if notification <> invalid
videoContainer.RemoveChild(notification)
end if
end function
function SponsorBlockNotifcationSetVisible(visible as boolean)
videoContainer = GetVideoContainer()
notification = videoContainer.findNode("sponsorBlockNotification")
if notification <> invalid
notification.visible = visible
end if
end function
@@ -1,5 +1,6 @@
import "pkg:/source/services/Invidious.bs"
import "pkg:/components/Dialog/DialogUtils.bs"
import "pkg:/components/SponsorBlockNotification/SponsorBlockNotificationManager.bs"
function PlayVideo(videoId as string, args = invalid as object)
sender = args?.sender
@@ -23,6 +24,7 @@ function PlayVideo(videoId as string, args = invalid as object)
videoContainer.sender = sender
end if
videoContainer.videoPlayer = videoContainer.createChild("VideoPlayer")
videoContainer.insertChild(videoContainer.videoPlayer, 0)
videoContainer.videoPlayer.id = "VideoPlayer"
videoContainer.videoPlayer.metadata = metadata
videoContainer.videoPlayer.videoId = videoId
@@ -49,6 +51,7 @@ function CloseVideo(setFocus = true as boolean)
videoContainer.sender.SetFocus(true)
end if
end if
SponsorBlockNotifcationSetVisible(false)
end function
function ToggleVideoPictureInPicture(sender = invalid as object) as boolean
@@ -4,6 +4,8 @@ import "pkg:/components/VideoPlayer/Video.bs"
import "pkg:/components/VideoPlayer/VideoDetailsTask.bs"
function Init()
m.videoContainer = GetVideoContainer()
SetupSponsorBlock()
SetupAnimation()
SetupBusySpinner()
@@ -12,7 +14,6 @@ function Init()
m.top.bufferingBar.filledBarBlendColor = "0xFF0000FF"
m.top.retrievingBar.filledBarBlendColor = "0xFF0000FF"
m.videoContainer = GetVideoContainer()
m.top.enableUI = m.videoContainer.fullscreen
m.videoContainer.observeFieldScoped("fullscreen", "OnFullScreenChange")
@@ -116,6 +117,14 @@ function OnVideoDetailsTaskResults(output as object) as void
end if
playletStreamUrls.push(hlsUrlLocal)
else
if metadata.formatStreams.Count() > 0
stream = metadata.formatStreams[metadata.formatStreams.Count() - 1]
itag = stream.itag
playletStreamUrls.push(Invidious.GetVideoUrl(videoId, itag, false))
playletStreamUrls.push(Invidious.GetVideoUrl(videoId, itag, true))
end if
if metadata.dashUrl <> invalid
#if DASH_THUMBNAILS
@@ -134,13 +143,6 @@ function OnVideoDetailsTaskResults(output as object) as void
playletStreamUrls.push(dashUrlLocal)
end if
if metadata.formatStreams.Count() > 0
stream = metadata.formatStreams[metadata.formatStreams.Count() - 1]
itag = stream.itag
playletStreamUrls.push(Invidious.GetVideoUrl(videoId, itag, false))
playletStreamUrls.push(Invidious.GetVideoUrl(videoId, itag, true))
end if
end if
metadata.playletStreamUrls = playletStreamUrls
@@ -335,4 +337,5 @@ function OnFullScreenChange()
m.translationAnimation.control = "start"
m.top.enableUI = m.videoContainer.fullscreen
SponsorBlockNotifcationSetVisible(m.videoContainer.fullscreen)
end function
@@ -3,6 +3,8 @@ function SetCaptions(metadata as object, videoPlayer as object, contentNode as o
return
end if
isoLanguageList = ParseJson(ReadAsciiFile("libpkg:/config/ISO-639-1-to-ISO-639-2T.json"))
' TODO: loop through instances until valid captions are found
' Captions are rate limited https://github.com/iv-org/invidious/issues/2567
instance = InvidiousSettings.GetSelectedInstance()
subtitleTracks = []
@@ -1,9 +1,13 @@
import "pkg:/source/asyncTask/asyncTask.bs"
import "pkg:/components/VideoPlayer/SponsorBlockTask.bs"
import "pkg:/components/VideoPlayer/SponsorBlockTrackingTask.bs"
import "pkg:/components/SponsorBlockNotification/SponsorBlockNotificationManager.bs"
function SetupSponsorBlock()
PositionChapterLabel()
SponsorBlockNotifcationSetVisible(m.videoContainer.fullscreen)
m.timeLabel = FindTimeLabel()
m.top.trickPlayBar.observeField("visible", "OnTrickPlayBarVisible")
m.chapterLabelTimer = m.top.findNode("chapterLabelTimer")
@@ -123,6 +127,7 @@ function OnPositionChangeSkipSponsorBlockSections() as void
' TODO: if segmentEnd is at the end of the video, close video
m.top.seek = segmentEnd
print("Skipping section:" + segment["category"])
ShowSponsorBlockNotifcation(segment)
SendSkippedSectionEvent(segment.UUID)
return
end if
@@ -87,7 +87,12 @@ function FormatViewCount(viewCount as dynamic) as string
end if
viewCount = viewCount / 1000
return `${FormatFloat(viewCount)}M views`
if viewCount < 1000
return `${FormatFloat(viewCount)}M views`
end if
viewCount = viewCount / 1000
return `${FormatFloat(viewCount)}B views`
end function
function FormatFloat(X as integer) as integer
@@ -36,7 +36,13 @@ namespace Http
' Token is encoded twice for some reason
token = request.query["token"].DecodeUri().DecodeUriComponent()
referer = request.query["ref"].DecodeUri()
InvidiousSettings.SetAuthToken(token, referer)
username = request.query["username"]
' TODO: remove null check after 6 months of https://github.com/iv-org/invidious/pull/3603
if username <> invalid
username = username.DecodeUriComponent().DecodeUriComponent()
end if
InvidiousSettings.SetAuthToken(token, referer, username)
server.task.top.login = true
end if
response.Redirect("/")
@@ -38,7 +38,8 @@ namespace Http
selected_instance: InvidiousSettings.GetSelectedInstance(),
auth_url: Invidious.GetAuthorizeTokenLink(),
logged_in: authToken <> invalid,
logged_in_instance: authToken <> invalid ? authToken.instance : invalid
logged_in_instance: authToken <> invalid ? authToken.instance : invalid,
logged_in_username: authToken <> invalid ? authToken.username : invalid
}
end if
@@ -43,11 +43,12 @@ function WebServerLoop()
return true
end function)
if IsDebugMode()
#if DEBUG
allowedOrigin = "*"
else
#else
allowedOrigin = `http://${GetLocalIpAddress()}:8888`
end if
#end if
m.server.UseRouter(new Http.CorsMiddleware(allowedOrigin))
#if WEB_SOCKETS
m.server.UseRouter(new Http.WebSocketMiddleware())
@@ -58,13 +59,13 @@ function WebServerLoop()
m.server.UseRouter(new Http.StateApiRouter())
m.server.UseRouter(new Http.InvidiousRouter())
m.server.UseRouter(new Http.HttpStaticFilesRouter("/", m.settings.WwwRoot, false, false, false))
if IsDebugMode()
#if DEBUG
m.server.UseRouter(new Http.HttpStaticFilesRouter("/debug/libpkg", "libpkg:/", true, true, false))
m.server.UseRouter(new Http.HttpStaticFilesRouter("/debug/pkg", "pkg:/", true, true))
m.server.UseRouter(new Http.HttpStaticFilesRouter("/debug/tmp", "tmp:/", true, true))
m.server.UseRouter(new Http.HttpStaticFilesRouter("/debug/cachefs", "cachefs:/", true, true))
m.server.UseRouter(new Http.HttpStaticFilesRouter("/debug/common", "common:/", true, true))
end if
#end if
#if WEB_SERVER_BASIC_AUTH
m.server.UseRouter(new Http.BasicAuthMiddleware())
#end if
@@ -5,5 +5,4 @@
<field id="login" type="boolean" alwaysNotify="true" />
<field id="command" type="string" alwaysNotify="true" />
</interface>
<script type="text/brightscript" uri="pkg:/source/utils/Debug.bs" />
</component>
@@ -36,13 +36,11 @@ namespace Web
secondByte = m.ReadByte()
m.is_masked = (secondByte and &h80) <> 0
m.payload_size = secondByte and &h7F
if not m.is_masked
return false
end if
if m.payload_size >= 126
if not m.ReadPayloadSize(secondByte)
return false
end if
@@ -56,13 +54,41 @@ namespace Web
return true
end function
function ReadPayloadSize(secondByte as integer) as boolean
payloadSize = secondByte and &h7F
if payloadSize < 126
m.payload_size = payloadSize
return true
else if payloadSize = 126
payloadSize = (m.ReadByte() << 8) or m.ReadByte()
m.payload_size = payloadSize
return true
else
'TODO: Read size in 8 bytes
return false
end if
end function
function WritePayloadSize(payloadSize as integer)
if payloadSize < 126
m.WriteByte(payloadSize)
else if payloadSize < 65536
m.WriteByte(126)
m.WriteByte(payloadSize >> 8)
m.WriteByte(payloadSize and &hFF)
else
m.WriteByte(127)
'TODO: Write size in 8 bytes
end if
end function
function WriteToBuffer(buffer as object, index as integer, length as integer) as integer
m.buffer = buffer
m.index = index
m.length = length
m.WriteByte(m.fin or m.opcode)
m.WriteByte(m.payload_size)
m.WritePayloadSize(m.payload_size)
for i = 0 to m.payload_size - 1
m.buffer[m.index] = m.payload[i]
@@ -0,0 +1,115 @@
{
"serverAddress": "https://sponsor.ajay.app",
"categoryList": [
"sponsor",
"selfpromo",
"exclusive_access",
"interaction",
"poi_highlight",
"intro",
"outro",
"preview",
"filler",
"chapter",
"music_offtopic"
],
"categories": {
"sponsor": {
"title": "Sponsor",
"short_title": "Sponsor",
"categorySupport": [
"skip",
"mute",
"full"
],
"color": "#00d400B3"
},
"selfpromo": {
"title": "Unpaid/Self Promotion",
"short_title": "Unpaid/Self Promotion",
"categorySupport": [
"skip",
"mute",
"full"
],
"color": "#ffff00B3"
},
"exclusive_access": {
"title": "Exclusive Access",
"short_title": "Exclusive Access",
"categorySupport": [
"full"
],
"color": "#008a5cB3"
},
"interaction": {
"title": "Interaction Reminder (Subscribe)",
"short_title": "Interaction Reminder",
"categorySupport": [
"skip",
"mute"
],
"color": "#cc00ffB3"
},
"poi_highlight": {
"title": "Highlight",
"short_title": "Highlight",
"categorySupport": [
"poi"
],
"color": "#ff1684B3"
},
"intro": {
"title": "Intermission/Intro Animation",
"short_title": "Intermission",
"categorySupport": [
"skip",
"mute"
],
"color": "#00ffffB3"
},
"outro": {
"title": "Endcards/Credits",
"short_title": "Endcards/Credits",
"categorySupport": [
"skip",
"mute"
],
"color": "#0202edB3"
},
"preview": {
"title": "Preview/Recap",
"short_title": "Preview/Recap",
"categorySupport": [
"skip",
"mute"
],
"color": "#008fd6B3"
},
"filler": {
"title": "Filler Tangent/Jokes",
"short_title": "Filler",
"categorySupport": [
"skip",
"mute"
],
"color": "#7300FFE6"
},
"chapter": {
"title": "Chapter",
"short_title": "Chapter",
"categorySupport": [
"chapter"
],
"color": "#FFFFFFC8"
},
"music_offtopic": {
"title": "Music: Non-Music Section",
"short_title": "Non-Music",
"categorySupport": [
"skip"
],
"color": "#ff9900B3"
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

+3 -1
View File
@@ -2,10 +2,12 @@ title=PlayletLib
# Do not update version manually, it is auto updated from package.json
major_version=0
minor_version=7
minor_version=8
build_version=00000
sg_component_libs_provided=PlayletLib
hidden=1
git_commit_sha=unknown
bs_const=DEBUG=false;WEB_SERVER_BASIC_AUTH=false;DASH_THUMBNAILS=false;WEB_SOCKETS=true
@@ -36,11 +36,16 @@ namespace InvidiousSettings
return instances[0]
end function
function SetAuthToken(token as string, instance as string)
json = FormatJson({
function SetAuthToken(token as string, instance as string, username as dynamic)
obj = {
token: token,
instance: instance
})
}
if username <> invalid
obj.username = username
end if
json = FormatJson(obj)
RegistryUtils.Write(RegistryUtils.INVIDIOUS_TOKEN, json)
instances = InvidiousSettings.GetCurrentInstances()
+34 -35
View File
@@ -1,54 +1,53 @@
import "pkg:/source/roku_modules/rokurequests/Requests.brs"
import "pkg:/source/utils/WebUtils.bs"
import "pkg:/source/utils/Crypto.bs"
import "pkg:/source/utils/ColorUtils.bs"
namespace SponsorBlock
const API_URL = "https://sponsor.ajay.app"
const SKIP_SEGMENT_ENDPOINT = "/api/skipSegments"
const VIEWED_SEGMENT_ENDPOINT = "/api/viewedVideoSponsorTime"
function SegmentColor(category as string) as integer
map = m.SponsorBlockColors
if map = invalid
map = {
sponsor: &h00D400FF,
selfpromo: &hFFFF00FF,
exclusive_access: &h008A5CFF,
interaction: &hCC00FFFF,
poi_highlight: &hFF1684FF,
intro: &h00FFFFFF,
outro: &h0202EDFF,
preview: &h008FD6FF,
filler: &h7300FFFF,
music_offtopic: &hFF9900FF
}
m.SponsorBlockColors = map
function GetSponsorBlockConfig() as object
if m.sponsorBlockConfig = invalid
m.sponsorBlockConfig = ParseJson(ReadAsciiFile("libpkg:/config/sponsorblock_config.json"))
end if
if map.doesexist(category)
return map[category]
return m.sponsorBlockConfig
end function
function SegmentColor(category as string) as integer
config = SponsorBlock.GetSponsorBlockConfig()
if config = invalid
return 0
end if
if config.categories.doesexist(category)
color = config.categories[category].color
return ColorUtils.HexToInt(color)
end if
return 0
end function
function SegmentTitle(category as string) as string
map = m.SponsorBlockTitles
if map = invalid
map = {
sponsor: "Sponsor",
selfpromo: "Unpaid/Self Promotion",
exclusive_access: "Exclusive Access",
interaction: "Interaction Reminder (Subscribe)",
poi_highlight: "Highlight",
intro: "Intermission/Intro Animation",
outro: "Endcards/Credits",
preview: "Preview/Recap",
filler: "Filler Tangent/Jokes",
music_offtopic: "Non-Music Section"
}
m.SponsorBlockTitles = map
config = SponsorBlock.GetSponsorBlockConfig()
if config = invalid
return ""
end if
if map.doesexist(category)
return map[category]
if config.categories.doesexist(category)
return config.categories[category].title
end if
return ""
end function
function SegmentShortTitle(category as string) as string
config = SponsorBlock.GetSponsorBlockConfig()
if config = invalid
return ""
end if
if config.categories.doesexist(category)
return config.categories[category].short_title
end if
return ""
end function
@@ -0,0 +1,30 @@
namespace ColorUtils
function HexToInt(color as dynamic) as integer
if color = invalid
return 0
end if
if color.left(1) = "#"
color = color.mid(1)
end if
value = Val(color.mid(0, 2), 16) * 16777216 + Val(color.mid(2, 2), 16) * 65536 + Val(color.mid(4, 2), 16) * 256
if color.Len() = 6
value += 255
else if color.Len() = 8
value += Val(color.mid(6, 2), 16)
end if
return value
end function
function IntToHex(color as integer) as string
hexDigits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
hexString = "#"
for i = 7 to 0 step -1
hexString = hexString + hexDigits[(color >> (i * 4)) and &hF]
end for
return hexString
end function
end namespace
+10 -7
View File
@@ -1,17 +1,20 @@
function GetSha256(input as string) as string
buffer = CreateObject("roByteArray")
buffer.FromAsciiString(input)
digest = CreateObject("roEVPDigest")
digest.Setup("sha256")
return digest.Process(buffer)
return GetEvpDigest(input, "sha256")
end function
function GetSha1(input as string) as string
return GetEvpDigest(input, "sha1")
end function
function GetMd5(input as string) as string
return GetEvpDigest(input, "md5")
end function
function GetEvpDigest(input as string, method as string) as string
buffer = CreateObject("roByteArray")
buffer.FromAsciiString(input)
digest = CreateObject("roEVPDigest")
digest.Setup("sha1")
digest.Setup(method)
return digest.Process(buffer)
end function
-17
View File
@@ -1,17 +0,0 @@
function IsDebugMode() as boolean
appInfo = CreateObject("roAppInfo")
bsConst = appInfo.GetValue("bs_const")
symbols = bsConst.Tokenize(";")
for each symbol in symbols
keyValuePair = symbol.Tokenize("=")
if keyValuePair.Count() <> 2
continue for
end if
if UCase(keyValuePair[0]) = "DEBUG"
return UCase(keyValuePair[1]) = "TRUE"
end if
end for
return false
end function
+31 -17
View File
@@ -1,6 +1,6 @@
import "pkg:/source/utils/StringUtils.bs"
function GetLocalIpAddress() as string
function GetLocalIpAddress() as dynamic
if m.ipAddress = invalid or m.ipAddress = ""
di = CreateObject("roDeviceInfo")
ips = di.GetIPAddrs()
@@ -25,7 +25,9 @@ function GetAppInfo() as object
m.appInfo = {
id: appInfo.GetID(),
version: appInfo.GetVersion(),
lib_version: GetLibVersion()
git_commit_hash: appInfo.GetValue("git_commit_sha"),
lib_version: GetLibVersion(),
lib_git_commit_hash: GetLibGitCommitHash()
}
end if
return m.appInfo
@@ -41,22 +43,34 @@ function GetLibVersion() as string
return `${Major}.${Minor}.${Build}`
end function
function GetLibManifestValues() as object
libManifest = ReadAsciiFile("libpkg:/manifest")
lines = libManifest.Tokenize(UnixNL())
values = {}
for each line in lines
if line.left(1) = "#"
continue for
end if
keyValuePair = line.Tokenize("=")
if keyValuePair.Count() <> 2
continue for
end if
function GetLibGitCommitHash() as string
values = GetLibManifestValues()
values[keyValuePair[0]] = keyValuePair[1]
end for
return values
if values.doesexist("git_commit_sha")
return values["git_commit_sha"]
end if
return ""
end function
function GetLibManifestValues() as object
if m.linManifestValues = invalid
libManifest = ReadAsciiFile("libpkg:/manifest")
lines = libManifest.Tokenize(UnixNL())
values = {}
for each line in lines
if line.left(1) = "#"
continue for
end if
keyValuePair = line.Tokenize("=")
if keyValuePair.Count() <> 2
continue for
end if
values[keyValuePair[0]] = keyValuePair[1]
end for
m.linManifestValues = values
end if
return m.linManifestValues
end function
function GetDeviceInfo() as object
+5 -3
View File
@@ -13,7 +13,7 @@ namespace WebUtils
if Instr(0, component, "=")
keyValue = component.split("=")
key = keyValue[0]
value = keyValue[1]
value = keyValue[1].DecodeUriComponent()
hasValue = true
end if
@@ -22,11 +22,13 @@ namespace WebUtils
if GetInterface(oldValue, "ifArray") = invalid
oldValue = [oldValue]
end if
oldValue.push(value)
oldValue.push(value.DecodeUriComponent())
value = oldValue
end if
query[key] = value
if key <> ""
query[key] = value
end if
end for
return query
end function
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "playlet-web",
"version": "0.7.0",
"version": "0.8.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "playlet-web",
"version": "0.7.0",
"version": "0.8.0",
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^1.1.0",
"@tsconfig/svelte": "^3.0.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "playlet-web",
"version": "0.7.0",
"version": "0.8.0",
"type": "module",
"scripts": {
"dev": "vite",
+8 -1
View File
@@ -261,7 +261,14 @@ ${JSON.stringify(window.appState.invidious, null, 2)}
document.getElementById("app-version").innerText = `Version: ${appState.app.version}`
if (appState.invidious.logged_in) {
document.getElementById("logged-in").innerHTML = `Logged In: true (<a href="${appState.invidious.logged_in_instance}" target="_blank">${appState.invidious.logged_in_instance}</a>)`
let loggedIn = 'Logged In '
if (appState.invidious.logged_in_username) {
loggedIn += `as "${appState.invidious.logged_in_username}"`
} else {
loggedIn += ": true"
}
loggedIn += ` (<a href="${appState.invidious.logged_in_instance}" target="_blank">${appState.invidious.logged_in_instance}</a>)`
document.getElementById("logged-in").innerHTML = loggedIn
} else {
document.getElementById("logged-in").innerHTML = "Logged In: false"
}
+13 -10
View File
@@ -1,24 +1,27 @@
import { defineConfig } from 'vite'
import { defineConfig, UserConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import { readFileSync } from 'fs'
import { readFileSync, existsSync } from 'fs'
import { parse as dotEnvParse } from 'dotenv'
import { internalIpV4Sync } from 'internal-ip';
const envVars = dotEnvParse(readFileSync('../.vscode/.env'))
const PORT = 5173
// https://vitejs.dev/config/
/** @type {import('vite').UserConfig} */
export default defineConfig({
const config: UserConfig = {
plugins: [svelte()],
build: {
outDir: "../playlet-lib/src/www",
emptyOutDir: true
},
server: {
}
}
if (existsSync('../.vscode/.env')) {
const envVars = dotEnvParse(readFileSync('../.vscode/.env'))
config.server = {
host: true,
port: PORT,
open: `http://${internalIpV4Sync()}:${PORT}/?host=${envVars.ROKU_DEV_TARGET}:8888`
}
})
}
// https://vitejs.dev/config/
export default defineConfig(config)
+3 -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=7
minor_version=8
build_version=00000
## Channel Assets
@@ -27,4 +27,6 @@ playlet_lib_remote_url=https://github.com/iBicha/playlet/releases/latest/downloa
playlet_lib_embedded_url=pkg:/lib/playlet-lib.zip
playlet_lib_debug_url=http://DEBUG_HOST_IP_ADDRESS:8080/playlet-lib.zip
git_commit_sha=unknown
bs_const=DEBUG=false;WEB_SERVER_BASIC_AUTH=false;DASH_THUMBNAILS=false;WEB_SOCKETS=true
+129
View File
@@ -0,0 +1,129 @@
const fs = require('fs');
const path = require('path');
if (process.argv.length !== 3) {
console.error("Invalid usage! usage: npm run generate-sponsorblock-config -- sponsorblock_root");
exit(-1);
}
const PLAYLEY_CONFIG_PATH = "./playlet-lib/src/config/sponsorblock_config.json"
const sponsorblockRoot = process.argv[2];
const configExamplePath = path.join(sponsorblockRoot, "config.json.example")
const englishLocalePath = path.join(sponsorblockRoot, "public/_locales/en/messages.json")
let configExample = JSON.parse(fs.readFileSync(configExamplePath, { encoding: 'utf8', flag: 'r' }))
let englishLocale = JSON.parse(fs.readFileSync(englishLocalePath, { encoding: 'utf8', flag: 'r' }))
// https://github.com/ajayyy/SponsorBlock/blob/f4d80d88438ff31bc067ff480fd94112d972718d/src/config.ts#L251
const barTypes = {
"preview-chooseACategory": {
color: "#ffffff",
opacity: "0.7"
},
"sponsor": {
color: "#00d400",
opacity: "0.7"
},
"preview-sponsor": {
color: "#007800",
opacity: "0.7"
},
"selfpromo": {
color: "#ffff00",
opacity: "0.7"
},
"preview-selfpromo": {
color: "#bfbf35",
opacity: "0.7"
},
"exclusive_access": {
color: "#008a5c",
opacity: "0.7"
},
"interaction": {
color: "#cc00ff",
opacity: "0.7"
},
"preview-interaction": {
color: "#6c0087",
opacity: "0.7"
},
"intro": {
color: "#00ffff",
opacity: "0.7"
},
"preview-intro": {
color: "#008080",
opacity: "0.7"
},
"outro": {
color: "#0202ed",
opacity: "0.7"
},
"preview-outro": {
color: "#000070",
opacity: "0.7"
},
"preview": {
color: "#008fd6",
opacity: "0.7"
},
"preview-preview": {
color: "#005799",
opacity: "0.7"
},
"music_offtopic": {
color: "#ff9900",
opacity: "0.7"
},
"preview-music_offtopic": {
color: "#a6634a",
opacity: "0.7"
},
"poi_highlight": {
color: "#ff1684",
opacity: "0.7"
},
"preview-poi_highlight": {
color: "#9b044c",
opacity: "0.7"
},
"filler": {
color: "#7300FF",
opacity: "0.9"
},
"preview-filler": {
color: "#2E0066",
opacity: "0.7"
}
}
function getColor(obj) {
if (!obj) {
return "#FFFFFFC8"
}
const opacity = (Math.round(parseFloat(obj.opacity) * 255)).toString(16).toUpperCase().padStart(2, "0")
return obj.color + opacity;
}
let playletConfig = {
serverAddress: configExample.serverAddress,
categoryList: configExample.categoryList,
categories: {}
}
playletConfig.categoryList.forEach(categoryId => {
const category = {}
category.title = englishLocale[`category_${categoryId}`].message
category.short_title = englishLocale[`category_${categoryId}_short`]?.message ?? category.title;
category.categorySupport = configExample.categorySupport[categoryId];
category.color = getColor(barTypes[categoryId]);
playletConfig.categories[categoryId] = category;
});
fs.writeFileSync(PLAYLEY_CONFIG_PATH, JSON.stringify(playletConfig, null, 4));
+134 -66
View File
@@ -11,59 +11,51 @@ const ip = require('ip');
const config = dotenv.parse(fs.readFileSync('.vscode/.env'));
const PLAYLEY_SERVER = `http://${config.ROKU_DEV_TARGET}:8888`;
async function updateFeed(sourceUrl, destinationPlaylist, invidiousInstance, token, browser = undefined, limit = 50) {
console.log(`Updating playlist "${destinationPlaylist}" from feed "${sourceUrl}"`)
async function importInvidiousProfile(invidiousInstance, token, profile) {
console.log(`Importing Invidious profile`)
await fetch(`${invidiousInstance}/api/v1/auth/import/invidious`, {
headers: {
"Authorization": `Bearer ${token}`,
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(profile)
})
}
const videos = await extractVideos(sourceUrl, browser, limit);
async function generatePlaylist(sourceUrl, playlistName, browser = undefined, limit = 100) {
console.log(`Updating playlist "${playlistName}" from feed "${sourceUrl}"`);
let playlist = await getPlaylist(invidiousInstance, token, destinationPlaylist)
if (playlist) {
await deletePlaylist(invidiousInstance, token, playlist)
}
const videos = await extractYtDlp(sourceUrl, browser, limit);
playlist = await createPlaylist(invidiousInstance, token, destinationPlaylist)
for (let i = 0; i < videos.length; i++) {
const videoId = videos[i];
console.log(`Adding video "${videoId}" (${i + 1}/${videos.length}) to playlist "${playlist.title}"`)
await addPlaylistVideo(invidiousInstance, token, playlist, videoId)
return {
title: playlistName,
description: "Imported from Youtube",
privacy: "private",
videos: videos
};
}
async function deletePlaylists(invidiousInstance, token, playlistNames) {
const playlistsToDelete = (await getPlaylists(invidiousInstance, token))
.filter(playlist => playlistNames.indexOf(playlist.title) !== -1);
for (let i = 0; i < playlistsToDelete.length; i++) {
const playlist = playlistsToDelete[i];
await deletePlaylist(invidiousInstance, token, playlist);
}
}
async function getPlaylist(invidiousInstance, token, playlistName) {
console.log(`Finding playlist ${playlistName}`)
async function getPlaylists(invidiousInstance, token) {
console.log(`Finding playlists`)
const response = await fetch(`${invidiousInstance}/api/v1/auth/playlists`, {
headers: {
"Authorization": `Bearer ${token}`
}
})
const playlists = await response.json()
return playlists.find(p => p.title === playlistName);
}
async function createPlaylist(invidiousInstance, token, playlistName) {
console.log(`Creating playlist "${playlistName}"`)
const response = await fetch(`${invidiousInstance}/api/v1/auth/playlists`, {
headers: {
"Authorization": `Bearer ${token}`,
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({ title: playlistName, privacy: "private" })
})
return await response.json()
}
async function addPlaylistVideo(invidiousInstance, token, playlist, videoId) {
await fetch(`${invidiousInstance}/api/v1/auth/playlists/${playlist.playlistId}/videos`, {
headers: {
"Authorization": `Bearer ${token}`,
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({ videoId: videoId })
})
}
async function deletePlaylist(invidiousInstance, token, playlist) {
console.log(`Playlist "${playlist.title}" exists. Deleting.`)
await fetch(`${invidiousInstance}/api/v1/auth/playlists/${playlist.playlistId}`, {
@@ -74,11 +66,59 @@ async function deletePlaylist(invidiousInstance, token, playlist) {
})
}
async function extractVideos(sourceUrl, browser = undefined, limit = 100) {
console.log(`Extracting videos from feed "${sourceUrl}" with limit "${limit}"`)
async function extractYtDlpPlaylists(browser) {
console.log(`Extracting playlists`)
return await new Promise(function (resolve, reject) {
let ytDlpErrors = ""
const videos = []
const items = []
args = ["https://www.youtube.com/feed/library", '--flat-playlist', '--lazy-playlist', '--dump-json', '--cookies-from-browser', browser]
const ytDlpProcess = spawn('yt-dlp', args);
ytDlpProcess.stdout.on('data', function (data) {
process.stdout.write('.')
newItems = data.toString()
.split('\n')
.map(item => item.trim())
.filter(i => i);
newItems.forEach(item => {
try {
const json = JSON.parse(item);
if (json.url?.startsWith("https://www.youtube.com/playlist?list")) {
items.push({
url: json.url,
title: json.title
})
}
} catch (error) {
console.error(error)
ytDlpErrors += error
}
});
});
ytDlpProcess.stderr.on('data', function (data) {
process.stdout.write('.')
ytDlpErrors += data.toString() + '\n'
});
ytDlpProcess.on('close', function (code) {
process.stdout.write('\n')
if (code === 0) {
resolve(items)
} else {
reject({ code: code, error: ytDlpErrors })
}
});
})
}
async function extractYtDlp(sourceUrl, browser = undefined, limit = 100) {
console.log(`Extracting from "${sourceUrl}" with limit "${limit}"`)
return await new Promise(function (resolve, reject) {
let ytDlpErrors = ""
const items = []
args = [sourceUrl, '--flat-playlist', '--lazy-playlist', '--print', '%(id)s']
if (browser) {
@@ -88,19 +128,19 @@ async function extractVideos(sourceUrl, browser = undefined, limit = 100) {
ytDlpProcess.stdout.on('data', function (data) {
process.stdout.write('.')
if (videos.length > limit) {
if (limit > 0 && items.length > limit) {
return;
}
newVideos = data.toString()
newItems = data.toString()
.split('\n')
.map(video => video.trim())
.map(item => item.trim())
.filter(i => i);
newVideos.forEach(video => {
videos.push(video)
newItems.forEach(item => {
items.push(item)
});
if (videos.length >= limit) {
if (limit > 0 && items.length >= limit) {
ytDlpProcess.kill()
}
});
@@ -112,8 +152,8 @@ async function extractVideos(sourceUrl, browser = undefined, limit = 100) {
ytDlpProcess.on('close', function (code) {
process.stdout.write('\n')
if (code === 0 || videos.length === limit) {
resolve(videos)
if (code === 0 || (limit > 0 && items.length === limit)) {
resolve(items)
} else {
reject({ code: code, error: ytDlpErrors })
}
@@ -170,7 +210,6 @@ async function deleteAccessToken(invidiousInstance, token) {
method: "POST",
body: token
})
}
(async () => {
@@ -183,28 +222,57 @@ async function deleteAccessToken(invidiousInstance, token) {
parser.add_argument('--browser', { help: 'Use cookies from browser' });
parser.add_argument('--invidious', { help: 'Invidious instance to sync to' });
parser.add_argument('--output-file', { help: 'Write profile to Invidious JSON compatible file' });
parser.add_argument('--playlist-limit', { help: 'Maximum playlist video count', default: 500 });
let args = parser.parse_args()
invidiousInstance = args.invidious
browser = args.browser
outputFile = args.output_file
playlistLimit = args.playlist_limit
if (!invidiousInstance) {
try {
invidiousInstance = await getInvidiousInstance()
} catch (error) {
throw new Error(`Could not connect to Playlet at ${PLAYLEY_SERVER}\n${error}`)
const profile = { playlists: [] }
profile.playlists.push(await generatePlaylist("https://www.youtube.com", "Recommended", browser, playlistLimit))
const playlistsToDelete = ["Recommended"]
if (browser) {
console.log("Updating subscriptions")
profile.subscriptions = await extractYtDlp("https://www.youtube.com/feed/channels", browser, -1)
console.log("Updating watch history")
profile.watch_history = await extractYtDlp("https://www.youtube.com/feed/history", browser, playlistLimit)
const playlists = await extractYtDlpPlaylists(browser);
for (let i = 0; i < playlists.length; i++) {
const playlist = playlists[i];
try {
profile.playlists.push(await generatePlaylist(playlist.url, playlist.title, browser, playlistLimit))
playlistsToDelete.push(playlist.title)
} catch (error) {
console.log(error)
}
}
}
token = await getAccessToken(invidiousInstance)
await updateFeed("https://www.youtube.com/", "Youtube - Recommended", invidiousInstance, token, browser)
if (browser) {
await updateFeed("https://www.youtube.com/feed/subscriptions", "Youtube - Subscriptions", invidiousInstance, token, browser)
await updateFeed("https://www.youtube.com/playlist?list=WL", "Youtube - Watch later", invidiousInstance, token, browser)
await updateFeed("https://www.youtube.com/playlist?list=LL", "Youtube - Liked Videos", invidiousInstance, token, browser)
await updateFeed("https://www.youtube.com/feed/history", "Youtube - History", invidiousInstance, token, browser)
if (outputFile) {
console.log(`Writing profile to ${outputFile}`)
fs.writeFileSync(outputFile, JSON.stringify(profile, null, 2))
} else {
if (!invidiousInstance) {
try {
invidiousInstance = await getInvidiousInstance()
} catch (error) {
throw new Error(`Could not connect to Playlet at ${PLAYLEY_SERVER}\n${error}`)
}
}
token = await getAccessToken(invidiousInstance)
await deletePlaylists(invidiousInstance, token, playlistsToDelete)
await importInvidiousProfile(invidiousInstance, token, profile);
}
}
catch (error) {
console.error(error);
@@ -213,7 +281,7 @@ async function deleteAccessToken(invidiousInstance, token) {
if (token) {
console.log("Deleting token")
await deleteAccessToken(invidiousInstance, token)
console.log("Done!")
}
console.log("Done!")
}
})();
+25
View File
@@ -0,0 +1,25 @@
const fs = require('fs');
const shell = require('shelljs');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
const gitStatus = shell.exec('git status --porcelain=v1');
if (gitStatus.stdout !== '') {
shell.echo('Found changed files. Aborting.');
shell.exit(1);
}
const gitCommitHash = shell.exec('git rev-parse HEAD').stdout.trim();
["playlet/src/manifest", "playlet-lib/src/manifest"].forEach(function (manifestPath) {
let appManifestContent = fs.readFileSync(manifestPath, { encoding: 'utf8', flag: 'r' });
const gitHashPattern = /git_commit_sha=(\w+)/;
appManifestContent = appManifestContent.replace(gitHashPattern, `git_commit_sha=${gitCommitHash}`);
fs.writeFileSync(manifestPath, appManifestContent);
})
+2 -2
View File
@@ -1,4 +1,3 @@
const path = require('path');
const fs = require('fs');
const { execSync } = require("child_process");
@@ -24,4 +23,5 @@ const parsedVersion = semverParse(version);
fs.writeFileSync(manifestPath, appManifestContent);
})
execSync(`npm version ${version} --allow-same-version`, { cwd: 'playlet-web' });
execSync(`npm version ${version} --allow-same-version --no-git-tag-version`);
execSync(`npm version ${version} --allow-same-version --no-git-tag-version`, { cwd: 'playlet-web' });