118 lines
2.5 KiB
JavaScript
118 lines
2.5 KiB
JavaScript
import { getConfig } from './config.js'
|
|
import fs from 'fs'
|
|
import readline from 'readline'
|
|
import path from 'path'
|
|
import { createHash } from 'crypto'
|
|
|
|
const DB = getConfig().DB
|
|
|
|
let People = {}
|
|
let Verse = {}
|
|
|
|
function getPeople() {
|
|
return People
|
|
}
|
|
function getVerse() {
|
|
return Verse
|
|
}
|
|
|
|
async function getPreview(number) {
|
|
const rl = readline.createInterface({
|
|
input: fs.createReadStream(path.join(DB, 'verse', String(number), 'text')),
|
|
crlfDelay: Infinity
|
|
})
|
|
const lines = []
|
|
for await (const line of rl) {
|
|
lines.push(line)
|
|
if (lines.length >= 4)
|
|
break
|
|
}
|
|
return lines.join('\n')
|
|
}
|
|
|
|
function getPeopleCount() {
|
|
return Object.keys(People).length
|
|
}
|
|
function getVerseCount() {
|
|
return Object.keys(Verse).length
|
|
}
|
|
|
|
function peopleNumberByLogin(login) {
|
|
for (let p in People)
|
|
if (People[p].LOGIN == login)
|
|
return p
|
|
return false
|
|
}
|
|
function peopleByLogin(login) {
|
|
const number = peopleNumberByLogin(login)
|
|
return number ? People[number] : false
|
|
}
|
|
|
|
function checkPassword(login, password) {
|
|
return peopleByLogin(login).HASH == createHash('sha256').update(password).digest('hex')
|
|
}
|
|
|
|
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, login, password) {
|
|
const p = {
|
|
NAME: name,
|
|
SUBNAME: subname,
|
|
LOGIN: login,
|
|
HASH: createHash('sha256').update(password).digest('hex')
|
|
}
|
|
const index = getPeopleCount() == 0 ? 1 : 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, login, genre, text) {
|
|
const v = {
|
|
TITLE: title,
|
|
AUTHOR: peopleNumberByLogin(login),
|
|
GENRE: genre
|
|
}
|
|
const index = getVerseCount() == 0 ? 1 : 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,
|
|
getPreview,
|
|
peopleNumberByLogin,
|
|
peopleByLogin,
|
|
checkPassword,
|
|
Init,
|
|
addPeople,
|
|
addVerse
|
|
}
|