]> git.r.bdr.sh - rbdr/blog/blobdiff - lib/blog.js
Add TXT support
[rbdr/blog] / lib / blog.js
index 483577ff3f147b30b02d818970d6ceb38e7ef514..541d6b35da767e6771b7a48dbac9e079253b70c2 100644 (file)
@@ -1,34 +1,28 @@
 'use strict';
 
-const Fs = require('fs');
-const Markdown = require('markdown');
-const Mustache = require('mustache');
-const Ncp = require('ncp');
-const Path = require('path');
-const Rimraf = require('rimraf');
-const Util = require('util');
+const { access, mkdir, readdir, readFile, rmdir, writeFile } = require('fs/promises');
+const { ncp } = require('ncp');
+const { join } = require('path');
+const Marked = require('marked');
+const { debuglog, promisify } = require('util');
+
+const StaticGenerator = require('./generators/static');
+const HTMLGenerator = require('./generators/html');
+const RSSGenerator = require('./generators/rss');
+const TXTGenerator = require('./generators/txt');
 
 const internals = {
 
   // Promisified functions
+  ncp: promisify(ncp),
 
-  fs: {
-    access: Util.promisify(Fs.access),
-    mkdir: Util.promisify(Fs.mkdir),
-    readdir: Util.promisify(Fs.readdir),
-    readFile: Util.promisify(Fs.readFile),
-    writeFile: Util.promisify(Fs.writeFile)
-  },
-  ncp: Util.promisify(Ncp.ncp),
-  rimraf: Util.promisify(Rimraf),
-  debuglog: Util.debuglog('blog'),
+  debuglog: debuglog('blog'),
 
   // constants
 
-  kAssetsDirectoryName: 'assets',
-  kIndexName: 'index.html',
   kFileNotFoundError: 'ENOENT',
   kMarkdownRe: /\.md$/i,
+  kMetadataFilename: 'metadata.json',
 
   // Strings
 
@@ -42,7 +36,7 @@ const internals = {
  * updating posts, and handling the publishing.
  *
  * @class Blog
- * @param {Potluck.tConfiguration} config the initialization options to
+ * @param {Blog.tConfiguration} config the initialization options to
  * extend the instance
  */
 module.exports = class Blog {
@@ -65,6 +59,7 @@ module.exports = class Blog {
    */
   async add(postLocation) {
 
+    await this._ensurePostsDirectoryExists();
     await this._shift();
     await this.update(postLocation);
   }
@@ -81,7 +76,11 @@ module.exports = class Blog {
    */
   async update(postLocation) {
 
+    const metadata = await this._getMetadata();
+    await this._ensurePostsDirectoryExists();
     await this._copyPost(postLocation);
+    await this._writeMetadata(metadata);
+
     await this._generate();
   }
 
@@ -93,64 +92,81 @@ module.exports = class Blog {
    * @return {Promise<undefined>} empty promise, returns no value
    * @instance
    */
-  async publish() {
+  publish() {
 
     console.error('Publishing not yet implemented');
+    return Promise.resolve();
   }
 
   // Parses markdown for each page, copies assets and generates index.
 
   async _generate() {
 
-    const assetsTarget = Path.join(this.staticDirectory, internals.kAssetsDirectoryName);
-    const indexTarget = Path.join(this.staticDirectory, internals.kIndexName);
-    const indexLocation = Path.join(this.templatesDirectory, internals.kIndexName);
-    const posts = [];
+    internals.debuglog('Generating output');
+
+    const posts = await this._readPosts(this.postsDirectory);
+
+    await StaticGenerator(this.postsDirectory, this.staticDirectory, posts);
+    await HTMLGenerator(this.templatesDirectory, this.staticDirectory, posts);
+    await RSSGenerator(this.templatesDirectory, this.staticDirectory, posts);
+    await TXTGenerator(this.templatesDirectory, this.staticDirectory, posts);
+  }
+
+  // Reads the posts into an array
+
+  async _readPosts(source) {
 
-    internals.debuglog(`Removing ${assetsTarget}`);
-    await internals.rimraf(assetsTarget);
+    internals.debuglog('Reading posts');
+    const posts = [];
 
     for (let i = 0; i < this.maxPosts; ++i) {
-      const sourcePath = Path.join(this.postsDirectory, `${i}`);
-      const assetsSource = Path.join(sourcePath, internals.kAssetsDirectoryName);
-      const postContentPath = await this._findBlogContent(sourcePath);
+      const postSourcePath = join(source, `${i}`);
 
-      internals.debuglog(`Copying ${assetsSource} to ${assetsTarget}`);
-      await internals.ncp(assetsSource, assetsTarget);
+      internals.debuglog(`Reading ${postSourcePath} into posts array`);
 
-      internals.debuglog(`Reading ${postContentPath}`);
-      const postContent = await internals.fs.readFile(postContentPath, { encoding: 'utf8' });
+      try {
+        await access(postSourcePath);
 
-      internals.debuglog('Parsing markdown');
-      posts.push({
-        html: Markdown.markdown.toHTML(postContent),
-        id: i + 1
-      });
-    }
+        const metadata = await this._getMetadata(i);
+
+        const postContentPath = await this._findBlogContent(postSourcePath);
+        internals.debuglog(`Reading ${postContentPath}`);
+        const postContent = await readFile(postContentPath, { encoding: 'utf8' });
+
+        internals.debuglog('Parsing markdown');
+        posts.push({
+          ...metadata,
+          html: Marked(postContent),
+          raw: postContent
+        });
+      }
+      catch (error) {
+        if (error.code === internals.kFileNotFoundError) {
+          internals.debuglog(`Skipping ${i}`);
+          continue;
+        }
 
-    internals.debuglog(`Reading ${indexLocation}`);
-    const indexTemplate = await internals.fs.readFile(indexLocation, { encoding: 'utf8' });
+        throw error;
+      }
+    }
 
-    internals.debuglog('Generating HTML');
-    const indexHtml = Mustache.render(indexTemplate, { posts });
-    await internals.fs.writeFile(indexTarget, indexHtml);
+    return posts;
   }
 
   // Shift the posts, delete any remainder.
 
   async _shift() {
 
-    await this._ensurePostsDirectoryExists();
 
-    for (let i = this.maxPosts - 1; i > 0; --i) {
-      const targetPath = Path.join(this.postsDirectory, `${i}`);
-      const sourcePath = Path.join(this.postsDirectory, `${i - 1}`);
+    for (let i = this.maxPosts - 1; i >= 0; --i) {
+      const targetPath = join(this.postsDirectory, `${i}`);
+      const sourcePath = join(this.postsDirectory, `${i - 1}`);
 
       try {
-        await internals.fs.access(sourcePath);
-
         internals.debuglog(`Removing ${targetPath}`);
-        await internals.rimraf(targetPath);
+        await rmdir(targetPath, { recursive: true });
+
+        await access(sourcePath); // check the source path
 
         internals.debuglog(`Shifting blog post ${sourcePath} to ${targetPath}`);
         await internals.ncp(sourcePath, targetPath);
@@ -166,16 +182,46 @@ module.exports = class Blog {
     }
   }
 
+  // Attempts to read existing metadata. Otherwise generates new set.
+
+  async _getMetadata(index = 0) {
+
+    const metadataTarget = join(this.postsDirectory, String(index), internals.kMetadataFilename);
+
+    try {
+      internals.debuglog(`Looking for metadata at ${metadataTarget}`);
+      return JSON.parse(await readFile(metadataTarget, { encoding: 'utf8' }));
+    }
+    catch (e) {
+      internals.debuglog(`Metadata not found or unreadable. Generating new set.`);
+      const createdOn = Date.now();
+      const metadata = {
+        id: String(createdOn),
+        createdOn
+      };
+
+      return metadata;
+    }
+  }
+
+  // Writes metadata. Assumes post 0 since it only gets written
+  // on create
+
+  async _writeMetadata(metadata) {
+
+    const metadataTarget = join(this.postsDirectory, '0', internals.kMetadataFilename);
+    internals.debuglog(`Writing ${metadataTarget}`);
+    await writeFile(metadataTarget, JSON.stringify(metadata, null, 2));
+  }
+
   // Copies a post directory to the latest slot.
 
   async _copyPost(postLocation) {
 
-    await this._ensurePostsDirectoryExists();
-
-    const targetPath = Path.join(this.postsDirectory, '0');
+    const targetPath = join(this.postsDirectory, '0');
 
     internals.debuglog(`Removing ${targetPath}`);
-    await internals.rimraf(targetPath);
+    await rmdir(targetPath, { recursive: true });
 
     internals.debuglog(`Adding ${postLocation} to ${targetPath}`);
     await internals.ncp(postLocation, targetPath);
@@ -187,12 +233,12 @@ module.exports = class Blog {
 
     internals.debuglog(`Checking if ${this.postsDirectory} exists.`);
     try {
-      await internals.fs.access(this.postsDirectory);
+      await access(this.postsDirectory);
     }
     catch (error) {
       if (error.code === internals.kFileNotFoundError) {
         internals.debuglog('Creating posts directory');
-        await internals.fs.mkdir(this.postsDirectory);
+        await mkdir(this.postsDirectory);
         return;
       }
 
@@ -204,11 +250,11 @@ module.exports = class Blog {
 
   async _findBlogContent(directory) {
 
-    const entries = await internals.fs.readdir(directory);
+    const entries = await readdir(directory);
 
     const markdownEntries = entries
       .filter((entry) => internals.kMarkdownRe.test(entry))
-      .map((entry) => Path.join(directory, entry));
+      .map((entry) => join(directory, entry));
 
     if (markdownEntries.length > 0) {
       internals.debuglog(`Found markdown file: ${markdownEntries[0]}`);