diff --git a/src/classes/filesystem/MediaLinksFile.js b/src/classes/filesystem/MediaLinksFile.js new file mode 100644 index 0000000..5d1c51a --- /dev/null +++ b/src/classes/filesystem/MediaLinksFile.js @@ -0,0 +1,74 @@ +const fs = require('fs'); +const path = require('path'); +const { FatalError } = require('../../errors'); + +class MediaLinksFile { + constructor(filename) { + this.file = path.join(process.cwd(), filename); + + if (!fs.existsSync(this.file)) { + throw new FatalError('The specified file could not be found!'); + } + } + + read() { + return new Promise((resolve, reject) => { + fs.readFile(this.file, (err, data) => { + if (err) { + return reject(err); + } + + return resolve(MediaLinksFile.parseBuffer(data)); + }); + }); + } + + write(newContent) { + return new Promise((resolve, reject) => { + fs.writeFile(this.file, newContent, null, (err) => { + if (err) { + return reject(err); + } + + return resolve(); + }); + }); + } + + async removeFirstLink() { + const items = await this.read(); + const serialized = MediaLinksFile.serialize(items.slice(1)); + await this.write(serialized); + } + + remove() { + return new Promise((resolve, reject) => { + fs.unlink(this.file, (err) => { + if (err) { + return reject(err); + } + + return resolve(); + }); + }); + } + + static serialize(content) { + return content.map((line) => `${line}\r`).join('\n'); + } + + static parseBuffer(buffer) { + return buffer.toString() + .split('\n') + .filter((line) => line) + .map((line) => { + const returnCarriageIndex = line.indexOf('\r'); + if (returnCarriageIndex < 0) { + return line; + } + return line.substring(0, returnCarriageIndex); + }); + } +} + +module.exports = MediaLinksFile;