Skip to content

Commit

Permalink
✨ Feature(custom): optimize webServer
Browse files Browse the repository at this point in the history
  • Loading branch information
Kuingsmile committed Apr 5, 2024
1 parent aa9e535 commit e6e9472
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 49 deletions.
110 changes: 61 additions & 49 deletions src/main/server/webServer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,92 +3,104 @@ import fs from 'fs-extra'
import path from 'path'
import picgo from '@core/picgo'
import logger from '../../apis/core/picgo/logger'
import { encodeFilePath } from '~/universal/utils/common'

const defaultPath = process.platform === 'win32' ? 'C:/Users/' : '/'
const defaultPath = process.platform === 'win32' ? 'C:\\Users' : '/'

function generateDirectoryListingHtml (files: any[], requestPath: any) {
let html = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body><h1>Directory Listing</h1><ul>'
files.forEach((file: string) => {
html += `<li><a href="${path.join(requestPath, file)}">${file}</a></li>`
const filePath = path.join(requestPath, file)
html += `<li><a href="${encodeFilePath(filePath)}">${file}</a></li>`
})
html += '</ul></body></html>'
return html
}

function serveDirectory (res: http.ServerResponse, filePath: fs.PathLike, requestPath: any) {
fs.readdir(filePath, (err, files) => {
if (err) {
res.writeHead(500)
res.end('Error listing directory contents')
} else {
res.writeHead(200, { 'Content-Type': 'text/html' })
res.end(generateDirectoryListingHtml(files, requestPath))
}
})
}

function serveFile (res:http.ServerResponse, filePath: fs.PathLike) {
const readStream = fs.createReadStream(filePath)
readStream.pipe(res)
readStream.on('error', () => {
res.writeHead(500)
res.end('Error reading file')
})
}

class WebServer {
private server: http.Server
private config: IStringKeyMap
private server!: http.Server
private config!: IStringKeyMap

constructor () {
this.config = this.getConfigWithDefaults()
this.server = this.getServer()
this.loadConfig()
this.initServer()
}

getConfigWithDefaults (): IStringKeyMap {
const enableWebServer = picgo.getConfig<boolean>('settings.enableWebServer') || false
const webServerHost = picgo.getConfig<string>('settings.webServerHost') || '0.0.0.0'
const webServerPort = picgo.getConfig<number>('settings.webServerPort') || 37777
const webServerPath = picgo.getConfig<string>('settings.webServerPath') || defaultPath
return { enableWebServer, webServerHost, webServerPort, webServerPath }
loadConfig (): void {
this.config = {
enableWebServer: picgo.getConfig<boolean>('settings.enableWebServer') || false,
webServerHost: picgo.getConfig<string>('settings.webServerHost') || '0.0.0.0',
webServerPort: picgo.getConfig<number>('settings.webServerPort') || 37777,
webServerPath: picgo.getConfig<string>('settings.webServerPath') || defaultPath
}
}

getServer (): http.Server {
return http.createServer((req, res) => {
initServer (): void {
this.server = http.createServer((req, res) => {
const requestPath = req.url?.split('?')[0]
const filePath = path.join(this.config.webServerPath, decodeURIComponent(requestPath as string))

fs.stat(filePath, (err, stats) => {
if (err) {
res.writeHead(404)
res.end('404 Not Found')
return
}
const filePath = path.join(this.config.webServerPath, decodeURIComponent(requestPath || ''))

try {
const stats = fs.statSync(filePath)
if (stats.isDirectory()) {
fs.readdir(filePath, (err, files) => {
if (err) {
res.writeHead(500)
res.end('Error listing directory contents')
} else {
res.writeHead(200, { 'Content-Type': 'text/html' })
res.end(generateDirectoryListingHtml(files, requestPath))
}
})
serveDirectory(res, filePath, requestPath)
} else {
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404)
res.end('404 Not Found')
} else {
res.end(data)
}
})
serveFile(res, filePath)
}
})
} catch (err) {
res.writeHead(404)
res.end('404 Not Found')
}
})
}

start () {
if (this.config.enableWebServer) {
this.server.listen(this.config.webServerPort, this.config.webServerHost, () => {
logger.info(`Web server is running, http://${this.config.webServerHost}:${this.config.webServerPort}, root path is ${this.config.webServerPath}`)
}).on('error', (err) => {
logger.error(err)
})
this.server
.listen(
this.config.webServerPort === 36699 ? 37777 : this.config.webServerPort,
this.config.webServerHost, () => {
logger.info(`Web server is running at http://${this.config.webServerHost}:${this.config.webServerPort}, root path is ${this.config.webServerPath}`)
})
.on('error', (err) => {
logger.error(err)
})
} else {
logger.info('Web server is not enabled')
}
}

stop () {
this.server.close()
logger.info('Web server is stopped')
this.server.close(() => {
logger.info('Web server is stopped')
})
}

restart () {
this.stop()
this.config = this.getConfigWithDefaults()
this.server = this.getServer()
this.loadConfig()
this.initServer()
this.start()
}
}
Expand Down
6 changes: 6 additions & 0 deletions src/universal/utils/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,9 @@ export function safeSliceF (str:string, total: number) {
}
return result
}

export function encodeFilePath (filePath: string) {
filePath = filePath.replace(/\\/g, '/')
const parts = filePath.split('/')
return parts.map(encodeURIComponent).join('/')
}

0 comments on commit e6e9472

Please sign in to comment.