diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d344ba6 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +config.json diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..2d5c1eb --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "www"] + path = www + url = https://git.debu.su/komp/www diff --git a/run b/run new file mode 100755 index 0000000..6b9f7e6 --- /dev/null +++ b/run @@ -0,0 +1,3 @@ +#!/bin/sh + +exec node src/server.js diff --git a/src/config.js b/src/config.js new file mode 100644 index 0000000..f32862c --- /dev/null +++ b/src/config.js @@ -0,0 +1,33 @@ +import fs from 'fs' + +let Config = { + WWW: './www', + DB: './db', + PORT: 8080 +} + +export function getConfig() { + return Config +} + +export function setConfig() { + let path = './config.json' + if (fs.existsSync(path)) { + console.log('Файл config.json найден! Конфигурация по нему.') + + let json = JSON.parse(fs.readFileSync(path)) + + Config.WWW = json.WWW || Config.WWW + Config.DB = json.DB || Config.DB + Config.PORT = json.PORT || Config.PORT + } + else + console.log('Файл config.json не найден, конфигурация по умолчанию.') + + console.log(`Веб-контент : ${Config.WWW}`) + console.log(`База данных : ${Config.DB}`) + console.log(`Порт : ${Config.PORT}`) + + fs.writeFileSync(path, JSON.stringify(Config, 0, 2)) + console.log('Конфигурация записана в файл config.json') +} diff --git a/src/db.js b/src/db.js new file mode 100644 index 0000000..3aa9405 --- /dev/null +++ b/src/db.js @@ -0,0 +1,77 @@ +import { getConfig } from './config.js' +import fs from 'fs' + +const DB = getConfig().DB + +let People = {} +let Verse = {} + +function getPeople() { + return People +} +function getVerse() { + return Verse +} + +function getPeopleCount() { + return Object.keys(People).length +} +function getVerseCount() { + return Object.keys(Verse).length +} + +function Init() { + const people = fs.readdirSync(DB + '/people') + for (let p of people) { + const info = JSON.parse(fs.readFileSync(`${DB}/people/${p}/info.json`)) + People[p] = info + } + + const verse = fs.readdirSync(DB + '/verse') + for (let v of verse) { + const info = JSON.parse(fs.readFileSync(`${DB}/verse/${v}/info.json`)) + Verse[v] = info + } +} + +function addPeople(name, subname, pseudonym, login, email) { + const p = { + NAME: name, + SUBNAME: subname, + PSEUDONYM: pseudonym, + LOGIN: login, + EMAIL: email + } + const index = Number(Object.keys(People)[getPeopleCount() - 1]) + 1 + + People[index] = p + + const dir = `${DB}/people/${index}` + fs.mkdir(dir, (err) => { + if (!err) + fs.writeFile(dir + '/info.json', JSON.stringify(p, 0, 2), () => {}) + }) +} + +function addVerse(title, author, genre, text) { + const v = { + TITLE: title, + AUTHOR: author, + GENRE: genre + } + const index = Number(Object.keys(Verse)[getVerseCount() - 1]) + 1 + + Verse[index] = v + + const dir = `${DB}/verse/${index}` + fs.mkdir(dir, (err) => { + if (!err) { + fs.writeFile(dir + '/info.json', JSON.stringify(v, 0, 2), () => {}) + fs.writeFile(dir + '/text', text, () => {}) + } + }) +} + +export default { + getPeople, getVerse, getPeopleCount, getVerseCount, Init, addPeople, addVerse +} diff --git a/src/server.js b/src/server.js new file mode 100644 index 0000000..871453d --- /dev/null +++ b/src/server.js @@ -0,0 +1,110 @@ +import { setConfig, getConfig } from './config.js' +import db from './db.js' +import fs from 'fs' +import { createServer } from 'http' + +setConfig() + +db.Init() + +const Config = getConfig() + +const server = createServer(async (req, res) => { + function sendText(text) { + res.setHeader('Content-Type', 'text/plain; charset=utf-8') + res.end(text) + } + function sendFile(path) { + fs.readFile(path, {}, (err, data) => { + if (err) { + sendText('Не удалось отправить Вам файл :(') + } + else { + const lastDotIndex = path.lastIndexOf('.') + if (lastDotIndex != -1) { + const format = path.slice(lastDotIndex + 1) + } + res.end(data) + } + }) + } + function notFound() { + res.statusCode = 404 + fs.readFile(Config.WWW + '/404.html', {}, (err, data) => { + if (err) + sendText('Файл не найден!') + else { + res.end(data) + } + }) + } + try { + const url = new URL(`http://${req.headers.host}${req.url}`) + const pathname = url.pathname + + const tokens = pathname.split('/').filter(el => el != '') + const People = db.getPeople() + + if (tokens.length == 0) + sendFile(Config.WWW + '/index.html') + else { + switch (tokens[0]) { + case 'api': + function error(text) { + sendText(text) + } + let OK + switch (tokens[1]) { + case 'login': + OK = true + for (let p in People) { + if (People[p].LOGIN == tokens[2]) { + sendText('Пользователь с таким логином уже есть в системе!') + OK = false + break + } + } + if (OK) { + sendText('Логин свободен!') + } + break + case 'email': + OK = true + for (let p in People) { + if (People[p].EMAIL == tokens[2]) { + sendText('Пользователь с такой почтой уже есть в системе!') + OK = false + break + } + } + if (OK) { + sendText('Почта свободна!') + } + break + default: + error(`ОШИБКА: в API нет метода '${tokens[1]}'`) + } + break + case 'signup': + if (tokens.length == 1) + sendFile(Config.WWW + '/signup.html') + else + notFound() + break + default: + const filePath = Config.WWW + pathname + fs.exists(filePath, (e) => { + if (e) + sendFile(filePath) + else + notFound() + }) + } + } + } catch (err) { + res.statusCode = 500 + sendText('Server Error') + } +}) + +server.listen(Config.PORT, console.log('Сервер запущен!')) diff --git a/www b/www new file mode 160000 index 0000000..6b9547b --- /dev/null +++ b/www @@ -0,0 +1 @@ +Subproject commit 6b9547b751637d15a17dbb157a4f7dcc30629b86