Skip to content

Commit

Permalink
Frontend API
Browse files Browse the repository at this point in the history
  • Loading branch information
msimmer committed Sep 29, 2019
1 parent d08ce39 commit a86e36c
Show file tree
Hide file tree
Showing 17 changed files with 288 additions and 51 deletions.
5 changes: 3 additions & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
module.exports = {
env: {
browser: true,
node: true,
es6: true
},
extends: 'eslint:recommended',
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
require: true,
process: true
jQuery: true,
$: true
},
parserOptions: {
ecmaVersion: 2018,
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.DS_Store
node_modules
env.sh
public/javascripts/vendor
8 changes: 5 additions & 3 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ const cookieParser = require('cookie-parser')
const logger = require('morgan')

const indexRouter = require('./routes/index')
const usersRouter = require('./routes/users')
const clientsRouter = require('./routes/clients')
const torrentsRouter = require('./routes/torrents')

const app = express()

Expand All @@ -20,15 +21,16 @@ app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

app.use('/', indexRouter)
app.use('/users', usersRouter)
app.use('/api/v1/clients', clientsRouter)
app.use('/api/v1/torrents', torrentsRouter)

// catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404))
})

// error handler
app.use((err, req, res, next) => {
app.use((err, req, res /*, next */) => {
// set locals, only providing error in development
res.locals.message = err.message
res.locals.error = req.app.get('env') === 'development' ? err : {}
Expand Down
80 changes: 73 additions & 7 deletions lib/api.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,79 @@
/* API for running shell scripts */

const { spawn } = require('child_process')

class API {
addClients() {}
removeClients() {}
exec(script, args, callback) {
const proc = spawn(script, args)

let stdout = ''
let stderr = ''

proc.stdout.on('data', data => (stdout += String(data)))
proc.stderr.on('data', data => (stderr += String(data)))

proc.on('close', code => {
if (code !== 0) return callback(stderr.trim())
return callback(null, stdout.trim())
})
}

addClients(rpcPorts, transmissionPorts, callback) {
let args = []
args = rpcPorts.reduce((acc, port) => acc.concat(['-p', port]), args)
args = transmissionPorts.reduce((acc, port) => acc.concat(['-P', port]), args)

this.exec(process.env.SCRIPT_CREATE_CLIENTS, args, callback)
}

removeClients(rpcPorts, callback) {
const args = rpcPorts.reduce((acc, port) => acc.concat(['-p', port]), [])
this.exec(process.env.SCRIPT_REMOVE_CLIENTS, args, callback)
}

startClients() {}
stopClients() {}
startClients(rpcPorts, callback) {
const args = rpcPorts.reduce((acc, port) => acc.concat(['-p', port]), [])
this.exec(process.env.SCRIPT_START_CLIENTS, args, callback)
}

addTorrents() {}
createTorrent() {}
removeTorrents() {}
stopClients(rpcPorts, callback) {
const args = rpcPorts.reduce((acc, port) => acc.concat(['-p', port]), [])
this.exec(process.env.SCRIPT_STOP_CLIENTS, args, callback)
}

createTorrent(fileName, callback) {
this.exec(process.env.SCRIPT_CREATE_TORRENT, [fileName], callback)
}

addTorrents(rpcPorts, torrents, callback) {
let args = []
args = rpcPorts.reduce((acc, port) => acc.concat(['-p', port]), args)
args = torrents.reduce((acc, port) => acc.concat(['-t', port]), args)

this.exec(process.env.SCRIPT_ADD_TORRENTS, args, callback)
}

removeTorrents(rpcPorts, torrents, callback) {
let args = []
args = rpcPorts.reduce((acc, port) => acc.concat(['-p', port]), args)
args = torrents.reduce((acc, port) => acc.concat(['-t', port]), args)

this.exec(process.env.SCRIPT_REMOVE_TORRENTS, args, callback)
}
}

// const callback = (err, data) => {
// if (err) return console.log('ERR!', err)
// console.log(data)
// }

// const api = new API()
// api.addClients([9091, 9092], [5111, 5222], callback)
// api.removeClients([9091, 9092], callback)
// api.startClients([9091, 9092], callback)
// api.stopClients([9091, 9092], callback)
// api.addTorrents([9091, 9092], ['torrent-1', 'torrent-2'], callback)
// api.removeTorrents([9091, 9092], ['torrent-1', 'torrent-2'], callback)
// api.createTorrent('foo', callback)

module.exports = new API()
13 changes: 13 additions & 0 deletions lib/create-table-clients.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports =
"DROP TABLE IF EXISTS `clients`; \
CREATE TABLE `clients` ( \
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, \
`name` varchar(255) COLLATE utf8mb4_unicode_520_ci NOT NULL, \
`rpc_port` bigint(20) unsigned NOT NULL, \
`transmission_port` bigint(20) unsigned NOT NULL, \
`active` tinyint(1) DEFAULT '0', \
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, \
PRIMARY KEY (`id`), \
UNIQUE KEY `rcp_port` (`rpc_port`), \
UNIQUE KEY `transmission_port` (`transmission_port`) \
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;"
10 changes: 10 additions & 0 deletions lib/create-table-ports.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports =
"DROP TABLE IF EXISTS `ports`; \
CREATE TABLE `ports` ( \
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, \
`rpc_port` bigint(20) unsigned NOT NULL, \
`transmission_port` bigint(20) unsigned NOT NULL, \
`available` tinyint(1) DEFAULT '1', \
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, \
PRIMARY KEY (`id`) \
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;"
76 changes: 47 additions & 29 deletions lib/db.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
const createClientsQuery = require('./create-table-clients')
const createPortsQuery = require('./create-table-ports')
const mysql = require('mysql')

const connection = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
Expand All @@ -16,6 +19,17 @@ class Database {
this.connection.end()
}

// Create tables
create(callback) {
return this.connection.query(createClientsQuery, error1 => {
if (error1) callback(error1)
return this.connection.query(createPortsQuery, error2 => {
if (error2) callback(error2)
return callback(null)
})
})
}

getClients(callback) {
return this.connection.query('SELECT * FROM clients', (error, results) => {
if (error) return callback(error)
Expand Down Expand Up @@ -45,59 +59,63 @@ class Database {
if (error2) return callback(error2)

// Set available status on ports table
return this.connection.query(
`UPDATE ports SET available = 0 WHERE rpc_port IN (${rpcPorts})`,
(error3, results3) => {
callback(null, results3)
}
)
return this.connection.query(`UPDATE ports SET available = 0 WHERE rpc_port IN (${rpcPorts})`, error3 => {
if (error3) return callback(error3)

// Get newly added clients ports
return this.connection.query(`SELECT * FROM clients WHERE rpc_port IN (${rpcPorts})`, (error4, results4) => {
if (error4) return callback(error4)
return callback(null, results4)
})
})
})
})
}

removeClients() {}
removeClients(ports, callback) {
// Release ports
const ports_ = ports.join()
this.connection.query(`UPDATE ports SET available = 1 WHERE rpc_port IN (${ports_})`, error1 => {
if (error1) callback(error1)

// Update client status
return this.connection.query(`DELETE FROM clients WHERE rpc_port IN (${ports_})`, (error2, results2) => {
if (error2) callback(error2)
return callback(null, results2)
})
})
}

startClients(ports, callback) {
const ports_ = ports.join()
return this.connection.query(`UPDATE clients SET active = 1 WHERE rpc_port IN (${ports_})`, (error, results) => {
if (error) return callback(error)
callback(null, results)
return callback(null, results)
})
}

stopClients(ports, callback) {
const ports_ = ports.join()
return this.connection.query(`UPDATE clients SET active = 0 WHERE rpc_port IN (${ports_})`, (error, results) => {
if (error) return callback(error)
callback(null, results)
return callback(null, results)
})
}
}

// module.exports = new Database()
// const callback = (err, results, fields) => {
// if (err) console.log('ERR!', err)
// console.log(results)
// console.log(fields)
// connection.end()
// }

const db = new Database()
const callback = (err, results) => {
if (err) console.log('ERR!', err)
console.log(results)
connection.end()
}
// const db = new Database()

// db.getClients(callback)
// db.addClients(2, callback)
// db.removeClients([9091, 9092], callback)
// db.startClients([9091, 9092], callback)
// db.stopClients([9091, 9092], callback)

/**
CREATE TABLE `clients` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_520_ci NOT NULL,
`rpc_port` bigint(20) unsigned NOT NULL,
`transmission_port` bigint(20) unsigned NOT NULL,
`active` tinyint(1) DEFAULT '0',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `rpc_port` (`rpc_port`),
UNIQUE KEY `transmission_port` (`transmission_port`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
*/
module.exports = new Database()
11 changes: 11 additions & 0 deletions lib/test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#! /bin/bash

# echo "$@"

# sleep 3
cmd="ls . > /dev/null 2>&1"
if eval "$cmd"; then
echo "$(jq -n '{ error: null, data: {} }')"
else
echo "ERR"
fi
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@
"version": "0.1.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
"scripts:vendor": "node scripts/copy-vendor-scripts.js",
"start": "npm run scripts:vendor && node ./bin/www",
"start:dev": ". ./env.sh && DEBUG=dashboard:* node ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"jquery": "^3.4.1",
"morgan": "~1.9.1",
"mysql": "^2.17.1",
"pug": "2.0.0-beta11"
Expand Down
25 changes: 25 additions & 0 deletions public/javascripts/application.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// eslint-disable-next-line no-extra-semi
;(function($) {
function request(url, type, data) {
return $.post({
url,
type,
data,
success: data => console.log(data),
error: (xhr, status, text) => console.log(status, text)
})
}

function run() {
// request('/api/v1/clients/add', 'POST', {
// n: 2
// })
request('/api/v1/clients/remove', 'POST', {
ports: [9091, 9092]
})
}

$(function() {
run()
})
})(jQuery)
Loading

0 comments on commit a86e36c

Please sign in to comment.