add a command to share recording on oisux nextcloud

This commit is contained in:
Association Oisux 2022-10-31 22:56:37 +01:00
parent dc65dbebf1
commit 8f79521cf5
10 changed files with 1440 additions and 3956 deletions

View File

@ -22,6 +22,8 @@ Built to be jusT cOol 👌🦄 !
Built while listening to [Nyan Cat](https://www.youtube.com/watch?v=QH2-TGUlwu4) 😛
**Guillaume**: and also for halloween night [Frank Zappa](https://www.youtube.com/watch?v=Mj1H2qhHuqI&list=PLIJmYQvaDU3GuFYKPiP2RsbLjXL2JbZIr&index=76) 🎃
---
<p align="center"><img src="/img/trending.png?raw=true"/></p>
@ -87,6 +89,18 @@ Built while listening to [Nyan Cat](https://www.youtube.com/watch?v=QH2-TGUlwu4)
* Letter spacing.
* Theme.
# Pour les membres de l'association Oisux
Je vous invite à consulter:
- [l'installation](#installation)
- la génération d'une configuration [globale](#configuration-globale) ou [locale](#configuration-locale)
- [l'insertion des identifiants NextCloud dans le fichier de configuration](#identifiants-nextcloud)
- [l'enregistrement d'une session de terminal](#enregistrement)
- [le partage du fichier enregistré dans le dossier terminalizer dans NextCloud](#partager)
Pour le reste, je vous laisse traduire.
# What's Next
* The `Generate` command to generate a web player for a recording file.
@ -94,10 +108,10 @@ Built while listening to [Nyan Cat](https://www.youtube.com/watch?v=QH2-TGUlwu4)
# Installation
You need to install [Node.js](https://nodejs.org/en/download/) first, then install the tool globally using this command:
Vous aurez besoin d'installer [Node.js](https://nodejs.org/en/download/) en premier, puis dans un terminal:
```bash
npm install -g terminalizer
npm install -g git+https://git.weblib.re/guillaume_oisux/terminalizer.git
```
<p align="center"><img src="/img/install.gif?raw=true"/></p>
@ -106,6 +120,18 @@ npm install -g terminalizer
The installation should be very smooth with Node.js v4-v16. For newer versions, if the installation is failed, you may need to install the development tools to build the `C++` add-ons. Check [node-gyp](https://github.com/nodejs/node-gyp#installation).
# Identifiants NextCloud
Vous aurez besoin de renseigner dans le fichier de configuration vos identifiants NextCloud. Remplacer le username par votre nom d'utilisateur et le password par votre mot de passe.
```yaml
webdav:
username: guillaume
password: xxxxxxxxxx
```
**Votre mot de passe ne sera pas partagé lors de la transmission du fichier d'enregistrement sur NextCloud**
# Getting Started
Start recording your terminal using the `record` command.
@ -138,28 +164,30 @@ GIF compression is not implemented yet. For now we recommend [https://gifcompres
terminalizer <command> [options]
```
## Init
## Configuration globale
> Create a global config directory
> Création d'une configuration globale
```bash
terminalizer init
```
## Config
> Puis
> Generate a config file in the current directory
## Configuration locale
> Génère un fichier de configuration dans le répertoire courant
```bash
terminalizer config
```
## Record
## Enregistrement
> Record your terminal and create a recording file
> Enregistrement du terminal dans un fichier
```bash
terminalizer record <recordingFile>
terminalizer record <nom_du_fichier_yml_sans_son_extension>
```
Options
@ -216,6 +244,14 @@ Options
terminalizer share <recordingFile>
```
## Partager
> Upload du fichier sur le NextCloud de l'association Oisux (nécessite d'être dans le groupe CA)
```bash
terminalizer partager <nom_du_fichier_yml_sans_son_extension>
```
## Generate
> Generate a web player for a recording file

3
app.js
View File

@ -18,6 +18,7 @@ global.ROOT_PATH = __dirname;
// The base url of the Terminalizer website
global.BASEURL = 'https://terminalizer.com';
global.WEBDAV_URL = 'https://cloud.oisux.org/remote.php/dav/files/';
// Dependency Injection
di.require('chalk');
@ -40,6 +41,7 @@ di.require('string-argv', 'stringArgv');
di.require('progress', 'ProgressBar');
di.require('gif-encoder', 'GIFEncoder');
di.require('inquirer');
di.require('webdav');
di.set('pty', require('node-pty-prebuilt-multiarch'));
di.set('PNG', require('pngjs').PNG);
@ -73,6 +75,7 @@ yargs.command(commands.init)
.command(commands.render)
.command(commands.share)
.command(commands.generate)
.command(commands.partager)
debugger;

0
bin/app.js Normal file → Executable file
View File

149
commands/partager.js Normal file
View File

@ -0,0 +1,149 @@
/**
* Share
* Upload a recording file and get a link for an online player
*
* @author Mohammad Fares <faressoft.com@gmail.com>
* @author Oisux <contact@oisux.org>
*/
/**
* Executed after the command completes its task
*
* @param {String} url the url of the uploaded recording
*/
function done(url) {
console.log(di.chalk.green('téléversement réussi'));
console.log("L'enregistrement est disponible sur le NexCloud de Oisux dans le dossier:");
console.log(di.chalk.magenta(url));
process.exit();
}
/**
* Check if the value is not an empty value
*
* - Throw `Required field` if empty
*
* @param {String} input
* @return {Boolean}
*/
function isSet(input) {
if (!input) {
return new Error('Champ requis');
}
return true;
}
/**
* Ask the user to enter meta data about the recording
*
* - Skip the task if already executed before
* and resolve with the last result
*
* @param {Object} context
* @return {Promise}
*/
function getMeta(context) {
const platform = di.utility.getOS();
const username = di.utility.getUsername();
// Already executed
if (typeof context.getMeta != 'undefined') {
return Promise.resolve(context.getMeta);
}
console.log('Entrer les metadonnées (attributs étendus) du fichier:');
return di.inquirer
.prompt([
{
type: 'input',
name: 'comments',
message: 'Commentaires',
default: 'Commentaires non fonctionnels pour l\'instant. Pressez la touche entrée',
validate: isSet,
},
])
.then(function (answers) {
const params = Object.assign({}, answers);
params.platform = platform;
params.username = username;
console.log();
return params;
});
}
/**
* Upload the recording
*
* @param {Object} context
* @return {Promise}
*/
function shareRecording(context) {
const { createWebdavClient, sendFile } = di.utility;
return sendFile(createWebdavClient(), context);
}
/**
* The command's main function
*
* @param {Object} argv
*/
function command(argv) {
// No global config
if (!di.utility.isGlobalDirectoryCreated()) {
require('./init.js').handler();
}
di.Flowa.run(
{
// Ask the user to enter meta data about the recording
getMeta: getMeta,
// Upload the recording
shareRecording: shareRecording,
},
argv
)
.then(function (context) {
done(context.shareRecording);
})
.catch(di.errorHandler);
}
////////////////////////////////////////////////////
// Command Definition //////////////////////////////
////////////////////////////////////////////////////
/**
* Command's usage
* @type {String}
*/
module.exports.command = 'partager <recordingFile>';
/**
* Command's description
* @type {String}
*/
module.exports.describe = 'Upload sur le dossier "terminalizer" partagé par le groupe CA';
/**
* Command's handler function
* @type {Function}
*/
module.exports.handler = command;
/**
* Builder
*
* @param {Object} yargs
*/
module.exports.builder = function (yargs) {
// Define the recordingFile argument
yargs.positional('recordingFile', {
describe: 'le fichier',
type: 'string',
coerce: di._.partial(di.utility.resolveFilePath, di._, 'yml'),
});
};

View File

@ -112,7 +112,7 @@ function renderFrames(records, options) {
// Execute the rendering process
var render = di.spawn(
di.electron,
[di.path.join(ROOT_PATH, "render/index.js"), options.step],
[di.path.join(ROOT_PATH, "render/index.js"), options.step ],
{ detached: false }
);

View File

@ -12,6 +12,10 @@ cwd: null
env:
recording: true
webdav:
username: guillaume
password: xxxxxxxxxx
# Explicitly set the number of columns
# or use `auto` to take the current
# number of columns of your shell
@ -105,3 +109,5 @@ theme:
brightMagenta: "#ae89fe"
brightCyan: "#b1c6ca"
brightWhite: "#f9f9f4"
comments: "__COMMENTS__"

5026
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -62,10 +62,11 @@
"require-dir": "^1.1.0",
"string-argv": "0.0.2",
"uuid": "^3.4.0",
"webdav": "^4.11.0",
"yargs": "^12.0.5"
},
"devDependencies": {
"ajv": "^6.12.0",
"ajv": "^7.2.4",
"clean-webpack-plugin": "^4.0.0",
"css-loader": "^1.0.0",
"jquery": "^3.4.1",

View File

@ -32,6 +32,10 @@ if (os.platform() == 'darwin') {
app.dock.hide();
}
// avoid common issue with gpu acceleration on chrome
app.commandLine.appendSwitch('disable-gpu');
app.commandLine.appendArgument('disable-gpu');
// When the app is ready
app.on('ready', createWindow);

View File

@ -1,53 +1,100 @@
/**
* Provide utility functions
*
*
* @author Mohammad Fares <faressoft.com@gmail.com>
*/
function getUsername() {
const {
webdav: { username },
} = di.utility.getDefaultConfig().json;
return username;
}
function createWebdavClient() {
const {
webdav: { username, password },
} = di.utility.getDefaultConfig().json;
return di.webdav.createClient(`${WEBDAV_URL}${username}/`, {
username: username,
password: password,
});
}
function sendFile(client, context) {
return new Promise(function (resolve, reject) {
(async () => {
const { recordingFile } = context;
const basename = getBasenameFormat(context);
try {
if ((await client.exists('/terminalizer')) === false) {
await client.createDirectory('/terminalizer');
}
let content = di.fs.readFileSync(recordingFile, { encoding: 'utf8', flag: 'r' });
content = hideSecret(content);
content = insertComments(content, context);
await client.putFileContents('/terminalizer/' + basename, content);
} catch (err) {
reject(err);
}
return 'terminalizer/' + basename;
})().then((remoteFilePath) => resolve(remoteFilePath));
});
}
function getBasenameFormat({ recordingFile, getMeta: { username } }) {
const todayFormat = new Date().toISOString().split('T')[0].replaceAll('-', '_');
const basename = recordingFile
.split('/')
.pop()
.replace(/\.yml$/, '');
return `${basename}_${username}_${todayFormat}.yml`;
}
function insertComments(content, { getMeta: { comments } }) {
return content.replace('__COMMENTS__', comments);
}
function hideSecret(content) {
return content.replace(/(?<=password:)(.+)\n/, ` ${'x'.repeat(10)}`);
}
/**
* Check if a path represents a valid path for a file
*
*
* @param {String} filePath an absolute or a relative path
* @return {Boolean}
*/
function isFile(filePath) {
// Resolve the path into an absolute path
filePath = di.path.resolve(filePath);
try {
return di.fs.statSync(filePath).isFile();
} catch (error) {
return false;
}
}
/**
* Check if a path represents a valid path for a directory
*
*
* @param {String} dirPath an absolute or a relative path
* @return {Boolean}
*/
function isDir(dirPath) {
// Resolve the path into an absolute path
dirPath = di.path.resolve(dirPath);
try {
return di.fs.statSync(dirPath).isDirectory();
} catch (error) {
return false;
}
}
/**
@ -59,13 +106,12 @@ function isDir(dirPath) {
* Throws
* - The provided file doesn't exit
* - Any reading errors
*
*
* @param {String} filePath an absolute or a relative path
* @param {String} extension
* @return {String}
*/
function loadFile(filePath, extension) {
var content = null;
// Resolve the path into an absolute path
@ -73,7 +119,7 @@ function loadFile(filePath, extension) {
// The file doesn't exist
if (!isFile(filePath)) {
throw new Error('The provided file doesn\'t exit');
throw new Error("The provided file doesn't exit");
}
// Read the file
@ -84,57 +130,49 @@ function loadFile(filePath, extension) {
}
return content;
}
/**
* Check, load, and parse YAML files
*
* - Add .yml extension when needed
*
*
* Throws
* - The provided file doesn't exit
* - The provided file is not a valid YAML file
* - Any reading errors
*
*
* @param {String} filePath an absolute or a relative path
* @return {Object}
*/
function loadYAML(filePath) {
var file = loadFile(filePath, 'yml');
// Parse the file
try {
return {
json: di.yaml.load(file),
raw: file.toString()
raw: file.toString(),
};
} catch (error) {
throw new Error('The provided file is not a valid YAML file');
}
}
/**
* Check, load, and parse JSON files
*
* - Add .json extension when needed
*
*
* Throws
* - The provided file doesn't exit
* - The provided file is not a valid JSON file
* - Any reading errors
*
*
* @param {String} filePath an absolute or a relative path
* @return {Object}
*/
function loadJSON(filePath) {
var file = loadFile(filePath, 'json');
// Read the file
@ -150,7 +188,6 @@ function loadJSON(filePath) {
} catch (error) {
throw new Error('The provided file is not a valid JSON file');
}
}
/**
@ -164,13 +201,12 @@ function loadJSON(filePath) {
*
* - Add the extension if not already added
* - Resolve to `/path/to/FileName.ext`
*
*
* @param {String} filePath an absolute or a relative path
* @param {String} extension
* @return {String}
*/
function resolveFilePath(filePath, extension) {
var resolvedPath = di.path.resolve(filePath);
// The extension is not added
@ -179,7 +215,6 @@ function resolveFilePath(filePath, extension) {
}
return resolvedPath;
}
/**
@ -188,11 +223,10 @@ function resolveFilePath(filePath, extension) {
* - Check if there is a global config file
* - Found: Get the global config file
* - Not Found: Get the default config file
*
*
* @return {Object} {json, raw}
*/
function getDefaultConfig() {
var defaultConfigPath = di.path.join(ROOT_PATH, 'config.yml');
var globalConfigPath = di.path.join(getGlobalDirectory(), 'config.yml');
@ -205,67 +239,59 @@ function getDefaultConfig() {
// Load global config file
return loadYAML(defaultConfigPath);
}
/**
* Change a value for a specific key in YAML
*
*
* - Works only with the first level keys
* - Works only with keys with a single value
* - Apply the changes on the json and raw
*
* @param {Object} data {json, raw}
* @param {Object} data {json, raw}
* @param {String} key
* @param {*} value
*/
function changeYAMLValue(data, key, value) {
data.json[key] = value;
data.raw = data.raw.replace(new RegExp('^' + key + ':.+$', 'm'), key + ': ' + value);
}
/**
* Get the path of the global config directory
*
* - For Windows, get the path of APPDATA
* - For Linux and MacOS, get the path of the home directory
*
* - For Linux and MacOS, get the path of the home directory
*
* @return {String}
*/
function getGlobalDirectory() {
// Windows
if (typeof process.env.APPDATA != 'undefined') {
return di.path.join(process.env.APPDATA, 'terminalizer');
}
return di.path.join(process.env.HOME, '.terminalizer');
}
/**
* Check if the global config directory is created
*
*
* @return {Boolean}
*/
function isGlobalDirectoryCreated() {
var globalDirPath = getGlobalDirectory();
return isDir(globalDirPath);
}
/**
* Generate and save a token to be used for uploading recordings
*
*
* @param {String} token
* @return {String}
*/
function generateToken(token) {
var token = di.uuid.v4();
var globalDirPath = getGlobalDirectory();
var tokenPath = di.path.join(globalDirPath, 'token.txt');
@ -273,16 +299,14 @@ function generateToken(token) {
di.fs.writeFileSync(tokenPath, token, 'utf8');
return token;
}
/**
* Get registered token for uploading recordings
*
*
* @return {String|Null}
*/
function getToken() {
var globalDirPath = getGlobalDirectory();
var tokenPath = di.path.join(globalDirPath, 'token.txt');
@ -292,14 +316,12 @@ function getToken() {
}
return di.fs.readFileSync(tokenPath, 'utf8');
}
/**
* Remove a registered token
*/
function removeToken() {
var globalDirPath = getGlobalDirectory();
var tokenPath = di.path.join(globalDirPath, 'token.txt');
@ -309,30 +331,24 @@ function removeToken() {
}
di.fs.unlinkSync(tokenPath);
}
/**
* Get the name of the current OS
*
*
* @return {String} mac, windows, linux
*/
function getOS() {
// MacOS
if (di.os.platform() == 'darwin') {
return 'mac';
// Windows
// Windows
} else if (di.os.platform() == 'win32') {
return 'windows';
}
return 'linux';
}
////////////////////////////////////////////////////
@ -340,6 +356,9 @@ function getOS() {
////////////////////////////////////////////////////
module.exports = {
getUsername: getUsername,
createWebdavClient: createWebdavClient,
sendFile: sendFile,
loadYAML: loadYAML,
loadJSON: loadJSON,
resolveFilePath: resolveFilePath,
@ -350,5 +369,5 @@ module.exports = {
generateToken: generateToken,
getToken: getToken,
removeToken: removeToken,
getOS: getOS
getOS: getOS,
};