Ajout peertubeRequester

This commit is contained in:
Amaury 2021-07-09 14:26:23 +02:00
parent 4f6587e1f6
commit 81f540e29d
5 changed files with 714 additions and 533 deletions

122
lib/peertubeRequester.ts Normal file
View File

@ -0,0 +1,122 @@
// import { ImplementableApi } from './implementableApi';
// Api request lib
import fetch, { FetchError, Headers } from "node-fetch";
import { URLSearchParams } from "url";
import FormData from "form-data";
// import dedent from "ts-dedent";
namespace PeerTubeRequester {
export type Config = {
domain_name: string;
username: string;
password: string;
};
}
type UploadInstruction = {
[key: string]: string;
channelId: string;
targetUrl: string;
};
type ClientToken = {
client_id: string;
client_secret: string;
grant_type: "password";
response_type: "code";
username: string;
password: string;
};
type UserToken = {
access_token: string;
token_type: string;
expires_in: string;
refresh_token: string;
};
class PeerTubeRequester {
readonly domain_name: string;
readonly username: string;
readonly password: string;
constructor(readonly config: PeerTubeRequester.Config) {
this.domain_name = config.domain_name;
this.username = config.username;
this.password = config.password;
}
async apiRequest(message: UploadInstruction): Promise<void> {
let response = await fetch(
`${this.domain_name}/api/v1/oauth-clients/local`
);
if (!response.ok) {
throw new Error(response.statusText); // CRASH
}
const { client_id, client_secret } = await response.json();
const client_info: { [key: string]: string } = {
client_id,
client_secret,
grant_type: "password",
response_type: "code",
username: this.username,
password: this.password,
};
let myParams = new URLSearchParams();
for (const key in client_info) myParams.append(key, client_info[key]);
response = await fetch(`${this.domain_name}/api/v1/users/token`, {
method: "post",
body: myParams,
});
if (!response.ok) {
throw new Error(response.statusText); // CRASH
}
const { access_token } = await response.json();
// Upload
const myUploadForm = new URLSearchParams();
const myHeader = new Headers();
myHeader.append("Authorization", `Bearer ${access_token}`);
for (const key in message) myUploadForm.append(key, message[key]);
response = await fetch(`${this.domain_name}/api/v1/videos/imports`, {
method: "post",
// headers: myHeader,
body: myUploadForm,
});
if (!response.ok) {
switch (response.status) {
case 400:
throw new Error(
`Your target URL was not accepted by the API.\
Actualy it's : ${message.targetUrl}
${response.statusText}`
);
break;
case 403:
throw new Error(response.statusText);
break;
case 409:
throw new Error(
`Oops, your instance had not allowed the HTTPS import.\
Contact your administrator.
${response.statusText}`
);
break;
default:
throw new Error(
`Oh, you resolved an undocumented issues.\
Please report this on the git if you have the time.
ERROR: ${response.statusText}`
);
break;
}
}
}
}
export { PeerTubeRequester };

998
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,38 +1,39 @@
{
"name": "peertube-plugin-auto-import-ytb",
"description": "PeerTube plugin quickstart",
"version": "0.0.2",
"author": "AmauryJOLY",
"bugs": "https://framagit.org/framasoft/peertube/peertube-plugin-quickstart/issues",
"clientScripts": [],
"css": [],
"devDependencies": {
"ts-node": "^10.0.0",
"typescript": "^4.3.4"
},
"engine": {
"peertube": ">=3.2.0"
},
"homepage": "https://framagit.org/framasoft/peertube/peertube-plugin-quickstart",
"keywords": [
"peertube",
"plugin"
],
"library": "./dist/main.js",
"files": [
"dist/",
"README.md"
],
"scripts": {
"buildAndDeploy": "npm run build && npm run deploy",
"deploy": "bash ./scripts/deploy.sh",
"build": "tsc"
},
"staticDirs": {},
"translations": {},
"dependencies": {
"form-data": "^4.0.0",
"listener-rss-agregator": "file:/tmp/tmp.lX4jI4rkxi/listener-rss-agregator",
"node-fetch": "^2.6.1"
}
"name": "peertube-plugin-auto-import-ytb",
"description": "PeerTube plugin quickstart",
"version": "0.0.2",
"author": "AmauryJOLY",
"bugs": "https://framagit.org/framasoft/peertube/peertube-plugin-quickstart/issues",
"clientScripts": [],
"css": [],
"devDependencies": {
"ts-node": "^10.0.0",
"typescript": "^4.3.4"
},
"engine": {
"peertube": ">=3.2.0"
},
"homepage": "https://framagit.org/framasoft/peertube/peertube-plugin-quickstart",
"keywords": [
"peertube",
"plugin"
],
"library": "./dist/src/main.js",
"files": [
"dist/",
"README.md"
],
"scripts": {
"buildAndDeploy": "npm run build && npm run deploy",
"deploy": "bash ./scripts/deploy.sh",
"build": "tsc"
},
"staticDirs": {},
"translations": {},
"dependencies": {
"@types/node-fetch": "^2.5.11",
"form-data": "^4.0.0",
"listener-rss-agregator": "file:/tmp/tmp.lX4jI4rkxi/listener-rss-agregator",
"node-fetch": "^2.6.1"
}
}

View File

@ -1,12 +1,16 @@
import { ListenerRssAggregator } from "listener-rss-agregator";
import { ListenerRSSInfos } from "listener-rss";
import { PeerTubeRequester } from "../lib/peertubeRequester";
type ListenerData = {
ChannelId: number;
type ListenerData = ListenerRSSInfos & {
address: string;
channelId: string;
};
let myManager: ListenerRssAggregator;
let listenersDataBinding = new Map<string, ListenerData>();
let logger: any;
let peertube: PeerTubeRequester;
import * as path from "path";
import fs from "fs";
@ -33,6 +37,12 @@ async function register({
);
myManager = new ListenerRssAggregator(configAggregator);
peertube = new PeerTubeRequester({
domain_name: "localhost:9000",
username: "root",
password: "test",
});
logger.warn("Aggregator created");
const inputs = await settingsManager.getSetting("ytb-urls");
@ -48,7 +58,17 @@ async function register({
const datas = listenersDataBinding.get(entries.addressListener);
if (!datas) return;
logger.warn("Nouvelles entrées détéctées: " + JSON.stringify(entries));
logger.warn(
"Nouvelles entrées détéctées: " +
JSON.stringify(entries) +
" de " +
datas.channelId
);
for (const item of entries.items)
peertube.apiRequest({
channelId: datas.channelId,
targetUrl: item.link,
});
});
}
@ -68,11 +88,7 @@ async function addListeners(listenerInput: string) {
);
for (const newItem of newListeners) {
listenersDataBinding.set(newItem.address, {
ChannelId: newItem.ChannelId,
firstUpdate: true,
address: newItem.address,
});
listenersDataBinding.set(newItem.address, newItem);
}
for (const removedUrl of removedUrls) {
listenersDataBinding.delete(removedUrl);
@ -80,7 +96,6 @@ async function addListeners(listenerInput: string) {
myManager.stopAll();
await myManager.saveOverride(listeners);
firstUpdate = true;
if (logger) logger.warn("Configuration modifiée: " + listenerInput);

View File

@ -4,8 +4,8 @@
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
@ -14,8 +14,8 @@
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist/", /* Redirect output structure to the directory. */
"rootDir": "./src/", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"outDir": "./dist/" /* Redirect output structure to the directory. */,
// "rootDir": "./src/", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
@ -25,7 +25,7 @@
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
@ -47,11 +47,14 @@
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
"rootDirs": [
"./src/",
"./lib/"
] /* List of root folders whose combined content represents the structure of the project at runtime. */,
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
@ -66,7 +69,7 @@
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}