]>
git.r.bdr.sh - rbdr/blog/blob - lib/blog.js
ca944cfbdfa2c55160aacfcf74dafbce63d5695f
3 const { access
, cp
, mkdir
, readdir
, readFile
, writeFile
} = require('fs/promises');
4 const { exec
} = require('child_process');
5 const { basename
, resolve
, join
} = require('path');
6 const ParseGemini
= require('gemini-to-html/parse');
7 const RenderGemini
= require('gemini-to-html/render');
8 const { debuglog
, promisify
} = require('util');
9 const { ensureDirectoryExists
, rmIfExists
} = require('./utils');
10 const { kFileNotFoundError
} = require('./constants');
12 // Generators for the Blog
14 const StaticGenerator
= require('./generators/static');
15 const HTMLGenerator
= require('./generators/html');
16 const RSSGenerator
= require('./generators/rss');
17 const TXTGenerator
= require('./generators/txt');
21 const GemlogArchiver
= require('./archivers/gemlog');
25 const Remote
= require('./remote');
29 // Promisified functions
30 exec: promisify(exec
),
32 debuglog: debuglog('blog'),
37 kMetadataFilename: 'metadata.json',
42 geminiNotFound: 'Gemini file was not found in blog directory. Please update.'
47 * The Blog class is the blog generator, it's in charge of adding and
48 * updating posts, and handling the publishing.
51 * @param {Blog.tConfiguration} config the initialization options to
54 module
.exports
= class Blog
{
58 Object
.assign(this, config
);
62 * Shifts the blog posts, adds the passed file to slot 0, and
67 * @param {string} postLocation the path to the blog post file
68 * @return {Promise<undefined>} empty promise, returns no value
71 async
add(postLocation
) {
73 await
ensureDirectoryExists(this.postsDirectory
);
75 await
this.syncDown();
79 const firstDirectory
= join(this.postsDirectory
, '0');
80 await
rmIfExists(firstDirectory
);
81 await
ensureDirectoryExists(firstDirectory
);
82 await
this._update(postLocation
);
86 * Update slot 0 with the passed gmi file, and generates files.
90 * @param {string} postLocation the path to the blog post file
91 * @return {Promise<undefined>} empty promise, returns no value
94 async
update(postLocation
) {
97 await
this.syncDown();
100 const metadata
= await
this._update(postLocation
);
104 * Publishes the files to a static host.
108 * @return {Promise<undefined>} empty promise, returns no value
111 async
publish(host
) {
113 internals
.debuglog(`Publishing to ${host}`);
115 await internals
.exec('which aws');
118 console
.error('Please install and configure AWS CLI to publish.');
122 internals
.debuglog(`Copying ephemeral blog from ${this.staticDirectory}`);
123 await internals
.exec(`rsync -r ${this.staticDirectory}/ ${host}`);
126 console
.error('Failed to publish');
127 console
.error(err
.stderr
);
130 internals
.debuglog('Finished publishing');
134 * Publishes the archive to a host using rsync. Currently assumes
137 * @function publishArchive
139 * @return {Promise<undefined>} empty promise, returns no value
142 async
publishArchive(host
) {
144 internals
.debuglog(`Publishing archive to ${host}`);
146 await internals
.exec('which rsync');
149 console
.error('Please install rsync to publish the archive.');
153 const gemlogPath
= resolve(join(__dirname
, '../', '.gemlog'));
154 internals
.debuglog(`Copying archive from ${gemlogPath}`);
155 await internals
.exec(`rsync -r ${gemlogPath}/ ${host}`);
158 console
.error('Failed to publish archive');
159 console
.error(err
.stderr
);
162 internals
.debuglog('Finished publishing');
168 * @function addRemote
170 * @return {Promise<undefined>} empty promise, returns no value
173 async
addRemote(remote
) {
174 await Remote
.add(this.remoteConfig
, remote
)
180 * @function removeRemote
182 * @return {Promise<undefined>} empty promise, returns no value
185 async
removeRemote() {
186 await Remote
.remove(this.remoteConfig
)
191 * Pulls the posts and archive from the remote
195 * @return {Promise<undefined>} empty promise, returns no value
199 internals
.debuglog('Pulling remote state');
200 await
ensureDirectoryExists(this.postsDirectory
);
201 await Remote
.syncDown(this.remoteConfig
, this.blogDirectory
)
202 internals
.debuglog('Pulled remote state');
206 * Pushes the posts and archive to the remote
210 * @return {Promise<undefined>} empty promise, returns no value
214 internals
.debuglog('Pushing remote state');
215 await
ensureDirectoryExists(this.postsDirectory
);
216 await Remote
.syncUp(this.remoteConfig
, this.blogDirectory
)
217 internals
.debuglog('Pushed remote state');
220 // Adds the passed path to slot 0, and generates files.
222 async
_update(postLocation
) {
224 const metadata
= await
this._getMetadata();
225 await
ensureDirectoryExists(this.postsDirectory
);
226 await
this._copyPost(postLocation
);
227 await
this._writeMetadata(metadata
);
229 await
this._archive(postLocation
);
231 await
this.generate();
239 // Parses Gemini for each page, copies assets and generates index.
243 internals
.debuglog('Generating output');
245 const posts
= await
this._readPosts();
247 await
StaticGenerator(this.postsDirectory
, this.staticDirectory
, posts
);
248 await
HTMLGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
249 await
RSSGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
250 await
TXTGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
252 await
GemlogArchiver(this.archiveDirectory
);
255 // Reads the posts into an array
259 internals
.debuglog('Reading posts');
262 for (let i
= 0; i
< this.maxPosts
; ++i
) {
264 posts
.push(await
this._readPost(i
));
267 if (error
.code
=== kFileNotFoundError
) {
268 internals
.debuglog(`Skipping ${i}`);
279 // Reads an individual post
281 async
_readPost(index
=0) {
282 const postSourcePath
= join(this.postsDirectory
, `${index}`);
284 internals
.debuglog(`Reading ${postSourcePath}`);
286 await
access(postSourcePath
);
288 const metadata
= await
this._getMetadata(index
);
290 const postContentPath
= await
this._findBlogContent(postSourcePath
);
291 internals
.debuglog(`Reading ${postContentPath}`);
292 const postContent
= await
readFile(postContentPath
, { encoding: 'utf8' });
294 internals
.debuglog('Parsing Gemini');
297 location: postSourcePath
,
299 html: RenderGemini(ParseGemini(postContent
)),
304 // Shift the posts, delete any remainder.
309 for (let i
= this.maxPosts
- 1; i
>= 1; --i
) {
310 const targetPath
= join(this.postsDirectory
, `${i}`);
311 const sourcePath
= join(this.postsDirectory
, `${i - 1}`);
314 internals
.debuglog(`Archiving ${targetPath}`);
315 await
rmIfExists(targetPath
);
316 await
access(sourcePath
); // check the source path
318 internals
.debuglog(`Shifting blog post ${sourcePath} to ${targetPath}`);
319 await
cp(sourcePath
, targetPath
, { recursive: true });
322 if (error
.code
=== kFileNotFoundError
) {
323 internals
.debuglog(`Skipping ${sourcePath}: Does not exist.`);
332 // Moves older posts to the archive
335 internals
.debuglog('Archiving post');
336 const post
= await
this._readPost(0);
337 await
ensureDirectoryExists(this.archiveDirectory
);
339 const targetPath
= join(this.archiveDirectory
, post
.id
);
341 internals
.debuglog(`Removing ${targetPath}`);
342 await
rmIfExists(targetPath
);
343 internals
.debuglog(`Adding ${post.location} to ${targetPath}`);
344 await
ensureDirectoryExists(targetPath
);
345 await
cp(post
.location
, targetPath
, { recursive: true });
346 internals
.debuglog(`Added ${post.location} to ${targetPath}`);
349 // Attempts to read existing metadata. Otherwise generates new set.
351 async
_getMetadata(index
= 0) {
353 const metadataTarget
= join(this.postsDirectory
, String(index
), internals
.kMetadataFilename
);
356 internals
.debuglog(`Looking for metadata at ${metadataTarget}`);
357 return JSON
.parse(await
readFile(metadataTarget
, { encoding: 'utf8' }));
360 internals
.debuglog(`Metadata not found or unreadable. Generating new set.`);
361 const createdOn
= Date
.now();
363 id: String(createdOn
),
371 // Writes metadata. Assumes post 0 since it only gets written
374 async
_writeMetadata(metadata
) {
376 const metadataTarget
= join(this.postsDirectory
, '0', internals
.kMetadataFilename
);
377 internals
.debuglog(`Writing ${metadataTarget}`);
378 await
writeFile(metadataTarget
, JSON
.stringify(metadata
, null, 2));
381 // Copies a post file to the latest slot.
383 async
_copyPost(postLocation
) {
385 internals
.debuglog(`Copying ${postLocation}`);
386 const targetPath
= join(this.postsDirectory
, '0');
387 const postName
= basename(postLocation
);
388 const targetPost
= join(targetPath
, postName
);
390 await
rmIfExists(targetPath
);
391 await
ensureDirectoryExists(targetPath
);
392 await
cp(postLocation
, targetPost
, { recursive: true });
393 internals
.debuglog(`Added ${postLocation} to ${targetPath}`);
396 // Looks for a `.gmi` file in the blog directory, and returns the path
398 async
_findBlogContent(directory
) {
400 const entries
= await
readdir(directory
);
402 const geminiEntries
= entries
403 .filter((entry
) => internals
.kGeminiRe
.test(entry
))
404 .map((entry
) => join(directory
, entry
));
406 if (geminiEntries
.length
> 0) {
407 internals
.debuglog(`Found gemini file: ${geminiEntries[0]}`);
408 return geminiEntries
[0];
411 throw new Error(internals
.strings
.geminiNotFound
);