forked from JoeyBling/hexo-filter-image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (68 loc) · 2.21 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use strict';
const _ = require('lodash');
/** Jquery库 */
const cheerio = require('cheerio');
// 项目访问上下文路径
var blogRoot = hexo.config.root || '/';
blogRoot = blogRoot.endsWith("/") ? blogRoot : blogRoot + '/';
/** 默认配置 */
const defaultConfig = {
// 日志是否启用
'log': true,
// 是否使用jsDelivr加速
'jsdelivr': null
};
// Apply options with default
let config = _.defaultsDeep({}, hexo.config.filter_image, hexo.theme.config.filter_image, defaultConfig);
/** 获取图片绝对路径 */
function urlForHelper (path = '/') {
if (path[0] === '#' || path.startsWith('//') || path.startsWith(blogRoot) || path.startsWith(config.jsdelivr)) {
return path;
}
// Prepend path
if (config.jsdelivr != null) {
path = path.replace(/\.{2,}/g, '.').replace(/\/{2,}/g, '/');
path = config.jsdelivr + path;
} else {
path = (blogRoot + path).replace(/\/{2,}/g, '/');
}
return path;
}
/** 在文章渲染完成后执行 */
hexo.extend.filter.register('after_post_render', function (data) {
// console.log("excerpt === " + data.excerpt);
// console.log("more === " + data.more);
// console.log("content === " + data.content);
// const config = hexo.config;
/** 摘录、详情、内容 */
const dispose = ['excerpt', 'more', 'content'];
for (var i = 0; i < dispose.length; i++) {
var key = dispose[i];
var $ = cheerio.load(data[key], {
ignoreWhitespace: false,
xmlMode: false,
lowerCaseTags: false,
decodeEntities: false
});
$('img,video').each(function () {
if ($(this).attr('src')) {
// For windows style path, we replace '\' to '/'.
var src = $(this).attr('src').replace('\\', '/');
if (!(/http[s]*.*|\/\/.*/.test(src) ||
/^\s+\//.test(src))) {
/* || /^\s*\/uploads|images\//.test(src) */
$(this).attr('src', urlForHelper(src));
if (config.log) {
console.info && console.info("update link as:-->" + urlForHelper(src));
}
}
} else {
if (config.log) {
console.info && console.info("no src attr, skipped...");
console.info && console.info($(this));
}
}
});
data[key] = $.html();
}
});