Skip to content
Permalink
ea888378d4
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
99 lines (75 sloc) 2.3 KB
'use strict'
const fs = require('fs-extra')
const sqlite = require('sqlite-async')
const Mailer = require('./mailer')
module.exports = class File {
constructor(dbName = ':memory:') {
return (async() => {
try{
this.db = await sqlite.open(dbName)
}catch(err) {
throw Error('Unable to connect to sqlite db')
}
const sql = `CREATE TABLE IF NOT EXISTS Files (
id INTEGER PRIMARY KEY AUTOINCREMENT, FileName TEXT, FileType BLOB,
FilePath TEXT, Size INT, Date TEXT, FileHash TEXT);`
try{
await this.db.run(sql)
}catch(err) {
throw Error('Not working')
}
return this
})()
}
async upload(extension, _name,_size,_date, _userName, path) {
try{
if (_name === '') throw new Error('String cannot be empty.')
if(_name.length >= 50) throw new Error('String size too big')
if(_size >= 1073741824) throw new Error('Size cannot be equal or greater than a GB')
const size = _size/1000
_date = _date.toString().slice(0,24)
const nameHash = Mailer.createHash(_name)
const nameExt = `${nameHash}.${extension}`
let targetPath = `/${ _userName }/${ nameExt}`
const sql = `INSERT INTO Files(FileName,FileType,FilePath,Size,Date,FileHash)
VALUES( "${_name}","${extension}", "${targetPath}", "${size}","${_date}","${nameHash}")`
await this.db.run(sql)
//save to directory on server
targetPath = `private${targetPath}`
await fs.copy(path, targetPath)
console.log('File saved on server')
return true
}catch(err) {
throw err
}
}
async generateLink(_fileName, username, fullLink) {
try {
//TODO: Only search table belonging to specific user
const sql = `SELECT FilePath, FileHash FROM Files
WHERE FileName LIKE '${_fileName}' OR
FileHash LIKE '${_fileName}'`
const data = await this.db.all(sql)
let link = data[0]['FilePath']
if (fullLink) {
link = `http://localhost:8080/download/${ username}/${data[0]['FileHash']}`
}
return link
} catch (err) {
throw err
}
}
async getFileInfo(_fileName, _userName) {
try {
_userName = ''
console.log(_userName)
//TODO: Only search table belonging to specific user
const sql = `SELECT * FROM Files
WHERE FileHash LIKE '${_fileName}'`
const data = await this.db.all(sql)
return data
} catch (err) {
throw err
}
}
}