Skip to content

Instantly share code, notes, and snippets.

@mockee
Created October 4, 2014 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mockee/5b3b8c80b1428f6bfb5c to your computer and use it in GitHub Desktop.
Save mockee/5b3b8c80b1428f6bfb5c to your computer and use it in GitHub Desktop.
Qiniu storage for Ghost 0.5.2
// # Local File System Image Storage module
// The (default) module for storing images, using the local file system
var express = require('express'),
fs = require('fs-extra'),
path = require('path'),
util = require('util'),
Promise = require('bluebird'),
errors = require('../errors'),
config = require('../config'),
utils = require('../utils'),
baseStore = require('./base'),
crypto = require('crypto'),
qiniu = require('qiniu'),
qiniuConfig = {
bucketname: '',
ACCESS_KEY: '',
SECRET_KEY: '',
root: '/images/',
prefix: ''
};
qiniu.conf.ACCESS_KEY = qiniuConfig.ACCESS_KEY;
qiniu.conf.SECRET_KEY = qiniuConfig.SECRET_KEY;
qiniu.conf.USER_AGENT = 'Ghost 0.5.2';
var putPolicy = new qiniu.rs.PutPolicy(qiniuConfig.bucketname),
uptoken = putPolicy.token();
function Qiniu() {}
util.inherits(Qiniu, baseStore);
// ### Save
// Saves the image to storage (the file system)
// - image is the express image object
// - returns a promise which ultimately returns the full url to the uploaded image
Qiniu.prototype.save = function (image) {
var md5sum = crypto.createHash('md5'),
ext = path.extname(image.name),
targetDirRoot = qiniuConfig.root,
targetFilename,
key,
extra = new qiniu.io.PutExtra();
var savedpath = path.join(config.paths.imagesPath, image.name);
return Promise.promisify(fs.copy)(image.path, savedpath).then(function() {
return Promise.promisify(fs.readFile)(savedpath);
}).then(function(data) {
var md5 = md5sum.update(data).digest('hex');
targetFilename = path.join(targetDirRoot, md5.replace(/^(\w{1})(\w{2})(\w+)$/, '$1/$2/$3')) + ext;
targetFilename = targetFilename.replace(/\\/g, '/');
key = targetFilename.replace(/^\//, '');
return Promise.promisify(qiniu.io.put)(uptoken, key, data, extra);
}).then(function () {
return qiniuConfig.prefix + targetFilename;
}).catch(function (e) {
errors.logError(e);
return Promise.reject(e);
});
};
Qiniu.prototype.exists = function (filename) {
return new Promise(function (resolve) {
fs.exists(filename, function (exists) {
resolve(exists);
});
});
};
// middleware for serving the files
Qiniu.prototype.serve = function () {
// For some reason send divides the max age number by 1000
return express['static'](config.paths.imagesPath, {maxAge: utils.ONE_YEAR_MS});
};
module.exports = Qiniu;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment