Skip to content

Commit

Permalink
update: 更新版本号 v1.8.0-230917
Browse files Browse the repository at this point in the history
fix(ChatClient): 保留 Web 接口下的进房消息
fix(Home.vue): 支持上传图片(合并原 Repo)
  • Loading branch information
DoodleBears committed Sep 16, 2023
1 parent 70d4f7d commit 78782a5
Show file tree
Hide file tree
Showing 15 changed files with 125 additions and 98 deletions.
16 changes: 1 addition & 15 deletions api/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,6 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.json_args: Optional[dict] = None

def set_default_headers(self):
# 跨域测试用
if not self.application.settings['debug']:
return
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Methods', 'OPTIONS, PUT, POST, GET, DELETE')
if 'Access-Control-Request-Headers' in self.request.headers:
self.set_header('Access-Control-Allow-Headers',
self.request.headers['Access-Control-Request-Headers'])

def prepare(self):
self.set_header('Cache-Control', 'no-cache')

Expand All @@ -28,8 +18,4 @@ def prepare(self):
try:
self.json_args = json.loads(self.request.body)
except json.JSONDecodeError:
pass

async def options(self, *_args, **_kwargs):
# 跨域测试用
self.set_status(204 if self.application.settings['debug'] else 405)
pass
2 changes: 1 addition & 1 deletion api/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def send_body_no_raise(self, body: Union[bytes, str, Dict[str, Any]]):
self.close()

async def _on_joined_room(self):
if self.application.settings['debug']:
if self.settings['debug']:
await self._send_test_message()

# 不允许自动翻译的提示
Expand Down
1 change: 1 addition & 0 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ async def get(self):
'version': update.VERSION,
'config': {
'enableTranslate': cfg.enable_translate,
'enableUploadFile': cfg.enable_upload_file,
'loaderUrl': cfg.loader_url
}
})
Expand Down
30 changes: 29 additions & 1 deletion frontend/src/api/chat/ChatClientDirectWeb.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,12 +175,40 @@ export default class ChatClientDirectWeb extends ChatClientOfficialBase {
}
this.onDelSuperChat({ ids })
}

// TODO: 欢迎入场 ws 的信息,然后给到 Room.vue
async interactWordCallback(command) {
if (!this.onInteractWord) {
return
}
if (command.data.text_large) {
return
}
let data = command.data
// console.log(`interactWordCallback data 是 ${JSON.stringify(data, null, 4)}`)

data = {
id: getUuid4Hex(),
roomId: data.roomid,
timestamp: data.timestamp,
avatarUrl: await chat.getAvatarUrl(data.uid, data.uname),
msgType: data.msg_type,
authorName: data.uname,
medalName: data.fans_medal.medal_level === 0 ? undefined : data.fans_medal.medal_name,
medalLevel: data.fans_medal.medal_level === 0 ? undefined : data.fans_medal.medal_level,
isFanGroup: data.roomid === data.fans_medal.medal_room_id ? true : false, // 是否是粉丝团(即粉丝勋章为当前直播间的粉丝勋章)
privilegeType: data.fans_medal.guard_level // 所带勋章牌子的舰队等级,0非舰队,1总督,2提督,3舰长(不一定是当前直播间的粉丝勋章)
}
this.onInteractWord(data)
}

}

const CMD_CALLBACK_MAP = {
DANMU_MSG: ChatClientDirectWeb.prototype.danmuMsgCallback,
SEND_GIFT: ChatClientDirectWeb.prototype.sendGiftCallback,
GUARD_BUY: ChatClientDirectWeb.prototype.guardBuyCallback,
SUPER_CHAT_MESSAGE: ChatClientDirectWeb.prototype.superChatMessageCallback,
SUPER_CHAT_MESSAGE_DELETE: ChatClientDirectWeb.prototype.superChatMessageDeleteCallback
SUPER_CHAT_MESSAGE_DELETE: ChatClientDirectWeb.prototype.superChatMessageDeleteCallback,
INTERACT_WORD: ChatClientDirectWeb.prototype.interactWordCallback,
}
13 changes: 6 additions & 7 deletions frontend/src/api/chat/ChatClientOfficialBase/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ export default class ChatClientOfficialBase {
this.onAddSuperChat = null
this.onDelSuperChat = null
this.onUpdateTranslation = null
this.onInteractWord = null

this.onFatalError = null

Expand Down Expand Up @@ -161,7 +160,7 @@ export default class ChatClientOfficialBase {
}

onReceiveTimeout() {
window.console.warn('接收消息超时')
console.warn('接收消息超时')
this.discardWebsocket()
}

Expand Down Expand Up @@ -205,9 +204,10 @@ export default class ChatClientOfficialBase {

onWsMessage(event) {
if (!(event.data instanceof ArrayBuffer)) {
window.console.warn('未知的websocket消息类型,data=', event.data)
console.warn('未知的websocket消息类型,data=', event.data)
return
}

let data = new Uint8Array(event.data)
this.parseWsMessage(data)

Expand Down Expand Up @@ -251,7 +251,7 @@ export default class ChatClientOfficialBase {
default: {
// 未知消息
let body = new Uint8Array(data.buffer, offset + rawHeaderSize, packLen - rawHeaderSize)
window.console.warn('未知包类型,operation=', operation, dataView, body)
console.warn('未知包类型,operation=', operation, dataView, body)
break
}
}
Expand All @@ -263,7 +263,6 @@ export default class ChatClientOfficialBase {

switch (operation) {
case OP_SEND_MSG_REPLY: {

// 业务消息
if (ver == WS_BODY_PROTOCOL_VERSION_BROTLI) {
// 压缩过的先解压
Expand All @@ -280,7 +279,7 @@ export default class ChatClientOfficialBase {
body = JSON.parse(textDecoder.decode(body))
this.handlerCommand(body)
} catch (e) {
window.console.error('body=', body)
console.error('body=', body)
throw e
}
}
Expand All @@ -301,7 +300,7 @@ export default class ChatClientOfficialBase {
}
default: {
// 未知消息
window.console.warn('未知包类型,operation=', operation, dataView, body)
console.warn('未知包类型,operation=', operation, dataView, body)
break
}
}
Expand Down
5 changes: 1 addition & 4 deletions frontend/src/api/chat/ChatClientRelay.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ export default class ChatClientRelay {
this.onAddSuperChat = null
this.onDelSuperChat = null
this.onUpdateTranslation = null
this.onInteractWord = null

this.onFatalError = null

Expand All @@ -52,9 +51,7 @@ export default class ChatClientRelay {
return
}
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'
// 开发时使用localhost:12450
const host = process.env.NODE_ENV === 'development' ? 'localhost:12450' : window.location.host
const url = `${protocol}://${host}/api/chat`
const url = `${protocol}://${window.location.host}/api/chat`
this.websocket = new WebSocket(url)
this.websocket.onopen = this.onWsOpen.bind(this)
this.websocket.onclose = this.onWsClose.bind(this)
Expand Down
8 changes: 3 additions & 5 deletions frontend/src/api/chat/ChatClientTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ const MESSAGE_GENERATORS = [
return {
type: constants.MESSAGE_TYPE_INTERACT,
message: {
avatarUrl: avatar.DEFAULT_AVATAR_URL,
avatarUrl: chat.DEFAULT_AVATAR_URL,
timestamp: new Date().getTime() / 1000,
msgType: randInt(1, 5),
authorName: randomChoose(NAMES),
Expand Down Expand Up @@ -279,7 +279,6 @@ const MESSAGE_GENERATORS = [
translation: '',
emoticon: null,
emots: randomChoose(EMOT_INFO_LIST),
textEmoticons: [],
}
}
}
Expand All @@ -305,7 +304,6 @@ const MESSAGE_GENERATORS = [
translation: '',
emoticon: randomChoose(EMOTICONS),
emoticonDetail: randomChoose(EMOT_DETAIL_LIST),
textEmoticons: [],
}
}
}
Expand All @@ -321,8 +319,8 @@ const MESSAGE_GENERATORS = [
id: getUuid4Hex(),
avatarUrl: chat.DEFAULT_AVATAR_URL,
timestamp: new Date().getTime() / 1000,
authorName: randomChoose(NAMES)
// num: 1
authorName: randomChoose(NAMES),
num: 1
}
}
}
Expand Down
1 change: 0 additions & 1 deletion frontend/src/api/chatConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -640,7 +640,6 @@ export function getLocalConfig() {
}
}

// FIXME: 前端上传表情包设置
export function sanitizeConfig(config) {
let newEmoticons = []
if (config.emoticons instanceof Array) {
Expand Down
11 changes: 11 additions & 0 deletions frontend/src/api/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import axios from 'axios'

export async function getServerInfo() {
return (await axios.get('/api/server_info')).data
}

export async function uploadEmoticon(file) {
let body = new FormData()
body.set('file', file)
return (await axios.post('/api/emoticon', body)).data
}
2 changes: 1 addition & 1 deletion frontend/src/layout/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
</router-link>
</div>
<div class="version">
{{ APP_VERSION }}-230709
{{ APP_VERSION }}-230917
</div>
<div class="version">
<a href="https://space.bilibili.com/12236936" target="_blank">只熊KUMA</a>
Expand Down
4 changes: 0 additions & 4 deletions frontend/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@ import Help from './views/Help'
import Room from './views/Room'
import NotFound from './views/NotFound'

if (process.env.NODE_ENV === 'development') {
// 开发时使用localhost:12450
axios.defaults.baseURL = 'http://localhost:12450'
}
axios.defaults.timeout = 10 * 1000

Vue.use(VueRouter)
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function toFloat(val, _default) {

export function formatCurrency(price) {
return new Intl.NumberFormat('zh-CN', {
minimumFractionDigits: price < 100 ? 1 : 0
minimumFractionDigits: price < 100 ? 2 : 0
}).format(price)
}

Expand Down
31 changes: 27 additions & 4 deletions frontend/src/views/Home.vue
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,9 @@
<el-table-column :label="$t('home.operation')" width="170">
<template slot-scope="scope">
<el-button-group>
<el-button type="primary" icon="el-icon-upload2" :disabled="!serverConfig.enableUploadFile"
@click="uploadEmoticon(scope.row)"
></el-button>
<el-button type="danger" icon="el-icon-minus" @click="delEmoticon(scope.$index)"></el-button>
</el-button-group>
</template>
Expand Down Expand Up @@ -852,10 +855,10 @@ a:hover {
</style>
<script>
import _ from 'lodash'
import axios from 'axios'
import download from 'downloadjs'
import { mergeConfig } from '@/utils'
import * as mainApi from '@/api/main'
import * as chatConfig from '@/api/chatConfig'
export default {
Expand Down Expand Up @@ -915,9 +918,10 @@ export default {
methods: {
async updateServerConfig() {
try {
this.serverConfig = (await axios.get('/api/server_info')).data.config
this.serverConfig = (await mainApi.getServerInfo()).config
} catch (e) {
this.$message.error(`Failed to fetch server information: ${e}`)
throw e
}
},
Expand Down Expand Up @@ -965,8 +969,27 @@ export default {
})
.catch(() => {})
},
uploadEmoticon() {
// TODO WIP
uploadEmoticon(emoticon) {
let input = document.createElement('input')
input.type = 'file'
input.accept = 'image/png, image/jpeg, image/jpg, image/gif'
input.onchange = async() => {
let file = input.files[0]
if (file.size > 1024 * 1024) {
this.$message.error(this.$t('home.emoticonFileTooLarge'))
return
}
let res
try {
res = await mainApi.uploadEmoticon(file)
} catch (e) {
this.$message.error(`Failed to upload: ${e}`)
throw e
}
emoticon.url = res.url
}
input.click()
},
enterRoom() {
Expand Down
Loading

0 comments on commit 78782a5

Please sign in to comment.