├── preview.md ├── .gitignore ├── .gitmodules ├── swagger-ui-dist ├── favicon-16x16.png ├── favicon-32x32.png ├── absolute-path.js ├── package.json ├── index.js ├── README.md ├── index.html └── oauth2-redirect.html ├── assets └── logo.art ├── src ├── models │ ├── user.js │ ├── user_config.js │ ├── index.js │ └── apikey.js ├── settings │ ├── errors.js │ ├── router.js │ └── controllers.js ├── service │ ├── register_models.js │ ├── user_config_service.js │ ├── data_service.js │ ├── user_service.js │ ├── config_service.js │ └── apikey_service.js ├── version.js ├── errorHandlers.js ├── auth │ ├── router.js │ └── controller.js ├── server │ ├── info.js │ ├── router.js │ ├── index.js │ ├── search.js │ ├── post.js │ ├── controller.js │ └── hexo.js ├── utils.js ├── lib │ └── koa-parallel.js ├── logger.js ├── install.js └── app.js ├── .eslintrc.js ├── config.default.js ├── package.json ├── scripts └── lib.js ├── bin └── www ├── README.md ├── update.js ├── install.js ├── LICENSE └── swagger.json /preview.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | data 3 | .vscode 4 | config.user.js 5 | log -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "frontend"] 2 | path = frontend 3 | url = https://github.com/YuJianghao/winwin-hexo-editor-client.git 4 | -------------------------------------------------------------------------------- /swagger-ui-dist/favicon-16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YuJianghao/winwin-hexo-editor/HEAD/swagger-ui-dist/favicon-16x16.png -------------------------------------------------------------------------------- /swagger-ui-dist/favicon-32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YuJianghao/winwin-hexo-editor/HEAD/swagger-ui-dist/favicon-32x32.png -------------------------------------------------------------------------------- /assets/logo.art: -------------------------------------------------------------------------------- 1 | _ ____ ________ 2 | | | / / / / / ____/ /// 3 | | |_/|_/ / /_/ / __/ / 4 | | / __ / /___ _____________________ 5 | |__/|__/_/ /_/_____/ -------------------------------------------------------------------------------- /src/models/user.js: -------------------------------------------------------------------------------- 1 | const { Schema } = require('warehouse') 2 | 3 | module.exports = ctx => { 4 | const User = new Schema({ 5 | username: String, 6 | password: String 7 | }) 8 | return User 9 | } 10 | -------------------------------------------------------------------------------- /src/models/user_config.js: -------------------------------------------------------------------------------- 1 | const { Schema } = require('warehouse') 2 | 3 | module.exports = ctx => { 4 | const Ui = new Schema({ 5 | config: Object, 6 | user_id: { type: Schema.Types.CUID, ref: 'User' } 7 | }) 8 | 9 | return Ui 10 | } 11 | -------------------------------------------------------------------------------- /src/settings/errors.js: -------------------------------------------------------------------------------- 1 | class SettingsError extends Error { 2 | constructor (message, code) { 3 | super(message) 4 | Error.captureStackTrace(this) 5 | this.code = code 6 | } 7 | } 8 | SettingsError.prototype.name = 'SettingsError' 9 | SettingsError.INVALID_PARAMS = 'INVALID_PARAMS' 10 | 11 | module.exports = SettingsError 12 | -------------------------------------------------------------------------------- /src/service/register_models.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const { models } = require('../models') 4 | 5 | module.exports = ctx => { 6 | const db = ctx.database 7 | 8 | const keys = Object.keys(models) 9 | 10 | for (let i = 0, len = keys.length; i < len; i++) { 11 | const key = keys[i] 12 | db.model(key, models[key](db)) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | browser: true, 4 | commonjs: true, 5 | es6: true 6 | }, 7 | extends: [ 8 | 'standard' 9 | ], 10 | globals: { 11 | Atomics: 'readonly', 12 | SharedArrayBuffer: 'readonly' 13 | }, 14 | parserOptions: { 15 | ecmaVersion: 2018 16 | }, 17 | rules: { 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /config.default.js: -------------------------------------------------------------------------------- 1 | let user 2 | try { 3 | user = require('./config.user') 4 | } catch (err) { 5 | user = {} 6 | } 7 | module.exports = Object.assign({ 8 | port: 5777, 9 | hexoRoot: '', 10 | apikeySecret: 'apikey', 11 | jwtSecret: 'secret', 12 | jwtExpire: '1h', 13 | jwtRefresh: '7d', 14 | username: 'admin', 15 | password: 'admin' 16 | }, user) 17 | -------------------------------------------------------------------------------- /src/models/index.js: -------------------------------------------------------------------------------- 1 | const User = require('./user') 2 | const Apikey = require('./apikey') 3 | const UserConfig = require('./user_config') 4 | 5 | exports.models = { User, Apikey, UserConfig } 6 | 7 | class ModelTypes {} 8 | ModelTypes.User = 'User' 9 | ModelTypes.Apikey = 'Apikey' 10 | ModelTypes.UserConfig = 'UserConfig' 11 | 12 | exports.ModelTypes = ModelTypes 13 | -------------------------------------------------------------------------------- /src/version.js: -------------------------------------------------------------------------------- 1 | const router = require('koa-router')() 2 | const version = require('../package.json').version 3 | const apidoc = require('../swagger.json') 4 | 5 | router.prefix('/info') 6 | 7 | router.get('/apidoc', async (ctx, next) => { 8 | ctx.body = apidoc 9 | }) 10 | 11 | router.get('/version', async (ctx, next) => { 12 | ctx.body = version 13 | }) 14 | 15 | module.exports = router 16 | -------------------------------------------------------------------------------- /src/errorHandlers.js: -------------------------------------------------------------------------------- 1 | const { DataServiceError } = require('./service/data_service') 2 | exports.dataServiceErrorHandler = async function (ctx, next) { 3 | try { 4 | await next() 5 | } catch (err) { 6 | if (err.code === DataServiceError.INITIATING) { 7 | ctx.status = 503 8 | ctx.body = { 9 | success: false, 10 | message: 'initiating, try again later' 11 | } 12 | } else { 13 | throw err 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/models/apikey.js: -------------------------------------------------------------------------------- 1 | const { Schema } = require('warehouse') 2 | 3 | module.exports = ctx => { 4 | const Apikey = new Schema({ 5 | apikey: String, 6 | deviceType: String, 7 | deviceSystem: String, 8 | issuedAt: Date, 9 | lastUsedAt: Date, 10 | user_id: { type: Schema.Types.CUID, ref: 'User' } 11 | }) 12 | 13 | Apikey.virtual('username').get(function () { 14 | const User = ctx.model('User') 15 | return User.findOne({ _id: this.user_id }).username 16 | }) 17 | 18 | return Apikey 19 | } 20 | -------------------------------------------------------------------------------- /swagger-ui-dist/absolute-path.js: -------------------------------------------------------------------------------- 1 | /* 2 | * getAbsoluteFSPath 3 | * @return {string} When run in NodeJS env, returns the absolute path to the current directory 4 | * When run outside of NodeJS, will return an error message 5 | */ 6 | const getAbsoluteFSPath = function () { 7 | // detect whether we are running in a browser or nodejs 8 | if (typeof module !== "undefined" && module.exports) { 9 | return require("path").resolve(__dirname) 10 | } 11 | throw new Error('getAbsoluteFSPath can only be called within a Nodejs environment'); 12 | } 13 | 14 | module.exports = getAbsoluteFSPath 15 | -------------------------------------------------------------------------------- /swagger-ui-dist/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "swagger-ui-dist", 3 | "version": "3.33.0", 4 | "main": "index.js", 5 | "repository": "git@github.com:swagger-api/swagger-ui.git", 6 | "contributors": [ 7 | "(in alphabetical order)", 8 | "Anna Bodnia ", 9 | "Buu Nguyen ", 10 | "Josh Ponelat ", 11 | "Kyle Shockey ", 12 | "Robert Barnwell ", 13 | "Sahar Jafari " 14 | ], 15 | "license": "Apache-2.0", 16 | "dependencies": {}, 17 | "devDependencies": {} 18 | } 19 | -------------------------------------------------------------------------------- /src/auth/router.js: -------------------------------------------------------------------------------- 1 | const router = require('koa-router')() 2 | const auth = require('./controller') 3 | 4 | router.prefix('/auth') 5 | 6 | router.post('/token', auth.basicAuth, auth.getToken) 7 | 8 | router.post('/refresh', auth.jwtAuth, auth.requestRefreshToken, auth.getToken) 9 | 10 | router.post('/apikeytoken', auth.jwtAuth, auth.requestApikey) 11 | 12 | router.get('/apikeys', auth.jwtAuth, auth.getAPIKEYInfo) 13 | 14 | router.delete('/apikey', auth.apiKeyAuth, auth.removeApikey) 15 | 16 | router.delete('/apikey/:id', auth.jwtAuth, auth.removeApikey) 17 | 18 | router.post('/apikey', auth.apiKeyJwtAuth, auth.addApikey) 19 | 20 | module.exports = router 21 | -------------------------------------------------------------------------------- /src/server/info.js: -------------------------------------------------------------------------------- 1 | const restrictedKeys = { 2 | post: [ 3 | '_id', 4 | 'title', 5 | 'date', 6 | 'updated', 7 | 'comments', 8 | 'layout', 9 | '_content', 10 | 'source', 11 | 'slug', 12 | 'photos', 13 | 'link', 14 | 'raw', 15 | 'published', 16 | 'content', 17 | 'excerpt', 18 | 'more', 19 | 'tags', 20 | 'category', 21 | 'categories' 22 | ], 23 | page: [ 24 | 'title', 25 | 'date', 26 | 'updated', 27 | 'comments', 28 | 'layout', 29 | '_content', 30 | 'source', 31 | 'path', 32 | 'raw', 33 | 'content', 34 | 'excerpt' 35 | ] 36 | } 37 | 38 | module.exports = { 39 | restrictedKeys 40 | } 41 | -------------------------------------------------------------------------------- /src/settings/router.js: -------------------------------------------------------------------------------- 1 | const controllers = require('./controllers') 2 | const Router = require('koa-router') 3 | const { apikeyOrJwt } = require('../auth/controller') 4 | const router = new Router() 5 | 6 | router.use(apikeyOrJwt) 7 | router.use(controllers.errorHandler) 8 | 9 | router.prefix('/settings') 10 | 11 | router.get('/user', controllers.getUser) 12 | router.get('/user/:id', controllers.getUser) 13 | router.put('/user', controllers.updateUser) 14 | router.put('/user/:id', controllers.updateUser) 15 | 16 | router.get('/hexo', controllers.getHexoInfo) 17 | router.put('/hexo', controllers.setHexoInfo) 18 | 19 | router.put('/security', controllers.security) 20 | 21 | router.get('/ui', controllers.getUiConfig) 22 | router.put('/ui', controllers.setUiConfig) 23 | 24 | module.exports = router 25 | -------------------------------------------------------------------------------- /swagger-ui-dist/index.js: -------------------------------------------------------------------------------- 1 | try { 2 | module.exports.SwaggerUIBundle = require("./swagger-ui-bundle.js") 3 | module.exports.SwaggerUIStandalonePreset = require("./swagger-ui-standalone-preset.js") 4 | } catch(e) { 5 | // swallow the error if there's a problem loading the assets. 6 | // allows this module to support providing the assets for browserish contexts, 7 | // without exploding in a Node context. 8 | // 9 | // see https://github.com/swagger-api/swagger-ui/issues/3291#issuecomment-311195388 10 | // for more information. 11 | } 12 | 13 | // `absolutePath` and `getAbsoluteFSPath` are both here because at one point, 14 | // we documented having one and actually implemented the other. 15 | // They were both retained so we don't break anyone's code. 16 | module.exports.absolutePath = require("./absolute-path.js") 17 | module.exports.getAbsoluteFSPath = require("./absolute-path.js") 18 | -------------------------------------------------------------------------------- /src/utils.js: -------------------------------------------------------------------------------- 1 | exports.isDev = process.env.NODE_ENV === 'development' 2 | const _ = require('lodash') 3 | /** 4 | * 格式化数据 5 | * @param {Object} obj 对象 6 | * @param {Object} schema 默认对象,每一个项目为部分对象或者 value => validatedValue 的函数 7 | */ 8 | const objparser = (obj = {}, schema, defaultObj) => { 9 | if (!schema) throw new Error('schema is required') 10 | if (!defaultObj) throw new Error('defaultObj is required') 11 | const newObj = _.merge(obj, defaultObj) 12 | Object.keys(newObj).map(key => { 13 | if (schema[key]) { 14 | if (typeof schema[key] === 'function') { 15 | if (obj) { 16 | newObj[key] = schema[key](obj[key]) ? obj[key] : defaultObj[key] 17 | } else { 18 | newObj[key] = defaultObj[key] 19 | } 20 | } else { 21 | newObj[key] = objparser(obj[key] ? obj[key] : {}, schema[key], defaultObj[key]) 22 | } 23 | } 24 | }) 25 | return newObj 26 | } 27 | 28 | exports.objparser = objparser 29 | -------------------------------------------------------------------------------- /swagger-ui-dist/README.md: -------------------------------------------------------------------------------- 1 | # Swagger UI Dist 2 | [![NPM version](https://badge.fury.io/js/swagger-ui-dist.svg)](http://badge.fury.io/js/swagger-ui-dist) 3 | 4 | # API 5 | 6 | This module, `swagger-ui-dist`, exposes Swagger-UI's entire dist folder as a dependency-free npm module. 7 | Use `swagger-ui` instead, if you'd like to have npm install dependencies for you. 8 | 9 | `SwaggerUIBundle` and `SwaggerUIStandalonePreset` can be imported: 10 | ```javascript 11 | import { SwaggerUIBundle, SwaggerUIStandalonePreset } from "swagger-ui-dist" 12 | ``` 13 | 14 | To get an absolute path to this directory for static file serving, use the exported `getAbsoluteFSPath` method: 15 | 16 | ```javascript 17 | const swaggerUiAssetPath = require("swagger-ui-dist").getAbsoluteFSPath() 18 | 19 | // then instantiate server that serves files from the swaggerUiAssetPath 20 | ``` 21 | 22 | For anything else, check the [Swagger-UI](https://github.com/swagger-api/swagger-ui) repository. 23 | -------------------------------------------------------------------------------- /src/lib/koa-parallel.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const Promise = require('any-promise') 4 | 5 | /** 6 | * Expose compositor. 7 | */ 8 | 9 | module.exports = compose 10 | 11 | /** 12 | * Compose `middleware` returning 13 | * a fully valid middleware comprised 14 | * of all those which are passed. 15 | * 16 | * @param {Array[Object]} middleware 17 | * @return {Function} 18 | * @api public 19 | */ 20 | 21 | function compose (middleware) { 22 | if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array[{fn,validator}]!') 23 | for (const item of middleware) { 24 | if (typeof item.fn !== 'function') throw new TypeError('Middleware must be composed of functions!') 25 | if (item.validator && typeof item.validator !== 'function') throw new TypeError('Validator must be composed of functions!') 26 | } 27 | 28 | /** 29 | * @param {Object} context 30 | * @return {Promise} 31 | * @api public 32 | */ 33 | 34 | return function (context, next) { 35 | // last called middleware # 36 | return dispatch(0) 37 | async function dispatch (i) { 38 | const fn = middleware[i].fn 39 | const validator = middleware[i].validator || function () { return true } 40 | try { 41 | const res = await fn(context, next) 42 | return Promise.resolve(res) 43 | } catch (err) { 44 | if (i + 1 < middleware.length && validator(err)) { 45 | return dispatch(i + 1) 46 | } else { 47 | return Promise.reject(err) 48 | } 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /swagger-ui-dist/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Swagger UI 7 | 8 | 9 | 10 | 31 | 32 | 33 | 34 |
35 | 36 | 37 | 38 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hexo-editor", 3 | "version": "0.6.0", 4 | "scripts": { 5 | "stop": "pm2 stop hexoeditor", 6 | "restart": "pm2 restart hexoeditor", 7 | "start": "node bin/www", 8 | "dev": "export DEBUG='hexo*' && export NODE_ENV='development' && npx nodemon -i ./data bin/www", 9 | "prd": "pm2 start bin/www --name hexoeditor -o log/pm2-log.log -e log/pm2-err.log", 10 | "test": "echo \"Error: no test specified\" && exit 1", 11 | "sub:fe": "cd frontend && git pull origin master" 12 | }, 13 | "dependencies": { 14 | "basic-auth": "^2.0.1", 15 | "chalk": "^4.1.0", 16 | "debug": "^4.1.1", 17 | "eslint": "^7.8.1", 18 | "eslint-config-standard": "^14.1.1", 19 | "eslint-friendly-formatter": "^4.0.1", 20 | "eslint-loader": "^4.0.2", 21 | "eslint-plugin-html": "^6.0.3", 22 | "eslint-plugin-import": "^2.22.0", 23 | "eslint-plugin-node": "^11.1.0", 24 | "eslint-plugin-promise": "^4.2.1", 25 | "eslint-plugin-standard": "^4.0.1", 26 | "hexo": "^5.1.1", 27 | "inquirer": "^7.3.3", 28 | "is-git-repository": "^2.0.0", 29 | "joi": "^17.2.1", 30 | "jsonwebtoken": "^8.5.1", 31 | "koa": "^2.13.0", 32 | "koa-bodyparser": "^4.3.0", 33 | "koa-compose": "^4.1.0", 34 | "koa-convert": "^1.2.0", 35 | "koa-cors": "0.0.16", 36 | "koa-json": "^2.0.2", 37 | "koa-logger": "^3.2.1", 38 | "koa-mount": "^4.0.0", 39 | "koa-onerror": "^4.1.0", 40 | "koa-router": "^9.4.0", 41 | "koa-static": "^5.0.0", 42 | "lodash": "^4.17.20", 43 | "log4js": "^6.3.0", 44 | "node-env-file": "^0.1.8", 45 | "simple-git": "^2.20.1", 46 | "simple-json-db": "^1.2.2", 47 | "warehouse": "^4.0.0", 48 | "yamljs": "^0.3.0" 49 | }, 50 | "devDependencies": { 51 | "nodemon": "^2.0.4" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/logger.js: -------------------------------------------------------------------------------- 1 | const log4js = require('log4js') 2 | const path = require('path') 3 | const fs = require('fs') 4 | const { 5 | isDev 6 | } = require('./utils') 7 | const logFolder = path.resolve(process.cwd(), 'log') 8 | const getLogfilePath = filename => { 9 | return path.resolve(logFolder, filename) 10 | } 11 | if (!fs.existsSync(logFolder)) { 12 | fs.mkdirSync(logFolder) 13 | } 14 | const NOCONSOLE_DEFAULT = { 15 | appenders: ['default'], 16 | level: isDev ? 'debug' : 'info' 17 | } 18 | const categories = { 19 | 'hexo-editor-server:hexo': { 20 | appenders: ['hexo-editor-server'].concat(isDev ? ['console'] : []), 21 | level: isDev ? 'debug' : 'info' 22 | }, 23 | 'hexo-editor-server': { 24 | appenders: ['hexo-editor-server'].concat(isDev ? ['console'] : []), 25 | level: isDev ? 'debug' : 'info' 26 | }, 27 | http: { 28 | appenders: ['console', 'hexo-editor-server', 'default'], 29 | level: isDev ? 'debug' : 'info' 30 | }, 31 | default: { 32 | appenders: ['console', 'default'], 33 | level: isDev ? 'debug' : 'info' 34 | } 35 | } 36 | const services = ['services:apikey-service', 'services:config-service', 'services:data-service'] 37 | services.map(key => { 38 | categories[key] = NOCONSOLE_DEFAULT 39 | }) 40 | log4js.configure({ 41 | appenders: { 42 | default: { 43 | type: 'file', 44 | filename: getLogfilePath('default.log'), 45 | removeColor: true 46 | }, 47 | 'hexo-editor-server': { 48 | type: 'file', 49 | filename: getLogfilePath('hexo-editor-server.log'), 50 | removeColor: true 51 | }, 52 | console: { 53 | type: 'console', 54 | layout: isDev ? { 55 | type: 'pattern', 56 | pattern: '%[[%d{hh:mm:ss.SSS}][%c][%p]%] %m' 57 | } : { 58 | type: 'pattern', 59 | pattern: '%[[winwin-hexo-editor][%p]%] %m' 60 | } 61 | } 62 | }, 63 | categories 64 | }) 65 | -------------------------------------------------------------------------------- /src/server/router.js: -------------------------------------------------------------------------------- 1 | const controller = require('./controller') 2 | 3 | module.exports = router => { 4 | router.all('/', (ctx, next) => { ctx.body = 'Greeting guys!' }) 5 | 6 | router.use(controller.errorHandler) 7 | 8 | router.get('/restrictedkeys', 9 | controller.getRestrictedKeys 10 | ) 11 | 12 | router.post('/post', 13 | // TODO: need validation 14 | controller.addPost 15 | ) 16 | 17 | router.post('/page', 18 | // TODO: need validation 19 | controller.addPage 20 | ) 21 | 22 | router.get('/posts', 23 | controller.getPosts 24 | ) 25 | 26 | router.get('/post/:id', 27 | controller.getPost 28 | ) 29 | 30 | router.get('/page/:id', 31 | controller.getPage 32 | ) 33 | 34 | router.put('/post/:id', 35 | controller.updatePost 36 | ) 37 | 38 | router.put('/page/:id', 39 | controller.updatePage 40 | ) 41 | 42 | router.delete('/post/:id', 43 | controller.removePost 44 | ) 45 | 46 | router.delete('/page/:id', 47 | controller.removePage 48 | ) 49 | 50 | router.post('/post/:id/publish', 51 | controller.publishPost 52 | ) 53 | 54 | router.post('/post/:id/unpublish', 55 | controller.unpublishPost 56 | ) 57 | 58 | router.get('/tags', 59 | controller.getTags 60 | ) 61 | 62 | router.get('/categories', 63 | controller.getCategories 64 | ) 65 | 66 | router.post('/reload', 67 | controller.reload 68 | ) 69 | 70 | router.post('/sync', 71 | controller.sync 72 | ) 73 | 74 | router.post('/reset', 75 | controller.reset 76 | ) 77 | 78 | router.post('/save', 79 | controller.save 80 | ) 81 | 82 | router.post('/deploy', 83 | controller.deploy 84 | ) 85 | 86 | router.post('/generate', 87 | controller.generate 88 | ) 89 | 90 | router.post('/clean', 91 | controller.clean 92 | ) 93 | 94 | router.get('/search', 95 | controller.search 96 | ) 97 | } 98 | -------------------------------------------------------------------------------- /scripts/lib.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | const chalk = require('chalk') 3 | const cp = require('child_process') 4 | 5 | exports.Printer = class Printer { 6 | constructor (prefix) { 7 | this.prefix = prefix 8 | } 9 | 10 | printSection (name) { 11 | console.log() 12 | console.log(chalk.blue.bold('⚙ ' + name)) 13 | console.log() 14 | } 15 | 16 | log () { 17 | console.log(...arguments) 18 | } 19 | 20 | printEmptyLine () { 21 | console.log() 22 | } 23 | 24 | success () { 25 | console.log(chalk.green(`[${this.prefix || 'SUCCESS'}]`), ...arguments) 26 | } 27 | 28 | info () { 29 | console.log(chalk.blue(`[${this.prefix || 'INFO'}]`), ...arguments) 30 | } 31 | 32 | warn () { 33 | console.log(chalk.yellow(`[${this.prefix || 'WARN'}]`), ...arguments) 34 | } 35 | 36 | error () { 37 | console.log(chalk.red(`[${this.prefix || 'ERROR'}]`), ...arguments) 38 | } 39 | 40 | clear () { 41 | console.clear(...arguments) 42 | } 43 | } 44 | 45 | class Executer { 46 | static setLog (log) { 47 | this.log = !!log 48 | } 49 | 50 | static run (command) { 51 | if (Executer.log) console.log(chalk.blue.bold('executer >'), command) 52 | 53 | return new Promise((resolve, reject) => { 54 | cp.exec(command, { log: Executer.log, cwd: process.cwd(0) }, (err, stdout, stderr) => { 55 | if (err) { 56 | err.stdout = stdout 57 | err.stderr = stderr 58 | reject(err) 59 | return 60 | } 61 | 62 | resolve(stdout) 63 | }) 64 | }) 65 | } 66 | 67 | static async hasCommand (cmd) { 68 | try { 69 | return !!await Executer.run(cmd) 70 | } catch (err) { 71 | return false 72 | } 73 | } 74 | } 75 | Executer.log = false 76 | exports.Executer = Executer 77 | 78 | exports.readJsonFile = filename => { 79 | const file = fs.readFileSync(filename) 80 | return JSON.parse(file) 81 | } 82 | -------------------------------------------------------------------------------- /src/install.js: -------------------------------------------------------------------------------- 1 | const Router = require('koa-router') 2 | const { initHexo, HexoError } = require('./server') 3 | const { dataService } = require('./service/data_service') 4 | const { configService } = require('./service/config_service') 5 | const { UserService } = require('./service/user_service') 6 | const router = new Router() 7 | const config = require('../config.default') 8 | router.prefix('/install') 9 | router.get('/info', async (ctx, next) => { 10 | if (configService.isInstalled()) { 11 | ctx.status = 404 12 | } else { 13 | ctx.status = 200 14 | } 15 | }) 16 | router.post('/do', async (ctx, next) => { 17 | if (configService.isInstalled()) { 18 | ctx.status = 404 19 | return 20 | } 21 | const username = ctx.request.body.username || config.username 22 | const password = ctx.request.body.password || config.password 23 | const HEXO_ROOT = ctx.request.body.HEXO_ROOT 24 | const JWT_SECRET = ctx.request.body.JWT_SECRET || config.jwtSecret 25 | const JW_EXPIRE = ctx.request.body.JW_EXPIRE || config.jwtExpire 26 | const JW_REFRESH = ctx.request.body.JW_REFRESH || config.jwtRefresh 27 | const APIKEY_SECRET = ctx.request.body.APIKEY_SECRET || config.apikeySecret 28 | try { 29 | await dataService.clear() 30 | await UserService.addUser(username, password) 31 | configService.clear() 32 | configService.setJwtSecret(JWT_SECRET) 33 | configService.setJwtExpire(JW_EXPIRE) 34 | configService.setJwtRefresh(JW_REFRESH) 35 | configService.setApikeySecret(APIKEY_SECRET) 36 | await configService.setHexoRoot(HEXO_ROOT) 37 | await initHexo(HEXO_ROOT) 38 | configService.markInstalled() 39 | ctx.body = 'installed' 40 | } catch (err) { 41 | if (err.code === HexoError.NOT_BLOG_ROOT || err.code === HexoError.EMPTY_HEXO_ROOT) { 42 | ctx.status = 400 43 | ctx.body = { 44 | success: false, 45 | message: err.message, 46 | data: err.data 47 | } 48 | return 49 | } 50 | throw err 51 | } 52 | }) 53 | 54 | module.exports = router 55 | -------------------------------------------------------------------------------- /src/service/user_config_service.js: -------------------------------------------------------------------------------- 1 | const { objparser } = require('../utils') 2 | const { dataService } = require('./data_service') 3 | 4 | class UserConfigService { 5 | static _parseConfig (config = {}, oldConfig) { 6 | return objparser(config, UserConfigService.schema, oldConfig || UserConfigService.defaultConfig) 7 | } 8 | 9 | static async _initConfigById (id) { 10 | const Model = dataService.model(dataService.modelTypes.UserConfig) 11 | await Model.insertOne({ 12 | config: {}, 13 | user_id: id 14 | }) 15 | await dataService.save() 16 | } 17 | 18 | static async _getOrCreateConfig (id) { 19 | const Model = dataService.model(dataService.modelTypes.UserConfig) 20 | let config = Model.findOne({ 21 | user_id: id 22 | }) 23 | if (!config) { 24 | await UserConfigService._initConfigById(id) 25 | config = Model.findOne({ 26 | user_id: id 27 | }) 28 | } 29 | return UserConfigService._parseConfig(config.toObject().config) 30 | } 31 | 32 | static async getConfigById (id, parts = []) { 33 | const config = await UserConfigService._getOrCreateConfig(id) 34 | const result = {} 35 | parts.map(key => { result[key] = config[key] }) 36 | return result 37 | } 38 | 39 | static async setConfigById (id, config = {}, parts = []) { 40 | const Model = dataService.model(dataService.modelTypes.UserConfig) 41 | const oldConfig = await UserConfigService._getOrCreateConfig(id) 42 | parts.map(key => { oldConfig[key] = config[key] }) 43 | await Model.replace({ user_id: id }, { 44 | config: oldConfig, 45 | user_id: id 46 | }) 47 | await dataService.save() 48 | return UserConfigService.getConfigById(id, parts) 49 | } 50 | } 51 | 52 | UserConfigService.schema = { 53 | // ui: { 54 | // editor: { 55 | // toolbar: { 56 | // direction: v => ['vertical', 'horizontal'].includes(v) 57 | // } 58 | // } 59 | // } 60 | } 61 | UserConfigService.defaultConfig = { 62 | // ui: { 63 | // editor: { 64 | // toolbar: { 65 | // direction: 'vertical' 66 | // } 67 | // } 68 | // } 69 | } 70 | 71 | module.exports = { 72 | UserConfigService 73 | } 74 | -------------------------------------------------------------------------------- /bin/www: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * load config 5 | */ 6 | const config = require('../config.default') 7 | 8 | /** 9 | * logger 10 | */ 11 | 12 | require('../src/logger') 13 | const logger = require('log4js').getLogger('server') 14 | logger.info('Starting server') 15 | 16 | /** 17 | * Module dependencies. 18 | */ 19 | 20 | const app = require('../src/app') 21 | const http = require('http') 22 | 23 | /** 24 | * Get port from environment and store in Express. 25 | */ 26 | 27 | const port = normalizePort(config.port || '3000') 28 | // app.set('port', port); 29 | 30 | /** 31 | * Create HTTP server. 32 | */ 33 | 34 | const server = http.createServer(app.callback()) 35 | 36 | /** 37 | * Listen on provided port, on all network interfaces. 38 | */ 39 | 40 | server.listen(port) 41 | server.on('error', onError) 42 | server.on('listening', onListening) 43 | 44 | /** 45 | * Normalize a port into a number, string, or false. 46 | */ 47 | 48 | function normalizePort (val) { 49 | const port = parseInt(val, 10) 50 | 51 | if (isNaN(port)) { 52 | // named pipe 53 | return val 54 | } 55 | 56 | if (port >= 0) { 57 | // port number 58 | return port 59 | } 60 | 61 | return false 62 | } 63 | 64 | /** 65 | * Event listener for HTTP server "error" event. 66 | */ 67 | 68 | function onError (error) { 69 | if (error.syscall !== 'listen') { 70 | throw error 71 | } 72 | 73 | const bind = typeof port === 'string' 74 | ? 'Pipe ' + port 75 | : 'Port ' + port 76 | 77 | // handle specific listen errors with friendly messages 78 | switch (error.code) { 79 | case 'EACCES': 80 | logger.error(bind + ' requires elevated privileges') 81 | process.exit(1) 82 | case 'EADDRINUSE': 83 | logger.error(bind + ' is already in use') 84 | process.exit(1) 85 | default: 86 | throw error 87 | } 88 | } 89 | 90 | /** 91 | * Event listener for HTTP server "listening" event. 92 | */ 93 | 94 | function onListening () { 95 | const addr = server.address() 96 | const bind = typeof addr === 'string' 97 | ? 'pipe ' + addr 98 | : 'port ' + addr.port 99 | logger.info('Server running on ' + bind) 100 | logger.info('Try visiting http://localhost:' + addr.port + ' through your browser') 101 | } 102 | -------------------------------------------------------------------------------- /src/service/data_service.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | const path = require('path') 3 | const logger = require('log4js').getLogger('services:data-service') 4 | const registerModels = require('./register_models') 5 | const Database = require('warehouse') 6 | const { ModelTypes } = require('../models') 7 | const DB_VERSION = 1 8 | const DB_PATH = '../../data/' 9 | const DB_FILE = 'wdb.json' 10 | 11 | class DataServiceError extends Error { 12 | constructor (message, code) { 13 | super(message) 14 | Error.captureStackTrace(this) 15 | this.code = code 16 | } 17 | } 18 | 19 | DataServiceError.prototype.name = 'DataServiceError' 20 | DataServiceError.INITIATING = 'INITIATING' 21 | 22 | class DataService { 23 | constructor () { 24 | this._ready = false 25 | this.modelTypes = ModelTypes 26 | this.init() 27 | } 28 | 29 | _checkReady () { 30 | if (!this._ready) { 31 | logger.warn('service initiating') 32 | throw new DataServiceError('service initiating', DataServiceError.INITIATING) 33 | } 34 | } 35 | 36 | async init () { 37 | logger.info('starting') 38 | // create database file 39 | try { 40 | if (!fs.existsSync(path.resolve(__dirname, DB_PATH))) { 41 | fs.mkdirSync(path.resolve(__dirname, DB_PATH)) 42 | } // 写文件可能失败 43 | } catch (err) { 44 | logger.error('fail to create database folder') 45 | throw err 46 | } 47 | // create database 48 | this.database = new Database({ 49 | version: DB_VERSION, 50 | path: path.resolve(__dirname, DB_PATH, DB_FILE) 51 | }) 52 | // register models 53 | registerModels(this) 54 | // load 55 | if (fs.existsSync(path.resolve(__dirname, DB_PATH, DB_FILE))) { 56 | await this.database.load() 57 | } 58 | logger.info('ready') 59 | this._ready = true 60 | } 61 | 62 | save () { 63 | this._checkReady() 64 | try { 65 | return this.database.save() 66 | } catch (err) { 67 | logger.error('fail to save database') 68 | throw err 69 | } 70 | } 71 | 72 | model (name, schema) { 73 | this._checkReady() 74 | return this.database.model(name, schema) 75 | } 76 | 77 | async clear () { 78 | this._checkReady() 79 | this.database = new Database({ 80 | version: DB_VERSION, 81 | path: path.resolve(__dirname, DB_PATH, 'wdb.json') 82 | }) 83 | await this.save() 84 | } 85 | } 86 | 87 | const dataService = new DataService() 88 | module.exports = { 89 | dataService, 90 | DataServiceError 91 | } 92 | -------------------------------------------------------------------------------- /src/server/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @module hexo-editor-serever 3 | * @author winwin2011 4 | */ 5 | 6 | const router = require('koa-router')() 7 | const chalk = require('chalk') 8 | const { HexoError } = require('./hexo') 9 | const logger = require('log4js').getLogger('hexo-editor-server') 10 | 11 | /** 12 | * mount hexo-editor-server to koa app 13 | * @param {Koa} app - koa app instance 14 | * @param {Object} opts - options 15 | * @param {String} [opts.base='/hexo/'] - hexo-editor-server base url. e.g. `/` or `/editor/`, default is `/hexo/`. Must match `^/?([a-zA-Z0-9]+/?)?$` 16 | * @param {Function} [opts.auth] - custom authentication middleware 17 | * @returns {void} 18 | */ 19 | exports.hexoeditorserver = function (app, opts = {}) { 20 | logger.debug('module opts input base:', opts.base) 21 | 22 | if (!app) { 23 | // check if koa app exists 24 | console.error('This is not a function. Koa app is required.') 25 | console.error('Use `hexoeditorserver(app)` instead') 26 | throw new Error('koa app required') 27 | } 28 | 29 | if (opts.base) { 30 | const reg = /^\/?([a-zA-Z0-9]+\/?)?$/i 31 | if (opts.base.search(reg) < 0) throw new Error('Invalid opts.base! Must match ^/?([a-zA-Z0-9]+/?)?$') 32 | // format server base and router prefix 33 | opts.base = (opts.base.slice(0, 1) === '/' ? '' : '/') + opts.base 34 | opts.base += opts.base.slice(-1) === '/' ? '' : '/' 35 | logger.debug('module opts formated base:', opts.base) 36 | } else { 37 | opts.base = '/hexo/' 38 | logger.info('using default base /hexo/') 39 | } 40 | opts.prefix = opts.base.slice(0, -1) 41 | 42 | // setup router prefix 43 | router.prefix(opts.prefix || '') 44 | 45 | // apply custom auth middleware 46 | if (opts.auth) { 47 | logger.debug('apply custom auth middleware') 48 | router.use(opts.auth) 49 | } 50 | 51 | // setup routes 52 | require('./router')(router) 53 | 54 | // setup router 55 | app.use(router.routes(), router.allowedMethods()) 56 | } 57 | 58 | /** 59 | * 可能的错误:HexoError.EMPTY_HEXO_ROOT | HexoError.NOT_BLOG_ROOT | other 60 | * @param {string} hexoRoot Hexo博客目录 61 | */ 62 | exports.initHexo = async (hexoRoot) => { 63 | const hexo = require('./controller').hexo 64 | return hexo.init(hexoRoot).catch(err => { 65 | switch (err.code) { 66 | case HexoError.EMPTY_HEXO_ROOT: 67 | logger.warn(chalk.yellow.bold('HEXO_ROOT is required!')) 68 | break 69 | case HexoError.NOT_BLOG_ROOT: 70 | logger.warn(chalk.yellow.bold('Hexo init failed, check your HEXO_ROOT settings first!')) 71 | break 72 | default: 73 | break 74 | } 75 | throw err 76 | }) 77 | } 78 | 79 | exports.HexoError = HexoError 80 | -------------------------------------------------------------------------------- /swagger-ui-dist/oauth2-redirect.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Swagger UI: OAuth2 Redirect 4 | 5 | 6 | 7 | 69 | -------------------------------------------------------------------------------- /src/app.js: -------------------------------------------------------------------------------- 1 | const Koa = require('koa') 2 | const app = new Koa() 3 | const json = require('koa-json') 4 | const onerror = require('koa-onerror') 5 | const bodyparser = require('koa-bodyparser') 6 | const koaLogger = require('koa-logger') 7 | const cors = require('koa-cors') 8 | const path = require('path') 9 | const log4js = require('log4js') 10 | const logger = log4js.getLogger('server') 11 | const authController = require('./auth/controller') 12 | const authRouter = require('./auth/router') 13 | const settings = require('./settings/router') 14 | const version = require('./version') 15 | const { configService } = require('./service/config_service') 16 | const { 17 | hexoeditorserver, 18 | initHexo, 19 | HexoError 20 | } = require('./server') 21 | 22 | // error handler 23 | onerror(app) 24 | app.use(async (ctx, next) => { 25 | try { 26 | await next() 27 | } catch (err) { 28 | ctx.status = err.status || 500 29 | ctx.body = { 30 | success: false, 31 | message: err.message 32 | } 33 | if (ctx.status === 500) { 34 | ctx.body.message = 'server internal error, try again later' 35 | logger.error(500, err) 36 | } 37 | } 38 | }) 39 | 40 | const { dataServiceErrorHandler } = require('./errorHandlers') 41 | app.use(dataServiceErrorHandler) 42 | 43 | // cors 44 | app.use(cors()) 45 | 46 | // middlewares 47 | app.use(bodyparser({ 48 | enableTypes: ['json', 'form', 'text'] 49 | })) 50 | app.use(json()) 51 | app.use(koaLogger((str, args) => { 52 | // redirect koa logger to other output pipe 53 | // default is process.stdout(by console.log function) 54 | log4js.getLogger('http').info(str) 55 | })) 56 | 57 | // static resources 58 | const serveStatic = require('koa-static') 59 | app.use(serveStatic(path.join(process.cwd(), '/frontend/dist/pwa'))) 60 | 61 | // install 62 | const isInstalled = configService.isInstalled() 63 | if (!isInstalled) { 64 | const install = require('./install') 65 | app.use(install.routes(), install.allowedMethods()) 66 | } else { 67 | initHexo(configService.getHexoRoot()).catch(err => { 68 | if (![HexoError.EMPTY_HEXO_ROOT, HexoError.NOT_BLOG_ROOT].includes(err.code)) { 69 | logger.error('Unknown Error:', err) 70 | process.exit(1) 71 | } 72 | }) 73 | } 74 | 75 | // hexo-editor-server 76 | hexoeditorserver(app, { 77 | base: 'hexoeditorserver', 78 | auth: authController.apikeyOrJwt 79 | }) 80 | 81 | // routes 82 | app.use(authRouter.routes(), authRouter.allowedMethods()) 83 | app.use(settings.routes(), settings.allowedMethods()) 84 | app.use(version.routes(), version.allowedMethods()) 85 | 86 | // error-handling 87 | app.on('error', (err, ctx) => { 88 | console.error('server error', err, ctx) 89 | }) 90 | 91 | module.exports = app 92 | -------------------------------------------------------------------------------- /src/service/user_service.js: -------------------------------------------------------------------------------- 1 | const { dataService } = require('./data_service') 2 | const config = require('../../config.default') 3 | const WarehouseError = require('warehouse/lib/error') 4 | 5 | class UserServiceError extends Error { 6 | constructor (message, code) { 7 | super(message) 8 | Error.captureStackTrace(this) 9 | this.code = code 10 | } 11 | } 12 | 13 | UserServiceError.prototype.name = 'UserServiceError' 14 | UserServiceError.USER_EXIST = 'USER_EXIST' 15 | UserServiceError.USER_NOT_EXIST = 'USER_NOT_EXIST' 16 | UserServiceError.SAVE_FAIL = 'SAVE_FAIL' 17 | 18 | class UserService { 19 | /** 20 | * 可能的错误:UserServiceError.USER_EXIST 21 | * @param {String} username 用户名 22 | * @param {String} password 密码 23 | */ 24 | static async addUser (username, password) { 25 | const User = dataService.model(dataService.modelTypes.User) 26 | if (User.findOne({ username })) { 27 | throw new UserServiceError('duplicate user:' + username, UserServiceError.USER_EXIST) 28 | } 29 | await User.insertOne({ username, password }) 30 | await dataService.save() 31 | } 32 | 33 | /** 34 | * 获取用户信息 35 | * @param {String} id 用户id 36 | * @param {Boolean} password 是否保留密码 37 | */ 38 | static async getUser (id, password) { 39 | const User = dataService.model(dataService.modelTypes.User) 40 | const result = User.findOne({ _id: id }) 41 | if (result && !password) delete result.password 42 | return result 43 | } 44 | 45 | /** 46 | * 可能的错误:UserServiceError.USER_NOT_EXIST | other 47 | * @param {String} id 用户id 48 | * @param {String} username 用户名 49 | * @param {String} password 密码 50 | */ 51 | static async updateUser (id, username, password) { 52 | const User = dataService.model(dataService.modelTypes.User) 53 | const update = {} 54 | update.username = username || config.username 55 | update.password = password || config.password 56 | try { 57 | await User.updateById(id, update) 58 | await dataService.save() 59 | } catch (err) { 60 | if (err.name === WarehouseError.ID_NOT_EXIST) { 61 | throw new UserServiceError('user not exists', UserServiceError.USER_NOT_EXIST) 62 | } 63 | throw err 64 | } 65 | } 66 | 67 | static async hasUserWithPassword (username, password) { 68 | const User = dataService.model(dataService.modelTypes.User) 69 | return User.findOne({ username, password }) 70 | } 71 | 72 | static async hasUserWithIdPassword (_id, password) { 73 | const User = dataService.model(dataService.modelTypes.User) 74 | return User.findOne({ _id, password }) 75 | } 76 | 77 | static async hasUser (username) { 78 | const User = dataService.model(dataService.modelTypes.User) 79 | return User.findOne({ username }) 80 | } 81 | 82 | static async hasUserById (_id) { 83 | const User = dataService.model(dataService.modelTypes.User) 84 | return User.findOne({ _id }) 85 | } 86 | } 87 | 88 | module.exports = { UserService, UserServiceError } 89 | -------------------------------------------------------------------------------- /src/server/search.js: -------------------------------------------------------------------------------- 1 | const { Hexo } = require('./hexo') 2 | const debug = require('debug')('hexo:search') 3 | 4 | class Search { 5 | /** 6 | * 初始化 7 | * @param {Hexo} hexo hexo实例 8 | */ 9 | constructor (hexo) { 10 | this._setHexoInstance(hexo) 11 | this.ready = true 12 | } 13 | 14 | /** 15 | * 设置hexo 16 | * @param {Hexo} hexo hexo实例 17 | */ 18 | _setHexoInstance (hexo) { 19 | debug('set hexo instance') 20 | if (!(hexo instanceof Hexo)) throw new Error('Not a Hexo instance!') 21 | this.hexo = hexo 22 | this.ready = true 23 | } 24 | 25 | /** 26 | * 检测是否完成初始化 27 | * @private 28 | */ 29 | async _checkReady () { 30 | if (!this.ready) { 31 | debug('Please set hexo instance before search') 32 | const err = new Error('Please set hexo instance before search') 33 | err.name = 'Need hexo' 34 | throw err 35 | } 36 | } 37 | 38 | /** 39 | * 从原始字符串中截取子串附近的内容 40 | * @param {String} str 原始字符串 41 | * @param {String} idx 子串位置 42 | * @param {Number}} queryLength 子串长度 43 | * @param {Number} size 返回查询字符串前后临近文字的数量,前后共2*size 44 | */ 45 | _getBrief (str, idx, queryLength, size) { 46 | const start = idx - size > 0 ? idx - size : 0 47 | const startIdx = idx - size > 0 ? size : idx 48 | const result = str.slice(start, start + queryLength + 2 * size) 49 | return { 50 | idx, 51 | str: result, 52 | start: startIdx 53 | } 54 | } 55 | 56 | /** 57 | * 查询字符串中所有子串的位置 58 | * @param {String} str 需要搜索的字符串 59 | * @param {String} q 子串 60 | */ 61 | _searchAll (str, q) { 62 | const idxs = [] 63 | const idx = str.indexOf(q) 64 | if (idx < 0) return [] 65 | if (idx + 1 > str.length) return [] 66 | idxs.push(idx) 67 | return idxs.concat(this._searchAll(str.slice(idx + 1), q).map(item => item + idx + 1)) 68 | } 69 | 70 | /** 71 | * 按文章内容查询 72 | * @param {Object} post 文章 73 | * @param {String} query 查询字符串 74 | * @param {Number} size 返回查询字符串前后临近文字的数量,前后共2*size 75 | */ 76 | _searchPost (post, query, size) { 77 | const raw = post.raw.toLowerCase() 78 | const idxs = this._searchAll(raw, query) 79 | return idxs.map(idx => this._getBrief(raw, idx, query.length, size)).map(item => { 80 | item._id = post._id 81 | return item 82 | }) 83 | } 84 | 85 | /** 86 | * 查询所有文章 87 | * @param {String} q 查询字符串 88 | * @param {Number} size 返回查询字符串前后临近文字的数量,前后共2*size 89 | */ 90 | async search (q = '', size = 200) { 91 | await this._checkReady() 92 | if (!q) { 93 | debug('empty search query') 94 | return {} 95 | } 96 | debug('search request:', '`' + q + '`', 'with size', size) 97 | const query = q.toLowerCase() 98 | const posts = await this.hexo.listArticlesRaw() 99 | return { 100 | result: posts.map(post => this._searchPost(post, query, size)).reduce((a, b) => a.concat(b)), 101 | size 102 | } 103 | } 104 | } 105 | 106 | module.exports = Search 107 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # This repo has been Archived for v0.1.0 ~ v0.6.x only 2 | 3 | ## For latest version, please visit [Hexon](https://github.com/gethexon/hexon) 4 | 5 | --- 6 | 7 | # @winwin/hexo-editor 8 | 9 | 一个在线hexo博客编辑器 | An online hexo blog editor by winwin2011 10 | 11 |
12 | 13 | 14 | 15 | ## 截图 | Screenshots 16 | 17 | [请访问主页](https://winwin_2011.gitee.io/winwin-hexo-editor/) | [Please visit homepage](https://yujianghao.github.io/winwin-hexo-editor/) 18 | 19 | [移动客户端](https://github.com/maomishen/winwin-hexo-editor-mobile) | [Mobile client](https://github.com/maomishen/winwin-hexo-editor-mobile) 20 | 21 | ![Main page](https://cdn.yujianghao.cn/uploads/2020/09/21/CNkHVagP_thumbnail-winwin-hexo-editor-v0.6.0-4.png) 22 | 23 | ## 功能 | Feature 24 | 25 | - [x] 文章增删改和预览 | Post/Page add/delete/update and preview 26 | - [x] 发布和草稿 | Post/Page puiblish/unpublish/drafts 27 | - [x] Markdown编辑 | Markdown editor 28 | - [x] 分类 | categories 29 | - [x] 标签 | tags 30 | - [x] git同步 | git push/reset/pull 31 | - [x] hexo命令 | hexo generate/deploy/clean 32 | - [x] 登录 | Basic authentication 33 | - [x] 文章排序 | Post/Page sort 34 | - [x] front-matters 35 | - [x] 文章搜索 | Search 36 | - [x] 自定义slug | Custom slug 37 | - [ ] ~~图床Image CDN~~(请使用[cloudreve](https://cloudreve.org/)替代 | use [cloudreve](https://cloudreve.org/) instead) 38 | - [ ] 亲,请告诉我您还需要什么 ~ | let me know what you need ... 39 | 40 | ## 如何使用 | How to use 41 | 42 | 请查看[文档](https://winwin_2011.gitee.io/winwin-hexo-editor/guide.html)。 | Please see [doc](https://yujianghao.github.io/winwin-hexo-editor/en/guide.html) 43 | 44 | ## 支持 | Support 45 | 46 | QQ群:590355610 47 | 48 | - [Gitee FAQ](https://winwin_2011.gitee.io/winwin-hexo-editor/support/) 49 | - [Gitee Issue](https://gitee.com/winwin_2011/winwin-hexo-editor/issues) 50 | - [Github FAQ](https://yujianghao.github.io/winwin-hexo-editor/support/) 51 | - [Github Issue](https://github.com/YuJianghao/winwin-hexo-editor/issues) 52 | 53 | ## 贡献 | Contribute 54 | 55 | 欢迎各种各样的PR(魔改也是可以的!) 56 | 57 | All kinds of PR are welcomed, including crazy change! 58 | 59 | 如果这项目帮到你了,点个爱的五角星呗~ 60 | 61 | If this project helped you a bit, please leave a ⭐ with your ❤ :p! 62 | 63 | ## 致谢 | Acknowledgement 64 | 65 | 感谢和我一起扣代码的[maomishen](https://github.com/maomishen/)小伙伴! 66 | 67 | [hexo-client](https://github.com/gaoyoubo/hexo-client) by [gaoyoubo](https://github.com/gaoyoubo), [homepage](https://www.mspring.org/tags/HexoClient/) 68 | 69 | [hexo-admin](https://github.com/jaredly/hexo-admin) by [jaredly](https://github.com/jaredly), [homepage](https://jaredforsyth.com/hexo-admin/) 70 | 71 | 感谢他们教会我怎么使用hexo!| I learnt a lot about hexo usage from them! 72 | 73 | [Qusar Login Form Card Component](https://gist.github.com/justinatack/39ec7f37064b2e9fa61fbd450cba3826) by [justinatack](https://gist.github.com/justinatack/) 74 | -------------------------------------------------------------------------------- /src/service/config_service.js: -------------------------------------------------------------------------------- 1 | const JSONdb = require('simple-json-db') 2 | const path = require('path') 3 | const logger = require('log4js').getLogger('services:config-service') 4 | const { initHexo } = require('../server') 5 | const JWT_SECRET = 'JWT_SECRET' 6 | const JW_EXPIRE = 'JW_EXPIRE' 7 | const JW_REFRESH = 'JW_REFRESH' 8 | const APIKEY_SECRET = 'APIKEY_SECRET' 9 | const HEXO_ROOT = 'HEXO_ROOT' 10 | const INSTALLED = 'INSTALLED' 11 | 12 | class ConfigServiceError extends Error { 13 | constructor (message, code) { 14 | super(message) 15 | Error.captureStackTrace(this) 16 | this.code = code 17 | } 18 | } 19 | 20 | ConfigServiceError.prototype.name = 'ConfigServiceError' 21 | ConfigServiceError.BAD_OPTIONS = 'BAD_OPTIONS' 22 | 23 | class ConfigService { 24 | constructor () { 25 | try { 26 | this._db = new JSONdb(path.resolve(process.cwd(), './data/db.json')) 27 | logger.info('database loaded') 28 | } catch (err) { 29 | logger.error('failed to create database from json file') 30 | throw err 31 | } 32 | } 33 | 34 | _get (key) { 35 | return this._db.get(key) 36 | } 37 | 38 | _set (key, value) { 39 | this._db.set(key, value) 40 | this.sync() 41 | } 42 | 43 | sync () { 44 | try { 45 | this._db.sync() 46 | logger.info('database synced') 47 | } catch (err) { 48 | logger.error('failed to save database to json file') 49 | throw err 50 | } 51 | } 52 | 53 | clear () { 54 | this._db.JSON({}) 55 | this.sync() 56 | } 57 | 58 | setJwtSecret (secret) { 59 | if (!secret) return 60 | this._db.set(JWT_SECRET, secret) 61 | this.sync() 62 | } 63 | 64 | getJwtSecret () { 65 | return this._db.get(JWT_SECRET) 66 | } 67 | 68 | setJwtExpire (expire) { 69 | if (!expire) return 70 | this._db.set(JW_EXPIRE, expire) 71 | this.sync() 72 | } 73 | 74 | getJwtExpire () { 75 | return this._db.get(JW_EXPIRE) 76 | } 77 | 78 | setJwtRefresh (refresh) { 79 | if (!refresh) return 80 | this._db.set(JW_REFRESH, refresh) 81 | this.sync() 82 | } 83 | 84 | getJwtRefresh () { 85 | return this._db.get(JW_REFRESH) 86 | } 87 | 88 | setApikeySecret (secret) { 89 | if (!secret) return 90 | this._db.set(APIKEY_SECRET, secret) 91 | this.sync() 92 | } 93 | 94 | getApikeySecret () { 95 | return this._db.get(APIKEY_SECRET) 96 | } 97 | 98 | async setHexoRoot (hexoRoot) { 99 | if (!hexoRoot) return 100 | const originalHexoRoot = this.getHexoRoot() 101 | this._db.set(HEXO_ROOT, hexoRoot) 102 | try { 103 | await initHexo(hexoRoot) 104 | } catch (err) { 105 | this._db.set(HEXO_ROOT, originalHexoRoot) 106 | throw err 107 | } 108 | this.sync() 109 | } 110 | 111 | getHexoRoot () { 112 | return this._db.get(HEXO_ROOT) 113 | } 114 | 115 | markInstalled () { 116 | this._db.set(INSTALLED, true) 117 | this._db.sync() 118 | } 119 | 120 | isInstalled () { 121 | return this._db.get(INSTALLED) 122 | } 123 | } 124 | const configService = new ConfigService() 125 | module.exports = { 126 | configService, 127 | ConfigServiceError 128 | } 129 | -------------------------------------------------------------------------------- /src/server/post.js: -------------------------------------------------------------------------------- 1 | const hfm = require('hexo-front-matter') 2 | const debug = require('debug')('hexo:post') 3 | const restrictedKeys = require('./info').restrictedKeys 4 | 5 | function postCategoriesArray2d2Raw (categoriesArray2D) { 6 | let categories = [] 7 | if (categoriesArray2D.length === 1) { 8 | if (categoriesArray2D[0].length === 1) { 9 | categories = categoriesArray2D[0][0] 10 | } else { 11 | categories = categoriesArray2D[0] 12 | } 13 | } else { 14 | categories = categoriesArray2D 15 | } 16 | return categories 17 | } 18 | 19 | function postCategoriesRaw2Array2d (categories) { 20 | if (!categories) return [[]] 21 | if (!Array.isArray(categories)) return [[categories]] 22 | else { 23 | if (!categories.filter(cat => Array.isArray(cat)).length) { return [categories] } 24 | return categories.map(cat => { 25 | return Array.isArray(cat) ? cat : [cat] 26 | }) 27 | } 28 | } 29 | 30 | /** 31 | * 用于存储不包含hexo默认值的文章信息 32 | * @class 33 | */ 34 | class Post { 35 | /** 36 | * @param {_Document|Object} [post] - hexo数据库中的post文档 37 | * @param {fromDB} [fromDB=true] - 是否是从数据库载入 38 | */ 39 | constructor (post, fromDB = true) { 40 | if (!post) return 41 | if (fromDB) { 42 | // 设置必须属性 43 | Array.from(['_id', 'slug', 'raw', 'layout', 'published']) 44 | .map(key => { 45 | if (post[key] !== undefined) { this[key] = post[key] } 46 | }) 47 | // 混合hexo-front-matters属性 48 | if (this.raw) { 49 | const data = hfm.parse(this.raw) 50 | this.frontmatters = {} 51 | let keys 52 | if (data.layout === 'page')keys = restrictedKeys.page 53 | else keys = restrictedKeys.post 54 | Object.keys(data).map(key => { 55 | if (keys.includes(key)) this[key] = data[key] 56 | else this.frontmatters[key] = data[key] 57 | }) 58 | } 59 | if (post.layout === 'page') { 60 | this.path = post.path.slice(0, post.path.length - 5) 61 | } 62 | // 转换日期为数字 63 | Array.from(['date', 'updated']).map(time => { 64 | if (this[time]) { 65 | this[time] = this[time].valueOf() 66 | } 67 | }) 68 | } else { 69 | Object.keys(post).map(key => { 70 | if (post[key]) { this[key] = post[key] } 71 | }) 72 | if (!this.frontmatters) { 73 | this.frontmatters = {} 74 | } 75 | } 76 | if (this.categories) { 77 | this.categories = postCategoriesRaw2Array2d(this.categories) 78 | } 79 | } 80 | 81 | /** 82 | * 从对象更新数据 83 | * @param {Object} obj - 需要更新的属性对象,`_id`属性将被忽略 84 | * @returns {Post} - 更新后的文章 85 | */ 86 | update (obj) { 87 | Object.keys(obj).map(key => { 88 | if (key === '_id') return 89 | delete this[key] 90 | this[key] = obj[key] 91 | }) 92 | return this 93 | } 94 | 95 | /** 96 | * 删除不用数据,准备使用hexo创建新文件 97 | */ 98 | freeze () { 99 | delete this._id 100 | delete this.raw 101 | delete this.published 102 | delete this.brief 103 | const keys = this.layout === 'page' ? restrictedKeys.page : restrictedKeys.post 104 | Object.keys(this).map(key => { 105 | if (key === 'frontmatters') return 106 | if (!keys.includes(key)) delete this[key] 107 | }) 108 | Object.keys(this.frontmatters).map(key => { 109 | if (!keys.includes(key)) { 110 | this[key] = this.frontmatters[key] 111 | } 112 | }) 113 | delete this.frontmatters 114 | if (this.categories) { 115 | this.categories = postCategoriesArray2d2Raw(this.categories) 116 | } 117 | debug('freeze post,', Object.keys(this).join(' | ')) 118 | return this 119 | } 120 | } 121 | 122 | module.exports = Post 123 | -------------------------------------------------------------------------------- /src/settings/controllers.js: -------------------------------------------------------------------------------- 1 | const { DataServiceError } = require('../service/data_service') 2 | const { configService } = require('../service/config_service') 3 | const { UserService, UserServiceError } = require('../service/user_service') 4 | const { UserConfigService } = require('../service/user_config_service') 5 | const SettingsError = require('./errors') 6 | const { HexoError } = require('../server/hexo') 7 | 8 | exports.errorHandler = async (ctx, next) => { 9 | try { 10 | await next() 11 | } catch (err) { 12 | switch (err.code) { 13 | case UserServiceError.USER_NOT_EXIST: 14 | err.status = 404 15 | break 16 | case DataServiceError.INITIATING: 17 | err.status = 503 18 | break 19 | case SettingsError.INVALID_PARAMS: 20 | err.status = 400 21 | break 22 | case HexoError.NOT_BLOG_ROOT: 23 | ctx.status = 404 24 | ctx.body = { 25 | success: false, 26 | message: err.message, 27 | data: err.data 28 | } 29 | return 30 | case HexoError.EMPTY_HEXO_ROOT: 31 | ctx.status = 404 32 | ctx.body = { 33 | success: false, 34 | message: err.message, 35 | data: err.data 36 | } 37 | break 38 | } 39 | throw err 40 | } 41 | } 42 | 43 | exports.updateUser = async (ctx, next) => { 44 | const id = ctx.params.id || ctx.state.user.id 45 | if (!id) throw new SettingsError('id is required', SettingsError.INVALID_PARAMS) 46 | const username = ctx.request.body.username 47 | const oldpassword = ctx.request.body.oldpassword 48 | const password = ctx.request.body.password 49 | if (!await UserService.hasUserWithIdPassword(id, oldpassword)) { 50 | ctx.status = 403 51 | ctx.body = { 52 | success: false, 53 | message: 'old password wrong' 54 | } 55 | return 56 | } 57 | await UserService.updateUser(id, username, password) 58 | const user = await UserService.getUser(id) 59 | ctx.body = { 60 | success: true, 61 | data: { 62 | user 63 | } 64 | } 65 | } 66 | 67 | exports.getUser = async (ctx, next) => { 68 | const id = ctx.params.id || ctx.state.user.id 69 | if (!id) throw new SettingsError('id is required', SettingsError.INVALID_PARAMS) 70 | const user = await UserService.getUser(id, false) 71 | ctx.body = { 72 | success: true, 73 | data: { 74 | user 75 | } 76 | } 77 | } 78 | 79 | exports.setHexoInfo = async (ctx, next) => { 80 | const HEXO_ROOT = ctx.request.body.HEXO_ROOT 81 | await configService.setHexoRoot(HEXO_ROOT) 82 | ctx.body = { 83 | success: true 84 | } 85 | } 86 | 87 | exports.getHexoInfo = async (ctx, next) => { 88 | const HEXO_ROOT = configService.getHexoRoot() 89 | ctx.body = { 90 | success: false, 91 | data: { 92 | HEXO_ROOT 93 | } 94 | } 95 | } 96 | 97 | exports.security = async (ctx, next) => { 98 | const JWT_SECRET = ctx.request.body.JWT_SECRET 99 | const JWT_EXPIRE = ctx.request.body.JWT_EXPIRE 100 | const JWT_REFRESH = ctx.request.body.JWT_REFRESH 101 | const APIKEY_SECRET = ctx.request.body.APIKEY_SECRET 102 | configService.setJwtSecret(JWT_SECRET) 103 | configService.setJwtExpire(JWT_EXPIRE) 104 | configService.setJwtRefresh(JWT_REFRESH) 105 | configService.setApikeySecret(APIKEY_SECRET) 106 | ctx.body = { 107 | success: true 108 | } 109 | } 110 | 111 | exports.getUiConfig = async (ctx, next) => { 112 | const id = ctx.state.user.id 113 | const config = await UserConfigService.getConfigById(id, ['ui']) 114 | ctx.body = { 115 | config 116 | } 117 | } 118 | 119 | exports.setUiConfig = async (ctx, next) => { 120 | const id = ctx.state.user.id 121 | const config = ctx.request.body 122 | const newConfig = await UserConfigService.setConfigById(id, { ui: config }, ['ui']) 123 | ctx.body = { 124 | config: newConfig 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /update.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | const chalk = require('chalk') 3 | const { Printer, Executer, readJsonFile } = require('./scripts/lib') 4 | const logo = fs.readFileSync('./assets/logo.art') 5 | const printer = new Printer() 6 | 7 | async function update () { 8 | // #region LOGO 9 | printer.log(chalk.blue.bold(logo + chalk.underline('/ winwin-hexo-editor ') + '/')) 10 | // #endregion 11 | 12 | // #region Version 13 | printer.printSection('Check Version') 14 | const oldVersion = readJsonFile('./package.json').version 15 | printer.info('Current Version ' + oldVersion) 16 | if (oldVersion.indexOf('-') >= 0) { 17 | printer.warn('This is a preview version!') 18 | } 19 | // #endregion 20 | 21 | // #region Check Dependences 22 | printer.printSection('Check Dependences') 23 | 24 | const NODE = 'node' 25 | const hasNode = await Executer.hasCommand(NODE + ' -v') 26 | if (!hasNode) { 27 | printer.error('Node is required! Please install node.js first') 28 | process.exit(101) 29 | } else { 30 | printer.info(`${NODE} : ${chalk.green('pass')}`) 31 | } 32 | 33 | const NPM = 'npm' 34 | const hasNPM = await Executer.hasCommand(NPM + ' -v') 35 | if (!hasNPM) { 36 | printer.error('npm not found, is there anything wrong with your node installation?') 37 | process.exit(102) 38 | } else { 39 | printer.info(`${NPM} : ${chalk.green('pass')}`) 40 | } 41 | 42 | const YARN = 'yarn' 43 | const hasYarn = await Executer.hasCommand(YARN + ' -v') 44 | if (!hasYarn) { 45 | printer.info(`${NODE} : ${chalk.red('pass')}`) 46 | printer.warn('yarn not found, use npm instead.') 47 | } else { 48 | printer.info(`${YARN} : ${chalk.green('pass')}`) 49 | } 50 | // #endregion 51 | 52 | // #region Fetch Updates 53 | printer.printSection('Fetch Updates') 54 | try { 55 | printer.info('Fetching updates') 56 | await Executer.run('git reset --hard') 57 | await Executer.run('git submodule foreach "git reset --hard"') 58 | await Executer.run('git pull') 59 | printer.success('Updated') 60 | } catch (err) { 61 | const failed = new Printer('Installation Failed') 62 | failed.error(err) 63 | failed.error('error occured when fetching updates') 64 | process.exit(201) 65 | } 66 | // #endregion 67 | 68 | // #region Fetch Submodules 69 | printer.printSection('Fetch Submodules') 70 | try { 71 | printer.info('Fetching submodules updates') 72 | await Executer.run('git submodule sync') 73 | await Executer.run('git submodule update --init --recursive') 74 | printer.success('Submodules updated') 75 | } catch (err) { 76 | const failed = new Printer('Installation Failed') 77 | failed.error(err) 78 | failed.error('error occured when fetching submodules') 79 | process.exit(301) 80 | } 81 | // #endregion 82 | 83 | // #region Install Dependences 84 | printer.printSection('Install Dependences') 85 | const cmd = hasYarn ? 'yarn' : 'npm install' 86 | try { 87 | printer.info('Dependences installing') 88 | await Executer.run(cmd) 89 | printer.success('Dependences installed') 90 | } catch (err) { 91 | const failed = new Printer('Installation Failed') 92 | failed.error(err) 93 | failed.error(cmd, 'failed') 94 | failed.error('error occured when install dependences') 95 | process.exit(401) 96 | } 97 | // #endregion 98 | 99 | // #region Finished 100 | printer.clear() 101 | printer.log(chalk.green.bold('Finished!')) 102 | 103 | // #region Version 104 | const newVersion = readJsonFile('./package.json').version 105 | printer.info('Current Version ' + newVersion) 106 | if (newVersion.indexOf('-') >= 0) { 107 | printer.warn('This is a preview version!') 108 | } 109 | // #endregion 110 | 111 | printer.log('Run ' + chalk.blue.bold('`npm start`') + ' to start with node') 112 | printer.log('Run ' + chalk.blue.bold('`npm run prd`') + ' to start with pm2') 113 | printer.log('Run ' + chalk.blue.bold('`npm run stop`') + ' to stop') 114 | printer.log('Run ' + chalk.blue.bold('`npm run restart`') + ' to restart') 115 | printer.log() 116 | printer.log(chalk.green.bold('Remember to restart your service manually!')) 117 | printer.log('Have fun :p') 118 | printer.log(chalk.grey('For uninstall:')) 119 | printer.log(chalk.grey('- Remove the following folder: ' + process.cwd())) 120 | printer.log(chalk.grey('- Stop youre service manually.')) 121 | // #endregion 122 | } 123 | 124 | update() 125 | -------------------------------------------------------------------------------- /install.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | const chalk = require('chalk') 3 | const inquirer = require('inquirer') 4 | const { Printer, Executer, readJsonFile } = require('./scripts/lib') 5 | const logo = fs.readFileSync('./assets/logo.art') 6 | const config = require('./config.default') 7 | const printer = new Printer() 8 | 9 | async function install () { 10 | // #region LOGO 11 | printer.log(chalk.blue.bold(logo + chalk.underline('/ winwin-hexo-editor ') + '/')) 12 | // #endregion 13 | 14 | // #region Version 15 | printer.printSection('Check Version') 16 | const oldVersion = readJsonFile('./package.json').version 17 | printer.info('Current Version ' + oldVersion) 18 | if (oldVersion.indexOf('-') >= 0) { 19 | printer.warn('This is a preview version!') 20 | } 21 | // #endregion 22 | 23 | // #region Check Dependences 24 | printer.printSection('Check Dependences') 25 | 26 | const NODE = 'node' 27 | const hasNode = await Executer.hasCommand(NODE + ' -v') 28 | if (!hasNode) { 29 | printer.error('Node is required! Please install node.js first') 30 | process.exit(101) 31 | } else { 32 | printer.info(`${NODE} : ${chalk.green('pass')}`) 33 | } 34 | 35 | const NPM = 'npm' 36 | const hasNPM = await Executer.hasCommand(NPM + ' -v') 37 | if (!hasNPM) { 38 | printer.error('npm not found, is there anything wrong with your node installation?') 39 | process.exit(102) 40 | } else { 41 | printer.info(`${NPM} : ${chalk.green('pass')}`) 42 | } 43 | 44 | const YARN = 'yarn' 45 | const hasYarn = await Executer.hasCommand(YARN + ' -v') 46 | if (!hasYarn) { 47 | printer.info(`${NODE} : ${chalk.red('pass')}`) 48 | printer.warn('yarn not found, use npm instead.') 49 | } else { 50 | printer.info(`${YARN} : ${chalk.green('pass')}`) 51 | } 52 | // #endregion 53 | 54 | // #region Fetch Submodules 55 | printer.printSection('Fetch Submodules') 56 | try { 57 | printer.info('Fetching submodules updates') 58 | await Executer.run('git submodule sync') 59 | await Executer.run('git submodule update --init --recursive') 60 | printer.success('Submodules updated') 61 | } catch (err) { 62 | const failed = new Printer('Installation Failed') 63 | failed.error(err) 64 | failed.error('error occured when fetching submodules') 65 | process.exit(201) 66 | } 67 | // #endregion 68 | 69 | // #region Install Dependences 70 | printer.printSection('Install Dependences') 71 | let cmd = 'yarn' 72 | if (fs.existsSync('./package-lock.json') || !hasYarn) { 73 | if (hasYarn) { 74 | printer.info('package-lock.json found, use npm') 75 | } 76 | cmd = 'npm install' 77 | } 78 | try { 79 | printer.info('Dependences installing') 80 | await Executer.run(cmd) 81 | printer.success('Dependences installed') 82 | } catch (err) { 83 | const failed = new Printer('Installation Failed') 84 | failed.error(err) 85 | failed.error(cmd, 'failed') 86 | failed.error('error occured when install dependences') 87 | process.exit(301) 88 | } 89 | // #endregion 90 | 91 | // #region Configuation 92 | printer.printSection('Configuation') 93 | const answer = await inquirer 94 | .prompt([{ 95 | name: 'port', 96 | message: 'Which port do you like your hexo-editor running at?', 97 | default: config.port || 5777, 98 | validate (v) { 99 | return !isNaN(v) || `number is required ${typeof v} given` 100 | }, 101 | prefix: chalk.blue('?') 102 | }]) 103 | fs.writeFileSync('./config.user.js', `module.exports = {\n port: ${answer.port}\n}\n`) 104 | if (!fs.existsSync('./log')) { 105 | fs.mkdirSync('./log') 106 | } 107 | // #endregion 108 | 109 | // #region Finished 110 | printer.clear() 111 | printer.log(chalk.green.bold('Finished!')) 112 | printer.log('Run ' + chalk.blue.bold('`npm start`') + ' to start with node') 113 | printer.log('Run ' + chalk.blue.bold('`npm run prd`') + ' to start with pm2') 114 | printer.log('Run ' + chalk.blue.bold('`npm run stop`') + ' to stop') 115 | printer.log('Run ' + chalk.blue.bold('`npm run restart`') + ' to restart') 116 | printer.log() 117 | printer.log(chalk.green.bold('Remember to finish the following steps:')) 118 | printer.log(chalk.blue.bold(' 1. (Re)Start your service manually!')) 119 | printer.log(chalk.blue.bold(' 2. Finish installation via your browser')) 120 | printer.log('Have fun :p') 121 | printer.log(chalk.grey('For uninstall:')) 122 | printer.log(chalk.grey('- Remove the following folder: ' + process.cwd())) 123 | printer.log(chalk.grey('- Stop youre service manually.')) 124 | // #endregion 125 | } 126 | 127 | install() 128 | -------------------------------------------------------------------------------- /src/service/apikey_service.js: -------------------------------------------------------------------------------- 1 | const jwt = require('jsonwebtoken') 2 | const { dataService } = require('./data_service') 3 | const { configService } = require('./config_service') 4 | const logger = require('log4js').getLogger('services:apikey-service') 5 | 6 | class ApikeyServiceError extends Error { 7 | constructor (message, code) { 8 | super(message) 9 | Error.captureStackTrace(this) 10 | this.code = code 11 | } 12 | } 13 | ApikeyServiceError.prototype.name = 'ApikeyServiceError' 14 | ApikeyServiceError.BAD_OPTIONS = 'BAD_OPTIONS' 15 | ApikeyServiceError.INVALID_APIKEY_TOKEN = 'INVALID_APIKEY_TOKEN' 16 | 17 | class ApikeyDocumentConverter { 18 | static documentToObject (doc, apikey = true) { 19 | if (!doc) return {} 20 | const obj = doc.toObject() 21 | const dateKeys = ['issuedAt', 'lastUsedAt'] 22 | dateKeys.map(key => { 23 | if (obj[key]) obj[key] = obj[key].valueOf() 24 | }) 25 | if (!apikey) { delete obj.apikey } 26 | return obj 27 | } 28 | } 29 | 30 | class ApikeyService { 31 | // #region 添加apikey 32 | /** 33 | * 为id用户申请新api 34 | * @param {String} id 用户id 35 | * @returns 返回用于新建apikey的token 36 | */ 37 | static requestApikey (id) { 38 | const apikeyToken = jwt.sign({ issueat: new Date().valueOf(), type: 'apikeytoken', id }, configService.getApikeySecret(), { expiresIn: '5min' }) 39 | ApikeyService.ApikeyTokens[apikeyToken] = apikeyToken 40 | Object.keys(ApikeyService.ApikeyTokens).map(key => { 41 | logger.info('apikey token') 42 | logger.debug(key) 43 | }) 44 | return apikeyToken 45 | } 46 | 47 | static decodeApikeyToken (apikeyToken) { 48 | const has = Object.keys(ApikeyService.ApikeyTokens).includes(apikeyToken) 49 | if (!has) { 50 | logger.info('invalid apikey token') 51 | logger.debug(apikeyToken) 52 | throw new ApikeyServiceError('invalid apikey token', ApikeyServiceError.INVALID_APIKEY_TOKEN) 53 | } 54 | try { 55 | const decoded = jwt.verify(apikeyToken, configService.getApikeySecret()) 56 | if (has) delete ApikeyService.ApikeyTokens[apikeyToken] 57 | logger.info('apikey token decoded') 58 | return decoded 59 | } catch (err) { 60 | logger.info('invalid apikey token') 61 | logger.debug(apikeyToken) 62 | throw new ApikeyServiceError('invalid apikey token', ApikeyServiceError.INVALID_APIKEY_TOKEN) 63 | } 64 | } 65 | 66 | /** 67 | * 为id用户添加一个apikey 68 | * @param {Object} opt 选项 69 | * @param {String} opt.id 用户id 70 | * @param {String} [opt.deviceType] 设备类型 71 | * @param {String} [opt.deviceSystem] 设备系统 72 | */ 73 | static async addApikey (opt) { 74 | // 格式化参数 75 | if (!opt.id) throw new ApikeyServiceError('opt.id is required', ApikeyServiceError.BAD_OPTIONS) 76 | const id = opt.id 77 | const apikey = jwt.sign({ issueat: new Date().valueOf(), type: 'apikey' }, 's' + Math.random()) 78 | const deviceType = opt.deviceType || 'unknown type' 79 | const deviceSystem = opt.deviceSystem || 'unknown system' 80 | const issuedAt = new Date().valueOf() 81 | const Apikey = dataService.model(dataService.modelTypes.Apikey) 82 | await Apikey.insert({ 83 | apikey, 84 | deviceType, 85 | deviceSystem, 86 | issuedAt, 87 | user_id: id 88 | }) 89 | dataService.save() 90 | logger.info('new apikey added', Apikey.findOne({ apikey })._id) 91 | return { apikey, deviceType, deviceSystem, issuedAt, id } 92 | } 93 | // #endregion 94 | 95 | // #region 获取apikey信息 96 | static getApikeysInfo () { 97 | const Apikey = dataService.model(dataService.modelTypes.Apikey) 98 | const result = Apikey.find({}).map(item => ApikeyDocumentConverter.documentToObject(item, false)) 99 | logger.info('get apikeys info', result.length) 100 | return result 101 | } 102 | // #endregion 103 | 104 | // #region apikey 使用 105 | static getUserFromApikey (apikey) { 106 | const Apikey = dataService.model(dataService.modelTypes.Apikey) 107 | const User = dataService.model(dataService.modelTypes.User) 108 | return User.findOne({ _id: Apikey.findOne({ apikey }).user_id }) 109 | } 110 | 111 | static async hasApikey (apikey) { 112 | const Apikey = dataService.model(dataService.modelTypes.Apikey) 113 | const has = Apikey.findOne({ apikey }) 114 | if (has) { 115 | await Apikey.update({ apikey }, { lastUsedAt: new Date() }) 116 | dataService.save() 117 | logger.info('apikey used', Apikey.findOne({ apikey })._id) 118 | } 119 | return has 120 | } 121 | 122 | static async removeApikeyById (_id) { 123 | const Apikey = dataService.model(dataService.modelTypes.Apikey) 124 | await Apikey.remove({ _id }) 125 | if (Apikey.findOne({ _id })) { 126 | logger.info('apikey removed', _id) 127 | } else { 128 | logger.info('invalid apikey id, do nothing', _id) 129 | } 130 | dataService.save() 131 | } 132 | 133 | static async removeApikeyByApikey (apikey) { 134 | const Apikey = dataService.model(dataService.modelTypes.Apikey) 135 | const one = Apikey.findOne({ apikey }) 136 | await Apikey.remove({ apikey }) 137 | if (one) { 138 | logger.info('apikey removed', one._id) 139 | } else { 140 | logger.info('invalid apikey, do nothing') 141 | logger.debug(apikey) 142 | } 143 | dataService.save() 144 | } 145 | // #endregion 146 | } 147 | 148 | ApikeyService.ApikeyTokens = {} 149 | 150 | module.exports = { ApikeyService, ApikeyServiceError } 151 | -------------------------------------------------------------------------------- /src/server/controller.js: -------------------------------------------------------------------------------- 1 | const { Hexo, HexoError } = require('./hexo') 2 | const hexo = new Hexo() 3 | const Search = require('./search') 4 | const search = new Search(hexo) 5 | const restrictedKeys = require('./info').restrictedKeys 6 | 7 | exports.hexo = hexo 8 | 9 | exports.getRestrictedKeys = async function (ctx, next) { 10 | ctx.body = { 11 | success: true, 12 | data: { 13 | restrictedKeys 14 | } 15 | } 16 | } 17 | 18 | exports.errorHandler = async function (ctx, next) { 19 | try { 20 | await next() 21 | } catch (err) { 22 | switch (err.code) { 23 | case HexoError.POST_NOT_FOUND: 24 | err.status = 404 25 | break 26 | case HexoError.UNINITIALIZED: 27 | err.status = 503 28 | break 29 | case HexoError.CANT_DEPLOY: 30 | err.status = 503 31 | break 32 | case HexoError.NOT_GIT_REPO: 33 | err.status = 503 34 | break 35 | case HexoError.BAD_PARAMS: 36 | err.status = 400 37 | break 38 | case HexoError.SHELL_COMMAND_FAIL: 39 | err.status = 503 40 | } 41 | throw err 42 | } 43 | } 44 | 45 | exports.reload = async function (ctx, next) { 46 | await hexo.load() 47 | ctx.body = { 48 | success: true 49 | } 50 | } 51 | 52 | exports.addPost = async function (ctx, next) { 53 | const post = await hexo.addPost(ctx.request.body) 54 | ctx.body = { 55 | success: true, 56 | data: { 57 | post: post 58 | } 59 | } 60 | } 61 | 62 | exports.addPage = async function (ctx, next) { 63 | const post = await hexo.addPost(ctx.request.body, true) 64 | ctx.body = { 65 | success: true, 66 | data: { 67 | post: post 68 | } 69 | } 70 | } 71 | 72 | exports.getPosts = async function (ctx, next) { 73 | const posts = await hexo.listArticles() 74 | ctx.body = { 75 | success: true, 76 | data: { 77 | posts: posts 78 | } 79 | } 80 | } 81 | 82 | exports.getPost = async function (ctx, next) { 83 | const post = await hexo.getPost(ctx.params.id) 84 | ctx.body = { 85 | success: true, 86 | data: { 87 | post: post 88 | } 89 | } 90 | } 91 | 92 | exports.getPage = async function (ctx, next) { 93 | const post = await hexo.getPost(ctx.params.id, true) 94 | ctx.body = { 95 | success: true, 96 | data: { 97 | post: post 98 | } 99 | } 100 | } 101 | 102 | exports.updatePost = async function (ctx, next) { 103 | const post = await hexo.updatePost({ _id: ctx.params.id, ...ctx.request.body }) 104 | ctx.body = { 105 | success: true, 106 | data: { 107 | post: post 108 | } 109 | } 110 | } 111 | 112 | exports.updatePage = async function (ctx, next) { 113 | const post = await hexo.updatePost({ _id: ctx.params.id, ...ctx.request.body }, true) 114 | ctx.body = { 115 | success: true, 116 | data: { 117 | post: post 118 | } 119 | } 120 | } 121 | 122 | exports.removePost = async function (ctx, next) { 123 | const post = await hexo.deletePost(ctx.params.id) 124 | ctx.body = { 125 | success: true, 126 | data: { 127 | post: post 128 | } 129 | } 130 | } 131 | 132 | exports.removePage = async function (ctx, next) { 133 | const post = await hexo.deletePost(ctx.params.id, true) 134 | ctx.body = { 135 | success: true, 136 | data: { 137 | post: post 138 | } 139 | } 140 | } 141 | 142 | exports.publishPost = async function (ctx, next) { 143 | const post = await hexo.publishPost(ctx.params.id) 144 | ctx.body = { 145 | success: true, 146 | data: { 147 | post: post 148 | } 149 | } 150 | } 151 | 152 | exports.unpublishPost = async function (ctx, next) { 153 | const post = await hexo.unpublishPost(ctx.params.id) 154 | ctx.body = { 155 | success: true, 156 | data: { 157 | post: post 158 | } 159 | } 160 | } 161 | 162 | exports.getTags = async function (ctx, next) { 163 | const tags = await hexo.listTags() 164 | ctx.body = { 165 | success: true, 166 | data: { 167 | tags: tags 168 | } 169 | } 170 | } 171 | 172 | exports.getCategories = async function (ctx, next) { 173 | const categories = await hexo.listCategories() 174 | ctx.body = { 175 | success: true, 176 | data: { 177 | categories: categories 178 | } 179 | } 180 | } 181 | 182 | exports.sync = async function (ctx, next) { 183 | const { remote } = await hexo.syncGit() 184 | ctx.body = { 185 | success: true, 186 | data: { remote } 187 | } 188 | } 189 | 190 | exports.reset = async function (ctx, next) { 191 | await hexo.resetGit() 192 | ctx.body = { 193 | success: true 194 | } 195 | } 196 | 197 | exports.save = async function (ctx, next) { 198 | const { remote } = await hexo.saveGit() 199 | ctx.body = { 200 | success: true, 201 | data: { remote } 202 | } 203 | } 204 | 205 | exports.deploy = async function (ctx, next) { 206 | await hexo.deploy() 207 | ctx.body = { 208 | success: true 209 | } 210 | } 211 | 212 | exports.generate = async function (ctx, next) { 213 | await hexo.generate() 214 | ctx.body = { 215 | success: true 216 | } 217 | } 218 | 219 | exports.clean = async function (ctx, next) { 220 | await hexo.clean() 221 | ctx.body = { 222 | success: true 223 | } 224 | } 225 | 226 | exports.search = async function (ctx, next) { 227 | const size = parseInt(ctx.query.size) 228 | let data 229 | if (!isNaN(size)) { 230 | data = await search.search(ctx.query.q, size) 231 | } else { 232 | data = await search.search(ctx.query.q) 233 | } 234 | ctx.body = { 235 | success: true, 236 | data: { 237 | ...data, 238 | q: ctx.query.q 239 | } 240 | } 241 | } 242 | -------------------------------------------------------------------------------- /src/auth/controller.js: -------------------------------------------------------------------------------- 1 | const auth = require('basic-auth') 2 | const jwt = require('jsonwebtoken') 3 | const compose = require('koa-compose') 4 | const logger = require('log4js').getLogger('server:auth') 5 | const parallel = require('../lib/koa-parallel') 6 | const fs = require('fs') 7 | if (!fs.existsSync('./data/'))fs.mkdirSync('./data') 8 | const { configService, ConfigServiceError } = require('../service/config_service') 9 | const { ApikeyService, ApikeyServiceError } = require('../service/apikey_service') 10 | const { UserService } = require('../service/user_service') 11 | const { DataServiceError } = require('../service/data_service') 12 | 13 | class AuthError extends Error { 14 | constructor (message, code) { 15 | super(message || code) 16 | Error.captureStackTrace(this) 17 | this.code = code 18 | this.status = 401 19 | } 20 | } 21 | AuthError.prototype.name = 'AuthError' 22 | AuthError.AuthticationError = 'AuthticationError' 23 | AuthError.NO_APIKEY = 'NO_APIKEY' 24 | AuthError.NO_BEARER_TOKEN = 'NO_BEARER_TOKEN' 25 | AuthError.API_TOKEN_EXPIRE = 'API_TOKEN_EXPIRE' 26 | 27 | function resolveAuthorizationHeader (ctx) { 28 | if (!ctx.header || !ctx.header.authorization) { 29 | return 30 | } 31 | 32 | const parts = ctx.header.authorization.split(' ') 33 | 34 | if (parts.length === 2) { 35 | const scheme = parts[0] 36 | const credentials = parts[1] 37 | 38 | if (/^Bearer$/i.test(scheme)) { 39 | return credentials 40 | } 41 | } 42 | ctx.throw(401, 'Bad Authorization header format. Format is "Authorization: Bearer "') 43 | } 44 | 45 | exports.apiKeyAuth = async function (ctx, next) { 46 | const apikey = resolveAuthorizationHeader(ctx) 47 | if (!apikey) { 48 | ctx.throw(new AuthError('APIKEY is required', AuthError.NO_APIKEY)) 49 | } else { 50 | if (await ApikeyService.hasApikey(apikey)) { 51 | logger.debug('apikey auth pass') 52 | ctx.state.apikey = apikey 53 | ctx.state.user = ApikeyService.getUserFromApikey(apikey).toObject() 54 | ctx.state.user.id = ctx.state.user._id 55 | delete ctx.state.user._id 56 | await next() 57 | } else { 58 | logger.debug('apikey auth failed, try others') 59 | ctx.throw(new AuthError('Authtication Error', AuthError.AuthticationError)) 60 | } 61 | } 62 | } 63 | 64 | exports.requestApikey = async function (ctx, next) { 65 | const token = ApikeyService.requestApikey(ctx.state.user.id) 66 | ctx.body = { 67 | success: true, 68 | data: { 69 | token 70 | } 71 | } 72 | } 73 | 74 | exports.removeApikey = async function (ctx, next) { 75 | if (ctx.state.apikey) { 76 | const apikey = ctx.state.apikey 77 | await ApikeyService.removeApikeyByApikey(apikey) 78 | } else { 79 | const _id = ctx.params.id 80 | await ApikeyService.removeApikeyById(_id) 81 | } 82 | ctx.body = { 83 | success: true 84 | } 85 | } 86 | 87 | exports.addApikey = async function (ctx, next) { 88 | // 这个apikey只是一个随机字符串没啥含义 89 | const id = ctx.state.user.id 90 | const deviceType = ctx.request.body.deviceType 91 | const deviceSystem = ctx.request.body.deviceSystem 92 | let data 93 | try { 94 | data = await ApikeyService.addApikey({ id, deviceType, deviceSystem }) 95 | } catch (err) { 96 | if (err.code === ConfigServiceError.BAD_OPTIONS) { 97 | logger.debug(err.message) 98 | ctx.status = 400 99 | ctx.body = { 100 | success: false, 101 | message: err.message 102 | } 103 | } else { 104 | throw err 105 | } 106 | } 107 | ctx.body = { 108 | success: true, 109 | data 110 | } 111 | } 112 | 113 | exports.getAPIKEYInfo = async function (ctx, next) { 114 | ctx.body = { 115 | success: true, 116 | data: { 117 | apikeys: ApikeyService.getApikeysInfo() 118 | } 119 | } 120 | } 121 | 122 | exports.apiKeyJwtAuth = async function (ctx, next) { 123 | const token = resolveAuthorizationHeader(ctx) 124 | if (!token) { 125 | ctx.throw(new AuthError('APIKEY is required', AuthError.NO_APIKEY)) 126 | } else { 127 | let decoded 128 | try { 129 | decoded = ApikeyService.decodeApikeyToken(token) 130 | } catch (e) { 131 | if (e.code === ApikeyServiceError.INVALID_APIKEY_TOKEN) { 132 | ctx.throw(new AuthError('Authtication Error', AuthError.AuthticationError)) 133 | } 134 | throw e 135 | } 136 | ctx.state.user = decoded 137 | await next() 138 | } 139 | } 140 | 141 | exports.jwtAuth = async function (ctx, next) { 142 | const token = resolveAuthorizationHeader(ctx) 143 | if (!token) { 144 | ctx.throw(new AuthError('Bearer token required', AuthError.NO_BEARER_TOKEN)) 145 | } else { 146 | try { 147 | const decoded = jwt.verify(token, configService.getJwtSecret()) 148 | logger.debug('jwt auth pass') 149 | ctx.state.user = decoded 150 | } catch (err) { 151 | ctx.throw(new AuthError('Authtication Error', AuthError.AuthticationError)) 152 | } 153 | if (!await UserService.hasUserById(ctx.state.user.id)) { 154 | ctx.throw(new AuthError('Authtication Error', AuthError.AuthticationError)) 155 | } 156 | await next() 157 | } 158 | } 159 | 160 | exports.requestAccessToken = async function (ctx, next) { 161 | if (ctx.state.user.type === 'refresh') { 162 | const err = new Error() 163 | err.status = 400 164 | err.name = 'Require Access token' 165 | err.message = 'Access Token is required.' 166 | throw err 167 | } 168 | await next() 169 | } 170 | 171 | exports.requestRefreshToken = async function (ctx, next) { 172 | if (ctx.state.user.type === 'access') { 173 | const err = new Error() 174 | err.status = 400 175 | err.name = 'Require Refresh token' 176 | err.message = 'Refresh Token is required.' 177 | throw err 178 | } 179 | await next() 180 | } 181 | 182 | exports.basicAuth = async function (ctx, next) { 183 | // get name and pass from reqest header 184 | var user = auth(ctx.request) 185 | if (!user) { 186 | // if not a valide basic auth header 187 | ctx.status = 401 188 | ctx.body = { 189 | success: false, 190 | message: 'basic authentication required' 191 | } 192 | } else { 193 | // find if user exist in database 194 | var dbuser = await UserService.hasUserWithPassword(user.name, user.pass) 195 | // var query = await User.find(user) 196 | if (dbuser) { 197 | // if user exist then set id 198 | ctx.state.id = dbuser._id 199 | ctx.state.name = dbuser.username 200 | await next() 201 | } else { 202 | ctx.status = 401 203 | ctx.body = { 204 | success: false, 205 | message: 'wrong username or password' 206 | } 207 | } 208 | } 209 | } 210 | 211 | exports.getToken = async function (ctx, next) { 212 | // set id and token type into jwt payload 213 | const id = ctx.state.id || ctx.state.user.id 214 | const name = ctx.state.name || ctx.state.user.name 215 | var token = jwt.sign({ id, name, type: 'access' }, configService.getJwtSecret(), { expiresIn: configService.getJwtExpire() }) 216 | var refreshToken = jwt.sign({ id, name, type: 'refresh' }, configService.getJwtSecret(), { expiresIn: configService.getJwtRefresh() }) 217 | ctx.body = { 218 | success: true, 219 | message: 'success', 220 | data: { id, name, token, refreshToken } 221 | } 222 | } 223 | 224 | exports.apikeyOrJwt = parallel([{ 225 | fn: exports.apiKeyAuth, 226 | validator: err => err.status === 401 227 | }, { 228 | fn: compose([exports.jwtAuth, exports.requestAccessToken]) 229 | }]) 230 | -------------------------------------------------------------------------------- /src/server/hexo.js: -------------------------------------------------------------------------------- 1 | const HexoAPI = require('hexo') 2 | const path = require('path') 3 | const YAML = require('yamljs') 4 | const fs = require('hexo-fs') 5 | const Git = require('simple-git/promise') 6 | const isGit = require('is-git-repository') 7 | const { exec } = require('child_process') 8 | const Post = require('./post') 9 | const logger = require('log4js').getLogger('hexo-editor-server:hexo') 10 | 11 | class HexoError extends Error { 12 | constructor (message, code) { 13 | super(message) 14 | Error.captureStackTrace(this) 15 | this.code = code 16 | } 17 | } 18 | HexoError.prototype.name = 'HexoError' 19 | HexoError.NOT_BLOG_ROOT = 'NOT_BLOG_ROOT' 20 | HexoError.EMPTY_HEXO_ROOT = 'EMPTY_HEXO_ROOT' 21 | HexoError.POST_NOT_FOUND = 'POST_NOT_FOUND' 22 | HexoError.UNINITIALIZED = 'UNINITIALIZED' 23 | HexoError.CANT_DEPLOY = 'CANT_DEPLOY' 24 | HexoError.BAD_PARAMS = 'BAD_PARAMS' 25 | HexoError.NOT_GIT_REPO = 'NOT_GIT_REPO' 26 | HexoError.SHELL_COMMAND_FAIL = 'SHELL_COMMAND_FAIL' 27 | 28 | /** 29 | * 用于和hexo交互的模型 30 | * @class 31 | */ 32 | class Hexo { 33 | /** 34 | * 初始化 35 | * @param {String} [cwd=process.cwd()] - 工作路径 36 | */ 37 | constructor () { 38 | this.ready = false 39 | this.git = null 40 | } 41 | 42 | /** 43 | * 检测是否是hexo博客目录 44 | * 如果没有依赖hexo或者没有`_config.yml`则视为不是博客目录 45 | * 可能的错误:HexoError.NOT_BLOG_ROOT | other 46 | * @private 47 | */ 48 | _checkIsBlog (cwd) { 49 | logger.debug('try HEXO_ROOT', cwd) 50 | let file 51 | try { 52 | // 检查是否有对应文件 53 | file = fs.readFileSync(path.join(cwd, 'package.json')) 54 | fs.readFileSync(path.join(cwd, '_config.yml')) 55 | } catch (err) { 56 | if (err.code === 'ENOENT') { 57 | const e = new HexoError(`${cwd} isn't a hexo blog folder!`, HexoError.NOT_BLOG_ROOT) 58 | e.data = { 59 | path: path.join(process.cwd(), cwd) 60 | } 61 | logger.warn(`${path.join(process.cwd(), cwd)} isn't a hexo blog folder!`) 62 | throw e 63 | } 64 | throw err 65 | } 66 | // 检查是否有hexo依赖 67 | const packageJSON = JSON.parse(file) 68 | if (!packageJSON.dependencies.hexo) throw new HexoError(`${cwd} isn't a hexo blog folder!`, HexoError.NOT_BLOG_ROOT) 69 | } 70 | 71 | /** 72 | * 检查是否存在hexo部署配置,如果_config.yml>deploy>type存在则视为有配置 73 | * 可能的错误:null 74 | * @private 75 | */ 76 | _checkCanDeploy () { 77 | logger.debug('checking blog can deploy') 78 | const hexoConfigYML = YAML.parse(fs.readFileSync(path.join(this.cwd, '_config.yml')).toString()) 79 | if (hexoConfigYML.deploy) { 80 | if (!Array.isArray(hexoConfigYML.deploy)) { 81 | this.canDeploy = !!hexoConfigYML.deploy.type 82 | } else { 83 | this.canDeploy = !!hexoConfigYML.deploy[0].type 84 | } 85 | } else { 86 | this.canDeploy = false 87 | } 88 | if (!this.canDeploy) { 89 | logger.warn(`Hexo deploy config not exists in ${this.cwd}. Can't deploy blog.`) 90 | } else { 91 | logger.debug('blog can deploy') 92 | } 93 | return this.canDeploy 94 | } 95 | 96 | _checkIsGit () { 97 | this.isGit = isGit(this.cwd) 98 | return this.isGit 99 | } 100 | 101 | /** 102 | * 初始化并开始监听文件 103 | * 可能的错误:HexoError.EMPTY_HEXO_ROOT | HexoError.NOT_BLOG_ROOT | other 104 | * @param {String} cwd Hexo博客目录 105 | */ 106 | async init (cwd) { 107 | logger.info('starting') 108 | if (!cwd) throw new HexoError('Hexo Root is required!', HexoError.EMPTY_HEXO_ROOT) 109 | this._checkIsBlog(cwd) 110 | this.cwd = cwd 111 | logger.debug('set HEXO_ROOT', this.cwd) 112 | this._checkCanDeploy() 113 | this._checkIsGit() 114 | if (!this.isGit) { 115 | logger.warn(`${this.cwd} isn't a git repository`) 116 | logger.warn('Function syncGit, resetGit and saveGit will work locally') 117 | } 118 | 119 | this.hexo = new HexoAPI(this.cwd, { debug: false, draft: true, silent: process.env.NODE_ENV !== 'development' }) 120 | if (this.isGit) { this.git = new Git(this.cwd) } 121 | 122 | // 初始化hexo 123 | await this.hexo.init() 124 | 125 | // 监听事件 126 | this.hexo.on('new', post => { 127 | logger.info('new file', post.path) 128 | }) 129 | 130 | // 载入数据 131 | await this.load() 132 | 133 | // Ready to go! 134 | this.ready = true 135 | logger.info('ready') 136 | } 137 | 138 | /** 139 | * 检测hexo是否完成初始化 140 | * @private 141 | */ 142 | _checkReady () { 143 | if (!this.ready) { 144 | logger.warn('Hexo uninitiated, try again later') 145 | throw new HexoError('Hexo uninitiated, try again later', HexoError.UNINITIALIZED) 146 | } 147 | } 148 | 149 | /** 150 | * 从磁盘载入数据 151 | * @private 152 | */ 153 | async load () { 154 | logger.debug('load data') 155 | await this.hexo.load() 156 | } 157 | 158 | unlinkSync () { 159 | try { 160 | fs.unlinkSync(...arguments) 161 | } catch (err) { 162 | logger.error('fail to delete fail:', ...arguments) 163 | throw err 164 | } 165 | } 166 | 167 | /** 168 | * 保存文章到磁盘 169 | * @param {Post[]} posts - 需要更新的文章 170 | * @returns {_Document[]} - 更新后的文章文档 171 | * @private 172 | */ 173 | async _save (posts) { 174 | const pathes = [] 175 | var file = null 176 | await Promise.all(posts.map(async item => { 177 | const { post, isPage } = item 178 | logger.info('save', post._id, 'is page:', isPage) 179 | const src = await this._get(post._id, isPage) 180 | // 删除源文件 181 | this.unlinkSync(src.full_source) 182 | if (!post.published && !isPage)post.layout = 'draft' 183 | // 创建新文件 184 | post.freeze() 185 | file = await this.hexo.post.create(post) 186 | pathes.push(file.path) 187 | })) 188 | // 更新数据 189 | await this.load() 190 | // 查询新数据 191 | const p1 = this.hexo.locals.get('posts').toArray() 192 | .filter(item => pathes.includes(item.full_source)) 193 | .map(doc => new Post(doc)) 194 | const p2 = this.hexo.locals.get('pages').toArray() 195 | .filter(item => pathes.includes(item.full_source)) 196 | .map(doc => new Post(doc)) 197 | return p1.concat(p2) 198 | } 199 | 200 | /** 201 | * 抛出文章未找到异常 202 | * @private 203 | */ 204 | _throwPostNotFound () { 205 | throw new HexoError('post not found', HexoError.POST_NOT_FOUND) 206 | } 207 | 208 | /** 209 | * 从磁盘和数据库删除文章 210 | * @param {String[]} ids - 需要删除的文章id列表 211 | * @returns {Post[]} - 已删除的文章列表 212 | * @private 213 | */ 214 | async _remove (ids) { 215 | var posts = [] 216 | var post = null 217 | await Promise.all(ids.map(async item => { 218 | const { id, isPage } = item 219 | logger.info('remove', id) 220 | post = await this._get(id, isPage) 221 | // 删除文件 222 | this.unlinkSync(post.full_source) 223 | // 清除数据 224 | await this.load() 225 | posts.push(new Post(post)) 226 | })) 227 | return posts 228 | } 229 | 230 | /** 231 | * 新建一篇文章 232 | * @param {Post} post - 用于新建的文章 233 | * @param {Number} [addon=0] - slug的后缀,如果不为零则添加此数字为后缀 234 | * @param {Boolean} isPage - 是否是page 235 | * @returns {Post} - 新建的文章 236 | * @private 237 | */ 238 | async _add (post, addon = 0, isPage = false) { 239 | logger.info('_add with slug', post.slug, Object.keys(post)) 240 | // 存在slug就查询slug是否被占用 241 | if (!isPage && post.slug && this.hexo.locals.get('posts').find({ slug: post.slug }).length) { 242 | // 如果被占用 243 | if (addon) { 244 | // 清除后缀 245 | post.slug = post.slug.slice(0, addon.toString().length) 246 | } 247 | // 添加后缀 slug1 248 | post.slug += (addon + 1) 249 | return this._add(post, addon + 1) 250 | } 251 | if (isPage) { 252 | delete post.slug 253 | post.layout = 'page' 254 | } else { 255 | post.layout = 'draft' 256 | } 257 | // 创建文件 258 | const file = await this.hexo.post.create(new Post(post, false).freeze()) 259 | // 更新数据 260 | await this.load() 261 | // 读取文件 262 | return new Post(this.hexo.locals.get(isPage ? 'pages' : 'posts') 263 | .findOne({ full_source: file.path })) 264 | } 265 | 266 | /** 267 | * 更新文章并存储 268 | * @param {Post} post - 需要更新的文章及其参数 269 | * @param {String} post._id - 文章id 270 | * @param {Boolean} isPage - 是否是page 271 | * @returns {Post} - 更新过的文章 272 | * @private 273 | */ 274 | async _update (post, isPage = false) { 275 | logger.info('update', post._id, Object.keys(post)) 276 | if (post.frontmatters) { 277 | logger.info('update', post._id, 'frontmatters', Object.keys(post.frontmatters)) 278 | } 279 | var src = await this._get(post._id, isPage) 280 | if (!src) return null 281 | src = new Post(src) 282 | src.update(post) 283 | var posts = await this._save([{ post: src, isPage }]) 284 | if (posts.length === 0) { 285 | const err = new Error() 286 | err.status = 500 287 | err.message = 'Unknown error' 288 | err.message = 'Cant find post' + post._id 289 | throw err 290 | } 291 | if (posts.length > 1) throw new Error('multiple posts found') 292 | return posts[0] 293 | } 294 | 295 | /** 296 | * 从_id读取数据库文章 297 | * @param {String} _id - 文章id 298 | * @param {Boolean} isPage - 是否是page 299 | * @returns {_Document} - 文章文档 300 | * @private 301 | */ 302 | async _get (_id, isPage = false) { 303 | const name = isPage ? 'pages' : 'posts' 304 | const query = this.hexo.locals.get(name).findOne({ _id }) 305 | if (!query) { 306 | logger.info('not found', _id) 307 | this._throwPostNotFound() 308 | } 309 | return query 310 | } 311 | 312 | /** 313 | * 获取文章列表 314 | * @returns {Post[]} - 文章列表 315 | * @public 316 | */ 317 | async listArticles () { 318 | this._checkReady() 319 | logger.info('list posts', this.hexo.locals.get('posts').toArray().length) 320 | await this.load() 321 | const posts = this.hexo.locals.get('posts') 322 | .map(doc => new Post(doc)).map(post => { 323 | post._whe_brief = post._content.slice(0, 200) 324 | delete post._content 325 | delete post.raw 326 | return post 327 | }) 328 | const pages = this.hexo.locals.get('pages') 329 | .map(doc => new Post(doc)).map(post => { 330 | post._whe_brief = post._content.slice(0, 200) 331 | delete post._content 332 | delete post.raw 333 | return post 334 | }) 335 | return posts.concat(pages) 336 | } 337 | 338 | async listArticlesRaw () { 339 | this._checkReady() 340 | logger.info('list posts', this.hexo.locals.get('posts').toArray().length) 341 | await this.load() 342 | const posts = this.hexo.locals.get('posts') 343 | .map(doc => new Post(doc)).map(post => { 344 | return { 345 | _id: post._id, 346 | raw: post.raw, 347 | layout: post.layout, 348 | published: post.published 349 | } 350 | }) 351 | const pages = this.hexo.locals.get('pages') 352 | .map(doc => new Post(doc)).map(post => { 353 | return { 354 | _id: post._id, 355 | raw: post.raw 356 | } 357 | }) 358 | return posts.concat(pages) 359 | } 360 | 361 | /** 362 | * 获取标签列表 363 | * @returns {Object[]} - 标签对象列表 364 | * @public 365 | */ 366 | async listTags () { 367 | this._checkReady() 368 | const tags = this.hexo.locals.get('tags') 369 | .toArray() 370 | .map(item => { 371 | return this._formatTag(item) 372 | }) 373 | logger.info('list tag', tags.length) 374 | return tags 375 | } 376 | 377 | /** 378 | * 获取分类列表 379 | * @returns {Object[]} - 分类列表 380 | * @public 381 | */ 382 | async listCategories () { 383 | this._checkReady() 384 | const categories = this.hexo.locals.get('categories') 385 | .toArray() 386 | .map(item => { 387 | return this._formatCategorie(item) 388 | }) 389 | logger.info('list categories', categories.length) 390 | return categories 391 | } 392 | 393 | /** 394 | * 获取单篇文章 395 | * @param {String} _id - 文章id 396 | * @param {Boolean} isPage - 是否是page 397 | * @returns {Post|null} - 文章对象,如果没有则为`null` 398 | * @public 399 | */ 400 | async getPost (_id, isPage = false) { 401 | this._checkReady() 402 | logger.info('get post', _id, 'is page:', isPage) 403 | if (!_id) throw new HexoError('_id should be String!', HexoError.BAD_PARAMS) 404 | const query = await this._get(_id, isPage) 405 | return query ? new Post(query) : null 406 | } 407 | 408 | /** 409 | * 新建一篇文章 410 | * @param {Object} options - 新建参数 411 | * @param {String} options.title - 文章名 412 | * @param {String} [options.slug] - 网址,参见[hexo API]{@link https://hexo.io/zh-cn/api/posts} 413 | * @param {Boolean} isPage - 是否是page 414 | * @returns {Post} - 新建的文章 415 | * @public 416 | */ 417 | async addPost (options, isPage) { 418 | this._checkReady() 419 | if (!options.title) throw new HexoError('post.title is required!', HexoError.BAD_PARAMS) 420 | logger.info('add post', Object.keys(options)) 421 | var post = new Post(options, false) 422 | // 新文章不能指定`_id` 423 | delete post._id 424 | // post.published是计算出来的,不是指定的 425 | delete post.published 426 | post = await this._add(post, undefined, isPage) 427 | return post 428 | } 429 | 430 | /** 431 | * 更新一篇文章 432 | * @param {Object} options - 更新参数 433 | * @param {String} options._id - 文章id 434 | * @param {Array} options._whe_delete - 需要删除的键的数组 435 | * @param {Boolean} isPage - 是否是page 436 | * @returns {Post} - 更新过的文章 437 | * @public 438 | */ 439 | async updatePost (options, isPage) { 440 | this._checkReady() 441 | if (!options._id) throw new Error('options._id is required!') 442 | logger.info('update post', options._id, 'isPage', isPage) 443 | return this._update(new Post(options, false), isPage) 444 | } 445 | 446 | /** 447 | * 删除一篇文章 448 | * @param {String} _id - 文章id 449 | * @returns {Post} - 被删除的文章 450 | */ 451 | async deletePost (_id, isPage = false, hard = true) { 452 | this._checkReady() 453 | if (!_id) throw new Error('_id is required!') 454 | logger.info('delete post', _id) 455 | if (hard) { 456 | var posts = await this._remove([{ id: _id, isPage }]) 457 | if (posts.length === 0) this._throwPostNotFound() 458 | if (posts.length > 1) { 459 | throw new Error('multiple posts found') 460 | } 461 | return posts[0] 462 | } else { 463 | const post = await this._get(_id, isPage) 464 | if (!post) this._throwPostNotFound() 465 | await this._moveFile('_discarded', post) 466 | await this.load() 467 | return new Post(post) 468 | } 469 | } 470 | 471 | /** 472 | * 发布文章 473 | * @param {String} _id - 文章id 474 | * @returns {Post} - 发布后的文章,**注意,id会改变!** 475 | * @public 476 | */ 477 | async publishPost (_id) { 478 | this._checkReady() 479 | if (!_id) throw new Error('_id is required!') 480 | logger.info('publish post', _id) 481 | var doc = await this._get(_id) 482 | try { 483 | await this.hexo.post.publish({ slug: doc.slug }, true) 484 | } catch (err) { 485 | this._throwPostNotFound() 486 | } 487 | await this.load() 488 | const post = this.hexo.locals.get('posts') 489 | .findOne({ slug: doc.slug }) 490 | if (!post) this._throwPostNotFound() 491 | return new Post(post) 492 | } 493 | 494 | /** 495 | * 取消发布文章 496 | * @param {String} _id - 文章id 497 | * @returns {Post} - 取消发布后的文章,**注意,id会改变!** 498 | * @public 499 | */ 500 | async unpublishPost (_id) { 501 | this._checkReady() 502 | if (!_id) throw new Error('_id is required!') 503 | logger.info('unpublish post', _id) 504 | var doc = await this._get(_id) 505 | var post = new Post(doc) 506 | post.published = false 507 | return this._update(post) 508 | } 509 | 510 | /** 511 | * 将hexo数据库中categories处理为可以序列化为json的对象 512 | * @param {Query} category - 分类 513 | * @returns {Object} - 可以转化为JSON的对象 514 | * @private 515 | */ 516 | _formatCategorie (category) { 517 | category = category.toObject() 518 | var posts = category.posts.toArray() 519 | category.posts = posts.map(post => post._id) 520 | return category 521 | } 522 | 523 | /** 524 | * 将hexo数据库中tags处理为可以序列化为json的对象 525 | * @param {_Document} tag - 标签文档 526 | * @returns {Object} - 可以转化为JSON的对象 527 | * @private 528 | */ 529 | _formatTag (tag) { 530 | tag = tag.toObject() 531 | var posts = tag.posts.toArray() 532 | tag.posts = posts.map(post => post._id) 533 | return tag 534 | } 535 | 536 | /** 537 | * 移动文章源文件 538 | * @param {String} to 539 | * @param {String} from 540 | * @param {String} folder source/_xxx 541 | * @param {String} data post.raw 542 | * @private 543 | */ 544 | async _moveFile (dest, post) { 545 | logger.info(`move file from ${post.source} to ${dest}/`) 546 | const src = post.full_source 547 | const des = post.full_source.replace(post.source.split(path.sep)[0], dest) 548 | const folder = path.join(this.hexo.source_dir, dest) 549 | 550 | if (!fs.exists(folder)) { 551 | fs.mkdir(folder) 552 | } 553 | fs.writeFile(des, post.raw) 554 | this.unlinkSync(src) 555 | } 556 | 557 | /** 558 | * 部署网站 559 | */ 560 | async deploy () { 561 | this._checkReady() 562 | if (!this._checkCanDeploy()) { 563 | throw new HexoError('No deploy config found. Can\'t deploy.', HexoError.CANT_DEPLOY) 564 | } 565 | logger.info('deploy') 566 | return this._runShell('hexo generate -d') 567 | } 568 | 569 | /** 570 | * 生成网站 571 | */ 572 | async generate () { 573 | this._checkReady() 574 | logger.info('generate') 575 | return this._runShell('hexo generate') 576 | } 577 | 578 | /** 579 | * 清理hexo数据 580 | */ 581 | async clean () { 582 | this._checkReady() 583 | logger.info('clean') 584 | return this._runShell('hexo clean') 585 | } 586 | 587 | /** 588 | * 运行控制台程序 589 | * @param {String} cmd 命令 590 | * @private 591 | */ 592 | async _runShell (cmd) { 593 | return new Promise((resolve, reject) => { 594 | const workProcess = exec(cmd, { 595 | cwd: this.cwd, 596 | maxBuffer: 5000 * 1024 // 默认 200 * 1024 597 | }) 598 | // 打印正常的后台可执行程序输出 599 | workProcess.stdout.on('data', function (data) { 600 | logger.info(data) 601 | }) 602 | 603 | // 打印错误的后台可执行程序输出 604 | workProcess.stderr.on('data', function (data) { 605 | logger.error(data) 606 | }) 607 | 608 | // 退出之后的输出 609 | workProcess.on('close', function (code, signal) { 610 | if (code === 0) { 611 | resolve(0) 612 | } else { 613 | logger.error('failed to run command', cmd) 614 | logger.error(code, signal) 615 | const err = new HexoError('failed to run command ' + cmd, HexoError.SHELL_COMMAND_FAIL) 616 | err.data = { code, signal } 617 | reject(err) 618 | } 619 | }) 620 | }) 621 | } 622 | 623 | /** 624 | * 运行简单控制台程序并获取输出 625 | * @param {String} cmd 命令 626 | * @private 627 | */ 628 | async _runSimpleShell (cmd) { 629 | return new Promise((resolve, reject) => { 630 | exec('git remote -v', { cwd: this.cwd }, (err, stdout, stderr) => { 631 | if (err) { 632 | err.stdout = stdout 633 | err.stderr = stderr 634 | reject(err) 635 | } 636 | resolve(stdout) 637 | }) 638 | }) 639 | } 640 | 641 | /** 642 | * 抛出不是git目录的异常 643 | * @private 644 | */ 645 | _notGitRepo () { 646 | throw new HexoError(`${this.cwd} isn't a git repository`, HexoError.NOT_GIT_REPO) 647 | } 648 | 649 | /** 650 | * 从GIT同步 651 | */ 652 | async syncGit () { 653 | logger.info('sync git') 654 | if (!this._checkIsGit()) this._notGitRepo() 655 | const stdout = await this._runSimpleShell('git remote -v') 656 | const remote = !!stdout 657 | await this.git.reset('hard') 658 | if (remote) await this.git.pull() 659 | return { remote } 660 | } 661 | 662 | /** 663 | * 重置本地文件 664 | */ 665 | async resetGit () { 666 | logger.info('reset git') 667 | if (!this._checkIsGit()) this._notGitRepo() 668 | await this.git.reset('hard') 669 | } 670 | 671 | /** 672 | * 保存到git 673 | */ 674 | async saveGit () { 675 | logger.info('save git') 676 | if (!this._checkIsGit()) this._notGitRepo() 677 | const stdout = await this._runSimpleShell('git remote -v') 678 | const remote = !!stdout 679 | await this._runShell('git add . --all') 680 | await this.git.commit('server update posts: ' + (new Date()).toString(), () => {}) 681 | if (remote) await this.git.push() 682 | return { remote } 683 | } 684 | } 685 | 686 | module.exports = { Hexo, HexoError } 687 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "openapi": "3.0.1", 3 | "info": { 4 | "title": "@winwin/hexo-editor-api", 5 | "version": "0.6.0-1", 6 | "description": "An api definition for @winwin/hexo-editor", 7 | "contact": { 8 | "email": "yjh2011@live.com", 9 | "name": "winwin2011", 10 | "url": "https://github.com/yuJianghao/winwin-hexo-editor-server" 11 | }, 12 | "license": { 13 | "name": "GPLv3" 14 | } 15 | }, 16 | "servers": [ 17 | { 18 | "url": "/" 19 | } 20 | ], 21 | "paths": { 22 | "/auth/token": { 23 | "summary": "获取登录token", 24 | "post": { 25 | "summary": "获取登录token", 26 | "responses": { 27 | "200": { 28 | "description": "OK", 29 | "content": { 30 | "application/json": { 31 | "schema": { 32 | "type": "object", 33 | "properties": { 34 | "success": { 35 | "type": "boolean" 36 | }, 37 | "data": { 38 | "type": "object", 39 | "properties": { 40 | "id": { 41 | "type": "string" 42 | }, 43 | "token": { 44 | "type": "string" 45 | }, 46 | "refreshToken": { 47 | "type": "string" 48 | } 49 | } 50 | } 51 | } 52 | } 53 | } 54 | } 55 | } 56 | }, 57 | "tags": [ 58 | "auth" 59 | ], 60 | "security": [ 61 | { 62 | "basicAuth": [] 63 | } 64 | ] 65 | } 66 | }, 67 | "/auth/refresh": { 68 | "summary": "刷新登录token", 69 | "post": { 70 | "summary": "刷新登录token", 71 | "responses": { 72 | "200": { 73 | "description": "OK", 74 | "content": { 75 | "application/json": { 76 | "schema": { 77 | "type": "object", 78 | "properties": { 79 | "success": { 80 | "type": "boolean" 81 | }, 82 | "data": { 83 | "type": "object", 84 | "properties": { 85 | "id": { 86 | "type": "string" 87 | }, 88 | "token": { 89 | "type": "string" 90 | }, 91 | "refreshToken": { 92 | "type": "string" 93 | } 94 | } 95 | } 96 | } 97 | } 98 | } 99 | } 100 | } 101 | }, 102 | "tags": [ 103 | "auth" 104 | ], 105 | "security": [ 106 | { 107 | "bearerAuthRefresh": [] 108 | } 109 | ] 110 | } 111 | }, 112 | "/auth/apikeytoken": { 113 | "summary": "获取用于申请apikey的token", 114 | "post": { 115 | "summary": "获取用于申请apikey的token", 116 | "description": "5分钟内有效,仅可使用一次,过期或使用后需要重新申请", 117 | "responses": { 118 | "200": { 119 | "description": "OK", 120 | "content": { 121 | "application/json": { 122 | "schema": { 123 | "type": "object", 124 | "properties": { 125 | "success": { 126 | "type": "boolean" 127 | }, 128 | "data": { 129 | "type": "object", 130 | "properties": { 131 | "token": { 132 | "type": "string" 133 | } 134 | } 135 | } 136 | } 137 | } 138 | } 139 | } 140 | } 141 | }, 142 | "tags": [ 143 | "auth" 144 | ], 145 | "security": [ 146 | { 147 | "bearerAuthToken": [] 148 | } 149 | ] 150 | } 151 | }, 152 | "/auth/apikeys": { 153 | "summary": "获取当前已授权的apikey列表", 154 | "get": { 155 | "summary": "获取当前已授权的apikey列表", 156 | "responses": { 157 | "200": { 158 | "description": "OK", 159 | "content": { 160 | "application/json": { 161 | "schema": { 162 | "type": "object", 163 | "properties": { 164 | "success": { 165 | "type": "boolean" 166 | }, 167 | "data": { 168 | "type": "object", 169 | "properties": { 170 | "apikeys": { 171 | "type": "array", 172 | "items": { 173 | "type": "object", 174 | "properties": { 175 | "deviceType": { 176 | "type": "string" 177 | }, 178 | "deviceSystem": { 179 | "type": "string" 180 | }, 181 | "issuedAt": { 182 | "type": "number" 183 | }, 184 | "user_id": { 185 | "type": "string" 186 | }, 187 | "_id": { 188 | "type": "string" 189 | }, 190 | "username": { 191 | "type": "string" 192 | } 193 | } 194 | } 195 | } 196 | } 197 | } 198 | } 199 | } 200 | } 201 | } 202 | } 203 | }, 204 | "tags": [ 205 | "auth" 206 | ], 207 | "security": [ 208 | { 209 | "bearerAuthToken": [] 210 | } 211 | ] 212 | } 213 | }, 214 | "/auth/apikey": { 215 | "summary": "apikey添加和删除", 216 | "post": { 217 | "summary": "添加一个apikey", 218 | "responses": { 219 | "200": { 220 | "description": "OK", 221 | "content": { 222 | "application/json": { 223 | "schema": { 224 | "type": "object", 225 | "properties": { 226 | "success": { 227 | "type": "boolean" 228 | }, 229 | "data": { 230 | "type": "object", 231 | "properties": { 232 | "apikey": { 233 | "type": "string" 234 | } 235 | } 236 | } 237 | } 238 | } 239 | } 240 | } 241 | } 242 | }, 243 | "tags": [ 244 | "auth" 245 | ], 246 | "security": [ 247 | { 248 | "bearerAuthAPIKEYToken": [] 249 | } 250 | ] 251 | }, 252 | "delete": { 253 | "summary": "删除一个apikey", 254 | "responses": { 255 | "200": { 256 | "description": "OK", 257 | "content": { 258 | "application/json": { 259 | "schema": { 260 | "type": "object", 261 | "properties": { 262 | "success": { 263 | "type": "boolean" 264 | } 265 | } 266 | } 267 | } 268 | } 269 | } 270 | }, 271 | "tags": [ 272 | "auth" 273 | ], 274 | "security": [ 275 | { 276 | "apikey": [] 277 | } 278 | ] 279 | } 280 | }, 281 | "/auth/apikey/{id}": { 282 | "summary": "apikey添加和删除", 283 | "delete": { 284 | "summary": "删除一个apikey", 285 | "description": "", 286 | "operationId": "", 287 | "parameters": [ 288 | { 289 | "name": "id", 290 | "in": "path", 291 | "description": "ID of the apikey", 292 | "required": true, 293 | "schema": { 294 | "type": "string" 295 | } 296 | } 297 | ], 298 | "responses": { 299 | "200": { 300 | "description": "OK", 301 | "content": { 302 | "application/json": { 303 | "schema": { 304 | "type": "object", 305 | "properties": { 306 | "success": { 307 | "type": "boolean" 308 | } 309 | } 310 | } 311 | } 312 | } 313 | } 314 | }, 315 | "tags": [ 316 | "auth" 317 | ], 318 | "security": [ 319 | { 320 | "apikey": [] 321 | } 322 | ] 323 | } 324 | }, 325 | "/hexoeditorserver/posts": { 326 | "summary": "Actions about posts", 327 | "get": { 328 | "summary": "Get all posts", 329 | "description": "", 330 | "operationId": "", 331 | "responses": { 332 | "200": { 333 | "description": "OK", 334 | "content": { 335 | "application/json": { 336 | "schema": { 337 | "type": "object", 338 | "properties": { 339 | "success": { 340 | "type": "boolean" 341 | }, 342 | "data": { 343 | "type": "object", 344 | "properties": { 345 | "posts": { 346 | "type": "array", 347 | "items": { 348 | "$ref": "#/components/schemas/Post" 349 | } 350 | } 351 | } 352 | } 353 | } 354 | } 355 | } 356 | } 357 | }, 358 | "default": { 359 | "$ref": "#/components/responses/DefaultError" 360 | } 361 | }, 362 | "tags": [ 363 | "lists" 364 | ], 365 | "security": [ 366 | { 367 | "bearerAuthToken": [] 368 | }, 369 | { 370 | "apikey": [] 371 | } 372 | ] 373 | } 374 | }, 375 | "/hexoeditorserver/tags": { 376 | "summary": "Actions about tags", 377 | "get": { 378 | "summary": "Get all tags", 379 | "description": "", 380 | "operationId": "", 381 | "responses": { 382 | "200": { 383 | "description": "OK", 384 | "content": { 385 | "application/json": { 386 | "schema": { 387 | "type": "object", 388 | "properties": { 389 | "success": { 390 | "type": "boolean" 391 | }, 392 | "data": { 393 | "type": "object", 394 | "properties": { 395 | "tags": { 396 | "type": "array", 397 | "items": { 398 | "$ref": "#/components/schemas/Tag" 399 | } 400 | } 401 | } 402 | } 403 | } 404 | } 405 | } 406 | } 407 | }, 408 | "default": { 409 | "$ref": "#/components/responses/DefaultError" 410 | } 411 | }, 412 | "tags": [ 413 | "lists" 414 | ], 415 | "security": [ 416 | { 417 | "bearerAuthToken": [] 418 | }, 419 | { 420 | "apikey": [] 421 | } 422 | ] 423 | } 424 | }, 425 | "/hexoeditorserver/categories": { 426 | "summary": "Actions about categories", 427 | "get": { 428 | "summary": "Get all categories", 429 | "description": "", 430 | "operationId": "", 431 | "responses": { 432 | "200": { 433 | "description": "OK", 434 | "content": { 435 | "application/json": { 436 | "schema": { 437 | "type": "object", 438 | "properties": { 439 | "success": { 440 | "type": "boolean" 441 | }, 442 | "data": { 443 | "type": "object", 444 | "properties": { 445 | "categories": { 446 | "type": "array", 447 | "items": { 448 | "$ref": "#/components/schemas/Category" 449 | } 450 | } 451 | } 452 | } 453 | } 454 | } 455 | } 456 | } 457 | }, 458 | "default": { 459 | "$ref": "#/components/responses/DefaultError" 460 | } 461 | }, 462 | "tags": [ 463 | "lists" 464 | ], 465 | "security": [ 466 | { 467 | "bearerAuthToken": [] 468 | }, 469 | { 470 | "apikey": [] 471 | } 472 | ] 473 | } 474 | }, 475 | "/hexoeditorserver/post": { 476 | "summary": "Actions about one specific post", 477 | "post": { 478 | "summary": "Add post by options", 479 | "description": "", 480 | "operationId": "", 481 | "requestBody": { 482 | "description": "Post object needs to add", 483 | "content": { 484 | "application/json": { 485 | "schema": { 486 | "type": "object", 487 | "properties": { 488 | "title": { 489 | "type": "string" 490 | } 491 | } 492 | } 493 | } 494 | } 495 | }, 496 | "responses": { 497 | "200": { 498 | "$ref": "#/components/responses/Post200" 499 | }, 500 | "404": { 501 | "$ref": "#/components/responses/Post404" 502 | }, 503 | "default": { 504 | "$ref": "#/components/responses/DefaultError" 505 | } 506 | }, 507 | "tags": [ 508 | "post" 509 | ], 510 | "security": [ 511 | { 512 | "bearerAuthToken": [] 513 | }, 514 | { 515 | "apikey": [] 516 | } 517 | ] 518 | } 519 | }, 520 | "/hexoeditorserver/post/{id}": { 521 | "summary": "Actions about one specific post", 522 | "get": { 523 | "summary": "Get post by id", 524 | "description": "", 525 | "operationId": "", 526 | "parameters": [ 527 | { 528 | "name": "id", 529 | "in": "path", 530 | "description": "ID of the post", 531 | "required": true, 532 | "schema": { 533 | "type": "string" 534 | } 535 | } 536 | ], 537 | "responses": { 538 | "200": { 539 | "$ref": "#/components/responses/Post200" 540 | }, 541 | "404": { 542 | "$ref": "#/components/responses/Post404" 543 | }, 544 | "default": { 545 | "$ref": "#/components/responses/DefaultError" 546 | } 547 | }, 548 | "tags": [ 549 | "post" 550 | ], 551 | "security": [ 552 | { 553 | "bearerAuthToken": [] 554 | }, 555 | { 556 | "apikey": [] 557 | } 558 | ] 559 | }, 560 | "put": { 561 | "summary": "Update post by id and options", 562 | "description": "", 563 | "operationId": "", 564 | "parameters": [ 565 | { 566 | "name": "id", 567 | "in": "path", 568 | "description": "ID of the post", 569 | "required": true, 570 | "schema": { 571 | "type": "string" 572 | } 573 | } 574 | ], 575 | "requestBody": { 576 | "description": "Post object needs to add", 577 | "content": { 578 | "application/json": { 579 | "schema": { 580 | "type": "object", 581 | "properties": { 582 | "title": { 583 | "type": "string" 584 | }, 585 | "slug": { 586 | "type": "string" 587 | } 588 | } 589 | } 590 | } 591 | } 592 | }, 593 | "responses": { 594 | "200": { 595 | "$ref": "#/components/responses/Post200" 596 | }, 597 | "404": { 598 | "$ref": "#/components/responses/Post404" 599 | }, 600 | "default": { 601 | "$ref": "#/components/responses/DefaultError" 602 | } 603 | }, 604 | "tags": [ 605 | "post" 606 | ], 607 | "security": [ 608 | { 609 | "bearerAuthToken": [] 610 | }, 611 | { 612 | "apikey": [] 613 | } 614 | ] 615 | }, 616 | "delete": { 617 | "summary": "Delete post by id", 618 | "description": "", 619 | "operationId": "", 620 | "parameters": [ 621 | { 622 | "name": "id", 623 | "in": "path", 624 | "description": "ID of the post", 625 | "required": true, 626 | "schema": { 627 | "type": "string" 628 | } 629 | } 630 | ], 631 | "responses": { 632 | "200": { 633 | "$ref": "#/components/responses/Post200" 634 | }, 635 | "404": { 636 | "$ref": "#/components/responses/Post404" 637 | }, 638 | "default": { 639 | "$ref": "#/components/responses/DefaultError" 640 | } 641 | }, 642 | "tags": [ 643 | "post" 644 | ], 645 | "security": [ 646 | { 647 | "bearerAuthToken": [] 648 | }, 649 | { 650 | "apikey": [] 651 | } 652 | ] 653 | } 654 | }, 655 | "/hexoeditorserver/post/{id}/publish": { 656 | "post": { 657 | "summary": "Publish post by id", 658 | "description": "", 659 | "operationId": "", 660 | "parameters": [ 661 | { 662 | "name": "id", 663 | "in": "path", 664 | "description": "ID of the post", 665 | "required": true, 666 | "schema": { 667 | "type": "string" 668 | } 669 | } 670 | ], 671 | "responses": { 672 | "200": { 673 | "$ref": "#/components/responses/Post200" 674 | }, 675 | "404": { 676 | "$ref": "#/components/responses/Post404" 677 | }, 678 | "default": { 679 | "$ref": "#/components/responses/DefaultError" 680 | } 681 | }, 682 | "tags": [ 683 | "post" 684 | ], 685 | "security": [ 686 | { 687 | "bearerAuthToken": [] 688 | }, 689 | { 690 | "apikey": [] 691 | } 692 | ] 693 | } 694 | }, 695 | "/hexoeditorserver/post/{id}/unpublish": { 696 | "post": { 697 | "summary": "Unpublish post by id", 698 | "description": "", 699 | "operationId": "", 700 | "parameters": [ 701 | { 702 | "name": "id", 703 | "in": "path", 704 | "description": "ID of the post", 705 | "required": true, 706 | "schema": { 707 | "type": "string" 708 | } 709 | } 710 | ], 711 | "responses": { 712 | "200": { 713 | "$ref": "#/components/responses/Post200" 714 | }, 715 | "404": { 716 | "$ref": "#/components/responses/Post404" 717 | }, 718 | "default": { 719 | "$ref": "#/components/responses/DefaultError" 720 | } 721 | }, 722 | "tags": [ 723 | "post" 724 | ], 725 | "security": [ 726 | { 727 | "bearerAuthToken": [] 728 | }, 729 | { 730 | "apikey": [] 731 | } 732 | ] 733 | } 734 | }, 735 | "/hexoeditorserver/page": { 736 | "summary": "Actions about one specific page", 737 | "post": { 738 | "summary": "Add page by options", 739 | "description": "", 740 | "operationId": "", 741 | "requestBody": { 742 | "description": "Post object needs to add", 743 | "content": { 744 | "application/json": { 745 | "schema": { 746 | "type": "object", 747 | "properties": { 748 | "title": { 749 | "type": "string" 750 | } 751 | } 752 | } 753 | } 754 | } 755 | }, 756 | "responses": { 757 | "200": { 758 | "$ref": "#/components/responses/Post200" 759 | }, 760 | "404": { 761 | "$ref": "#/components/responses/Post404" 762 | }, 763 | "default": { 764 | "$ref": "#/components/responses/DefaultError" 765 | } 766 | }, 767 | "tags": [ 768 | "page" 769 | ], 770 | "security": [ 771 | { 772 | "bearerAuthToken": [] 773 | }, 774 | { 775 | "apikey": [] 776 | } 777 | ] 778 | } 779 | }, 780 | "/hexoeditorserver/page/{id}": { 781 | "summary": "Actions about one specific page", 782 | "get": { 783 | "summary": "Get page by id", 784 | "description": "", 785 | "operationId": "", 786 | "parameters": [ 787 | { 788 | "name": "id", 789 | "in": "path", 790 | "description": "ID of the page", 791 | "required": true, 792 | "schema": { 793 | "type": "string" 794 | } 795 | } 796 | ], 797 | "responses": { 798 | "200": { 799 | "$ref": "#/components/responses/Post200" 800 | }, 801 | "404": { 802 | "$ref": "#/components/responses/Post404" 803 | }, 804 | "default": { 805 | "$ref": "#/components/responses/DefaultError" 806 | } 807 | }, 808 | "tags": [ 809 | "page" 810 | ], 811 | "security": [ 812 | { 813 | "bearerAuthToken": [] 814 | }, 815 | { 816 | "apikey": [] 817 | } 818 | ] 819 | }, 820 | "put": { 821 | "summary": "Update post by id and options", 822 | "description": "", 823 | "operationId": "", 824 | "parameters": [ 825 | { 826 | "name": "id", 827 | "in": "path", 828 | "description": "ID of the post", 829 | "required": true, 830 | "schema": { 831 | "type": "string" 832 | } 833 | } 834 | ], 835 | "requestBody": { 836 | "description": "Post object needs to add", 837 | "content": { 838 | "application/json": { 839 | "schema": { 840 | "type": "object", 841 | "properties": { 842 | "title": { 843 | "type": "string" 844 | }, 845 | "slug": { 846 | "type": "string" 847 | } 848 | } 849 | } 850 | } 851 | } 852 | }, 853 | "responses": { 854 | "200": { 855 | "$ref": "#/components/responses/Post200" 856 | }, 857 | "404": { 858 | "$ref": "#/components/responses/Post404" 859 | }, 860 | "default": { 861 | "$ref": "#/components/responses/DefaultError" 862 | } 863 | }, 864 | "tags": [ 865 | "page" 866 | ], 867 | "security": [ 868 | { 869 | "bearerAuthToken": [] 870 | }, 871 | { 872 | "apikey": [] 873 | } 874 | ] 875 | }, 876 | "delete": { 877 | "summary": "Delete post by id", 878 | "description": "", 879 | "operationId": "", 880 | "parameters": [ 881 | { 882 | "name": "id", 883 | "in": "path", 884 | "description": "ID of the post", 885 | "required": true, 886 | "schema": { 887 | "type": "string" 888 | } 889 | } 890 | ], 891 | "responses": { 892 | "200": { 893 | "$ref": "#/components/responses/Post200" 894 | }, 895 | "404": { 896 | "$ref": "#/components/responses/Post404" 897 | }, 898 | "default": { 899 | "$ref": "#/components/responses/DefaultError" 900 | } 901 | }, 902 | "tags": [ 903 | "page" 904 | ], 905 | "security": [ 906 | { 907 | "bearerAuthToken": [] 908 | }, 909 | { 910 | "apikey": [] 911 | } 912 | ] 913 | } 914 | }, 915 | "/hexoeditorserver/reload": { 916 | "post": { 917 | "summary": "Reload hexo data from files", 918 | "description": "", 919 | "operationId": "", 920 | "responses": { 921 | "200": { 922 | "$ref": "#/components/responses/Default200" 923 | }, 924 | "default": { 925 | "$ref": "#/components/responses/DefaultError" 926 | } 927 | }, 928 | "tags": [ 929 | "hexo action" 930 | ], 931 | "security": [ 932 | { 933 | "bearerAuthToken": [] 934 | }, 935 | { 936 | "apikey": [] 937 | } 938 | ] 939 | } 940 | }, 941 | "/hexoeditorserver/generate": { 942 | "post": { 943 | "summary": "Generate blog", 944 | "description": "Run `hexo g`", 945 | "operationId": "", 946 | "responses": { 947 | "200": { 948 | "$ref": "#/components/responses/Default200" 949 | }, 950 | "default": { 951 | "$ref": "#/components/responses/DefaultError" 952 | } 953 | }, 954 | "tags": [ 955 | "hexo action" 956 | ], 957 | "security": [ 958 | { 959 | "bearerAuthToken": [] 960 | }, 961 | { 962 | "apikey": [] 963 | } 964 | ] 965 | } 966 | }, 967 | "/hexoeditorserver/deploy": { 968 | "post": { 969 | "summary": "Deploy blog", 970 | "description": "Run `hexo g -d`", 971 | "operationId": "", 972 | "responses": { 973 | "200": { 974 | "$ref": "#/components/responses/Default200" 975 | }, 976 | "503": { 977 | "description": "Hexo deploy config not exits, can't deploy", 978 | "content": { 979 | "application/json": { 980 | "schema": { 981 | "$ref": "#/components/schemas/ErrorResponseBody" 982 | } 983 | } 984 | } 985 | }, 986 | "default": { 987 | "$ref": "#/components/responses/DefaultError" 988 | } 989 | }, 990 | "tags": [ 991 | "hexo action" 992 | ], 993 | "security": [ 994 | { 995 | "bearerAuthToken": [] 996 | }, 997 | { 998 | "apikey": [] 999 | } 1000 | ] 1001 | } 1002 | }, 1003 | "/hexoeditorserver/clean": { 1004 | "post": { 1005 | "summary": "Clean hexo database and generated public files", 1006 | "description": "Run `hexo clean`", 1007 | "operationId": "", 1008 | "responses": { 1009 | "200": { 1010 | "$ref": "#/components/responses/Default200" 1011 | }, 1012 | "default": { 1013 | "$ref": "#/components/responses/DefaultError" 1014 | } 1015 | }, 1016 | "tags": [ 1017 | "hexo action" 1018 | ], 1019 | "security": [ 1020 | { 1021 | "bearerAuthToken": [] 1022 | }, 1023 | { 1024 | "apikey": [] 1025 | } 1026 | ] 1027 | } 1028 | }, 1029 | "/hexoeditorserver/sync": { 1030 | "post": { 1031 | "summary": "Download files from git remote origin", 1032 | "description": "Run `git reset --hard && git pull`", 1033 | "operationId": "", 1034 | "responses": { 1035 | "200": { 1036 | "$ref": "#/components/responses/Default200" 1037 | }, 1038 | "503": { 1039 | "description": "DNot a git repo or do not have remote origin, can't pull", 1040 | "content": { 1041 | "application/json": { 1042 | "schema": { 1043 | "$ref": "#/components/schemas/ErrorResponseBody" 1044 | } 1045 | } 1046 | } 1047 | }, 1048 | "default": { 1049 | "$ref": "#/components/responses/DefaultError" 1050 | } 1051 | }, 1052 | "tags": [ 1053 | "git action" 1054 | ], 1055 | "security": [ 1056 | { 1057 | "bearerAuthToken": [] 1058 | }, 1059 | { 1060 | "apikey": [] 1061 | } 1062 | ] 1063 | } 1064 | }, 1065 | "/hexoeditorserver/reset": { 1066 | "post": { 1067 | "summary": "Reset files from git", 1068 | "description": "Run `git reset --hard`", 1069 | "operationId": "", 1070 | "responses": { 1071 | "200": { 1072 | "$ref": "#/components/responses/Default200" 1073 | }, 1074 | "503": { 1075 | "description": "Not a git repo, can't reset", 1076 | "content": { 1077 | "application/json": { 1078 | "schema": { 1079 | "$ref": "#/components/schemas/ErrorResponseBody" 1080 | } 1081 | } 1082 | } 1083 | }, 1084 | "default": { 1085 | "$ref": "#/components/responses/DefaultError" 1086 | } 1087 | }, 1088 | "tags": [ 1089 | "git action" 1090 | ], 1091 | "security": [ 1092 | { 1093 | "bearerAuthToken": [] 1094 | }, 1095 | { 1096 | "apikey": [] 1097 | } 1098 | ] 1099 | } 1100 | }, 1101 | "/hexoeditorserver/save": { 1102 | "post": { 1103 | "summary": "Save files to git remote origin", 1104 | "description": "Run `git add. && git commit && git push`", 1105 | "operationId": "", 1106 | "responses": { 1107 | "200": { 1108 | "$ref": "#/components/responses/Default200" 1109 | }, 1110 | "503": { 1111 | "description": "Not a git repo or do not have remote origin, can't pull", 1112 | "content": { 1113 | "application/json": { 1114 | "schema": { 1115 | "$ref": "#/components/schemas/ErrorResponseBody" 1116 | } 1117 | } 1118 | } 1119 | }, 1120 | "default": { 1121 | "$ref": "#/components/responses/DefaultError" 1122 | } 1123 | }, 1124 | "tags": [ 1125 | "git action" 1126 | ], 1127 | "security": [ 1128 | { 1129 | "bearerAuthToken": [] 1130 | }, 1131 | { 1132 | "apikey": [] 1133 | } 1134 | ] 1135 | } 1136 | }, 1137 | "/info/apidoc": { 1138 | "get": { 1139 | "summary": "获取json格式的api文档", 1140 | "operationId": "", 1141 | "responses": { 1142 | "200": { 1143 | "description": "OK", 1144 | "content": { 1145 | "application/json": { 1146 | "schema": { 1147 | "type": "object" 1148 | } 1149 | } 1150 | } 1151 | }, 1152 | "default": { 1153 | "$ref": "#/components/responses/DefaultError" 1154 | } 1155 | }, 1156 | "tags": [ 1157 | "info" 1158 | ] 1159 | } 1160 | }, 1161 | "/info/version": { 1162 | "get": { 1163 | "summary": "主程序版本", 1164 | "operationId": "", 1165 | "responses": { 1166 | "200": { 1167 | "description": "OK", 1168 | "content": { 1169 | "application/json": { 1170 | "schema": { 1171 | "type": "string" 1172 | } 1173 | } 1174 | } 1175 | }, 1176 | "default": { 1177 | "$ref": "#/components/responses/DefaultError" 1178 | } 1179 | }, 1180 | "tags": [ 1181 | "info" 1182 | ] 1183 | } 1184 | } 1185 | }, 1186 | "components": { 1187 | "securitySchemes": { 1188 | "basicAuth": { 1189 | "type": "http", 1190 | "scheme": "basic" 1191 | }, 1192 | "bearerAuthToken": { 1193 | "type": "http", 1194 | "scheme": "bearer", 1195 | "bearerFormat": "JWT" 1196 | }, 1197 | "bearerAuthAPIKEYToken": { 1198 | "type": "http", 1199 | "scheme": "bearer", 1200 | "bearerFormat": "JWT" 1201 | }, 1202 | "bearerAuthRefresh": { 1203 | "type": "http", 1204 | "scheme": "bearer", 1205 | "bearerFormat": "JWT" 1206 | }, 1207 | "apikey": { 1208 | "type": "http", 1209 | "scheme": "bearer", 1210 | "bearerFormat": "JWT" 1211 | } 1212 | }, 1213 | "schemas": { 1214 | "Post": { 1215 | "type": "object", 1216 | "properties": { 1217 | "_id": { 1218 | "type": "string" 1219 | }, 1220 | "title": { 1221 | "type": "string" 1222 | }, 1223 | "date": { 1224 | "type": "number" 1225 | }, 1226 | "updated": { 1227 | "type": "number" 1228 | }, 1229 | "layout": { 1230 | "type": "string" 1231 | }, 1232 | "source": { 1233 | "type": "string" 1234 | }, 1235 | "slug": { 1236 | "type": "string" 1237 | }, 1238 | "raw": { 1239 | "type": "string" 1240 | }, 1241 | "published": { 1242 | "type": "boolean" 1243 | }, 1244 | "_content": { 1245 | "type": "string" 1246 | }, 1247 | "tags": { 1248 | "type": "array", 1249 | "items": { 1250 | "type": "string" 1251 | } 1252 | }, 1253 | "categories": { 1254 | "type": "array", 1255 | "items": { 1256 | "type": "array", 1257 | "items": { 1258 | "type": "string" 1259 | } 1260 | } 1261 | }, 1262 | "frontmatters": { 1263 | "type": "object" 1264 | } 1265 | } 1266 | }, 1267 | "Tag": { 1268 | "type": "object", 1269 | "properties": { 1270 | "name": { 1271 | "type": "string" 1272 | }, 1273 | "_id": { 1274 | "type": "string" 1275 | }, 1276 | "slug": { 1277 | "type": "string" 1278 | }, 1279 | "path": { 1280 | "type": "string" 1281 | }, 1282 | "permalink": { 1283 | "type": "string" 1284 | }, 1285 | "posts": { 1286 | "type": "array", 1287 | "items": { 1288 | "type": "string" 1289 | } 1290 | }, 1291 | "length": { 1292 | "type": "integer" 1293 | } 1294 | } 1295 | }, 1296 | "Category": { 1297 | "type": "object", 1298 | "properties": { 1299 | "name": { 1300 | "type": "string" 1301 | }, 1302 | "_id": { 1303 | "type": "string" 1304 | }, 1305 | "slug": { 1306 | "type": "string" 1307 | }, 1308 | "path": { 1309 | "type": "string" 1310 | }, 1311 | "permalink": { 1312 | "type": "string" 1313 | }, 1314 | "posts": { 1315 | "type": "array", 1316 | "items": { 1317 | "type": "string" 1318 | } 1319 | }, 1320 | "length": { 1321 | "type": "integer" 1322 | } 1323 | } 1324 | }, 1325 | "ErrorResponseBody": { 1326 | "type": "object", 1327 | "properties": { 1328 | "success": { 1329 | "type": "boolean" 1330 | }, 1331 | "message": { 1332 | "type": "string" 1333 | }, 1334 | "details": { 1335 | "type": "string" 1336 | } 1337 | } 1338 | } 1339 | }, 1340 | "responses": { 1341 | "Default200": { 1342 | "description": "OK", 1343 | "content": { 1344 | "application/json": { 1345 | "schema": { 1346 | "type": "object", 1347 | "properties": { 1348 | "success": { 1349 | "type": "boolean" 1350 | } 1351 | } 1352 | } 1353 | } 1354 | } 1355 | }, 1356 | "DefaultError": { 1357 | "description": "Unexpected Error", 1358 | "content": { 1359 | "application/json": { 1360 | "schema": { 1361 | "$ref": "#/components/schemas/ErrorResponseBody" 1362 | } 1363 | } 1364 | } 1365 | }, 1366 | "Post404": { 1367 | "description": "Post required not fould", 1368 | "content": { 1369 | "application/json": { 1370 | "schema": { 1371 | "$ref": "#/components/schemas/ErrorResponseBody" 1372 | } 1373 | } 1374 | } 1375 | }, 1376 | "Post200": { 1377 | "description": "OK", 1378 | "content": { 1379 | "application/json": { 1380 | "schema": { 1381 | "type": "object", 1382 | "properties": { 1383 | "success": { 1384 | "type": "boolean" 1385 | }, 1386 | "data": { 1387 | "type": "object", 1388 | "properties": { 1389 | "post": { 1390 | "type": "array", 1391 | "items": { 1392 | "$ref": "#/components/schemas/Post" 1393 | } 1394 | } 1395 | } 1396 | } 1397 | } 1398 | } 1399 | } 1400 | } 1401 | } 1402 | } 1403 | } 1404 | } --------------------------------------------------------------------------------