Skip to content

Commit

Permalink
update: 调整web端日志存储逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
flxxyz committed Jul 16, 2020
1 parent d534033 commit d620b15
Show file tree
Hide file tree
Showing 8 changed files with 442 additions and 2,376 deletions.
2,552 changes: 305 additions & 2,247 deletions dist/douyudanmaku.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/douyudanmaku.js.map

Large diffs are not rendered by default.

9 changes: 1 addition & 8 deletions dist/douyudanmaku.min.js

Large diffs are not rendered by default.

12 changes: 6 additions & 6 deletions example/cli.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
//引入类库
const douyudanmaku = require('../src/index')
const danmaku = require('../src/index')

//设置房间号,初始化
const roomId = 102965
const room = new douyudanmaku(roomId)
const room = new danmaku(roomId)

//系统事件
room.on('connect', function () {
Expand All @@ -12,18 +12,18 @@ room.on('connect', function () {
room.on('disconnect', function () {
console.log('[disconnect] roomId=%s', this.roomId)
})
room.on('error', function(err) {
room.on('error', function (err) {
console.log('[error] roomId=%s', this.roomId)
})

//消息事件
room.on('chatmsg', function(res) {
room.on('chatmsg', function (res) {
console.log('[chatmsg]', `<lv ${res.level}> [${res.nn}] ${res.txt}`)
})
room.on('loginres', function(res) {
room.on('loginres', function (res) {
console.log('[loginres]', '登录成功')
})
room.on('uenter', function(res) {
room.on('uenter', function (res) {
console.log('[uenter]', `${res.nn}进入房间`)
})

Expand Down
22 changes: 16 additions & 6 deletions example/web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>演示页面</title>
<script src="https://flxxyz.github.io/douyudm/dist/douyudanmaku.min.js"></script>
<script src="https://flxxyz.github.io/douyudm/dist/douyudanmaku.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
.messageList {
Expand All @@ -24,8 +24,8 @@
<button @click='enter'>确定</button>
<button @click='close' :disabled='isClosed'>关闭</button>
<button @click='clear' :disabled='isClosed'>清屏</button>
<button @click='loggerExport' :disabled='!debug'>导出日志</button>
<button @click='loggerClear' :disabled='!debug'>清除日志</button>
<button @click='loggerExport' :disabled='!isDebug'>导出日志</button>
<button @click='loggerClear' :disabled='!isDebug'>清除日志</button>
<input type="checkbox" v-model='debug'><label for="checkbox">调试模式</label>
<span>{{ tips }}</span>
</div>
Expand Down Expand Up @@ -66,7 +66,7 @@
url: 'https://flxxyz.github.io/douyudm/example/web/host.json',
douyuUrl: '',
giftUrl: '',
debug: false,
debug: true,
}
},
methods: {
Expand Down Expand Up @@ -196,11 +196,21 @@
},
loggerExport: function () {
if (this.roomId && this.roomId > 0) {
danmaku.logger.export(this.roomId)
this.room.logger.export(this.roomId)
}
},
loggerClear: function () {
danmaku.logger.clear()
if (this.roomId && this.roomId > 0) {
this.room.logger.clear(this.roomId)
}
}
},
computed: {
isDebug() {
if (!this.isClosed && this.debug) {
return true
}
return false
}
},
created() {
Expand Down
13 changes: 7 additions & 6 deletions src/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ const stt = require('./stt')
const util = require('./util')
const packet = require('./packet')
const messageEvent = require('./messageEvent')
const logger = require('./logger')

class Client {
constructor(roomId, opts) {
this.roomId = roomId
this.ws = null
this.logger = null
this.heartbeatTask = null
this.messageEvent = messageEvent
this.ignore = []
Expand Down Expand Up @@ -73,8 +73,10 @@ class Client {
clearInterval(this.heartbeatTask)
}

run(websocket) {
let ws = websocket || require('./websocket')
run(websocket, logger) {
const ws = websocket || require('./websocket')
const Logger = logger || require('./logger')
this.logger = new Logger()
this.initSocket(ws)
}

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

if (this.options.debug) {
const dbname = util.isBrowser() ? this.roomId : this.options.logfile
logger.init(dbname)
logger.echo(r)
this.logger.init(util.isBrowser() ? this.roomId : this.options.logfile)
this.logger.echo(r)
}

if (Object.keys(this.messageEvent).filter(v => {
Expand Down
150 changes: 48 additions & 102 deletions src/logger.js
Original file line number Diff line number Diff line change
@@ -1,124 +1,77 @@
const util = require('./util')

const Logger = function () {
this.name = 'unknown'
this.db = null
this.inited = false
}
class Logger {
constructor() {
this.name = 'unknown'
this.inited = false
this.db = null
this.version = 2
}

Logger.prototype.init = function (name) {
if (!this.inited) {
this.name = name
init(name) {
if (!this.inited) {
this.name = name

if (util.isBrowser()) {
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB
this._sql = indexedDB.open('danmaku', 2)
this._sql.addEventListener('success', e => {
console.log('连接数据库成功')
this.db = event.target.result
const IndexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB
this.DB = IndexedDB.open('danmaku', this.version)
this.DB.addEventListener('success', e => {
console.log('连接数据库')
this.db = e.target.result
})

this._sql.addEventListener('upgradeneeded', e => {
this.db = event.target.result
this.db.createObjectStore('douyu', {
this.DB.addEventListener('upgradeneeded', e => {
console.log('升级数据库')
this.db = e.target.result
const store = this.db.createObjectStore('douyu', {
keyPath: 'id',
autoIncrement: true
autoIncrement: true,
})
this.db.createIndex('roomId', 'roomId', {
store.createIndex('idx_room_id', 'room_id', {
unique: false
})
})

this._sql.addEventListener('error', e => {
this.DB.addEventListener('error', e => {
console.log('连接数据库出错 Error:', e)
})
} else {
this._fs = require('fs')
}
this.inited = true
}
}

if (!util.isBrowser()) {
Logger.prototype.echo = function (data) {
this._fs.appendFile(
this.name,
JSON.stringify({
t: new Date().getTime(),
frame: data
}) + '\n',
function (err) {
if (err) {
console.error('日志保存出错, Error:', err)
}
})
}

Logger.prototype.all = function () {
return new Promise((resolve, reject) => {
this._fs.readFile(this.name, 'utf8', function (err, str) {
if (err) {
reject(err)
} else {
resolve(str)
}
})
})
}

Logger.prototype.len = function () {
return new Promise(async (resolve, reject) => {
const content = await this.all()
resolve(content.split('\n').filter(v => v !== '').length)
})
}

Logger.prototype.export = function () {
return this._fs.readFileSync(this.name, 'utf8')
}

Logger.prototype.clear = function () {
try {
return this._fs.writeFileSync(this.name, '', 'utf8')
} catch (err) {
return false
this.inited = true
}
}
} else {
Logger.prototype.echo = function (data) {

echo(data) {
if (this.db !== null) {
const tx = this.db.transaction('douyu', 'readwrite')
const store = tx.objectStore('douyu')
store.add({
roomId: this.name,
room_id: this.name,
timestamp: new Date().getTime(),
frame: data
})
}
}

Logger.prototype.all = function () {
all(roomId) {
if (this.db !== null) {
const tx = this.db.transaction('douyu', 'readonly')
const store = tx.objectStore('douyu')
const req = (roomId ? store.index('idx_room_id').getAll(roomId) : store.getAll())
return new Promise(function (resolve, reject) {
const req = store.getAll()
req.addEventListener('success', function (e) {
resolve(req.result)
resolve(e.target.result)
})
req.addEventListener('error', function (e) {
reject(false)
})
})
}

}

Logger.prototype._index = function (roomId) {
count(roomId) {
if (this.db !== null) {
const tx = this.db.transaction('douyu', 'readonly')
const store = tx.objectStore('douyu')
const req = store.index('roomId').get(roomId)
const req = (roomId ? store.index('idx_room_id').count(roomId) : store.count())
return new Promise(function (resolve, reject) {
req.addEventListener('success', function (e) {
resolve(req.result)
Expand All @@ -128,29 +81,11 @@ if (!util.isBrowser()) {
})
})
}

}

Logger.prototype.len = function () {
async export (roomId) {
if (this.db !== null) {
const tx = this.db.transaction('douyu', 'readonly')
const store = tx.objectStore('douyu')
return new Promise(function (resolve, reject) {
const req = store.count()
req.addEventListener('success', function (e) {
resolve(req.result)
})
req.addEventListener('error', function (e) {
reject(false)
})
})
}

}

Logger.prototype.export = async function () {
if (this.db !== null) {
const r = await (roomId ? this._index(roomId) : this.all())
const r = await this.all(roomId)
const text = r.reduce((arr, row) => {
const v = {
timestamp: row.timestamp,
Expand All @@ -163,16 +98,27 @@ if (!util.isBrowser()) {
util.download(this.name, text.join('\n'))
return text
}

}

Logger.prototype.clear = function () {
clear(roomId) {
if (this.db !== null) {
const tx = this.db.transaction('douyu', 'readwrite')
const store = tx.objectStore('douyu')
store.clear()
if (roomId) {
const index = store.index('idx_room_id')
const req = index.openCursor(IDBKeyRange.only(roomId))
req.addEventListener('success', function () {
const cursor = req.result
if (cursor) {
cursor.delete()
cursor.continue()
}
})
} else {
store.clear()
}
}
}
}

module.exports = new Logger()
module.exports = util.isBrowser() ? Logger : require('./loggerNode')
Loading

0 comments on commit d620b15

Please sign in to comment.