import 'virtual:windi.css' import IndexedDB from './indexeddb.js' import MusicList from './music.js' import ClientList from './client.js' import Chat from './chat.js' import { Buffer } from "buffer" import process from "process" window.Buffer = Buffer window.process = process import { parseBlob } from 'music-metadata-browser' // 缓冲分片发送 const CHUNK_SIZE = 1024 * 64 // 默认每个块的大小为128KB const THRESHOLD = 1024 * 1024 // 默认缓冲区的阈值为1MB const DELAY = 50 // 默认延迟500ms // 将两个ArrayBuffer合并成一个 function appendBuffer(buffer1, buffer2) { const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength) tmp.set(new Uint8Array(buffer1), 0) tmp.set(new Uint8Array(buffer2), buffer1.byteLength) return tmp.buffer } // 读取本地音乐列表并标识为缓存状态(本地缓存) const database = new IndexedDB('musicDatabase', 1) await database.store('musicObjectStore') // 音乐(为什么会用这么丑的格式呢) // 读取本地音乐列表并标识为缓存状态(本地缓存) const list = await Promise.all((await database.getAll('musicObjectStore')).map(async item => { if (!item.picture) { const blob = new Blob([item.arrayBuffer], { type: item.type }) const metadata = await parseBlob(blob) const picture = metadata.common.picture?.[0] if (picture) { const format = picture.format const data = picture.data item.picture = `data:${format};base64,${Buffer.from(data).toString('base64')}` } } return { save: true, ...item } })) // 读取本地用户名(本地缓存) const name = localStorage.getItem('username') ?? '匿' const avatar = localStorage.getItem('avatar') ?? '/favicon.ico' // 初始化客户端列表 const clientList = new ClientList({ name, onexit: async client => { console.log(client.name, '离开频道') // 从列表中移除未缓存的此用户的音乐, 但可能多人都有此音乐且未缓存 // 因此每条音乐都要检查是否有其他用户也有此音乐, 如果有则不移除 const 此用户音乐 = client.musicList?.map(item => item.id) || [] musicList.list.filter(item => !item.arrayBuffer).filter(item => { return 此用户音乐.includes(item.id) }).forEach(item => { const client = clientList.clientlist.find(client => { return client?.musicList?.find(x => x.id === item.id) }) if (!client) musicList.remove(item) }) } }) // 初始化音乐列表(加入本地缓存) const musicList = new MusicList({ list, onplay: item => { console.log('播放音乐', item.name) }, onstop: item => { console.log('停止音乐', item?.name) }, onlike: (item, list) => { console.log('喜欢音乐', item.name) if (item.arrayBuffer) { //musicStore.add(item) database.add('musicObjectStore', item) clientList.send('base', JSON.stringify({ type: 'set_music_list', list: list.map(({ id, name, size, type }) => ({ id, name, size, type })) })) } }, onunlike: (item, list) => { console.log('取消喜欢', item.name) if (item.arrayBuffer) { database.delete('musicObjectStore', item.id) //musicStore.delete(item.id) clientList.send('base', JSON.stringify({ type: 'set_music_list', list: list.map(({ id, name, size, type }) => ({ id, name, size, type })) })) } }, onban: item => { //console.info('禁止音乐', item.name) }, onunban: item => { //console.info('解禁音乐', item.name) }, onremove: item => { //console.info('移除音乐', item.name) //musicStore.delete(item.id) database.delete('musicObjectStore', item.id) }, onadd: (item, list) => { //console.info('添加音乐', item.name) }, onupdate: item => { //console.info('更新音乐', item.name) }, onerror: error => { console.error('音乐列表错误', error) }, onload: async item => { console.info('加载音乐', item) return await new Promise((resolve) => { var buffer = new ArrayBuffer(0) // 接收音乐数据 var count = 0 // 接收分片计数 const chunkNumber = Math.ceil(item.size / 1024 / 64) // 64KB每片 clientList.setChannel(`music-data-${item.id}`, { onmessage: async (event, client) => { console.log('收到音乐数据 chunk', `${count + 1}/${chunkNumber}`, buffer.byteLength) buffer = appendBuffer(buffer, event.data) // 合并分片准备存储 item.arrayBufferChunks?.push(event.data) // 保存分片给边下边播 count++ if (buffer.byteLength >= item.size) { console.log('音乐数据接收完毕') item.arrayBuffer = buffer event.target.close() // 关闭信道 resolve(item) } } }) const client = clientList.clientlist.find(client => { return client.musicList.find(x => x.id === item.id) }) console.info('向', client.name, '请求音乐数据') const c = Math.ceil(item.size / CHUNK_SIZE) console.log('需要接收', c, '个分片') clientList.sendto(client.id, 'base', JSON.stringify({ type: 'get_music_data', id: item.id, channel: `music-data-${item.id}` })) }) } }) const chat = new Chat({ name: 'default', onsend: async (text, list) => { clientList.send('chat', JSON.stringify({ type: 'message', text })) }, onexit: async () => { console.log('退出聊天室') } }) // 与每个客户端都建立聊天信道 clientList.setChannel('chat', { onopen: async (event, client) => { const start = localStorage.getItem('store-chat-default') || 0 const end = new Date().getTime() clientList.sendto(client.id, 'chat', JSON.stringify({ type: 'pull', start, end })) }, onmessage: async (event, client) => { const data = JSON.parse(event.data) if (data.type === 'message') { console.log(client.name, '发来消息:', data) chat.收到消息({ name: client.name, ...data.text }) return } if (data.type === 'answer') { console.log(client.name, '发来应答:', data) chat.answer(data) return } if (data.type === 'pull') { const list = (await chat.筛选指定范围的消息({ start: data.start, end: data.end })).map(item => { return { timestamp: new Date(item.time).getTime(), ...item } }) clientList.sendto(client.id, 'chat', JSON.stringify({ type: 'list', list })) console.log(client.name, `拉取了 ${list.length} 条消息`) return } if (data.type === 'list') { console.log(client.name, `同步来 ${data.list.length} 条消息`, data.list) await chat.合并消息列表(data.list) return } console.log('未知类型:', data.type) }, onclose: event => { console.log('关闭信道', event.target.label) }, onerror: event => { console.error('信道错误', event.target.label, event.error) } }) const file_cache = [] // 与每个客户端都建立文件传输信道 clientList.setChannel('file', { onopen: async (event, client) => { //console.debug('打开信道', event.target.label) //clientList.sendto(client.id, 'file', JSON.stringify({ id: '', start: 0, end: 16384 })) //clientList.sendto(client.id, 'file', new ArrayBuffer(1024)) }, onmessage: async (event, client) => { if (typeof event.data === 'string') { console.log(client.name, '文件请求:', event.data) const { id, start, end } = JSON.parse(event.data) const file = file_cache.find(file => file.id === id) const data = file.chunk.slice(start, end) // 分片发送 const c = Math.ceil(file.chunk.length / (CHUNK_SIZE - (12 * 8))) console.log('需要发送', c, '个分片') const chunks = [] for (let i = 0; i < c; i++) { const chunk = new ArrayBuffer(CHUNK_SIZE) const view = new Uint32Array(chunk) view[0] = file.id view[1] = i * (CHUNK_SIZE - (12 * 8)) view[2] = (i + 1) * (CHUNK_SIZE - (12 * 8)) const data = new Uint8Array(chunk, 12) data.set(new Uint8Array(file.chunk[i])) chunks.push(chunk) } for (let i = 0; i < chunks.length; i++) { const chunk = chunks[i] console.log('发送分片', `${i + 1}/${chunks.length}`, chunk.byteLength) clientList.sendto(client.id, 'file', chunk) await new Promise((resolve) => setTimeout(resolve, DELAY)) } console.log('文件发送完毕') return } if (event.data instanceof ArrayBuffer) { console.log(client.name, '发来文件:', event.data) // 判断分片是哪个文件的 const file = file_cache.find(file => file.hash === event.target.label) if (!file) { console.log('未知文件:', event.target.label) return } // 将分片保存到文件的分片列表中 file.chunk.push(event.data) // 判断文件是否接收完毕 if (file.chunk.length === file.chunkNumber) { console.log('文件接收完毕:', file) // 将分片列表合并成一个文件 file.arrayBuffer = file.chunk.reduce((prev, curr) => appendBuffer(prev, curr)) // 将文件保存到本地 //fileStore.add(file) // 将文件添加到音乐列表 //musicList.add(file) // 将文件从缓存列表中移除 file_cache.splice(file_cache.indexOf(file), 1) } return } console.log('未知类型:', event) } }) // 与每个客户端都建立交换身份信道 clientList.setChannel('profile', { onopen: async (event, client) => { clientList.sendto(client.id, 'profile', JSON.stringify({ name: name, avatar: avatar, })) }, onmessage: async (event, client) => { //console.log(client.name, '发来身份信息:', event.data) const data = JSON.parse(event.data) client.name = data.name client.avatar = data.avatar clientList.用户更新({ id: client.id, ...data }) }, onclose: event => { console.log('关闭信道', event.target.label) }, onerror: event => { console.error('信道错误', event.target.label, event.error) } }) // 与每个客户端都建立基本信道, 用于交换和调度信息 clientList.setChannel('base', { onopen: async event => { clientList.send('base', JSON.stringify({ type: 'get_music_list' })) // 要求对方发送音乐列表 }, onmessage: async (event, client) => { const data = JSON.parse(event.data) if (data.type === 'get_music_list') { const ms = musicList.list.filter(item => item.arrayBuffer) clientList.sendto(client.id, 'base', JSON.stringify({ type: 'set_music_list', list: ms.map(({ id, name, size, type }) => ({ id, name, size, type })) })) return } if (data.type === 'set_music_list') { client.musicList = data.list client.musicList.forEach(music => musicList.add(music)) return } if (data.type === 'get_music_data') { console.log(client.name, '建立一个信道, 用于传输音乐数据', musicList.list) musicList.list.filter(item => item.id === data.id).forEach(item => { const ch = client.webrtc.createDataChannel(data.channel, { reliable: true }) ch.onopen = async event => { console.log(client.name, `打开 ${data.channel} 信道传输音乐数据`, item.name) // 将音乐数据分成多个小块,并逐个发送 async function sendChunk(dataChannel, data, index = 0, buffer = new ArrayBuffer(0)) { while (index < data.byteLength) { if (dataChannel.bufferedAmount <= THRESHOLD) { const chunk = data.slice(index, index + CHUNK_SIZE) dataChannel.send(chunk) index += CHUNK_SIZE buffer = appendBuffer(buffer, chunk) } await new Promise((resolve) => setTimeout(resolve, DELAY)) } return buffer } await sendChunk(ch, item.arrayBuffer) console.log(client.name, `获取 ${data.channel} 信道数据结束`, item.name) ch.close() // 关闭信道 } }) return } console.log('未知类型:', data.type) }, //onclose: event => { // console.log('关闭信道', event.target.label) //}, //onerror: event => { // console.error('信道错误', event.target.label, event.error) //} }) // 设置标签为自己的头像 if (localStorage.getItem('avatar')) { const favicon = document.createElement('link') favicon.rel = 'icon' favicon.href = localStorage.getItem('avatar') document.head.appendChild(favicon) } // 设置标题为自己的昵称 if (localStorage.getItem('username')) { document.title = localStorage.getItem('username') }