From 95f48b24ba68171a7a2822f1f0c80dce24178a7d Mon Sep 17 00:00:00 2001 From: Hippo Date: Tue, 24 Dec 2019 14:50:48 +0530 Subject: [PATCH] Implement "image upload" part of push-ghost command --- functions.js | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/functions.js b/functions.js index ffa30ee..ca362de 100644 --- a/functions.js +++ b/functions.js @@ -3,6 +3,7 @@ const path = require('path') const fs = require('fs') const getPost = require('mediumexporter').getPost const { createClient } = require('webdav') +const readline = require('readline') /** * function [fetchFromMedium] @@ -66,6 +67,80 @@ const fetchFromMedium = async (mediumUrl) => { */ const pushToGhost = (postSlug) => { console.info('Pushing: ' + postSlug); + + // Decide working path + postFolder = path.resolve('content/' + postSlug) + + // Verify file exists + if (!fs.existsSync(postFolder)) { + console.error('Could not find post folder! Is it fetched?') + return false + } + + // Decide file + const postContent = path.join(postFolder, 'index.md') + const postOutput = path.join(postFolder, 'ghost.md') + + // Verify post exists + if (!fs.existsSync(postContent)) { + console.error("Could not find 'index.md' in " + postSlug + "! Is it fetched?") + return false + } + + // Decide WebDAV upload path + current_date = new Date() + + var uploadPath = path.join( + current_date.getUTCFullYear().toString(), + current_date.getUTCMonth().toString(), + postSlug + ) + + // Path where WebDAV files will be placed (eg. https://example.com:2078) + var davPath = path.join(process.env.WEBDAV_PATH_PREFIX, uploadPath) + + // Public path to upload those files (eg. https://media.example.com/uploads) + // We'll do it directly since path.join mangles the protocol + var uploadedPath = process.env.WEBDAV_UPLOADED_PATH_PREFIX + '/' + uploadPath + + // Process lines + const readInterface = readline.createInterface({ + input: fs.createReadStream(postContent), + output: process.stdout, + terminal: false + }) + + const outStream = fs.createWriteStream(postOutput, { encoding: 'utf-8' }) + + readInterface.on('line', (line) => { + console.log('Line: ' + line + '\n') + + // TODO: actually process line + var newLine = line + + // check for images + const reImage = new RegExp('^!\\[(.*)\\]\\((\\S+?)\\)(.*)') + var m = reImage.exec(line) + if (m) { + // Get image name + var imageAlt = m[1] + var imageName = m[2].replace('*', '') + var imagePath = path.join(postFolder, 'images', imageName) + + if (!fs.existsSync(imagePath)) { + console.warn('Skipping missing image: ' + imageName) + } else { + // TODO: upload pic + uploadDav(davPath, imagePath) + + newLine = '![' + imageAlt + '](' + uploadedPath + '/' + imageName + ')' + } + } + + outStream.write(newLine + '\n') + }) + + console.log('Processing over. Rest needs to be implemented :P') }; /**