Skip to content

Commit d620b15

Browse files
committed
update: 调整web端日志存储逻辑
1 parent d534033 commit d620b15

File tree

8 files changed

+442
-2376
lines changed

8 files changed

+442
-2376
lines changed

dist/douyudanmaku.js

Lines changed: 305 additions & 2247 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

dist/douyudanmaku.js.map

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

dist/douyudanmaku.min.js

Lines changed: 1 addition & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

example/cli.js

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
//引入类库
2-
const douyudanmaku = require('../src/index')
2+
const danmaku = require('../src/index')
33

44
//设置房间号,初始化
55
const roomId = 102965
6-
const room = new douyudanmaku(roomId)
6+
const room = new danmaku(roomId)
77

88
//系统事件
99
room.on('connect', function () {
@@ -12,18 +12,18 @@ room.on('connect', function () {
1212
room.on('disconnect', function () {
1313
console.log('[disconnect] roomId=%s', this.roomId)
1414
})
15-
room.on('error', function(err) {
15+
room.on('error', function (err) {
1616
console.log('[error] roomId=%s', this.roomId)
1717
})
1818

1919
//消息事件
20-
room.on('chatmsg', function(res) {
20+
room.on('chatmsg', function (res) {
2121
console.log('[chatmsg]', `<lv ${res.level}> [${res.nn}] ${res.txt}`)
2222
})
23-
room.on('loginres', function(res) {
23+
room.on('loginres', function (res) {
2424
console.log('[loginres]', '登录成功')
2525
})
26-
room.on('uenter', function(res) {
26+
room.on('uenter', function (res) {
2727
console.log('[uenter]', `${res.nn}进入房间`)
2828
})
2929

example/web/index.html

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
<meta charset="UTF-8">
66
<meta name="viewport" content="width=device-width, initial-scale=1.0">
77
<title>演示页面</title>
8-
<script src="https://flxxyz.github.io/douyudm/dist/douyudanmaku.min.js"></script>
8+
<script src="https://flxxyz.github.io/douyudm/dist/douyudanmaku.js"></script>
99
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
1010
<style>
1111
.messageList {
@@ -24,8 +24,8 @@
2424
<button @click='enter'>确定</button>
2525
<button @click='close' :disabled='isClosed'>关闭</button>
2626
<button @click='clear' :disabled='isClosed'>清屏</button>
27-
<button @click='loggerExport' :disabled='!debug'>导出日志</button>
28-
<button @click='loggerClear' :disabled='!debug'>清除日志</button>
27+
<button @click='loggerExport' :disabled='!isDebug'>导出日志</button>
28+
<button @click='loggerClear' :disabled='!isDebug'>清除日志</button>
2929
<input type="checkbox" v-model='debug'><label for="checkbox">调试模式</label>
3030
<span>{{ tips }}</span>
3131
</div>
@@ -66,7 +66,7 @@
6666
url: 'https://flxxyz.github.io/douyudm/example/web/host.json',
6767
douyuUrl: '',
6868
giftUrl: '',
69-
debug: false,
69+
debug: true,
7070
}
7171
},
7272
methods: {
@@ -196,11 +196,21 @@
196196
},
197197
loggerExport: function () {
198198
if (this.roomId && this.roomId > 0) {
199-
danmaku.logger.export(this.roomId)
199+
this.room.logger.export(this.roomId)
200200
}
201201
},
202202
loggerClear: function () {
203-
danmaku.logger.clear()
203+
if (this.roomId && this.roomId > 0) {
204+
this.room.logger.clear(this.roomId)
205+
}
206+
}
207+
},
208+
computed: {
209+
isDebug() {
210+
if (!this.isClosed && this.debug) {
211+
return true
212+
}
213+
return false
204214
}
205215
},
206216
created() {

src/client.js

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@ const stt = require('./stt')
44
const util = require('./util')
55
const packet = require('./packet')
66
const messageEvent = require('./messageEvent')
7-
const logger = require('./logger')
87

98
class Client {
109
constructor(roomId, opts) {
1110
this.roomId = roomId
1211
this.ws = null
12+
this.logger = null
1313
this.heartbeatTask = null
1414
this.messageEvent = messageEvent
1515
this.ignore = []
@@ -73,8 +73,10 @@ class Client {
7373
clearInterval(this.heartbeatTask)
7474
}
7575

76-
run(websocket) {
77-
let ws = websocket || require('./websocket')
76+
run(websocket, logger) {
77+
const ws = websocket || require('./websocket')
78+
const Logger = logger || require('./logger')
79+
this.logger = new Logger()
7880
this.initSocket(ws)
7981
}
8082

@@ -121,9 +123,8 @@ class Client {
121123
const r = stt.deserialize(m)
122124

123125
if (this.options.debug) {
124-
const dbname = util.isBrowser() ? this.roomId : this.options.logfile
125-
logger.init(dbname)
126-
logger.echo(r)
126+
this.logger.init(util.isBrowser() ? this.roomId : this.options.logfile)
127+
this.logger.echo(r)
127128
}
128129

129130
if (Object.keys(this.messageEvent).filter(v => {

src/logger.js

Lines changed: 48 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -1,124 +1,77 @@
11
const util = require('./util')
22

3-
const Logger = function () {
4-
this.name = 'unknown'
5-
this.db = null
6-
this.inited = false
7-
}
3+
class Logger {
4+
constructor() {
5+
this.name = 'unknown'
6+
this.inited = false
7+
this.db = null
8+
this.version = 2
9+
}
810

9-
Logger.prototype.init = function (name) {
10-
if (!this.inited) {
11-
this.name = name
11+
init(name) {
12+
if (!this.inited) {
13+
this.name = name
1214

13-
if (util.isBrowser()) {
14-
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB
15-
this._sql = indexedDB.open('danmaku', 2)
16-
this._sql.addEventListener('success', e => {
17-
console.log('连接数据库成功')
18-
this.db = event.target.result
15+
const IndexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB
16+
this.DB = IndexedDB.open('danmaku', this.version)
17+
this.DB.addEventListener('success', e => {
18+
console.log('连接数据库')
19+
this.db = e.target.result
1920
})
2021

21-
this._sql.addEventListener('upgradeneeded', e => {
22-
this.db = event.target.result
23-
this.db.createObjectStore('douyu', {
22+
this.DB.addEventListener('upgradeneeded', e => {
23+
console.log('升级数据库')
24+
this.db = e.target.result
25+
const store = this.db.createObjectStore('douyu', {
2426
keyPath: 'id',
25-
autoIncrement: true
27+
autoIncrement: true,
2628
})
27-
this.db.createIndex('roomId', 'roomId', {
29+
store.createIndex('idx_room_id', 'room_id', {
2830
unique: false
2931
})
3032
})
3133

32-
this._sql.addEventListener('error', e => {
34+
this.DB.addEventListener('error', e => {
3335
console.log('连接数据库出错 Error:', e)
3436
})
35-
} else {
36-
this._fs = require('fs')
37-
}
38-
this.inited = true
39-
}
40-
}
41-
42-
if (!util.isBrowser()) {
43-
Logger.prototype.echo = function (data) {
44-
this._fs.appendFile(
45-
this.name,
46-
JSON.stringify({
47-
t: new Date().getTime(),
48-
frame: data
49-
}) + '\n',
50-
function (err) {
51-
if (err) {
52-
console.error('日志保存出错, Error:', err)
53-
}
54-
})
55-
}
56-
57-
Logger.prototype.all = function () {
58-
return new Promise((resolve, reject) => {
59-
this._fs.readFile(this.name, 'utf8', function (err, str) {
60-
if (err) {
61-
reject(err)
62-
} else {
63-
resolve(str)
64-
}
65-
})
66-
})
67-
}
68-
69-
Logger.prototype.len = function () {
70-
return new Promise(async (resolve, reject) => {
71-
const content = await this.all()
72-
resolve(content.split('\n').filter(v => v !== '').length)
73-
})
74-
}
75-
76-
Logger.prototype.export = function () {
77-
return this._fs.readFileSync(this.name, 'utf8')
78-
}
7937

80-
Logger.prototype.clear = function () {
81-
try {
82-
return this._fs.writeFileSync(this.name, '', 'utf8')
83-
} catch (err) {
84-
return false
38+
this.inited = true
8539
}
8640
}
87-
} else {
88-
Logger.prototype.echo = function (data) {
41+
42+
echo(data) {
8943
if (this.db !== null) {
9044
const tx = this.db.transaction('douyu', 'readwrite')
9145
const store = tx.objectStore('douyu')
9246
store.add({
93-
roomId: this.name,
47+
room_id: this.name,
9448
timestamp: new Date().getTime(),
9549
frame: data
9650
})
9751
}
9852
}
9953

100-
Logger.prototype.all = function () {
54+
all(roomId) {
10155
if (this.db !== null) {
10256
const tx = this.db.transaction('douyu', 'readonly')
10357
const store = tx.objectStore('douyu')
58+
const req = (roomId ? store.index('idx_room_id').getAll(roomId) : store.getAll())
10459
return new Promise(function (resolve, reject) {
105-
const req = store.getAll()
10660
req.addEventListener('success', function (e) {
107-
resolve(req.result)
61+
resolve(e.target.result)
10862
})
10963
req.addEventListener('error', function (e) {
11064
reject(false)
11165
})
11266
})
11367
}
114-
11568
}
11669

117-
Logger.prototype._index = function (roomId) {
70+
count(roomId) {
11871
if (this.db !== null) {
11972
const tx = this.db.transaction('douyu', 'readonly')
12073
const store = tx.objectStore('douyu')
121-
const req = store.index('roomId').get(roomId)
74+
const req = (roomId ? store.index('idx_room_id').count(roomId) : store.count())
12275
return new Promise(function (resolve, reject) {
12376
req.addEventListener('success', function (e) {
12477
resolve(req.result)
@@ -128,29 +81,11 @@ if (!util.isBrowser()) {
12881
})
12982
})
13083
}
131-
13284
}
13385

134-
Logger.prototype.len = function () {
86+
async export (roomId) {
13587
if (this.db !== null) {
136-
const tx = this.db.transaction('douyu', 'readonly')
137-
const store = tx.objectStore('douyu')
138-
return new Promise(function (resolve, reject) {
139-
const req = store.count()
140-
req.addEventListener('success', function (e) {
141-
resolve(req.result)
142-
})
143-
req.addEventListener('error', function (e) {
144-
reject(false)
145-
})
146-
})
147-
}
148-
149-
}
150-
151-
Logger.prototype.export = async function () {
152-
if (this.db !== null) {
153-
const r = await (roomId ? this._index(roomId) : this.all())
88+
const r = await this.all(roomId)
15489
const text = r.reduce((arr, row) => {
15590
const v = {
15691
timestamp: row.timestamp,
@@ -163,16 +98,27 @@ if (!util.isBrowser()) {
16398
util.download(this.name, text.join('\n'))
16499
return text
165100
}
166-
167101
}
168102

169-
Logger.prototype.clear = function () {
103+
clear(roomId) {
170104
if (this.db !== null) {
171105
const tx = this.db.transaction('douyu', 'readwrite')
172106
const store = tx.objectStore('douyu')
173-
store.clear()
107+
if (roomId) {
108+
const index = store.index('idx_room_id')
109+
const req = index.openCursor(IDBKeyRange.only(roomId))
110+
req.addEventListener('success', function () {
111+
const cursor = req.result
112+
if (cursor) {
113+
cursor.delete()
114+
cursor.continue()
115+
}
116+
})
117+
} else {
118+
store.clear()
119+
}
174120
}
175121
}
176122
}
177123

178-
module.exports = new Logger()
124+
module.exports = util.isBrowser() ? Logger : require('./loggerNode')

0 commit comments

Comments
 (0)