]>
git.r.bdr.sh - rbdr/blog/blob - lib/blog.js
ba9ae534f25b067acde2b271f2139f51b02b79f7
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 await
this._ensurePostsDirectoryExists(join(this.postsDirectory
, '0'));
80 await
this.update(postLocation
);
84 * Adds the passed path to slot 0, and generates files.
88 * @param {string} postLocation the path to the directory containing
90 * @return {Promise<undefined>} empty promise, returns no value
93 async
update(postLocation
) {
96 await
this.syncDown();
99 const metadata
= await
this._getMetadata();
100 await
this._ensurePostsDirectoryExists();
101 await
this._copyPost(postLocation
);
102 await
this._writeMetadata(metadata
);
104 await
this._archive(postLocation
);
106 await
this.generate();
114 * Publishes the files to a static host.
118 * @return {Promise<undefined>} empty promise, returns no value
121 async
publish(bucket
) {
123 internals
.debuglog(`Publishing to ${bucket}`);
125 await internals
.exec('which aws');
128 console
.error('Please install and configure AWS CLI to publish.');
132 await internals
.exec(`aws s3 sync --acl public-read --delete ${this.staticDirectory} s3://${bucket}`);
133 await internals
.exec(`aws s3 cp --content-type 'text/plain; charset=utf-8 ' --acl public-read ${this.staticDirectory}/index.txt s3://${bucket}`);
136 console
.error('Failed to publish');
137 console
.error(err
.stderr
);
140 internals
.debuglog('Finished publishing');
144 * Publishes the archive to a host using rsync. Currently assumes
147 * @function publishArchive
149 * @return {Promise<undefined>} empty promise, returns no value
152 async
publishArchive(host
) {
154 internals
.debuglog(`Publishing archive to ${host}`);
156 await internals
.exec('which rsync');
159 console
.error('Please install rsync to publish the archive.');
163 const gemlogPath
= resolve(join(__dirname
, '../', '.gemlog'));
164 internals
.debuglog(`Reading archive from ${gemlogPath}`);
165 await internals
.exec(`rsync -r ${gemlogPath}/ ${host}`);
168 console
.error('Failed to publish archive');
169 console
.error(err
.stderr
);
172 internals
.debuglog('Finished publishing');
178 * @function addRemote
180 * @return {Promise<undefined>} empty promise, returns no value
183 async
addRemote(remote
) {
184 await Remote
.add(this.remoteConfig
, remote
)
190 * @function removeRemote
192 * @return {Promise<undefined>} empty promise, returns no value
195 async
removeRemote() {
196 await Remote
.remove(this.remoteConfig
)
201 * Pulls the posts and archive from the remote
205 * @return {Promise<undefined>} empty promise, returns no value
209 await Remote
.syncDown(this.remoteConfig
, this.blogDirectory
)
213 * Pushes the posts and archive to the remote
217 * @return {Promise<undefined>} empty promise, returns no value
221 await Remote
.syncUp(this.remoteConfig
, this.blogDirectory
)
224 // Parses Gemini for each page, copies assets and generates index.
228 internals
.debuglog('Generating output');
230 const posts
= await
this._readPosts();
232 await
StaticGenerator(this.postsDirectory
, this.staticDirectory
, posts
);
233 await
HTMLGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
234 await
RSSGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
235 await
TXTGenerator(this.templatesDirectory
, this.staticDirectory
, posts
);
237 await
GemlogArchiver(this.archiveDirectory
);
240 // Reads the posts into an array
244 internals
.debuglog('Reading posts');
247 for (let i
= 0; i
< this.maxPosts
; ++i
) {
249 posts
.push(await
this._readPost(i
));
252 if (error
.code
=== internals
.kFileNotFoundError
) {
253 internals
.debuglog(`Skipping ${i}`);
264 // Reads an individual post
266 async
_readPost(index
=0) {
267 const postSourcePath
= join(this.postsDirectory
, `${index}`);
269 internals
.debuglog(`Reading ${postSourcePath}`);
271 await
access(postSourcePath
);
273 const metadata
= await
this._getMetadata(index
);
275 const postContentPath
= await
this._findBlogContent(postSourcePath
);
276 internals
.debuglog(`Reading ${postContentPath}`);
277 const postContent
= await
readFile(postContentPath
, { encoding: 'utf8' });
279 internals
.debuglog('Parsing Gemini');
282 location: postSourcePath
,
284 html: RenderGemini(ParseGemini(postContent
)),
289 // Shift the posts, delete any remainder.
294 for (let i
= this.maxPosts
- 1; i
>= 1; --i
) {
295 const targetPath
= join(this.postsDirectory
, `${i}`);
296 const sourcePath
= join(this.postsDirectory
, `${i - 1}`);
299 internals
.debuglog(`Archiving ${targetPath}`);
300 await
rm(targetPath
, { recursive: true, force: true });
301 await
access(sourcePath
); // check the source path
303 internals
.debuglog(`Shifting blog post ${sourcePath} to ${targetPath}`);
304 await
cp(sourcePath
, targetPath
, { recursive: true });
307 if (error
.code
=== internals
.kFileNotFoundError
) {
308 internals
.debuglog(`Skipping ${sourcePath}: Does not exist.`);
317 // Moves older posts to the archive
320 internals
.debuglog('Archiving post');
321 const post
= await
this._readPost(0);
322 await
this._ensureDirectoryExists(this.archiveDirectory
);
324 const targetPath
= join(this.archiveDirectory
, post
.id
);
326 internals
.debuglog(`Removing ${targetPath}`);
327 await
rm(targetPath
, { recursive: true, force: true });
328 internals
.debuglog(`Adding ${post.location} to ${targetPath}`);
329 await
this._ensureDirectoryExists(targetPath
);
330 await
cp(post
.location
, targetPath
, { recursive: true });
331 internals
.debuglog(`Added ${post.location} to ${targetPath}`);
334 // Attempts to read existing metadata. Otherwise generates new set.
336 async
_getMetadata(index
= 0) {
338 const metadataTarget
= join(this.postsDirectory
, String(index
), internals
.kMetadataFilename
);
341 internals
.debuglog(`Looking for metadata at ${metadataTarget}`);
342 return JSON
.parse(await
readFile(metadataTarget
, { encoding: 'utf8' }));
345 internals
.debuglog(`Metadata not found or unreadable. Generating new set.`);
346 const createdOn
= Date
.now();
348 id: String(createdOn
),
356 // Writes metadata. Assumes post 0 since it only gets written
359 async
_writeMetadata(metadata
) {
361 const metadataTarget
= join(this.postsDirectory
, '0', internals
.kMetadataFilename
);
362 internals
.debuglog(`Writing ${metadataTarget}`);
363 await
writeFile(metadataTarget
, JSON
.stringify(metadata
, null, 2));
366 // Copies a post directory to the latest slot.
368 async
_copyPost(postLocation
) {
370 const targetPath
= join(this.postsDirectory
, '0');
371 const postName
= basename(postLocation
);
372 const targetPost
= join(targetPath
, postName
);
374 internals
.debuglog(`Removing ${targetPath}`);
375 await
rm(targetPath
, { recursive: true, force: true });
376 await
this._ensureDirectoryExists(targetPath
);
377 internals
.debuglog(`Adding ${postLocation} to ${targetPost}`);
378 await
cp(postLocation
, targetPost
, { recursive: true });
379 internals
.debuglog(`Added ${postLocation} to ${targetPath}`);
382 // Ensures a directory exists.
384 async
_ensureDirectoryExists(directory
) {
386 internals
.debuglog(`Checking if ${directory} exists.`);
388 await
access(directory
);
391 if (error
.code
=== internals
.kFileNotFoundError
) {
392 internals
.debuglog(`Creating ${directory}`);
393 await
mkdir(directory
, { recursive: true });
401 // Ensures posts directory exists
403 async
_ensurePostsDirectoryExists() {
405 return this._ensureDirectoryExists(this.postsDirectory
);
408 // Looks for a `.gmi` file in the blog directory, and returns the path
410 async
_findBlogContent(directory
) {
412 const entries
= await
readdir(directory
);
414 const geminiEntries
= entries
415 .filter((entry
) => internals
.kGeminiRe
.test(entry
))
416 .map((entry
) => join(directory
, entry
));
418 if (geminiEntries
.length
> 0) {
419 internals
.debuglog(`Found gemini file: ${geminiEntries[0]}`);
420 return geminiEntries
[0];
423 throw new Error(internals
.strings
.geminiNotFound
);