362 lines
12 KiB
Vue
362 lines
12 KiB
Vue
<script>
|
|
|
|
import { fetcher, Button, Dialog, FileUploader, InputDialog, MainLayout, TopBar } from 'pankow';
|
|
|
|
import '@xterm/xterm/css/xterm.css';
|
|
import { Terminal } from '@xterm/xterm';
|
|
import { AttachAddon } from '@xterm/addon-attach';
|
|
import { FitAddon } from '@xterm/addon-fit';
|
|
|
|
import AppsModel from '../models/AppsModel.js';
|
|
import { createDirectoryModel } from '../models/DirectoryModel.js';
|
|
|
|
const API_ORIGIN = import.meta.env.VITE_API_ORIGIN ? import.meta.env.VITE_API_ORIGIN : window.location.origin;
|
|
|
|
export default {
|
|
name: 'Terminal',
|
|
components: {
|
|
Button,
|
|
Dialog,
|
|
FileUploader,
|
|
InputDialog,
|
|
MainLayout,
|
|
TopBar
|
|
},
|
|
data() {
|
|
return {
|
|
accessToken: localStorage.token,
|
|
appsModel: null,
|
|
directoryModel: null,
|
|
fatalError: false,
|
|
busyRestart: false,
|
|
connected: false,
|
|
addons: {},
|
|
showFilemanager: false,
|
|
schedulerTasks: [],
|
|
manifestVersion: '',
|
|
schedulerMenuModel: [],
|
|
id: '',
|
|
name: '',
|
|
socket: null,
|
|
terminal: null,
|
|
downloadFileDownloadUrl: ''
|
|
};
|
|
},
|
|
methods: {
|
|
onFatalError(errorMessage) {
|
|
this.fatalError = errorMessage;
|
|
this.$refs.fatalErrorDialog.open();
|
|
},
|
|
// generic dialog focus handler TODO move to pankow and reuse in filemanger
|
|
onDialogShow(focusElementId) {
|
|
setTimeout(() => document.getElementById(focusElementId).focus(), 0);
|
|
},
|
|
async onDownload() {
|
|
this.downloadFileDownloadUrl = '';
|
|
|
|
const downloadFileName = await this.$refs.inputDialog.prompt({
|
|
message: this.$t('terminal.downloadAction'),
|
|
value: '',
|
|
confirmStyle: 'success',
|
|
confirmLabel: this.$t('terminal.download.download'),
|
|
rejectLabel: this.$t('main.dialog.cancel'),
|
|
modal: false
|
|
});
|
|
|
|
if (!downloadFileName) return;
|
|
|
|
try {
|
|
await fetcher.head(`${API_ORIGIN}/api/v1/apps/${this.id}/download`, {
|
|
file: downloadFileName,
|
|
access_token: this.accessToken
|
|
});
|
|
} catch (error) {
|
|
if (error.status === 404) console.error('The requested file does not exist.');
|
|
else console.error('Failed', error);
|
|
|
|
return;
|
|
}
|
|
|
|
this.downloadFileDownloadUrl = `${API_ORIGIN}/api/v1/apps/${this.id}/download?file=${encodeURIComponent(downloadFileName)}&access_token=${this.accessToken}`;
|
|
|
|
// we have to click the link to make the browser do the download
|
|
// don't know how to prevent the browsers
|
|
this.$nextTick(() => {
|
|
document.getElementById('fileDownloadLink').click();
|
|
});
|
|
},
|
|
onUpload() {
|
|
this.$refs.fileUploader.onUploadFile('/');
|
|
},
|
|
async uploadHandler(targetDir, file, progressHandler) {
|
|
await this.directoryModel.upload(targetDir, file, progressHandler);
|
|
},
|
|
usesAddon(addon) {
|
|
return !!Object.keys(this.addons).find(function (a) { return a === addon; });
|
|
},
|
|
terminalInject(addon, command) {
|
|
if (!this.socket) return;
|
|
|
|
let cmd = '';
|
|
if (addon === 'mysql') {
|
|
if (this.manifestVersion === 1) {
|
|
cmd = 'mysql --user=${MYSQL_USERNAME} --password=${MYSQL_PASSWORD} --host=${MYSQL_HOST} ${MYSQL_DATABASE}';
|
|
} else {
|
|
cmd = 'mysql --user=${CLOUDRON_MYSQL_USERNAME} --password=${CLOUDRON_MYSQL_PASSWORD} --host=${CLOUDRON_MYSQL_HOST} ${CLOUDRON_MYSQL_DATABASE}';
|
|
}
|
|
} else if (addon === 'postgresql') {
|
|
if (this.manifestVersion === 1) {
|
|
cmd = 'PGPASSWORD=${POSTGRESQL_PASSWORD} psql -h ${POSTGRESQL_HOST} -p ${POSTGRESQL_PORT} -U ${POSTGRESQL_USERNAME} -d ${POSTGRESQL_DATABASE}';
|
|
} else {
|
|
cmd = 'PGPASSWORD=${CLOUDRON_POSTGRESQL_PASSWORD} psql -h ${CLOUDRON_POSTGRESQL_HOST} -p ${CLOUDRON_POSTGRESQL_PORT} -U ${CLOUDRON_POSTGRESQL_USERNAME} -d ${CLOUDRON_POSTGRESQL_DATABASE}';
|
|
}
|
|
} else if (addon === 'mongodb') {
|
|
if (this.manifestVersion === 1) {
|
|
cmd = 'mongo -u "${MONGODB_USERNAME}" -p "${MONGODB_PASSWORD}" ${MONGODB_HOST}:${MONGODB_PORT}/${MONGODB_DATABASE}';
|
|
} else {
|
|
cmd = 'mongosh -u "${CLOUDRON_MONGODB_USERNAME}" -p "${CLOUDRON_MONGODB_PASSWORD}" ${CLOUDRON_MONGODB_HOST}:${CLOUDRON_MONGODB_PORT}/${CLOUDRON_MONGODB_DATABASE}';
|
|
}
|
|
} else if (addon === 'redis') {
|
|
if (this.manifestVersion === 1) {
|
|
cmd = 'redis-cli -h "${REDIS_HOST}" -p "${REDIS_PORT}" -a "${REDIS_PASSWORD}"';
|
|
} else if (this.addons['redis'].noPassword) {
|
|
cmd = 'redis-cli -h "${CLOUDRON_REDIS_HOST}" -p "${CLOUDRON_REDIS_PORT}"';
|
|
} else {
|
|
cmd = 'redis-cli -h "${CLOUDRON_REDIS_HOST}" -p "${CLOUDRON_REDIS_PORT}" -a "${CLOUDRON_REDIS_PASSWORD}" --no-auth-warning';
|
|
}
|
|
} else if (addon === 'scheduler' && command) {
|
|
cmd = command;
|
|
}
|
|
|
|
if (!cmd) return;
|
|
|
|
cmd += ' ';
|
|
|
|
this.socket.send(cmd);
|
|
this.terminal.focus();
|
|
},
|
|
onSchedulerMenu(event) {
|
|
this.$refs.schedulerMenu.toggle(event);
|
|
},
|
|
async onRestartApp() {
|
|
const confirmed = await this.$refs.inputDialog.confirm({
|
|
message: this.$t('filemanager.toolbar.restartApp') + '?',
|
|
confirmStyle: 'danger',
|
|
confirmLabel: this.$t('main.dialog.yes'),
|
|
rejectLabel: this.$t('main.dialog.no')
|
|
});
|
|
|
|
if (!confirmed) return;
|
|
|
|
this.busyRestart = true;
|
|
await this.appsModel.restart(this.id);
|
|
this.busyRestart = false;
|
|
},
|
|
async connect(retry = false) {
|
|
document.getElementsByClassName('pankow-main-layout-body')[0].innerHTML = '';
|
|
|
|
let execId;
|
|
try {
|
|
const result = await fetcher.post(`${API_ORIGIN}/api/v1/apps/${this.id}/exec`, { cmd: [ '/bin/bash' ], tty: true, lang: 'C.UTF-8' }, { access_token: this.accessToken });
|
|
execId = result.body.id;
|
|
} catch (error) {
|
|
console.error('Cannot create socket.', error);
|
|
return setTimeout(() => this.connect(true), 1000);
|
|
}
|
|
|
|
this.terminal = new Terminal();
|
|
this.terminal.open(document.getElementsByClassName('pankow-main-layout-body')[0]);
|
|
|
|
if (retry) this.terminal.writeln('Reconnecting...');
|
|
else this.terminal.writeln('Connecting...');
|
|
|
|
const fitAddon = new FitAddon();
|
|
this.terminal.loadAddon(fitAddon);
|
|
fitAddon.fit();
|
|
|
|
// Let the browser handle paste
|
|
this.terminal.attachCustomKeyEventHandler(function (e) {
|
|
if (e.key === 'V' && (e.ctrlKey || e.metaKey)) return false;
|
|
});
|
|
|
|
// websocket cannot use relative urls
|
|
const url = `${API_ORIGIN.replace('https', 'wss')}/api/v1/apps/${this.id}/exec/${execId}/startws?tty=true&rows=${this.terminal.rows}&columns=${this.terminal.cols}&access_token=${this.accessToken}`;
|
|
this.socket = new WebSocket(url);
|
|
|
|
this.terminal.loadAddon(new AttachAddon(this.socket));
|
|
|
|
this.socket.addEventListener('open', (event) => {
|
|
this.connected = true;
|
|
});
|
|
|
|
this.socket.addEventListener('close', (event) => {
|
|
this.connected = false;
|
|
console.log('Socket closed. Reconnecting...');
|
|
return setTimeout(() => this.connect(true), 1000);
|
|
});
|
|
|
|
this.socket.addEventListener('error', (error) => {
|
|
this.connected = false;
|
|
console.log('Socket error. Reconnecting...', error);
|
|
return setTimeout(() => this.connect(true), 1000);
|
|
});
|
|
|
|
this.terminal.focus();
|
|
}
|
|
},
|
|
async mounted() {
|
|
if (!localStorage.token) {
|
|
console.error('Set localStorage.token');
|
|
return;
|
|
}
|
|
|
|
const urlParams = new URLSearchParams(window.location.search);
|
|
const id = urlParams.get('id');
|
|
|
|
if (!id) {
|
|
console.error('No app id specified');
|
|
return;
|
|
}
|
|
|
|
this.id = id;
|
|
this.name = id;
|
|
|
|
this.appsModel = AppsModel.create();
|
|
this.directoryModel = createDirectoryModel(API_ORIGIN, this.accessToken, `apps/${id}`);
|
|
|
|
const [error, app] = await this.appsModel.get(this.id);
|
|
if (error) {
|
|
console.error(`Failed to get app info for ${this.id}:`, error);
|
|
return this.onFatalError(`Unknown app ${this.id}. Cannot continue.`);
|
|
}
|
|
|
|
this.name = `${app.label || app.fqdn} (${app.manifest.title})`;
|
|
this.addons = app.manifest.addons;
|
|
this.manifestVersion = app.manifest.manifestVersion;
|
|
this.showFilemanager = !!app.manifest.addons.localstorage;
|
|
|
|
this.schedulerMenuModel = !app.manifest.addons.scheduler ? [] : Object.keys(app.manifest.addons.scheduler).map((k) => {
|
|
return {
|
|
label: k,
|
|
action: () => this.terminalInject('scheduler', app.manifest.addons.scheduler[k].command)
|
|
};
|
|
});
|
|
|
|
window.document.title = `Terminal - ${this.name}`;
|
|
|
|
window.addEventListener('beforeunload', function (e) {
|
|
e.stopPropagation();
|
|
e.preventDefault();
|
|
return false;
|
|
}, true );
|
|
|
|
window.addEventListener('keydown', (event) => {
|
|
if (event.key === 'C' && (event.ctrlKey || event.metaKey)) { // ctrl shift c
|
|
event.preventDefault();
|
|
|
|
if (!this.terminal) return;
|
|
|
|
// execCommand('copy') would copy any selection from the page, so do this only if terminal has a selection
|
|
if (!this.terminal.getSelection()) return;
|
|
|
|
document.execCommand('copy');
|
|
|
|
this.terminal.focus();
|
|
}
|
|
});
|
|
|
|
this.connect();
|
|
}
|
|
};
|
|
|
|
</script>
|
|
|
|
<template>
|
|
<MainLayout :gap="false">
|
|
<template #dialogs>
|
|
<Dialog ref="fatalErrorDialog" modal title="Error">
|
|
<p>{{ fatalError }}</p>
|
|
</Dialog>
|
|
|
|
<InputDialog ref="inputDialog" />
|
|
<a id="fileDownloadLink" :href="downloadFileDownloadUrl" target="_blank"></a>
|
|
</template>
|
|
<template #header>
|
|
<TopBar class="navbar">
|
|
<template #left>
|
|
<span class="title">{{ name }}</span>
|
|
</template>
|
|
<template #right>
|
|
<!-- Scheduler/cron tasks -->
|
|
<Button success :menu="schedulerMenuModel" v-show="usesAddon('scheduler')" @click="onSchedulerMenu">{{ $t('terminal.scheduler') }}</Button>
|
|
|
|
<!-- addon actions -->
|
|
<Button success @click="terminalInject('mysql')" v-show="usesAddon('mysql')" :disabled="!connected">MySQL</Button>
|
|
<Button success @click="terminalInject('postgresql')" v-show="usesAddon('postgresql')" :disabled="!connected">Postgres</Button>
|
|
<Button success @click="terminalInject('mongodb')" v-show="usesAddon('mongodb')" :disabled="!connected">MongoDB</Button>
|
|
<Button success @click="terminalInject('redis')" v-show="usesAddon('redis')" :disabled="!connected">Redis</Button>
|
|
|
|
<!-- upload/download actions -->
|
|
<Button style="margin-left: 20px;" :disabled="!connected" @click="onUpload" icon="fa-solid fa-upload">{{ $t('terminal.uploadTo', { path: '/app/data/' }) }}</Button>
|
|
<Button :disabled="!connected" @click="onDownload" icon="fa-solid fa-download">{{ $t('terminal.downloadAction') }}</Button>
|
|
|
|
<Button style="margin-left: 20px;" :title="$t('filemanager.toolbar.restartApp')" secondary tool :loading="busyRestart" icon="fa-solid fa-arrows-rotate" @click="onRestartApp"/>
|
|
<Button v-show="showFilemanager" :href="'/filemanager.html#/home/app/' + id" target="_blank" secondary tool icon="fa-solid fa-folder" :title="$t('filemanager.title')" />
|
|
<Button :href="'/logs.html?appId=' + id" target="_blank" secondary tool icon="fa-solid fa-align-left" :title="$t('logs.title')" />
|
|
</template>
|
|
</TopBar>
|
|
</template>
|
|
<template #body>
|
|
<!-- terminal will be injected here -->
|
|
</template>
|
|
<template #footer>
|
|
<FileUploader
|
|
ref="fileUploader"
|
|
:upload-handler="uploadHandler"
|
|
:tr="$t"
|
|
/>
|
|
</template>
|
|
</MainLayout>
|
|
</template>
|
|
|
|
<style>
|
|
|
|
body {
|
|
background-color: black !important;
|
|
overflow: hidden;
|
|
}
|
|
|
|
.title {
|
|
font-size: 20px;
|
|
}
|
|
|
|
.pankow-top-bar {
|
|
background-color: black;
|
|
color: white;
|
|
margin-bottom: 0 !important;
|
|
padding: 5px 10px;
|
|
}
|
|
|
|
</style>
|
|
|
|
<style scoped>
|
|
|
|
.dialog-header {
|
|
font-weight: 600;
|
|
font-size: 1.25rem;
|
|
}
|
|
|
|
.dialog-single-input {
|
|
display: block;
|
|
width: 100%;
|
|
margin-top: 5px;
|
|
margin-bottom: 1.5rem;
|
|
}
|
|
|
|
.dialog-single-input-submit {
|
|
margin-top: 5px;
|
|
}
|
|
|
|
</style>
|
|
|