]>
git.r.bdr.sh - rbdr/blog/blob - lib/blog.js
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 path to slot 0, and
67 * @param {string} postLocation the path to the directory containing
69 * @return {Promise<undefined>} empty promise, returns no value
72 async
add(postLocation
) {
74 await
ensureDirectoryExists(this.postsDirectory
);
76 await
this.syncDown();
80 const firstDirectory
= join(this.postsDirectory
, '0');
81 await
rmIfExists(firstDirectory
);
82 await
ensureDirectoryExists(firstDirectory
);
83 await
this._update(postLocation
);
87 * Adds the passed path to slot 0, and generates files.
91 * @param {string} postLocation the path to the directory containing
93 * @return {Promise<undefined>} empty promise, returns no value
96 async
update(postLocation
) {
99 await
this.syncDown();
102 const metadata
= await
this._update();
106 * Publishes the files to a static host.
110 * @return {Promise<undefined>} empty promise, returns no value
113 async
publish(bucket
) {
115 internals
.debuglog(`Publishing to ${bucket}`);
117 await internals
.exec('which aws');
120 console
.error('Please install and configure AWS CLI to publish.');
124 await internals
.exec(`aws s3 sync --acl public-read --delete ${this.staticDirectory} s3://${bucket}`);
125 await internals
.exec(`aws s3 cp --content-type 'text/plain; charset=utf-8 ' --acl public-read ${this.staticDirectory}/index.txt s3://${bucket}`);
128 console
.error('Failed to publish');
129 console
.error(err
.stderr
);
132 internals
.debuglog('Finished publishing');
136 * Publishes the archive to a host using rsync. Currently assumes
139 * @function publishArchive
141 * @return {Promise<undefined>} empty promise, returns no value
144 async
publishArchive(host
) {
146 internals
.debuglog(`Publishing archive to ${host}`);
148 await internals
.exec('which rsync');
151 console
.error('Please install rsync to publish the archive.');
155 const gemlogPath
= resolve(join(__dirname
, '../', '.gemlog'));
156 internals
.debuglog(`Reading archive from ${gemlogPath}`);
157 await internals
.exec(`rsync -r ${gemlogPath}/ ${host}`);
160 console
.error('Failed to publish archive');
161 console
.error(err
.stderr
);
164 internals
.debuglog('Finished publishing');
170 * @function addRemote
172 * @return {Promise<undefined>} empty promise, returns no value
175 async
addRemote(remote
) {
176 await Remote
.add(this.remoteConfig
, remote
)
182 * @function removeRemote
184 * @return {Promise<undefined>} empty promise, returns no value
187 async
removeRemote() {
188 await Remote
.remove(this.remoteConfig
)
193 * Pulls the posts and archive from the remote
197 * @return {Promise<undefined>} empty promise, returns no value
201 internals
.debuglog('Pulling remote state');
202 await
ensureDirectoryExists(this.postsDirectory
);
203 await Remote
.syncDown(this.remoteConfig
, this.blogDirectory
)
204 internals
.debuglog('Pulled remote state');
208 * Pushes the posts and archive to the remote
212 * @return {Promise<undefined>} empty promise, returns no value
216 internals
.debuglog('Pushing remote state');
217 await
ensureDirectoryExists(this.postsDirectory
);
218 await Remote
.syncUp(this.remoteConfig
, this.blogDirectory
)
219 internals
.debuglog('Pushed remote state');
222 // Adds the passed path to slot 0, and generates files.
224 async
_update(postLocation
) {
226 const metadata
= await
this._getMetadata();
227 await
ensureDirectoryExists(this.postsDirectory
);
228 await
this._copyPost(postLocation
);
229 await
this._writeMetadata(metadata
);
231 await
this._archive(postLocation
);
233 await
this.generate();
241 // Parses Gemini for each page, copies assets and generates index.
245 internals
.debuglog('Generating output');
247 const posts
= await
this._readPosts();
249 await
StaticGenerator(this.postsDirectory
, this.staticDirectory
, posts
);
250 await
HTMLGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
251 await
RSSGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
252 await
TXTGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
254 await
GemlogArchiver(this.archiveDirectory
);
257 // Reads the posts into an array
261 internals
.debuglog('Reading posts');
264 for (let i
= 0; i
< this.maxPosts
; ++i
) {
266 posts
.push(await
this._readPost(i
));
269 if (error
.code
=== kFileNotFoundError
) {
270 internals
.debuglog(`Skipping ${i}`);
281 // Reads an individual post
283 async
_readPost(index
=0) {
284 const postSourcePath
= join(this.postsDirectory
, `${index}`);
286 internals
.debuglog(`Reading ${postSourcePath}`);
288 await
access(postSourcePath
);
290 const metadata
= await
this._getMetadata(index
);
292 const postContentPath
= await
this._findBlogContent(postSourcePath
);
293 internals
.debuglog(`Reading ${postContentPath}`);
294 const postContent
= await
readFile(postContentPath
, { encoding: 'utf8' });
296 internals
.debuglog('Parsing Gemini');
299 location: postSourcePath
,
301 html: RenderGemini(ParseGemini(postContent
)),
306 // Shift the posts, delete any remainder.
311 for (let i
= this.maxPosts
- 1; i
>= 1; --i
) {
312 const targetPath
= join(this.postsDirectory
, `${i}`);
313 const sourcePath
= join(this.postsDirectory
, `${i - 1}`);
316 internals
.debuglog(`Archiving ${targetPath}`);
317 await
rmIfExists(targetPath
);
318 await
access(sourcePath
); // check the source path
320 internals
.debuglog(`Shifting blog post ${sourcePath} to ${targetPath}`);
321 await
cp(sourcePath
, targetPath
, { recursive: true });
324 if (error
.code
=== kFileNotFoundError
) {
325 internals
.debuglog(`Skipping ${sourcePath}: Does not exist.`);
334 // Moves older posts to the archive
337 internals
.debuglog('Archiving post');
338 const post
= await
this._readPost(0);
339 await
ensureDirectoryExists(this.archiveDirectory
);
341 const targetPath
= join(this.archiveDirectory
, post
.id
);
343 internals
.debuglog(`Removing ${targetPath}`);
344 await
rmIfExists(targetPath
);
345 internals
.debuglog(`Adding ${post.location} to ${targetPath}`);
346 await
ensureDirectoryExists(targetPath
);
347 await
cp(post
.location
, targetPath
, { recursive: true });
348 internals
.debuglog(`Added ${post.location} to ${targetPath}`);
351 // Attempts to read existing metadata. Otherwise generates new set.
353 async
_getMetadata(index
= 0) {
355 const metadataTarget
= join(this.postsDirectory
, String(index
), internals
.kMetadataFilename
);
358 internals
.debuglog(`Looking for metadata at ${metadataTarget}`);
359 return JSON
.parse(await
readFile(metadataTarget
, { encoding: 'utf8' }));
362 internals
.debuglog(`Metadata not found or unreadable. Generating new set.`);
363 const createdOn
= Date
.now();
365 id: String(createdOn
),
373 // Writes metadata. Assumes post 0 since it only gets written
376 async
_writeMetadata(metadata
) {
378 const metadataTarget
= join(this.postsDirectory
, '0', internals
.kMetadataFilename
);
379 internals
.debuglog(`Writing ${metadataTarget}`);
380 await
writeFile(metadataTarget
, JSON
.stringify(metadata
, null, 2));
383 // Copies a post directory to the latest slot.
385 async
_copyPost(postLocation
) {
387 const targetPath
= join(this.postsDirectory
, '0');
388 const postName
= basename(postLocation
);
389 const targetPost
= join(targetPath
, postName
);
391 internals
.debuglog(`Removing ${targetPath}`);
392 await
rmIfExists(targetPath
);
393 await
ensureDirectoryExists(targetPath
);
394 internals
.debuglog(`Adding ${postLocation} to ${targetPost}`);
395 await
cp(postLocation
, targetPost
, { recursive: true });
396 internals
.debuglog(`Added ${postLocation} to ${targetPath}`);
399 // Looks for a `.gmi` file in the blog directory, and returns the path
401 async
_findBlogContent(directory
) {
403 const entries
= await
readdir(directory
);
405 const geminiEntries
= entries
406 .filter((entry
) => internals
.kGeminiRe
.test(entry
))
407 .map((entry
) => join(directory
, entry
));
409 if (geminiEntries
.length
> 0) {
410 internals
.debuglog(`Found gemini file: ${geminiEntries[0]}`);
411 return geminiEntries
[0];
414 throw new Error(internals
.strings
.geminiNotFound
);