You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
filepizza/lib/stores/UploadStore.js

72 lines
1.6 KiB
JavaScript

import UploadActions from '../actions/UploadActions'
import UploadFile from '../UploadFile'
import alt from '../alt'
import peer from 'filepizza-peerjs'
import socket from 'filepizza-socket'
export default alt.createStore(class UploadStore {
constructor() {
this.bindActions(UploadActions)
this.status = 'ready'
this.token = null
this.file = null
this.peerProgress = {}
}
onUploadFile(file) {
if (this.status !== 'ready') return
this.status = 'processing'
this.file = new UploadFile(file)
socket.emit('upload', {
name: this.file.name,
size: this.file.size,
type: this.file.type
}, (token) => {
this.setState({
status: 'uploading',
token: token
})
})
}
onSendToDownloader(peerID) {
if (this.status !== 'uploading') return
let conn = peer.connect(peerID, {
reliable: true
})
let totalChunks = this.file.countChunks()
let i = 0
let sendNextChunk = () => {
if (i === totalChunks) return
let packet = this.file.getChunk(i)
conn.send(packet)
i++
this.peerProgress[peerID] = i/totalChunks
}
conn.on('open', () => {
sendNextChunk()
this.setState({ peerProgress: this.peerProgress })
})
conn.on('data', (data) => {
if (data === 'more') sendNextChunk()
this.setState({ peerProgress: this.peerProgress })
})
conn.on('close', () => {
if (this.peerProgress[peerID] < 1) {
this.peerProgress[peerID] = -1
}
this.setState({ peerProgress: this.peerProgress })
})
}
}, 'UploadStore')