Create Component Library (#43)

* Move src under playlet-lib

* Update configuration

* Update script

* Update script

* Working version

* Vs code config WIP

* Package lock sync

* Lint fix

* Fix images

* Reuse config files

* Kind of a working setup

* Lock node version

* Rename scripts to tools

* Fix build scripts, lib url system

* Lint fix

* rale

* Fix args and web server

* Load fallbacks and build script cleanups

* Remove unused method

* no message

* no message

* Remove generic message field

* Lint fix

* no message

* Use loading indicator on main app

* Add playlet lib version to settings

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>
This commit is contained in:
Brahim Hadricheandgithub-action linter authored and GitHub committed 2023-01-29 16:50:28 -05:00
1 parent 90df81df4b
commit 9d8a3d1cea
156 files changed
+3341 -213

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
Roku Advanced Layout Editor
Copyright © 2022 Roku, Inc.
The Roku Advanced Layout Editor and associated documentation (collectively, the “Software”)
is licensed under the Apache License, Version 2.0 (the "License");
you may not use this Software except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, the Software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
File diff suppressed because it is too large. Load diff
+198
View File
@@ -0,0 +1,198 @@
import {
CompilerPlugin,
BscFile,
BeforeFileTranspileEvent,
isBrsFile,
WalkMode,
createVisitor,
DiagnosticSeverity,
Program,
FunctionStatement,
BeforeFileValidateEvent,
} from 'brighterscript';
declare type FunctionInFile = {
functionStatement: FunctionStatement,
file: BscFile
}
export class AsyncTaskPlugin implements CompilerPlugin {
public name = 'asyncTaskPlugin';
private asyncTaskFunctions: FunctionInFile[] = []
private duplicatesReporeted: FunctionInFile[] = []
beforeProgramValidate(program: Program) {
this.asyncTaskFunctions = []
this.duplicatesReporeted = []
}
beforeFileValidate(event: BeforeFileValidateEvent) {
if (!isBrsFile(event.file)) {
return
}
event.file.ast.walk(createVisitor({
FunctionExpression: (func) => {
if (!this.isAsyncTask(func.functionStatement)) {
return
}
this.asyncTaskFunctions.push({
file: event.file,
functionStatement: func.functionStatement!
})
},
}), {
walkMode: WalkMode.visitExpressionsRecursive
});
}
afterFileValidate(file: BscFile) {
if (!isBrsFile(file)) {
return
}
const functionsWithDuplicates = this.getFunctionsWithDuplicatesForFile(file);
for (let index = 0; index < functionsWithDuplicates.length; index++) {
const fn = functionsWithDuplicates[index];
if (this.duplicatesReporeted.indexOf(fn) !== -1) {
continue
}
file.addDiagnostics([{
code: 6661,
message: `Duplicate async task '${fn.functionStatement.name.text}', use a different function name`,
range: fn.functionStatement.range,
file: fn.file,
source: "AsyncTaskPlugin",
severity: DiagnosticSeverity.Error,
}])
this.duplicatesReporeted.push(fn)
}
}
beforeFileTranspile(event: BeforeFileTranspileEvent) {
if (!isBrsFile(event.file)) {
return
}
const functions = this.asyncTaskFunctions
.filter((fn) => fn.file === event.file)
if (functions.length === 0) {
return
}
event.file.ast.walk(createVisitor({
FunctionExpression: (func) => {
if (!this.isAsyncTask(func.functionStatement)) {
return
}
const functionName = func.functionStatement!.name.text
const hasParams = func.functionStatement!.func.parameters.length > 0
const taskName = `${functionName}_asynctask`
const bs = this.generateBsTask(functionName, hasParams, event.file)
const bsFile = `components/asynctasks/generated/${taskName}.bs`
const xml = this.generateXmlTask(taskName, bsFile)
const xmlFile = `components/asynctasks/generated/${taskName}.xml`
event.program.setFile(xmlFile, xml)
event.program.setFile(bsFile, bs)
},
}), {
walkMode: WalkMode.visitExpressionsRecursive
});
}
isAsyncTask(functionStatement: FunctionStatement | undefined) {
const annotations = functionStatement?.annotations
if (!annotations || annotations.length === 0) {
return false
}
for (let index = 0; index < annotations.length; index++) {
const annotation = annotations[index];
if (annotation.name === "asynctask") {
return true
}
}
return false
}
getFunctionsWithDuplicatesForFile(filterFile: BscFile) {
const fileFunctions = this.asyncTaskFunctions
.filter((fn) => fn.file === filterFile)
if (fileFunctions.length === 0) {
return []
}
const uniqueNames: { [name: string]: FunctionInFile | undefined } = {}
const duplicatesNames: { [name: string]: boolean } = {}
const duplicates: FunctionInFile[] = []
for (var i = 0; i < this.asyncTaskFunctions.length; i++) {
const fnName = this.asyncTaskFunctions[i].functionStatement.name.text.toLowerCase()
if (duplicatesNames[fnName]) {
duplicates.push(this.asyncTaskFunctions[i])
continue
}
if (uniqueNames[fnName]) {
duplicates.push(uniqueNames[fnName]!)
uniqueNames[fnName] = undefined
duplicatesNames[fnName] = true
duplicates.push(this.asyncTaskFunctions[i])
continue
}
uniqueNames[fnName] = this.asyncTaskFunctions[i]
}
return duplicates
}
generateBsTask(functionName: string, hasInput: boolean, file: BscFile): string {
return `
import "pkg:/${file.pkgPath}"
function Init()
m.top.functionName = "TaskMain"
end function
function TaskMain()
try
result = ${functionName}(${(hasInput ? "m.top.input" : "")})
m.top.setField("output", {
success: true,
result: result
})
catch e
m.top.setField("output", {
success: false,
error: e
})
end try
end function
`
}
generateXmlTask(taskName: string, bsFile: string): string {
return `<?xml version="1.0" encoding="UTF-8" ?>
<component name="${taskName}" extends="Task">
<interface>
<field id="input" type="assocarray" />
<field id="output" type="assocarray" />
</interface>
<script type="text/brightscript" uri="pkg:/${bsFile}" />
</component>`
}
}
export default () => {
return new AsyncTaskPlugin();
};
+76
View File
@@ -0,0 +1,76 @@
const fs = require('fs');
const path = require('path');
const { convertFile } = require('convert-svg-to-png');
const logoPoster = './playlet/src/images/vector/logo-light.svg';
const logoSplash = './playlet/src/images/vector/logo-dark.svg';
const logoOutput = {
// Logo
"splash-screen_fhd.jpg": {
width: 1920,
height: 1080,
background: "#242424",
from: logoSplash
},
"splash-screen_hd.jpg": {
width: 1280,
height: 720,
background: "#242424",
from: logoSplash
},
"splash-screen_sd.jpg": {
width: 720,
height: 480,
background: "#242424",
from: logoSplash
},
"channel-poster_fhd.png": {
width: 540,
height: 405,
background: "#FFFFFF",
from: logoPoster
},
"channel-poster_hd.png": {
width: 290,
height: 218,
background: "#FFFFFF",
from: logoPoster
},
"channel-poster_sd.png": {
width: 246,
height: 140,
background: "#FFFFFF",
from: logoPoster
},
};
const iconsInput = './playlet/src/images/vector/icons';
const iconsOutput = './playlet-lib/src/images/icons';
(async () => {
for (var logo in logoOutput) {
await convertFile(logoOutput[logo].from, {
outputFilePath: './playlet/src/images/' + logo,
background: logoOutput[logo].background,
height: logoOutput[logo].height,
width: logoOutput[logo].width,
});
console.log(`Generated ${logo}`);
}
const iconFiles = fs.readdirSync(iconsInput);
for (var i in iconFiles) {
const input = path.join(iconsInput, iconFiles[i]);
const output = path.join(iconsOutput, iconFiles[i].replace('.svg', '.png'));
await convertFile(input, {
outputFilePath: output,
width: 64,
height: 64,
});
console.log(`Generated ${output}`);
}
})();
+28
View File
@@ -0,0 +1,28 @@
import {
CompilerPlugin,
ProgramBuilder,
FileObj
} from 'brighterscript';
import path from 'path';
import fs from 'fs';
export class ManifestBsConstDebugPlugin implements CompilerPlugin {
public name = 'manifestBsConstDebugPlugin';
beforePublish(builder: ProgramBuilder, files: FileObj[]) {
const debugFlag = process.argv.find(arg => /--debug=(true|false)/i.test(arg))
if (!debugFlag) {
return;
}
const value = /--debug=(true|false)/i.exec(debugFlag)![1].toLowerCase()
builder.logger.log(`Setting bs_const DEBUG to ${value}`)
const manifestPath = path.join(builder.options.stagingDir!, "manifest")
let manifestContent = fs.readFileSync(manifestPath, { encoding: 'utf8', flag: 'r' })
manifestContent = manifestContent.replace(/DEBUG=(true|false)/i, `DEBUG=${value}`);
fs.writeFileSync(manifestPath, manifestContent)
}
}
export default () => {
return new ManifestBsConstDebugPlugin();
};
+219
View File
@@ -0,0 +1,219 @@
// This script reads recommendations, subscriptions, watch later, liked, and history from Youtube
// and imports them into invidious.
const { ArgumentParser } = require('argparse')
const fs = require('fs');
const dotenv = require('dotenv');
const spawn = require('child_process').spawn;
const express = require('express')
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}"`)
const videos = await extractVideos(sourceUrl, browser, limit);
let playlist = await getPlaylist(invidiousInstance, token, destinationPlaylist)
if (playlist) {
await deletePlaylist(invidiousInstance, token, playlist)
}
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)
}
}
async function getPlaylist(invidiousInstance, token, playlistName) {
console.log(`Finding playlist ${playlistName}`)
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}`, {
headers: {
"Authorization": `Bearer ${token}`,
},
method: "DELETE"
})
}
async function extractVideos(sourceUrl, browser = undefined, limit = 100) {
console.log(`Extracting videos from feed "${sourceUrl}" with limit "${limit}"`)
return await new Promise(function (resolve, reject) {
let ytDlpErrors = ""
const videos = []
args = [sourceUrl, '--flat-playlist', '--lazy-playlist', '--print', '%(id)s']
if (browser) {
args.push('--cookies-from-browser', browser)
}
const ytDlpProcess = spawn('yt-dlp', args);
ytDlpProcess.stdout.on('data', function (data) {
process.stdout.write('.')
if (videos.length > limit) {
return;
}
newVideos = data.toString()
.split('\n')
.map(video => video.trim())
.filter(i => i);
newVideos.forEach(video => {
videos.push(video)
});
if (videos.length >= limit) {
ytDlpProcess.kill()
}
});
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 || videos.length === limit) {
resolve(videos)
} else {
reject({ code: code, error: ytDlpErrors })
}
});
})
}
async function getInvidiousInstance() {
const state = await (await fetch(`${PLAYLEY_SERVER}/api/state?key=invidious`)).json()
if (!state.invidious.logged_in) {
throw new Error("Playlet not logged in")
}
console.log(`Invidious instance: ${state.invidious.logged_in_instance}`)
return state.invidious.logged_in_instance;
}
async function getAccessToken(invidiousInstance) {
return new Promise(function (resolve, reject) {
let server = undefined;
const app = express()
const port = 55432
app.get('/invidious/token_callback', (req, res) => {
if (!req.query.token) {
console.warn('No token received on /invidious/token_callback')
res.status(400).send('No token received on /invidious/token_callback')
return
}
token = decodeURIComponent(decodeURIComponent(req.query.token))
resolve(token)
console.log(`Access token received: ${token}`)
res.send("Token received. You can close this window now.")
server.close()
})
const scope = ":*"
const expire = Date.now() + 60 * 60 * 2;
const callbackUrl = `http://${ip.address()}:${port}/invidious/token_callback`
const authLink = `${invidiousInstance}/authorize_token?scopes=${scope}&callback_url=${callbackUrl}&expire=${expire}`
server = app.listen(port, () => {
console.log(`server is listening on http://localhost:${port}`);
console.log(`Login using your browser: ${authLink}`)
});
})
}
async function deleteAccessToken(invidiousInstance, token) {
await fetch(`${invidiousInstance}/api/v1/auth/tokens/unregister`, {
headers: {
"Authorization": `Bearer ${token}`,
'Content-Type': 'application/json'
},
method: "POST",
body: token
})
}
(async () => {
let invidiousInstance = undefined
let token = undefined;
try {
const parser = new ArgumentParser({
description: 'Sync Youtube profile with Invidious'
});
parser.add_argument('--browser', { help: 'Use cookies from browser' });
parser.add_argument('--invidious', { help: 'Invidious instance to sync to' });
let args = parser.parse_args()
invidiousInstance = args.invidious
browser = args.browser
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 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)
}
}
catch (error) {
console.error(error);
}
finally {
if (token) {
console.log("Deleting token")
await deleteAccessToken(invidiousInstance, token)
console.log("Done!")
}
}
})();
+29
View File
@@ -0,0 +1,29 @@
const rokuDeploy = require('roku-deploy');
const dotenv = require('dotenv');
const fs = require('fs');
const { exit } = require('process');
if(process.argv.length !== 3) {
console.error("Invalid usage! usage: npm run screenshot -- filename");
exit(-1);
}
const filename = process.argv[2];
const config = dotenv.parse(fs.readFileSync('.vscode/.env'));
const options = {
host: config.ROKU_DEV_TARGET,
password: config.ROKU_DEVPASSWORD,
outDir: '.',
outFile: filename
};
(async () => {
try {
await rokuDeploy.takeScreenshot(options);
console.log(`${filename} created`);
}
catch (error) {
console.error(error);
}
})();
+28
View File
@@ -0,0 +1,28 @@
const dotenv = require('dotenv');
const fs = require('fs');
const rokuDeploy = require('roku-deploy');
const config = dotenv.parse(fs.readFileSync('.vscode/.env'));
const options = {
host: config.ROKU_DEV_TARGET,
password: config.ROKU_DEVPASSWORD,
outDir: 'release',
outFile: 'playlet.zip',
failOnCompileError: true,
stagingDir: 'dist/build/playlet',
retainStagingDir: true,
signingPassword: config.ROKU_SIGN_PASSWORD,
};
(async () => {
try {
await rokuDeploy.publish(options);
const remotePkgPath = await rokuDeploy.signExistingPackage(options);
const localPkgFilePath = await rokuDeploy.retrieveSignedPackage(remotePkgPath, options);
console.log(`Created signed package: ${localPkgFilePath}`)
}
catch (error) {
console.error(error);
}
})();
+27
View File
@@ -0,0 +1,27 @@
const path = require('path');
const fs = require('fs');
const { execSync } = require("child_process");
const semverParse = require('semver/functions/parse');
const packageJsonContent = fs.readFileSync("./package.json", { encoding: 'utf8', flag: 'r' });
const packageJson = JSON.parse(packageJsonContent);
const version = packageJson.version;
const parsedVersion = semverParse(version);
["playlet/src/manifest", "playlet-lib/src/manifest"].forEach(function (manifestPath) {
let appManifestContent = fs.readFileSync(manifestPath, { encoding: 'utf8', flag: 'r' });
const majorPattern = /major_version=(\d+)/;
const minorPattern = /minor_version=(\d+)/;
const buildPattern = /build_version=(\d+)/;
appManifestContent = appManifestContent.replace(majorPattern, `major_version=${parsedVersion.major}`);
appManifestContent = appManifestContent.replace(minorPattern, `minor_version=${parsedVersion.minor}`);
appManifestContent = appManifestContent.replace(buildPattern, `build_version=${String(parsedVersion.patch).padStart(5, '0')}`);
fs.writeFileSync(manifestPath, appManifestContent);
})
execSync(`npm version ${version} --allow-same-version`, { cwd: 'playlet-web' });