File size: 12,417 Bytes
181e22f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import CopyToClipboard from 'react-copy-to-clipboard';
import prettyBytes from 'pretty-bytes';
import classnames from 'classnames';
import uuidv4 from 'uuid/v4';
import {
Link,
} from 'react-router-dom';
import QRCode from 'qrcode.react';
import Dropzone from 'react-dropzone';
import Icon from './common/Icon';
import Button from './common/Button';
import Steps from './common/Steps';
import Toast from './common/Toast';
import FileBox from './FileBox';
import Peer from '../Peer';
import FileChunker from '../FileChunker';
import { calcPercent } from '../common/util';
import { prepareSend, deleteRecvCode } from '../actions/file';
import styles from './SendFilePanel.cm.styl';
const Step = Steps.Step;
class SendFilePanel extends Component {
constructor(props) {
super(props);
this.peer = new Peer();
this.inputRef = React.createRef();
this.onChangeFile = this.onChangeFile.bind(this);
this.onRemoveFile = this.onRemoveFile.bind(this);
this.onClickSelectDone = this.onClickSelectDone.bind(this);
this.onClickBack = this.onClickBack.bind(this);
this.onReset = this.onReset.bind(this); // 回到初始状态,用在点击取消或发送完成继续发送等地方
this.onRecvPeerData = this.onRecvPeerData.bind(this);
this.handlePeerMsg = this.handlePeerMsg.bind(this);
this.sendSizes = {};
this.lastPeerRecvBytes = 0; // (上次)接收方接收到的字节数,用于计算bps
this.bps = 0;
this.timer = setInterval(() => {
const files = this.props.files.map(f => {
const sendSize = this.sendSizes[f.uid] || 0;
const pct = calcPercent(sendSize, f.size);
return {
...f,
pct,
};
});
this.props.setState({ files, bps: this.bps });
this.bps = 0;
}, 1000);
}
componentDidMount() {
document.title = '小鹿快传|简单安全高效的P2P文件传输服务 - 发送文件';
}
componentWillUnmount() {
clearInterval(this.timer);
}
onClickSelectDone() {
this.props.setState({
waitingPrepareSend: true,
});
const files = this.props.files.map(f => {
return {
uid: f.uid,
name: f.name,
size: f.size,
type: f.type,
};
});
prepareSend(files);
const peer = this.peer;
peer.on('connecting', () => {
this.props.setState({
peerState: 'connecting',
});
});
peer.on('connected', () => {
this.props.setState({
peerState: 'connected',
});
});
peer.on('connectFailed', () => {
this.props.setState({
peerState: 'connectFailed',
});
Toast.error('连接失败');
});
peer.on('disconnected', async() => {
this.props.setState({
peerState: 'disconnected',
});
});
peer.on('channelOpen', async() => {
this.props.setState({
curStep: 3,
peerState: 'transfer',
});
const files = this.props.files;
for (let i = 0; i < files.length; i++) {
const file = files[i];
const fileId = file.uid;
await peer.sendJSON({
type: 'fileStart',
fileId,
});
this.props.setState({
curFileId: fileId,
});
const chunker = new FileChunker(file.realFile);
let done = false;
this.lastPeerRecvBytes = 0;
while (!done) {
const result = await chunker.getNextChunk();
done = result.done;
const {
chunk,
} = result;
try {
await peer.send(chunk);
} catch (err) {
Toast.error('传输错误:' + err);
break;
}
}
if (done) {
await peer.sendJSON({
type: 'fileEnd',
fileId,
});
}
}
});
peer.on('data', this.onRecvPeerData);
}
onRecvPeerData(data) {
if (typeof data === 'string') {
const msg = JSON.parse(data);
this.handlePeerMsg(msg);
}
}
handlePeerMsg(msg) {
const {
type,
payload,
} = msg;
if (type === 'chunkReceived') {
const {
fileId,
recvBytes,
} = payload;
this.sendSizes[fileId] = recvBytes;
this.bps += (recvBytes - this.lastPeerRecvBytes);
this.lastPeerRecvBytes = recvBytes;
}
}
onClickBack() {
deleteRecvCode(this.props.recvCode);
this.props.setState({ curStep: this.props.curStep - 1 });
}
onReset() {
this.peer.destroy();
this.props.setState({
curStep: 1,
files: [],
peerState: '',
waitingPrepareSend: false,
});
}
onChangeFile(files) {
const filteredFiles = files.filter(f => {
const existed = this.props.files.find(_f1 => {
const f1 = _f1.realFile;
if (f1.name === f.name && f1.size === f.size && f1.lastModified === f.lastModified && f1.type === f.type) {
return true;
}
return false;
});
return !existed;
}).map(f => {
return {
realFile: f,
uid: uuidv4(),
name: f.name,
size: f.size,
type: f.type,
};
});
if (filteredFiles.length !== files.length) {
Toast.info('发现疑似相同的文件,已自动过滤');
}
const nextFiles = this.props.files.concat(filteredFiles);
this.props.setState({
files: nextFiles,
});
event.target.value = null;
}
onRemoveFile(uid) {
return () => {
const nextFiles = this.props.files.filter(f => f.uid !== uid);
this.props.setState({ files: nextFiles });
};
}
renderStep1() {
const {
files,
waitingPrepareSend,
} = this.props;
const totalBytes = files.reduce((sum, cur) => {
return sum + cur.size;
}, 0);
return (
<Dropzone onDrop={this.onChangeFile} noClick>
{({ getRootProps, getInputProps, isDragActive, open }) => (
<>
<div className={classnames(styles.uploadArea, isDragActive && styles.dragActive)} {...getRootProps()}>
{files.length === 0 && (
<>
<div className={styles.iconPlusWrapper}>
<Icon name="plus" className={styles.iconPlus} />
</div>
<div className={styles.uploadTip}>
将文件拖动到方框内或点击下方按钮
</div>
<Button
type="primary"
className={styles.uploadBtn}
onClick={() => open()}
>
上传文件
</Button>
</>
)}
{files.length > 0 && (
<FileBox
files={files}
removable
onRemoveFile={this.onRemoveFile}
/>
)}
<input {...getInputProps()} />
</div>
{files.length === 0 && (
<div className={styles.recvGuide}>
已有收件码?点击
<Link to="/recv" className={styles.link}> 接收文件</Link>
</div>
)}
{files.length > 0 && (
<>
<div className={styles.uploadMore}>
<div className={styles.addMore}>
<span onClick={() => open()}>添加文件</span>
</div>
<div className={styles.fileSummary}>{files.length} 个文件,共 {prettyBytes(totalBytes)}</div>
</div>
<Button type="primary" loading={waitingPrepareSend} className={styles.btnSelectFileDone} onClick={this.onClickSelectDone}>
选好了
</Button>
</>
)}
</>
)}
</Dropzone>
);
}
renderStep2() {
const {
recvCode,
} = this.props;
const recvLink = `http://${document.location.host}/recv/${recvCode}`;
return (
<>
<div className={styles.selectSendMethod}>
请选择发送方式:
</div>
<div className={styles.sendMethod1}>
1. 通过链接发送(对方打开链接即可下载文件)
</div>
<div className={styles.recvLinkContainer}>
<span className={styles.recvLink}>
{recvLink}
</span>
<CopyToClipboard text={recvLink} onCopy={() => Toast.success('复制成功')}>
<span className={styles.btnCopy}>
复制
</span>
</CopyToClipboard>
</div>
<div>
2. 通过6位数取件码(对方在小鹿快传网站输入即可下载文件)
</div>
<div className={styles.recvCodeContainer}>
<span className={styles.recvCode}>
{recvCode}
</span>
<CopyToClipboard text={recvCode} onCopy={() => Toast.success('复制成功')}>
<span className={styles.btnCopy}>
复制
</span>
</CopyToClipboard>
</div>
<div>
3. 扫描下方二维码:
</div>
<div className={styles.qrcodeContainer}>
<QRCode value={recvLink} />
</div>
<div className={styles.connectTips}>
温馨提示:<br />
以上取件码在10分钟内有效,请尽快发送给对方 <br />
对方输入取件码并确认之后会自动开始发送
</div>
<Button type="primary" className={styles.btnWaitConnect} loading>
等待连接...
</Button>
</>
);
}
renderStep3() {
const {
curFileId,
files,
peerState,
} = this.props;
const totalBytes = files.reduce((sum, cur) => {
return sum + cur.size;
}, 0);
let allCompleted = true;
files.forEach(f => {
if (f.pct < 100) {
allCompleted = false;
}
});
let btnContent;
if (allCompleted) {
btnContent = '继续发送';
} else if (peerState === 'connecting') {
btnContent = '正在连接...';
} else if (peerState === 'connected') {
btnContent = '连接成功';
} else if (peerState === 'transfer') {
btnContent = `正在发送...(${prettyBytes(this.bps || 0)}/s)`;
} else if (peerState === 'disconnected' || peerState === 'connectFailed') {
btnContent = '连接断开,等待重连...';
}
let loading = true;
if (allCompleted) {
loading = false;
}
return (
<>
<div className={styles.sendingBox}>
<FileBox files={files} curFileId={curFileId} />
</div>
<div className={styles.sendingSummary}>
<div>{files.length}个文件,共{prettyBytes(totalBytes)}</div>
</div>
<Button type="primary" className={styles.btnSending} loading={loading} onClick={this.onReset}>
{btnContent}
</Button>
</>
);
}
render() {
const {
curStep,
files,
} = this.props;
return (
<div className={styles.base}>
<div className={styles.titleRow}>
{((curStep === 1 && files.length > 0) || (curStep === 3)) && (
<div className={styles.back} onClick={this.onReset}>
取消
</div>
)}
{curStep === 2 && (
<div className={styles.back} onClick={this.onClickBack}>
返回
</div>
)}
<div className={styles.title}>
发送文件
</div>
</div>
<Steps>
<Step
index={1}
title="选择文件"
active={curStep === 1}
/>
<Step index={2} title="收件码" active={curStep === 2} />
<Step index={3} title="发送" active={curStep === 3} />
</Steps>
{curStep === 1 && this.renderStep1()}
{curStep === 2 && this.renderStep2()}
{curStep === 3 && this.renderStep3()}
</div>
);
}
}
SendFilePanel.propTypes = {
curStep: PropTypes.number,
files: PropTypes.array,
waitingPrepareSend: PropTypes.bool,
curFileId: PropTypes.string,
peerState: PropTypes.string,
recvCode: PropTypes.string,
setState: PropTypes.func,
};
export default SendFilePanel;
|