Skip to content

Commit

Permalink
修复一个大bug,支持Range分段获取数据
Browse files Browse the repository at this point in the history
  • Loading branch information
williamnie committed Apr 14, 2021
1 parent 2c1638e commit b2ae1f4
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 43 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "umi-electron",
"version": "1.0.0",
"name": "NetSend",
"version": "1.1.0",
"description": "an example based on umijs + electron",
"main": "./dist/main/main.js",
"build": {
Expand Down Expand Up @@ -42,6 +42,7 @@
"pack": "npm run build:renderer && npm run build-main-prod && electron-builder --dir",
"exe": "npm run build:renderer && npm run build-main-prod && electron-builder --win",
"dist": "npm run build:renderer && npm run build-main-prod && electron-builder",
"release": "npm run build:renderer && npm run build-main-prod && electron-builder && electron-builder --win",
"prettier": "prettier --list-different \"./**/*.{ts,tsx,js,jsx,less}\""
},
"keywords": [
Expand Down
31 changes: 3 additions & 28 deletions src/main/db.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
* @Author: xiaobei
* @Date: 2021-02-02 15:51:58
* @LastEditTime: 2021-02-19 23:20:42
* @LastEditTime: 2021-04-14 15:01:29
* @LastEditors: xiaobei
* @desc: 我为啥要写这么复杂🤣🤣🤣
*/
Expand All @@ -14,7 +14,6 @@ export default class DB {
this.dbPath = `${__dirname}/db.json`;
this.state = []; //数据集合
this.idIndex = null // 以id为key的索引
this.nameIndex = null // 以name为key的索引
/**
* 虽然数据量很小,但还是选择建索引了,哈哈哈!
*/
Expand All @@ -36,22 +35,17 @@ export default class DB {
createIndex() {
const length = this.state.length
this.idIndex = this.idIndex || {}
this.nameIndex = this.nameIndex || {}

for (let index = 0; index < length; index++) {
this.idIndex[this.state[index].id] = this.state
this.nameIndex[this.state[index].name] = this.state
this.idIndex[this.state[index].id] = this.state[index]
}
}

updateIndex(obj) {
this.idIndex[obj.id] = obj
this.nameIndex[obj.name] = obj
}

deleteIndex(obj) {
this.idIndex[obj.id] = undefined
this.nameIndex[obj.name] = undefined
}

async saveDataToDisk() {
Expand All @@ -77,42 +71,23 @@ export default class DB {
} else {
const id = genId()
const ele = { ...data, id }
console.log('tthis.state', this.state);
this.state.push(ele)
this.updateIndex(ele)
res = ele
}
setTimeout(() => {
this.saveDataToDisk()
}, 1000)
console.log('res', res);
return res
}

/**
*
* @param {} name
* 根据name查找,有索引的时候,去索引里查询
* 如果查不到,默认在从所有数据里查一遍
* 以防索引有遗漏,但几率很小
* 如果此时没有索引,则直接从所有数据里查询
*/
async findByName(name) {
let data
if (this.nameIndex) {
data = this.nameIndex[name] || this.state.find((item) => { return item.name === name })
} else {
data = this.state.find((item) => { return item.name === name })
}
return data
}

async findById(id) {
let data
if (this.idIndex) {
data = this.idIndex[id] || this.state.find((item) => { return item.id === id })
} else {
Fdata = this.state.find((item) => { return item.id === id })
data = this.state.find((item) => { return item.id === id })
}
return data
}
Expand Down
25 changes: 20 additions & 5 deletions src/main/koa.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
* @Author: xiaobei
* @Date: 2021-01-29 15:43:57
* @LastEditTime: 2021-02-05 17:52:36
* @LastEditTime: 2021-04-14 15:00:41
* @LastEditors: xiaobei
*/
import Koa from 'koa';
Expand All @@ -17,23 +17,37 @@ const app = new Koa();
const router = new Router();
const db = new DB()

const defaultPort = 23456
const defaultPort = 23456;
const parseRange = (range, size) => {
if (range) {
const [start, end] = range.replace('bytes=', '').split('-')
return { start: +start, end: +end }
} else {
return { start: 0, end: size }
}
}


let serverStatus

router.get('/file/:id/:name', async (ctx, next) => {
const { id } = ctx.params;
// 拿到文件名,检查文件是否存在,存在则返回文件流,不存在404
const file = await db.findById(id)
const range = ctx.get('Range')
if (file) {
try {
// 如果文件不存在,则stat会报错,直接404
const stats = fs.statSync(file.path);
const filename = path.basename(file.path)
const { start, end } = parseRange(range, stats.size)
ctx.set('Content-Type', 'application/octet-stream');
ctx.set('Content-Disposition', 'attachment; filename=' + filename);
ctx.set('Content-Length', stats.size);
ctx.body = fs.createReadStream(file.path);
ctx.set('Content-Disposition', 'attachment; filename=' + encodeURIComponent(filename));
ctx.set('Content-Length', end === stats.size ? stats.size : end + 1);
ctx.body = fs.createReadStream(file.path, {
start,
end
});
} catch (error) {
ctx.status = 404
ctx.body = '文件不存在'
Expand All @@ -59,6 +73,7 @@ router.post('/api/createFile', async (ctx, next) => {
ctx.body = res
})


app
.use(cors())
.use(bodyParser())
Expand Down
2 changes: 1 addition & 1 deletion src/renderer/components/FIleItem/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const FileItem = (props) => {
const ips = getIPAddress()

const copyFile = (url,item) => {
clipboard.writeText(`${url}/${item.id}/${item.name}`)
clipboard.writeText(`${url}/${item.id}/${encodeURIComponent(data.name)}`)
}

const deleteFileById = (id) => {
Expand Down
18 changes: 11 additions & 7 deletions src/renderer/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,17 @@ const Index = (props) => {
})
if (data && data.id) {
const urls = baseFileUrl();
notification.success({
message: format('successMsg'),
description: urls.length > 1 ? format('manyIps') : `${urls[0]}/${data.id}/${data.name}`,
onClick: () => {
urls.length === 1 && clipboard.writeText(`${urls[0]}/${data.id}/${data.name}`)
},
})
// 如果list是展开状态,就不在弹出message
const { visible } = fileListRef.current
if (!visible) {
notification.success({
message: format('successMsg'),
description: urls.length > 1 ? format('manyIps') : `${urls[0]}/${data.id}/${data.name}`,
onClick: () => {
urls.length === 1 && clipboard.writeText(`${urls[0]}/${data.id}/${encodeURIComponent(data.name)}`)
},
})
}
}
} else {
notification.error({
Expand Down

0 comments on commit b2ae1f4

Please sign in to comment.