create session added

This commit is contained in:
C
2022-11-22 18:28:29 +05:00
parent c3dedbc530
commit 33222ea5b0
13 changed files with 7127 additions and 77 deletions
+51
View File
@@ -0,0 +1,51 @@
1. открыли страницу стриминга, после нажатия на кнопку демонстрации отправляем запрос на сервер для
получения названий жк, их описаний, картинок
Зпрос:
{"verb":"GET_TITLES", "start":0, "count":50}
Ответ:
[{
"title": {
"en": "Title",
"ru": "Название"
},
"location": {
"en": "Russia, Moscow",
"ru": "Россия, Москва"
},
"description": {
"en": "Best RC ...",
"ru": "Лучший ЖК ..."
},
"image": {
"main": "URL1",
"second": "URL2"
}
},
{
"title": {
"en": "Title",
"ru": "Название"
},
"location": {
"en": "Russia, Moscow",
"ru": "Россия, Москва"
},
"description": {
"en": "Best RC ...",
"ru": "Лучший ЖК ..."
},
"image": {
"main": "URL1",
"second": "URL2"
}
}]
2. если пользователь нажал на один из жк для создания сессии отправляем запрос
Запрос:
{"verb":"CREATE_SESSION", "title":"SomeRC"}
Ответ:
{"msg":"SESSION_CREATED", "link":"google.com"}
+22
View File
@@ -42,3 +42,25 @@
{"verb":"CONNECT_SESSION_WITH_CODE", "code":"1234"},
в ответ придёт {"verb":"CONNECT_TO_SESSION", "ip":"0.0.0.1", "port":"1111", "code":"1234"}, или
если сессии не существует {"msg":"SESSION_NOT_EXIST"}.
COMMANDS:
{"verb":"GET_TITLES", "start":0, "count":50}
{"verb":"PLAN_SESSION", "title":"SomeRC", "year":2022, "month":11, "day":4, "hour":20, "minute":13, "period_minute":30}
{
"title":"SomeRC",
"data":[
{
"ip":"127.0.0.1",
"port":"0000",
"copies":5
},
{
"ip":"127.0.0.2",
"port":"0001",
"copies":2
}
]}
{"verb":"CREATE_SESSION", "title":"SomeRC"}
+8 -8
View File
@@ -1,13 +1,13 @@
CHECKOUT_DATABASE:
how dbs - show all dbs
se some_name_db - set current db
how collections - all collections of current db
b.stats() - stats of DB
b.users.stats() - some stats
show dbs - show all dbs
set some_name_db - set current db
show collections - all collections of current db
db.stats() - stats of DB
db.users.stats() - some stats
ADD_DATA:
nsertOne() - insert document to collection
nsertMany()
insertOne() - insert document to collection
insertMany()
EXAMPLE:
db.collection_name.insertOne({"name":"Tom", "age": 28, languages: ["english":"spanish"]})
@@ -25,7 +25,7 @@ WITH_FILE: example.js AND CONTENT
load("example.js") - this command will load previous example in db
DOCUMENT_FILTER:
b.collection_name.find() - show all documents in colleciton
db.collection_name.find() - show all documents in colleciton
EXAMPLES:
db.collection_name.find({name: "Tom"}) - find documents with names
+111 -69
View File
@@ -1,11 +1,18 @@
// coordinator
// http
const http = require('http')
// filesystem
const fs = require('fs')
// server config
var config = require('./config.json');
const config = require('./config.json')
// node date time
var node_time = require('node-datetime')
const node_time = require('node-datetime')
const mongodb_client = require('./mongodb_client.js')
const crypto = require('crypto')
var querystring = require('querystring')
// write startup server history
var logs_dir = './logs'
@@ -15,89 +22,124 @@ if (!fs.existsSync(logs_dir))
fs.appendFileSync(`./${logs_dir}/launch_history.log`, (node_time.create().format('Y-m-d H:M:S')).toString() + '\n')
// mongodb connect function
async function connect_mongodb(MongoClient)
{
const mongodb_client = new MongoClient(config.mongodb_url)
try
{
// connect to the MongoDB cluster (now just database)
await mongodb_client.connect()
// connect to database
const database = mongodb_client.db(config.database_name)
console.log('Database connection status:', await database.command({ping: 1}))
// get titles collection
var title = database.collection("title")
console.log(`Titles count: ${await title.countDocuments()}`)
title.insertOne({title:{en:"Title", ru:"Название"},
location:{en:"Russia, Moscow", ru:"Россия, Москва"},
description:{en:"Best RC ...", ru:"Лучший ЖК ..."},
image:{main:"URL1", second:"URL2"}
async function PostSessionServer(data, ip, port, callback) {
// Build the post string from an object
// An object of options to indicate where to post to
var post_options = {
host: ip,
port: port,
method: 'POST',
headers: {
'Content-Type': 'applicaiton/json',
'Content-Length': Buffer.byteLength(data)
}
}
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8')
res.on('data', async function (answer) {
callback(answer)
})
}
catch(e)
{
console.error(e)
}
// finally
// {
// await mongodb_client.close()
// console.log("Database connection closed")
// }
})
// post the data
post_req.write(data)
post_req.end()
}
// response function
function create_response(request)
{
var request_json = JSON.parse(request)
switch(request_json.verb)
{
case 'GET_TITLES':
break;
case 'PLAN_SESSION':
break;
case 'CREATE_SESSION':
break;
case 'CONNECT_SESSION':
break;
case 'CONNECT_SESSION_WITH_CODE':
break;
default:
async function create_response(request, callback) {
var mongo_client = new mongodb_client(config.mongodb_url)
var database = await mongo_client.connect_database(config.database_name)
var response = ''
try {
if (request.verb == 'GET_TITLES') {
var title = database.collection('title')
response = await title.find().skip(request.start).limit(request.count).toArray()
response = JSON.stringify(response)
callback(response)
} else if (request.verb == 'PLAN_SESSION') {
var session_sheduled = database.collection('session_sheduled')
var sessions = await session_sheduled.find().toArray()
} else if (request.verb == 'CREATE_SESSION') {
var session_server = database.collection('session_server')
var servers = await session_server.find({'title':request.title}).toArray()
if (!servers.length) {
response = '{"msg":"SERVERS_NOT_FOUND"}'
callback(response)
}
// find free server and create session
var session_active = database.collection('session_active')
// find free server
var free_server
var servers_length = servers.length
for (var i = 0; i < servers_length; ++i) {
var sessions = await session_active.find({'server_id':servers[i].server_id}).toArray()
if (servers[i].limit > sessions.length) {
free_server = servers[i]
break
}
}
if (free_server == null) {
response = '{"msg":"SESSION_LIMIT_REACHED"}'
callback(response)
}
PostSessionServer(`{"verb":"CREATE_SESSION", "title":"${request.title}"}`, free_server.ip, free_server.port, async function(answer) {
var json_answer = JSON.parse(answer)
// add session to database
await session_active.insertOne({
server_id:free_server.server_id,
link:json_answer.link
})
response = `{"msg":"SESSION_CREATED", "link":"${json_answer.link}"}`
callback(response)
})
} else if (request.verb == 'CONNECT_SESSION') {
callback(response)
} else {
response = '{"msg":"UNKNOWN_VERB"}'
callback(response)
}
}
catch(e) {
console.error(e)
}
return '{"verb":"WAIT"}'
}
// connect to mongodb
const {MongoClient} = require('mongodb')
connect_mongodb(MongoClient).catch(console.error)
// start http server
const server = http.createServer(function(request, response)
{
var message = ''
if (request.method == 'POST')
{
const server = http.createServer(function(request, response) {
if (request.method == 'POST') {
var body = ''
request.on('data', function(data)
{
request.on('data', function(data) {
body += data
})
request.on('end', function()
{
request.on('end', function() {
response.writeHead(200, {'Content-Type': 'message'})
response.end(create_response(body))
console.log(body)
try {
create_response(JSON.parse(body), function(message) {
response.end(message)
})
}
catch(e) {
console.error(e)
}
console.log('received: "', body, '"')
})
}
else
{
message = 'UNDEFINED_REQUEST' + ': ' + request.method.toString()
else {
var message = 'UNDEFINED_REQUEST' + ': ' + request.method.toString()
response.writeHead(200, {'Content-Type': 'message'})
response.end(message)
console.log(message)
+26
View File
@@ -0,0 +1,26 @@
module.exports = class mongodb_client {
mongo_client
constructor(url) {
const {MongoClient} = require('mongodb')
this.mongo_client = new MongoClient(url)
}
// database connect function
async connect_database(database_name) {
try {
await this.mongo_client.connect()
const database = this.mongo_client.db(database_name)
console.log('Database connection status:', await database.command({ping: 1}))
return database
}
catch(e) {
console.error(e)
}
// finally
// {
// await mongodb_client.close()
// console.log("Database connection closed")
// }
}
}
View File
File diff suppressed because it is too large Load Diff
+18
View File
@@ -0,0 +1,18 @@
{
"name": "coordinator",
"version": "1.0.0",
"description": "",
"main": "coordinator.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"dependencies": {
"express": "^4.18.2",
"mongodb": "^4.12.0",
"node-datetime": "^2.1.2"
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"ip" : "127.0.0.1",
"port" : "3002"
}
File diff suppressed because it is too large Load Diff
+18
View File
@@ -0,0 +1,18 @@
{
"name": "coordinator",
"version": "1.0.0",
"description": "",
"main": "coordinator.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"dependencies": {
"express": "^4.18.2",
"mongodb": "^4.12.0",
"node-datetime": "^2.1.2"
}
}
+91
View File
@@ -0,0 +1,91 @@
// session server
// http
const http = require('http')
// filesystem
const fs = require('fs')
// server config
const config = require('./config.json');
// node date time
const node_time = require('node-datetime')
// titles for process creation
const titles = require('./titles.json')
const { spawn } = require('node:child_process')
// write startup server history
var logs_dir = './logs'
if (!fs.existsSync(logs_dir))
fs.mkdirSync(logs_dir)
fs.appendFileSync(`./${logs_dir}/launch_history.log`, (node_time.create().format('Y-m-d H:M:S')).toString() + '\n')
// response function
async function create_response(request, callback) {
var response = ''
try {
switch(request.verb) {
case 'CREATE_SESSION':
var title_info
titles.forEach((title) => {
if (title.title == request.title) {
title_info = title
}
})
if (title_info == null) {
response = '{"msg":"TITLE_NOT_EXISTS"}'
break
}
const process = spawn(title_info.path, ['', ''])
process.on('close', (code) => {
console.log(`child process exited with code ${code}`);
})
response = `{"msg":"SESSION_CREATED", "link":"http://${title_info.title}"}`
break
case 'CONNECT_SESSION':
break
default:
response = '{"msg":"UNKNOWN_VERB"}'
}
callback(response)
}
catch(e) {
console.error(e)
}
}
// start http server
const server = http.createServer(function(request, response) {
if (request.method == 'POST') {
var body = ''
request.on('data', function(data) {
body += data
})
request.on('end', function() {
response.writeHead(200, {'Content-Type': 'message'})
try {
create_response(JSON.parse(body), function(message) {
response.end(message)
})
}
catch(e) {
console.error(e)
}
console.log('received: "', body, '"')
})
}
else {
var message = 'UNDEFINED_REQUEST' + ': ' + request.method.toString()
response.writeHead(200, {'Content-Type': 'message'})
response.end(message)
console.log(message)
}
})
server.listen(config.port, config.ip)
console.log(`Listening at http://${config.ip}:${config.port}`)
+10
View File
@@ -0,0 +1,10 @@
[
{
"title":"Fortis",
"path":"D:/shared/Builds/Fortis_UnStable_64/WindowsNoEditor/FORTIS_Taktika.exe"
},
{
"title":"Ivazowsky",
"path":"D:/shared/Builds/Ivaz_Optimized_2/Ivazowsky.exe"
}
]