forked from linuxdeepin/dde-cooperation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransferhelper.cpp
637 lines (547 loc) · 21.1 KB
/
transferhelper.cpp
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
// SPDX-FileCopyrightText: 2023 - 2024 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later
#include "transferhelper.h"
#include "transferhelper_p.h"
#include "configs/settings/configmanager.h"
#include "utils/cooperationutil.h"
#include "utils/historymanager.h"
#include "net/networkutil.h"
#include "net/cooconstrants.h"
#include "common/constant.h"
#include "common/commonutils.h"
#include <QDesktopServices>
#include <QApplication>
#include <QFileDialog>
#include <QStandardPaths>
#include <QTime>
#include <QProcess>
#include <QRegularExpression>
#ifdef __linux__
# include "base/reportlog/reportlogmanager.h"
# include <QDBusInterface>
# include <QDBusReply>
#endif
using ButtonStateCallback = std::function<bool(const QString &, const DeviceInfoPointer)>;
using ClickedCallback = std::function<void(const QString &, const DeviceInfoPointer)>;
Q_DECLARE_METATYPE(ButtonStateCallback)
Q_DECLARE_METATYPE(ClickedCallback)
inline constexpr int TransferJobStartId = 1000;
inline constexpr char HistoryButtonId[] { "history-button" };
inline constexpr char TransferButtonId[] { "transfer-button" };
inline constexpr char NotifyCancelAction[] { "cancel" };
inline constexpr char NotifyRejectAction[] { "reject" };
inline constexpr char NotifyAcceptAction[] { "accept" };
inline constexpr char NotifyCloseAction[] { "close" };
inline constexpr char NotifyViewAction[] { "view" };
using TransHistoryInfo = QMap<QString, QString>;
Q_GLOBAL_STATIC(TransHistoryInfo, transHistory)
#ifdef __linux__
inline constexpr char Khistory[] { "history" };
inline constexpr char Ksend[] { "send" };
#else
inline constexpr char Khistory[] { ":/icons/deepin/builtin/texts/history_18px.svg" };
inline constexpr char Ksend[] { ":/icons/deepin/builtin/texts/send_18px.svg" };
#endif
using namespace deepin_cross;
using namespace cooperation_core;
TransferHelperPrivate::TransferHelperPrivate(TransferHelper *qq)
: QObject(qq),
q(qq)
{
*transHistory = HistoryManager::instance()->getTransHistory();
connect(HistoryManager::instance(), &HistoryManager::transHistoryUpdated, q,
[] {
*transHistory = HistoryManager::instance()->getTransHistory();
});
initConnect();
}
TransferHelperPrivate::~TransferHelperPrivate()
{
}
void TransferHelperPrivate::initConnect()
{
#ifdef __linux__
notice = new NoticeUtil(q);
connect(notice, &NoticeUtil::onConfirmTimeout, q, &TransferHelper::onVerifyTimeout);
connect(notice, &NoticeUtil::ActionInvoked, q, &TransferHelper::onActionTriggered);
#endif
confirmTimer.setInterval(10 * 1000);
confirmTimer.setSingleShot(true);
connect(&confirmTimer, &QTimer::timeout, q, &TransferHelper::onVerifyTimeout);
connect(transDialog(), &CooperationTransDialog::cancelApply, q, &TransferHelper::cancelTransferApply);
connect(transDialog(), &CooperationTransDialog::cancel, q, [this] { q->onActionTriggered(NotifyCancelAction); });
connect(transDialog(), &CooperationTransDialog::rejected, q, [this] { q->onActionTriggered(NotifyRejectAction); });
connect(transDialog(), &CooperationTransDialog::accepted, q, [this] { q->onActionTriggered(NotifyAcceptAction); });
connect(transDialog(), &CooperationTransDialog::viewed, q, [this] { q->onActionTriggered(NotifyViewAction); });
}
CooperationTransDialog *TransferHelperPrivate::transDialog()
{
if (!dialog) {
dialog = new CooperationTransDialog(qApp->activeWindow());
dialog->setModal(true);
}
return dialog;
}
void TransferHelperPrivate::reportTransferResult(bool result)
{
#ifdef __linux__
QVariantMap map;
map.insert("deliveryResult", result);
ReportLogManager::instance()->commit(ReportAttribute::FileDelivery, map);
#endif
}
void TransferHelperPrivate::notifyMessage(const QString &body, const QStringList &actions, int expireTimeout)
{
#ifdef __linux__
notice->notifyMessage(tr("File transfer"), body, actions, QVariantMap(), expireTimeout);
#endif
}
TransferHelper::TransferHelper(QObject *parent)
: QObject(parent),
d(new TransferHelperPrivate(this))
{
}
TransferHelper::~TransferHelper()
{
}
TransferHelper *TransferHelper::instance()
{
static TransferHelper ins;
return &ins;
}
void TransferHelper::registBtn()
{
ClickedCallback clickedCb = TransferHelper::buttonClicked;
ButtonStateCallback visibleCb = TransferHelper::buttonVisible;
ButtonStateCallback clickableCb = TransferHelper::buttonClickable;
QVariantMap historyInfo { { "id", HistoryButtonId },
{ "description", tr("View transfer history") },
{ "icon-name", Khistory },
{ "location", 2 },
{ "button-style", 0 },
{ "clicked-callback", QVariant::fromValue(clickedCb) },
{ "visible-callback", QVariant::fromValue(visibleCb) },
{ "clickable-callback", QVariant::fromValue(clickableCb) } };
QVariantMap transferInfo { { "id", TransferButtonId },
{ "description", tr("Send files") },
{ "icon-name", Ksend },
{ "location", 3 },
{ "button-style", 1 },
{ "clicked-callback", QVariant::fromValue(clickedCb) },
{ "visible-callback", QVariant::fromValue(visibleCb) },
{ "clickable-callback", QVariant::fromValue(clickableCb) } };
CooperationUtil::instance()->registerDeviceOperation(historyInfo);
CooperationUtil::instance()->registerDeviceOperation(transferInfo);
}
void TransferHelper::sendFiles(const QString &ip, const QString &devName, const QStringList &fileList)
{
d->who = devName;
d->readyToSendFiles = fileList;
if (fileList.isEmpty())
return;
if (!d->status.testAndSetRelease(TransferHelper::Idle, TransferHelper::Connecting)) {
d->status.storeRelease(TransferHelper::Idle);
return;
}
// send the transfer file RPC request
NetworkUtil::instance()->tryTransApply(ip);
waitForConfirm();
}
TransferHelper::TransferStatus TransferHelper::transferStatus()
{
return static_cast<TransferStatus>(d->status.loadAcquire());
}
void TransferHelper::buttonClicked(const QString &id, const DeviceInfoPointer info)
{
QString ip = info->ipAddress();
QString name = info->deviceName();
LOG << "button clicked, button id: " << id.toStdString()
<< " ip: " << ip.toStdString()
<< " device name: " << name.toStdString();
if (id == TransferButtonId) {
QStringList selectedFiles = qApp->property("sendFiles").toStringList();
if (selectedFiles.isEmpty())
selectedFiles = QFileDialog::getOpenFileNames(qApp->activeWindow());
if (selectedFiles.isEmpty())
return;
if (qApp->property("onlyTransfer").toBool()) {
// send command to local socket.
QStringList msgs;
// must be in the format of: <ip> <name> <files>
msgs << "-f" << ip << name << selectedFiles;
emit TransferHelper::instance()->deliverMessage(MainAppName, msgs);
qApp->exit(0);
} else {
TransferHelper::instance()->sendFiles(ip, name, selectedFiles);
}
} else if (id == HistoryButtonId) {
if (!transHistory->contains(ip))
return;
QDesktopServices::openUrl(QUrl::fromLocalFile(transHistory->value(ip)));
}
}
bool TransferHelper::buttonVisible(const QString &id, const DeviceInfoPointer info)
{
if (id == TransferButtonId) {
switch (info->transMode()) {
case DeviceInfo::TransMode::Everyone:
return info->connectStatus() != DeviceInfo::Offline;
case DeviceInfo::TransMode::OnlyConnected:
return info->connectStatus() == DeviceInfo::Connected;
default:
return false;
}
}
if (id == HistoryButtonId) {
if (qApp->property("onlyTransfer").toBool())
return false;
if (!transHistory->contains(info->ipAddress()))
return false;
bool exists = QFile::exists(transHistory->value(info->ipAddress()));
if (!exists)
HistoryManager::instance()->removeTransHistory(info->ipAddress());
return exists;
}
return true;
}
bool TransferHelper::buttonClickable(const QString &id, const DeviceInfoPointer info)
{
Q_UNUSED(info)
if (id == TransferButtonId)
return TransferHelper::instance()->transferStatus() == Idle;
return true;
}
void TransferHelper::onVerifyTimeout()
{
d->isTransTimeout = true;
if (d->status.loadAcquire() != TransferHelper::Confirming)
return;
d->status.storeRelease(Idle);
d->transDialog()->showResultDialog(false, tr("The other party did not receive, the files failed to send"));
}
void TransferHelper::transferResult(bool result, const QString &msg)
{
#ifdef __linux__
if (d->role != Server) {
QStringList actions;
if (result)
actions << NotifyViewAction << tr("View");
d->notifyMessage(msg, actions, 3 * 1000);
d->notice->resetNotifyId();
return;
}
#endif
d->transDialog()->showResultDialog(result, msg, d->role != Server);
d->reportTransferResult(result);
}
void TransferHelper::updateProgress(int value, const QString &remainTime)
{
#ifdef __linux__
if (d->role != Server) {
// 在通知中心中,如果通知内容包含“%”且actions中存在“cancel”,则不会在通知中心显示
QStringList actions { NotifyCancelAction, tr("Cancel") };
// dde-session-ui 5.7.2.2 版本后,支持设置该属性使消息不进通知中心
QVariantMap hitMap { { "x-deepin-ShowInNotifyCenter", false } };
QString msg(tr("File receiving %1% | Remaining time %2").arg(QString::number(value), remainTime));
d->notifyMessage(msg, actions, 15 * 1000);
return;
}
#endif
QString title = d->role == Server ? tr("Sending files to \"%1\"") : tr("Receiving files from \"%1\"");
title = title.arg(CommonUitls::elidedText(d->who, Qt::ElideMiddle, 15));
d->transDialog()->showProgressDialog(title);
d->transDialog()->updateProgress(value, remainTime);
}
void TransferHelper::onActionTriggered(const QString &action)
{
// clear transfer info
d->transferInfo.clear();
if (action == NotifyCancelAction) {
cancelTransfer(true); // do UI first
NetworkUtil::instance()->cancelTrans();
} else if (action == NotifyRejectAction) {
NetworkUtil::instance()->replyTransRequest(false);
} else if (action == NotifyAcceptAction) {
d->role = Client;
NetworkUtil::instance()->replyTransRequest(true);
} else if (action == NotifyCloseAction) {
#ifdef __linux__
d->notice->closeNotification();
#endif
} else if (action == NotifyViewAction) {
auto fileurl = d->recvFilesSavePath;
if (fileurl.isEmpty()) {
auto value = ConfigManager::instance()->appAttribute(AppSettings::GenericGroup, AppSettings::StoragePathKey);
fileurl = value.isValid() ? value.toString() : QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
}
openFileLocation(fileurl);
}
}
void TransferHelper::openFileLocation(const QString &path)
{
#ifdef __linux__
QProcess::execute("dde-file-manager", QStringList() << path);
#else
QDesktopServices::openUrl(QUrl::fromLocalFile(path));
d->transDialog()->close();
#endif
}
void TransferHelper::notifyTransferRequest(const QString &nick, const QString &ip)
{
DLOG << "request info: " << nick.toStdString() << ip.toStdString();
auto storageFolder = nick + "(" + ip + ")";
NetworkUtil::instance()->setStorageFolder(storageFolder);
static QString msg(tr("\"%1\" send some files to you"));
d->who = nick;
#ifdef __linux__
QStringList actions { NotifyRejectAction, tr("Reject"),
NotifyAcceptAction, tr("Accept"),
NotifyCloseAction, tr("Close") };
d->notifyMessage(msg.arg(CommonUitls::elidedText(nick, Qt::ElideMiddle, 25)), actions, 10 * 1000);
#else
d->transDialog()->showConfirmDialog(nick);
#endif
}
void TransferHelper::handleCancelTransferApply()
{
static QString body(tr("The other party has cancelled the transfer request !"));
#ifdef __linux__
d->notifyMessage(body, {}, 3 * 1000);
d->notice->resetNotifyId();
#else
d->transDialog()->showResultDialog(false, body);
#endif
}
void TransferHelper::onConnectStatusChanged(int result, const QString &msg, const bool isself)
{
LOG << "connect status: " << result << " msg:" << msg.toStdString();
if (result > 0) {
if (!isself)
return;
d->status.storeRelease(Confirming);
} else {
if (Idle == d->status.loadAcquire())
return;
d->status.storeRelease(Idle);
transferResult(false, tr("Connect to \"%1\" failed").arg(msg));
}
}
void TransferHelper::onTransChanged(int status, const QString &path, quint64 size)
{
#ifdef QT_DEBUG
// DLOG << "status: " << status << " path=" << path.toStdString();
#endif
switch (status) {
case TRANS_CANCELED:
cancelTransfer(false);
break;
case TRANS_EXCEPTION:
// exception reason: "io_error" "net_error" "not_found" "fs_exception"
d->status.storeRelease(Idle);
if (path == "io_error") {
transferResult(false, tr("Insufficient storage space, file delivery failed this time. Please clean up disk space and try again!"));
} else if (path == "net_error") {
transferResult(false, tr("Network not connected, file delivery failed this time. Please connect to the network and try again!"));
} else {
transferResult(false, tr("File read/write exception"));
}
break;
case TRANS_COUNT_SIZE:
// only update the total size while rpc notice
d->transferInfo.totalSize = size;
break;
case TRANS_WHOLE_START:
d->status.storeRelease(Transfering);
updateTransProgress(0);
break;
case TRANS_WHOLE_FINISH:
d->status.storeRelease(Idle);
if (d->role == Client) {
d->recvFilesSavePath = NetworkUtil::instance()->getStorageFolder();
HistoryManager::instance()->writeIntoTransHistory(NetworkUtil::instance()->getConfirmTargetAddress(), d->recvFilesSavePath);
}
transferResult(true, tr("File sent successfully"));
break;
case TRANS_INDEX_CHANGE:
break;
case TRANS_FILE_CHANGE:
break;
case TRANS_FILE_SPEED: {
d->transferInfo.transferSize += size;
d->transferInfo.maxTimeS += 1; // 每1秒收到此信息
updateTransProgress(d->transferInfo.transferSize);
// double speed = (static_cast<double>(size)) / (1024 * 1024); // 计算下载速度,单位为兆字节/秒
// QString formattedSpeed = QString::number(speed, 'f', 2); // 格式化速度为保留两位小数的字符串
// DLOG << "Transfer speed: " << formattedSpeed.toStdString() << " M/s";
} break;
case TRANS_FILE_DONE:
break;
}
}
void TransferHelper::updateTransProgress(uint64_t current)
{
QTime time(0, 0, 0);
if (d->transferInfo.totalSize < 1) {
// the total has not been set.
updateProgress(0, time.toString("hh:mm:ss"));
return;
}
// 计算整体进度和预估剩余时间
double value = static_cast<double>(current) / d->transferInfo.totalSize;
int progressValue = static_cast<int>(value * 100);
int remain_time;
if (progressValue <= 0) {
return;
} else if (progressValue >= 100) {
progressValue = 100;
remain_time = 0;
} else {
remain_time = (d->transferInfo.maxTimeS * 100 / progressValue - d->transferInfo.maxTimeS);
}
time = time.addSecs(remain_time);
#ifdef QT_DEBUG
// DLOG << "progressbar: " << progressValue << " remain_time=" << remain_time;
// DLOG << "totalSize: " << d->transferInfo.totalSize << " transferSize=" << current;
#endif
updateProgress(progressValue, time.toString("hh:mm:ss"));
}
void TransferHelper::waitForConfirm()
{
d->isTransTimeout = false;
d->transferInfo.clear();
d->recvFilesSavePath.clear();
// 超时处理
d->confirmTimer.start();
d->transDialog()->showWaitConfirmDialog();
}
void TransferHelper::accepted()
{
if (!d->status.testAndSetRelease(Confirming, Transfering)) {
d->status.storeRelease(Idle);
return;
}
d->role = Server;
d->status.storeRelease(Transfering);
updateProgress(1, tr("calculating"));
NetworkUtil::instance()->doSendFiles(d->readyToSendFiles);
}
void TransferHelper::rejected()
{
DLOG << "file transfer rejected >>> ";
d->status.storeRelease(Idle);
if (!d->isTransTimeout)
transferResult(false, tr("The other party rejects your request"));
d->transDialog()->hide();
}
void TransferHelper::cancelTransfer(bool click)
{
if (Idle == d->status.loadAcquire()) {
WLOG << "Transfer Idle, ignore cancel again!";
return;
}
d->status.storeRelease(Idle);
if (click) {
// just hide dislog if user click cancel button
d->transDialog()->hide();
} else {
transferResult(false, tr("The other party has canceled the file transfer"));
}
}
void TransferHelper::cancelTransferApply()
{
d->status.storeRelease(Idle);
d->confirmTimer.stop();
d->transDialog()->hide();
NetworkUtil::instance()->cancelApply("transfer");
}
// ----------compat the old protocol-----------
void TransferHelper::compatTransJobStatusChanged(int id, int result, const QString &msg)
{
LOG << "id: " << id << " result: " << result << " msg: " << msg.toStdString();
switch (result) {
case JOB_TRANS_FAILED:
if (Server == d->role) {
// Cancel by self clicked
d->status.storeRelease(Idle);
d->transDialog()->hide();
return;
}
if (msg.contains("::not enough")) {
transferResult(false, tr("Insufficient storage space, file delivery failed this time. Please clean up disk space and try again!"));
} else if (msg.contains("::off line")) {
transferResult(false, tr("Network not connected, file delivery failed this time. Please connect to the network and try again!"));
} else {
transferResult(false, tr("File read/write exception"));
}
break;
case JOB_TRANS_DOING:
d->status.storeRelease(Transfering);
break;
case JOB_TRANS_FINISHED: {
d->status.storeRelease(Idle);
d->recvFilesSavePath = msg;
if (d->role == Client) {
// get ip address
QRegularExpression ipRegex(R"((\d{1,3}\.){3}\d{1,3})");
QRegularExpressionMatch match = ipRegex.match(msg);
QString ip = match.hasMatch() ? match.captured(0) : "";
HistoryManager::instance()->writeIntoTransHistory(ip, d->recvFilesSavePath);
}
transferResult(true, tr("File sent successfully"));
} break;
case JOB_TRANS_CANCELED:
d->status.storeRelease(Idle);
transferResult(false, tr("The other party has canceled the file transfer"));
break;
default:
break;
}
}
void TransferHelper::compatFileTransStatusChanged(quint64 total, quint64 current, quint64 millisec)
{
d->transferInfo.totalSize = total;
d->transferInfo.transferSize = current;
d->transferInfo.maxTimeS = millisec / 1000;
// 计算整体进度和预估剩余时间
double value = static_cast<double>(d->transferInfo.transferSize) / d->transferInfo.totalSize;
int progressValue = static_cast<int>(value * 100);
QTime time(0, 0, 0);
int remain_time;
if (progressValue <= 0) {
return;
} else if (progressValue >= 100) {
progressValue = 100;
remain_time = 0;
} else {
remain_time = (d->transferInfo.maxTimeS * 100 / progressValue - d->transferInfo.maxTimeS);
}
time = time.addSecs(remain_time);
// LOG << "progressbar: " << progressValue << " remain_time=" << remain_time;
// LOG << "totalSize: " << d->transferInfo.totalSize << " transferSize=" << d->transferInfo.transferSize;
updateProgress(progressValue, time.toString("hh:mm:ss"));
}
void TransferHelper::onTransferExcepted(int type, const QString &remote)
{
if (Idle == d->status.loadAcquire()) {
WLOG << "Transfer Idle, ignore exception:" << type << " " << remote.toStdString();
return;
}
cancelTransfer(true); // hide dialog first and show exception
// cancel transfer and hide progress
NetworkUtil::instance()->cancelTrans();
switch (type) {
case EX_NETWORK_PINGOUT:
transferResult(false, tr("Network not connected, file delivery failed this time. Please connect to the network and try again!"));
break;
case EX_SPACE_NOTENOUGH:
transferResult(false, tr("Insufficient storage space, file delivery failed this time. Please clean up disk space and try again!"));
break;
case EX_FS_RWERROR: {
transferResult(false, tr("File read/write exception"));
} break;
case EX_OTHER:
default:
break;
}
}