Skip to content

Commit

Permalink
精简代码
Browse files Browse the repository at this point in the history
  • Loading branch information
realhuhu committed Aug 10, 2024
1 parent 5f0e1a2 commit babe4f0
Show file tree
Hide file tree
Showing 17 changed files with 300 additions and 359 deletions.
4 changes: 1 addition & 3 deletions node-proxy/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import path from 'path'
import http from 'http'

import Koa from 'koa'
import serve from 'koa-static'

import { port } from '@/config'
import { logger } from '@/common/logger'
Expand All @@ -11,13 +10,12 @@ import otherRouter from '@/router/other'
import webdavRouter from '@/router/webdav'
import staticRouter from '@/router/static'
import webuiRouter from '@/router/webui'
import { exceptionMiddleware, loggerMiddleware } from '@/middleware/common'
import { exceptionMiddleware, loggerMiddleware } from './src/utils/middlewares'

const app = new Koa()

app.use(loggerMiddleware)
app.use(exceptionMiddleware)
app.use(serve(path.dirname(process.argv[1]), { root: 'public' }))
app.use(alisRouter.routes())
app.use(webuiRouter.routes())
app.use(webdavRouter.routes())
Expand Down
2 changes: 1 addition & 1 deletion node-proxy/src/dao/fileDao.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@ export async function getFileInfo(path: string): Promise<alist.FileInfo | Webdav
export async function deleteFileInfo(path: string) {
const pathKey = decodeURIComponent(fileInfoTable + path)
logger.info(`FileDao 删除文件信息: ${pathKey}`)
await nedb.datastore.removeMany({ key: pathKey }, {})
await nedb.removeValue(pathKey)
}
4 changes: 4 additions & 0 deletions node-proxy/src/dao/levelDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ class Nedb {
return null
}
}

async removeValue(key: string): Promise<void> {
await this.datastore.removeMany({ key }, {})
}
}

const nedb = new Nedb()
Expand Down
212 changes: 0 additions & 212 deletions node-proxy/src/middleware/common.ts

This file was deleted.

2 changes: 1 addition & 1 deletion node-proxy/src/router/alist/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { alistServer } from '@/config'
import { copyOrMoveFileMiddleware } from '@/router/alist/utils'
import { cacheFileInfo, getFileInfo } from '@/dao/fileDao'
import { httpClient, httpFlowClient } from '@/utils/httpClient'
import { bodyParserMiddleware, emptyMiddleware } from '@/middleware/common'
import { bodyParserMiddleware, emptyMiddleware } from '@/utils/middlewares'
import { convertRealName, convertShowName, encodeName, pathFindPasswd } from '@/utils/cryptoUtil'
import type { alist } from '@/@types/alist'

Expand Down
27 changes: 10 additions & 17 deletions node-proxy/src/router/other/index.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,20 @@
import Router from 'koa-router'
import { flat, preProxy } from '@/utils/common'
import { alistServer, version } from '@/config'
import levelDB from '@/dao/levelDB'

import nedb from '@/dao/levelDB'
import FlowEnc from '@/utils/flowEnc'
import { logger } from '@/common/logger'
import { pathExec } from '@/utils/cryptoUtil'
import { flat, preProxy } from '@/utils/common'
import { alistServer, version } from '@/config'
import { httpClient, httpFlowClient } from '@/utils/httpClient'
import { logger } from '@/common/logger'
import { bodyParserMiddleware, compose, proxyHandler } from '@/middleware/common'
import { downloadMiddleware } from '@/router/other/utils'
import { bodyParserMiddleware, compose } from '@/utils/middlewares'
import { downloadMiddleware } from '@/router/other/middlewares'

const otherRouter = new Router()

otherRouter.get<ProxiedState<AlistServer>, EmptyObj>(
/^\/d\/*/,
compose(bodyParserMiddleware, preProxy(alistServer, false), downloadMiddleware),
proxyHandler
)
otherRouter.get<ProxiedState<AlistServer>, EmptyObj>(/^\/d\/*/, compose(bodyParserMiddleware, preProxy(alistServer, false)), downloadMiddleware)

otherRouter.get<ProxiedState<AlistServer>, EmptyObj>(
/^\/p\/*/,
compose(bodyParserMiddleware, preProxy(alistServer, false), downloadMiddleware),
proxyHandler
)
otherRouter.get<ProxiedState<AlistServer>, EmptyObj>(/^\/p\/*/, compose(bodyParserMiddleware, preProxy(alistServer, false)), downloadMiddleware)

// 修复alist 图标不显示的问题
otherRouter.all(/^\/images\/*/, compose(bodyParserMiddleware, preProxy(alistServer, false)), async (ctx) => {
Expand All @@ -41,7 +34,7 @@ otherRouter.all('/redirect/:key', async (ctx) => {
const request = ctx.req
const response = ctx.res
// 这里还是要encodeURIComponent ,因为http服务器会自动对url进行decodeURIComponent
const data = await levelDB.getValue(ctx.params.key)
const data = await nedb.getValue(ctx.params.key)

if (data === null) {
ctx.body = 'no found'
Expand Down
85 changes: 85 additions & 0 deletions node-proxy/src/router/other/middlewares.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import path from 'path'
import type { Transform } from 'stream'

import type { Middleware, ParameterizedContext } from 'koa'

import FlowEnc from '@/utils/flowEnc'
import { logger } from '@/common/logger'
import { getFileInfo } from '@/dao/fileDao'
import { httpFlowClient } from '@/utils/httpClient'
import { convertRealName, encodeName, pathFindPasswd } from '@/utils/cryptoUtil'

export const downloadMiddleware: Middleware = async <T extends AlistServer>(ctx: ParameterizedContext<ProxiedState<T>>) => {
const state = ctx.state
let urlAddr = state.urlAddr
let urlPath = new URL(urlAddr).pathname
// 如果是alist的话,那么必然有这个文件的size缓存(进过list就会被缓存起来)
let fileSize = 0

// 这里需要处理掉/p 路径
if (urlPath.indexOf('/d/') === 0) {
urlPath = urlPath.replace('/d/', '/')
}

// 这个不需要处理
if (urlPath.indexOf('/p/') === 0) {
urlPath = urlPath.replace('/p/', '/')
}

// 要定位请求文件的位置 bytes=98304-
const range = ctx.req.headers.range
const start = range ? Number(range.replace('bytes=', '').split('-')[0]) : 0
const { passwdInfo } = pathFindPasswd(state.serverConfig.passwdList, urlPath)

logger.info('匹配密码信息', passwdInfo === null ? '无密码' : passwdInfo.password)

let decryptTransform: Transform

// 如果是下载文件,那么就进行判断是否解密
if (passwdInfo && passwdInfo.encName) {
delete ctx.req.headers['content-length']
// check fileName is not enc or it is dir
const fileName = path.basename(urlPath)
const realName = convertRealName(passwdInfo.password, passwdInfo.encType, fileName)
logger.info(`转换为原始文件名: ${fileName} -> ${realName}`)

urlPath = path.dirname(urlPath) + '/' + realName
urlAddr = path.dirname(urlAddr) + '/' + realName
logger.info('准备获取文件', urlAddr)

// 尝试获取文件信息,如果未找到相应的文件信息,则对文件名进行加密处理后重新尝试获取文件信息
let fileInfo = await getFileInfo(urlPath)

if (fileInfo === null) {
const rawFileName = decodeURIComponent(path.basename(urlPath))
const ext = path.extname(rawFileName)
const encodedRawFileName = encodeURIComponent(rawFileName)
const encFileName = encodeName(passwdInfo.password, passwdInfo.encType, rawFileName)
const newFileName = encFileName + ext
const newFilePath = urlPath.replace(encodedRawFileName, newFileName)

urlAddr = urlAddr.replace(encodedRawFileName, newFileName)
fileInfo = await getFileInfo(newFilePath)
}

logger.info('获取文件信息:', urlPath, JSON.stringify(fileInfo))

if (fileInfo) fileSize = fileInfo.size

if (fileSize !== 0) {
const flowEnc = new FlowEnc(passwdInfo.password, passwdInfo.encType, fileSize)
if (start) await flowEnc.setPosition(start)
decryptTransform = flowEnc.decryptTransform()
}
}

await httpFlowClient({
urlAddr,
passwdInfo,
fileSize,
request: ctx.req,
response: ctx.res,
encryptTransform: undefined,
decryptTransform,
})
}
Loading

0 comments on commit babe4f0

Please sign in to comment.