Skip to content
Permalink
06daf82dec
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
176 lines (136 sloc) 4.06 KB
/* eslint-disable max-lines-per-function */
'use strict'
const fs = require('fs-extra')
const sqlite = require('sqlite-async')
const Mailer = require('./mailer')
function addDays(date, days) {
const copy = new Date(Number(date))
copy.setDate(date.getDate() + days)
return copy
}
module.exports = class File {
constructor(dbName = ':memory:') {
return (async() => {
try{
this.db = await sqlite.open(dbName)
}catch(err) {
/* istanbul ignore next */
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 DATE NOT NULL DEFAULT (date('now')),
FileHash TEXT, ExpDate TEXT, Downloaded TEXT DEFAULT false);`
try{
await this.db.run(sql)
// CURRENT_TIMESTAMP
}catch(err) {
/* istanbul ignore next */
throw Error(err)
}
return this
})()
}
// eslint-disable-next-line max-statements
async upload(extension, _name,_size, _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
const nameHash = Mailer.createHash(_name)
const nameExt = `${nameHash}.${extension}`
let targetPath = `/${ _userName }/${ nameExt}`
//calculate expiry date
const today = new Date()
const later = addDays(today, 3)
const expire = `${later.getFullYear()}-${later.getMonth() + 1}-${later.getDate()}`
const sql = `INSERT INTO Files(FileName,FileType,FilePath,Size, FileHash, ExpDate)
VALUES( "${_name}","${extension}", "${targetPath}", "${size}","${nameHash}","${expire}")`
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) {
/* istanbul ignore next */
throw err
}
}
async deleteExpired() {
try{
// eslint-disable-next-line quotes
let sql = `SELECT FileHash, FilePath FROM Files WHERE date('now') > date(Date, '+3 days')
OR Downloaded LIKE true`
const data = await this.db.all(sql)
for (const key in data) {
fs.unlinkSync(`private${data[key]['FilePath']}`)
sql = `DELETE FROM Files WHERE FileHash LIKE '${data[key]['FileHash']}'`
await this.db.run(sql)
}
console.log('Expired files deleted')
return true
}catch(err) {
/* istanbul ignore next */
throw err
}
}
async updateValue(_fileHash) {
try {
// eslint-disable-next-line quotes
const sql = `UPDATE Files SET Downloaded=true WHERE FileHash LIKE '${_fileHash}' OR FileName LIKE '${_fileHash}'`
await this.db.run(sql)
return true
} catch (err) {
/* istanbul ignore next */
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) {
/* istanbul ignore next */
throw err
}
}
async countItems() {
try {
const sql = 'SELECT COUNT(*) AS count FROM Files'
let count = await this.db.all(sql)
count = count[0]['count']
return count
} catch (err) {
/* istanbul ignore next */
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}' OR FileName LIKE '${_fileName}'`
const data = await this.db.all(sql)
return data
} catch (err) {
/* istanbul ignore next */
throw err
}
}
/* istanbul ignore next */
async tearDown() {
await this.db.close()
}
}