app2-api/helpers/cdn.helper.js

97 lines
2.4 KiB
JavaScript
Raw Normal View History

2019-08-07 18:32:13 +00:00
const Path = require("path");
2019-07-24 14:50:41 +00:00
const config = require('../config');
2019-08-07 18:32:13 +00:00
const sanitize = require("sanitize-filename");
const safename = require("safename");
2019-08-15 21:44:09 +00:00
const unf = require('unique-file-name');
2019-07-24 14:50:41 +00:00
const assetsUrl = config.cdn.hostname;
const CDN_PATHS = {
BLOG: "blog/",
CITIES: "cities/",
2019-08-19 17:54:39 +00:00
EVENT: "events/",
2019-07-24 14:50:41 +00:00
PROFILE: "profile/",
SPEAKERS: "speakers/",
2019-08-19 17:54:39 +00:00
WALLPAPERS: "wallpapers/",
XLSX: "xlsx/",
2019-07-24 14:50:41 +00:00
};
2019-08-07 18:32:13 +00:00
const sanitizeFilename = (filename) => safename(sanitize(filename, { replacement: "_" }));
2019-07-24 14:50:41 +00:00
2019-08-15 22:22:48 +00:00
const getUniqueName = function (_path, _filename) {
2019-08-15 21:44:09 +00:00
const namer = unf({
2019-08-15 22:22:48 +00:00
format: '%48b_%2i%4e',
dir: _path
2019-08-15 21:44:09 +00:00
});
2019-08-15 22:22:48 +00:00
return namer(_filename)
2019-08-15 21:44:09 +00:00
}
2019-07-24 14:50:41 +00:00
const getCDNMediaUrl = (mediaUri) => {
if (mediaUri) {
const pathParsed = mediaUri.indexOf("media") == 0 ? mediaUri.substr("media/".length, mediaUri.length) : mediaUri;
return encodeURI(encodeURI(`${assetsUrl}/${pathParsed}`));
}
else {
return encodeURI(dummyMedia);
}
}
const getCDNCityMediaUrl = (cityName) => encodeURI(`${assetsUrl}/${CDN_PATHS.CITIES}/${cityName}.jpg`);
2019-08-15 21:44:09 +00:00
const getCDNPath = (type = '') => {
2019-08-07 18:32:13 +00:00
var cdnPath = '';
switch (type) {
case 'speaker':
cdnPath = CDN_PATHS.SPEAKERS;
break;
case 'event':
cdnPath = CDN_PATHS.EVENT;
break;
case 'post':
cdnPath = CDN_PATHS.BLOG;
break;
2019-08-19 17:54:39 +00:00
case 'xlsx':
cdnPath = CDN_PATHS.XLSX;
break;
2019-08-07 18:32:13 +00:00
default:
2019-08-15 21:44:09 +00:00
var _date = new Date();
2019-08-15 22:22:48 +00:00
cdnPath = _date.getFullYear() + '/' + (_date.getMonth() + 1) + '/';
2019-08-15 21:44:09 +00:00
break;
}
return Path.join(config.uploads.path, cdnPath);
}
const getCDNFilenameWithPath = (filename, type) => {
var cdnPath = '';
switch (type) {
case 'speaker':
cdnPath = CDN_PATHS.SPEAKERS;
break;
case 'event':
cdnPath = CDN_PATHS.EVENT;
break;
case 'post':
cdnPath = CDN_PATHS.BLOG;
break;
default:
var _date = new Date();
cdnPath = _date.getFullYear() + '/' + _date.getMonth() + '/';
break;
2019-08-07 18:32:13 +00:00
}
return Path.join(cdnPath, sanitizeFilename(filename));
}
2019-07-24 14:50:41 +00:00
module.exports = {
2019-08-15 21:44:09 +00:00
sanitizeFilename,
2019-08-07 18:32:13 +00:00
CDN_PATHS,
2019-07-24 14:50:41 +00:00
getCDNCityMediaUrl,
2019-08-07 18:32:13 +00:00
getCDNMediaUrl,
2019-08-15 21:44:09 +00:00
getCDNPath,
getCDNFilenameWithPath,
getUniqueName
2019-07-24 14:50:41 +00:00
}