Skip to content

Commit

Permalink
feat:support theme
Browse files Browse the repository at this point in the history
  • Loading branch information
reruin committed Jan 24, 2021
1 parent 1f4bf8f commit 24f0ce3
Show file tree
Hide file tree
Showing 42 changed files with 247 additions and 101 deletions.
6 changes: 6 additions & 0 deletions app/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,12 @@ const getSkin = (key) => {
return db.get('skin') || 'default'
}

const setSkin = (name) => {
if( name != getSkin('skin') ){
save({skin:key})
}
}

const getPluginOption = (key) => {
let p = db.get('plugin_option') || []
let hit = p.find(i => i.key == key )
Expand Down
3 changes: 3 additions & 0 deletions app/controllers/sharelist.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,9 @@ const output = async (ctx , data)=>{
await service.stream(ctx , url , 'url' , protocol , data)
}
}else{
if( data.headers ){
ctx.set(data.headers)
}
ctx.redirect( url )
}
}
Expand Down
27 changes: 11 additions & 16 deletions app/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,19 @@ const json = require('koa-json')
const onerror = require('koa-onerror')
const koaBody = require('koa-body')
const logger = require('koa-logger')
const koaStatic = require('koa-static')
const locales = require('koa-locales')
const i18n = require('koa-i18n')
const path = require('path')
const session = require('koa-session-minimal')
const os = require('os')
const less = require('./middleware/koa-less')
const addr = require('./middleware/koa-addr')
const paths = require('./middleware/koa-paths')
const render = require('./middleware/koa-render')
const staticCache = require('koa-static-cache')
const Router = require('koa-router')

const routers = require('./routers/index')
const routers = require('./router')
const cors = require('@koa/cors')
const config = require('./config')

const themeManger = require('./services/theme')
const { loader , bonjour } = require('./services/plugin')
const fs = require('fs')

Expand Down Expand Up @@ -61,38 +57,37 @@ app.use(addr)

app.use(paths)

app.use(render)

// 配置控制台日志中间件
app.use(logger())

//less 中间件
app.use(less(__dirname + '/public' , { dest: os.tmpdir() + '/sharelist'}))
themeManger(app , { dir : path.resolve(__dirname,'../theme') })


// 配置静态资源加载中间件
/*// 配置静态资源加载中间件
app.use(staticCache(__dirname + '/public' , {maxage:30 * 24 * 60 * 60 }))
app.use(staticCache(os.tmpdir()+'/sharelist' , {maxage:30 * 24 * 60 * 60 , dynamic:true}))
staticCache(os.tmpdir()+'/sharelist' , {maxage:30 * 24 * 60 * 60 , dynamic:true})*/

app.use(async (ctx , next) => {
ctx.state.__ = ctx.__.bind(ctx)
ctx.state._config_ = config.getConfig.bind(ctx)
await next()
})



// 配置服务端模板渲染引擎中间件
app.use(views(__dirname + '/views', {
/*app.use(views(__dirname + '/views', {
extension: 'pug'
}))
}))*/

// 初始化路由中间件
app.use(routers.routes()).use(routers.allowedMethods())

app.use(async (ctx) => {
console.log(ctx.error)
switch (ctx.status) {
case 404:
await ctx.render('404');
await ctx.renderSkin('404');
break;
}
})
Expand Down
33 changes: 33 additions & 0 deletions app/router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const router = require('koa-router')()
const sharelist = require('./controllers/sharelist')
const manage = require('./controllers/manage')
const install = require('./controllers/install')
const webdav = require('./controllers/webdav')
const installMid = require('./middleware/koa-install')

router.get('/manage', installMid, manage.home)
.post('/manage', installMid, manage.home)
.post('/manage/api' ,installMid, manage.api)
.post('/manage/api/:token', installMid, manage.api_token)
.get('/manage/api/:token', installMid, manage.api_token)
.get('/manage/shell', installMid, manage.shell)
.post('/manage/shell', installMid, manage.shell_exec)
.get('/admin',(ctx) => {
ctx.redirect('/manage')
})



.get('/install', install.home)
.post('/install', install.save)


.all('/:path(.*)',async (ctx, next) => {
if (ctx.webdav) {
await webdav(ctx, next)
} else {
await sharelist.index(ctx, next)
}
})

module.exports = router
11 changes: 0 additions & 11 deletions app/routers/api.js

This file was deleted.

27 changes: 0 additions & 27 deletions app/routers/index.js

This file was deleted.

9 changes: 0 additions & 9 deletions app/routers/install.js

This file was deleted.

20 changes: 0 additions & 20 deletions app/routers/manage.js

This file was deleted.

17 changes: 0 additions & 17 deletions app/routers/page.js

This file was deleted.

102 changes: 102 additions & 0 deletions app/services/theme.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
const less = require('less-middleware');
const path = require('path')
const os = require('os')
const fs = require('fs')
const staticCache = require('koa-static-cache')
const pug = require('pug')
const mime = require('mime')
const crypto = require('crypto')

const { getSkin , getConfig } = require('../config')

const options = {
theme:'default',
cacheStore:{},
staticMap:{}
}


const render = (ctx, filename , locals = {}) => {
const state = Object.assign(locals, ctx.state || {})
pug.renderFile(filename , state, (err, html) => {
ctx.type = 'text/html'
ctx.body = html
})
}

const renderMiddleware = ({ dir }) => (ctx, next) => {
if(ctx.renderSkin) return next()
ctx.response.renderSkin = ctx.renderSkin = (relPath , options) => {
let data = { ...options , __path__:dir,g_config:{
custom_style:getConfig('custom_style'),
custom_script:getConfig('custom_script'),
}}

return render(ctx, path.resolve(dir, getSkin(), 'view',relPath+'.pug') , data)
}
return next()
}


const lessMiddleware = (url , options) => (ctx, next) => new Promise(function (resolve, reject) {
less(url , options)(ctx.req, ctx.res , (error) =>{
if(error){
reject(error);
}else{
resolve();
}
})
}).then(()=>{
return next();
})

module.exports = (app , { dir , defaultTheme = 'default' } = {}) => {
options.theme = defaultTheme
let dest = os.tmpdir() + '/sharelist'
app.use(lessMiddleware(dir , {
dest,
preprocess:{
path:(src, req) => {
let relpath = path.relative(dir,src)
let p = path.resolve(dir,options.theme,relpath)
options.staticMap[ '\\' + relpath.replace('.less','.css') ] = path.resolve(dest,relpath.replace('.less','.css'))
return p
}
}
}))

app.use(renderMiddleware({ dir }))

let maxage = 30 * 24 * 60 * 60
app.use(staticCache(dir, {maxage, preload:false }, {
get(key){
//let pathname = path.normalize(path.join(options.prefix, name))
if (!options.cacheStore[key]) options.cacheStore[key] = {}

let obj = options.cacheStore[key]

let filename = obj.path = options.staticMap[key] || path.join(dir, options.theme,key)
let stats , buffer
try {
stats = fs.statSync(filename)
buffer = fs.readFileSync(filename)

} catch (err) {
return null
}

obj.cacheControl = undefined
obj.maxAge = obj.maxAge ? obj.maxAge : maxage || 0
obj.type = obj.mime = mime.getType(path.extname(filename)) || 'application/octet-stream'
obj.mtime = stats.mtime
obj.length = stats.size
obj.md5 = crypto.createHash('md5').update(buffer).digest('base64')

return obj
},
set(key, value){
cacheStore[key] = value
}
}))

}
Loading

0 comments on commit 24f0ce3

Please sign in to comment.