]>
git.r.bdr.sh - rbdr/blog/blob - lib/blog.js
0b291dfa71b8c00dd40438c30e5728459f38ae52
3 const { access
, cp
, mkdir
, readdir
, readFile
, rm
, 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');
10 // Generators for the Blog
12 const StaticGenerator
= require('./generators/static');
13 const HTMLGenerator
= require('./generators/html');
14 const RSSGenerator
= require('./generators/rss');
15 const TXTGenerator
= require('./generators/txt');
19 const GemlogArchiver
= require('./archivers/gemlog');
23 const Remote
= require('./remote');
27 // Promisified functions
28 exec: promisify(exec
),
30 debuglog: debuglog('blog'),
34 kFileNotFoundError: 'ENOENT',
36 kMetadataFilename: 'metadata.json',
41 geminiNotFound: 'Gemini file was not found in blog directory. Please update.'
46 * The Blog class is the blog generator, it's in charge of adding and
47 * updating posts, and handling the publishing.
50 * @param {Blog.tConfiguration} config the initialization options to
53 module
.exports
= class Blog
{
57 Object
.assign(this, config
);
61 * Shifts the blog posts, adds the passed path to slot 0, and
66 * @param {string} postLocation the path to the directory containing
68 * @return {Promise<undefined>} empty promise, returns no value
71 async
add(postLocation
) {
73 await
this._ensurePostsDirectoryExists();
75 await
this.syncDown();
79 const firstDirectory
= join(this.postsDirectory
, '0');
80 await
rm(firstDirectory
, { recursive: true, force: true });
81 await
this._ensurePostsDirectoryExists(firstDirectory
);
82 await
this._update(postLocation
);
86 * Adds the passed path to slot 0, and generates files.
90 * @param {string} postLocation the path to the directory containing
92 * @return {Promise<undefined>} empty promise, returns no value
95 async
update(postLocation
) {
98 await
this.syncDown();
101 const metadata
= await
this._update();
105 * Publishes the files to a static host.
109 * @return {Promise<undefined>} empty promise, returns no value
112 async
publish(bucket
) {
114 internals
.debuglog(`Publishing to ${bucket}`);
116 await internals
.exec('which aws');
119 console
.error('Please install and configure AWS CLI to publish.');
123 await internals
.exec(`aws s3 sync --acl public-read --delete ${this.staticDirectory} s3://${bucket}`);
124 await internals
.exec(`aws s3 cp --content-type 'text/plain; charset=utf-8 ' --acl public-read ${this.staticDirectory}/index.txt s3://${bucket}`);
127 console
.error('Failed to publish');
128 console
.error(err
.stderr
);
131 internals
.debuglog('Finished publishing');
135 * Publishes the archive to a host using rsync. Currently assumes
138 * @function publishArchive
140 * @return {Promise<undefined>} empty promise, returns no value
143 async
publishArchive(host
) {
145 internals
.debuglog(`Publishing archive to ${host}`);
147 await internals
.exec('which rsync');
150 console
.error('Please install rsync to publish the archive.');
154 const gemlogPath
= resolve(join(__dirname
, '../', '.gemlog'));
155 internals
.debuglog(`Reading archive from ${gemlogPath}`);
156 await internals
.exec(`rsync -r ${gemlogPath}/ ${host}`);
159 console
.error('Failed to publish archive');
160 console
.error(err
.stderr
);
163 internals
.debuglog('Finished publishing');
169 * @function addRemote
171 * @return {Promise<undefined>} empty promise, returns no value
174 async
addRemote(remote
) {
175 await Remote
.add(this.remoteConfig
, remote
)
181 * @function removeRemote
183 * @return {Promise<undefined>} empty promise, returns no value
186 async
removeRemote() {
187 await Remote
.remove(this.remoteConfig
)
192 * Pulls the posts and archive from the remote
196 * @return {Promise<undefined>} empty promise, returns no value
200 internals
.debuglog('Pulling remote state');
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 Remote
.syncUp(this.remoteConfig
, this.blogDirectory
)
216 internals
.debuglog('Pushed remote state');
219 // Adds the passed path to slot 0, and generates files.
221 async
_update(postLocation
) {
223 const metadata
= await
this._getMetadata();
224 await
this._ensurePostsDirectoryExists();
225 await
this._copyPost(postLocation
);
226 await
this._writeMetadata(metadata
);
228 await
this._archive(postLocation
);
230 await
this.generate();
238 // Parses Gemini for each page, copies assets and generates index.
242 internals
.debuglog('Generating output');
244 const posts
= await
this._readPosts();
246 await
StaticGenerator(this.postsDirectory
, this.staticDirectory
, posts
);
247 await
HTMLGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
248 await
RSSGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
249 await
TXTGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
251 await
GemlogArchiver(this.archiveDirectory
);
254 // Reads the posts into an array
258 internals
.debuglog('Reading posts');
261 for (let i
= 0; i
< this.maxPosts
; ++i
) {
263 posts
.push(await
this._readPost(i
));
266 if (error
.code
=== internals
.kFileNotFoundError
) {
267 internals
.debuglog(`Skipping ${i}`);
278 // Reads an individual post
280 async
_readPost(index
=0) {
281 const postSourcePath
= join(this.postsDirectory
, `${index}`);
283 internals
.debuglog(`Reading ${postSourcePath}`);
285 await
access(postSourcePath
);
287 const metadata
= await
this._getMetadata(index
);
289 const postContentPath
= await
this._findBlogContent(postSourcePath
);
290 internals
.debuglog(`Reading ${postContentPath}`);
291 const postContent
= await
readFile(postContentPath
, { encoding: 'utf8' });
293 internals
.debuglog('Parsing Gemini');
296 location: postSourcePath
,
298 html: RenderGemini(ParseGemini(postContent
)),
303 // Shift the posts, delete any remainder.
308 for (let i
= this.maxPosts
- 1; i
>= 1; --i
) {
309 const targetPath
= join(this.postsDirectory
, `${i}`);
310 const sourcePath
= join(this.postsDirectory
, `${i - 1}`);
313 internals
.debuglog(`Archiving ${targetPath}`);
314 await
rm(targetPath
, { recursive: true, force: true });
315 await
access(sourcePath
); // check the source path
317 internals
.debuglog(`Shifting blog post ${sourcePath} to ${targetPath}`);
318 await
cp(sourcePath
, targetPath
, { recursive: true });
321 if (error
.code
=== internals
.kFileNotFoundError
) {
322 internals
.debuglog(`Skipping ${sourcePath}: Does not exist.`);
331 // Moves older posts to the archive
334 internals
.debuglog('Archiving post');
335 const post
= await
this._readPost(0);
336 await
this._ensureDirectoryExists(this.archiveDirectory
);
338 const targetPath
= join(this.archiveDirectory
, post
.id
);
340 internals
.debuglog(`Removing ${targetPath}`);
341 await
rm(targetPath
, { recursive: true, force: true });
342 internals
.debuglog(`Adding ${post.location} to ${targetPath}`);
343 await
this._ensureDirectoryExists(targetPath
);
344 await
cp(post
.location
, targetPath
, { recursive: true });
345 internals
.debuglog(`Added ${post.location} to ${targetPath}`);
348 // Attempts to read existing metadata. Otherwise generates new set.
350 async
_getMetadata(index
= 0) {
352 const metadataTarget
= join(this.postsDirectory
, String(index
), internals
.kMetadataFilename
);
355 internals
.debuglog(`Looking for metadata at ${metadataTarget}`);
356 return JSON
.parse(await
readFile(metadataTarget
, { encoding: 'utf8' }));
359 internals
.debuglog(`Metadata not found or unreadable. Generating new set.`);
360 const createdOn
= Date
.now();
362 id: String(createdOn
),
370 // Writes metadata. Assumes post 0 since it only gets written
373 async
_writeMetadata(metadata
) {
375 const metadataTarget
= join(this.postsDirectory
, '0', internals
.kMetadataFilename
);
376 internals
.debuglog(`Writing ${metadataTarget}`);
377 await
writeFile(metadataTarget
, JSON
.stringify(metadata
, null, 2));
380 // Copies a post directory to the latest slot.
382 async
_copyPost(postLocation
) {
384 const targetPath
= join(this.postsDirectory
, '0');
385 const postName
= basename(postLocation
);
386 const targetPost
= join(targetPath
, postName
);
388 internals
.debuglog(`Removing ${targetPath}`);
389 await
rm(targetPath
, { recursive: true, force: true });
390 await
this._ensureDirectoryExists(targetPath
);
391 internals
.debuglog(`Adding ${postLocation} to ${targetPost}`);
392 await
cp(postLocation
, targetPost
, { recursive: true });
393 internals
.debuglog(`Added ${postLocation} to ${targetPath}`);
396 // Ensures a directory exists.
398 async
_ensureDirectoryExists(directory
) {
400 internals
.debuglog(`Checking if ${directory} exists.`);
402 await
access(directory
);
405 if (error
.code
=== internals
.kFileNotFoundError
) {
406 internals
.debuglog(`Creating ${directory}`);
407 await
mkdir(directory
, { recursive: true });
415 // Ensures posts directory exists
417 async
_ensurePostsDirectoryExists() {
419 return this._ensureDirectoryExists(this.postsDirectory
);
422 // Looks for a `.gmi` file in the blog directory, and returns the path
424 async
_findBlogContent(directory
) {
426 const entries
= await
readdir(directory
);
428 const geminiEntries
= entries
429 .filter((entry
) => internals
.kGeminiRe
.test(entry
))
430 .map((entry
) => join(directory
, entry
));
432 if (geminiEntries
.length
> 0) {
433 internals
.debuglog(`Found gemini file: ${geminiEntries[0]}`);
434 return geminiEntries
[0];
437 throw new Error(internals
.strings
.geminiNotFound
);