forked from cool2528/baiduCDP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WkeWindow.cpp
2533 lines (2453 loc) · 84.5 KB
/
WkeWindow.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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "WkeWindow.h"
#include <shlwapi.h>
#include <WinInet.h>
#include <io.h>
#include <fstream>
#include <stdexcept>
#include <boost/format.hpp>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "CEncryption.h"
#include "resource.h"
#pragma comment(lib,"Wininet.lib")
#pragma comment(lib,"shlwapi.lib")
#pragma warning(disable:4996)
std::mutex g_mutx;
std::shared_ptr<CWkeWindow> CWkeWindow::Instance = nullptr;
WNDPROC CWkeWindow::m_oldProc = NULL;
void* CWkeWindow::AlloclocalHeap(const std::string& strBuffer)
{
char* pResutPtr = nullptr;
if (strBuffer.empty())
return pResutPtr;
int nLen = strBuffer.length() + 1;
pResutPtr = new char[nLen];
if (!pResutPtr)
return pResutPtr;
ZeroMemory(pResutPtr, nLen);
CopyMemory(pResutPtr, strBuffer.c_str(),strBuffer.length());
return pResutPtr;
}
#if 1
void CWkeWindow::ParseAria2JsonInfo(const std::string& strJSon)
{
rapidjson::Document dc;
dc.Parse(strJSon.c_str());
if (!dc.IsObject())
return;
std::string strDownStatus;
std::string strGidItem;
if (dc.HasMember("method") && dc["method"].IsString())
{
strDownStatus = dc["method"].GetString();
if (dc.HasMember("params") && dc["params"].IsArray())
{
for (auto &v : dc["params"].GetArray())
{
if (!v.IsObject())
continue;
if (v.HasMember("gid") && v["gid"].IsString())
strGidItem = v["gid"].GetString();
}
}
if (strDownStatus == ARIA2_DOWNLOAD_COMPLATE)
{
PVOID sendPtr = AlloclocalHeap(strGidItem);
::PostMessage(m_hwnd, ARIA2_DOWNLOAD_COMPLATE_MSG, NULL, (LPARAM)sendPtr);
}
else if (strDownStatus == ARIA2_DOWNLOAD_START)
{
PVOID sendPtr = AlloclocalHeap(strGidItem);
::PostMessage(m_hwnd, ARIA2_DOWNLOAD_START_MSG, NULL, (LPARAM)sendPtr);
}
else if (strDownStatus == ARIA2_DOWNLOAD_STOP)
{
PVOID sendPtr = AlloclocalHeap(strGidItem);
::PostMessage(m_hwnd, ARIA2_DOWNLOAD_STOP_MSG, NULL, (LPARAM)sendPtr);
}
else if (strDownStatus == ARIA2_DOWNLOAD_PAUSE)
{
PVOID sendPtr = AlloclocalHeap(strGidItem);
::PostMessage(m_hwnd, ARIA2_DOWNLOAD_PAUSE_MSG, NULL, (LPARAM)sendPtr);
}
else if (strDownStatus == ARIA2_DOWNLOAD_ERROR)
{
PVOID sendPtr = AlloclocalHeap(strGidItem);
::PostMessage(m_hwnd, ARIA2_DOWNLOAD_ERROR_MSG, NULL, (LPARAM)sendPtr);
}
}
if (dc.HasMember("result") && dc["result"].IsArray())
{
if (dc["result"].GetArray().Size()==0)
{
return;
}
//开始组装json发送给UI线程处理渲染到界面
rapidjson::Document sendJson;
sendJson.SetObject();
rapidjson::Value arrlist(rapidjson::kArrayType);
int nErrorcount = 0;
for (auto& v : dc["result"].GetArray())
{
rapidjson::Value sendItemObj(rapidjson::kObjectType);
DOWNFILELISTINFO ItemValue;
ZeroMemory(&ItemValue, sizeof(DOWNFILELISTINFO));
ULONGLONG totalLength, completedLength, downloadSpeed;
if (v.HasMember("totalLength") && v["totalLength"].IsString())
sscanf_s(v["totalLength"].GetString(), "%I64d", &totalLength);
if (v.HasMember("completedLength") && v["completedLength"].IsString())
sscanf_s(v["completedLength"].GetString(), "%I64d", &completedLength);
if (v.HasMember("downloadSpeed") && v["downloadSpeed"].IsString())
sscanf_s(v["downloadSpeed"].GetString(), "%I64d", &downloadSpeed);
if (v.HasMember("connections") && v["connections"].IsString())
ItemValue.connections = v["connections"].GetString();
if (v.HasMember("gid") && v["gid"].IsString())
ItemValue.strFileGid = v["gid"].GetString();
if (v.HasMember("status") && v["status"].IsString())
ItemValue.strStatus = v["status"].GetString();
if (v.HasMember("errorMessage") && v["errorMessage"].IsString() && v.HasMember("errorCode") && v["errorCode"].IsString())
{
nErrorcount++;
ItemValue.nErrCode = atoi(v["errorCode"].GetString());
ItemValue.strErrMessage = v["errorMessage"].GetString();
}
if (v.HasMember("files") && v["files"].IsArray())
{
for (auto& keyval : v["files"].GetArray())
{
if (keyval.HasMember("path") && keyval["path"].IsString())
{
char szName[MAX_PATH];
ZeroMemory(szName, MAX_PATH);
std::string szFileName = m_BaiduPare.Utf8_To_Gbk(keyval["path"].GetString());
ItemValue.strPath = szFileName;
CopyMemory(szName, szFileName.c_str(), szFileName.length());
PathStripPathA(szName);
ItemValue.strFileName = szName;
}
}
}
ItemValue.Downloadpercentage = (size_t)Getpercentage(completedLength, totalLength);
DOWNLOADSPEEDINFO szFileSize = GetFileSizeType(downloadSpeed);
int isRate = 0;
if (szFileSize.strUnit =="B")
{
ItemValue.DownloadSpeed = str(boost::format("%.1f B") % szFileSize.dwSize);
isRate = 1;
}else if (szFileSize.strUnit == "KB")
{
ItemValue.DownloadSpeed = str(boost::format("%.1f KB") % szFileSize.dwSize);
if(szFileSize.dwSize<100)
isRate = 1;
}
else if (szFileSize.strUnit == "MB")
{
ItemValue.DownloadSpeed = str(boost::format("%.1f MB") % szFileSize.dwSize);
}
else if (szFileSize.strUnit == "GB")
{
ItemValue.DownloadSpeed = str(boost::format("%.1f GB") % szFileSize.dwSize);
}
rapidjson::Value isRateLimiting(rapidjson::kNumberType); //是否限速
isRateLimiting.SetInt(isRate);
sendItemObj.AddMember(rapidjson::StringRef("isRateLimiting"), isRateLimiting, sendJson.GetAllocator());
rapidjson::Value connections(rapidjson::kStringType);//当前服务器下载链接数量
connections.SetString(ItemValue.connections.c_str(), ItemValue.connections.length(), sendJson.GetAllocator());
sendItemObj.AddMember(rapidjson::StringRef("connections"), connections, sendJson.GetAllocator());
rapidjson::Value downloadSpeedItem(rapidjson::kStringType);//下载速度每秒
downloadSpeedItem.SetString(ItemValue.DownloadSpeed.c_str(), ItemValue.DownloadSpeed.length(), sendJson.GetAllocator());
sendItemObj.AddMember(rapidjson::StringRef("downloadSpeed"), downloadSpeedItem, sendJson.GetAllocator());
rapidjson::Value FileName(rapidjson::kStringType);//当前任务的文件名
FileName.SetString(ItemValue.strFileName.c_str(), ItemValue.strFileName.length(), sendJson.GetAllocator());
sendItemObj.AddMember(rapidjson::StringRef("name"), FileName, sendJson.GetAllocator());
rapidjson::Value Gid(rapidjson::kStringType);//当前任务GID唯一标识符
Gid.SetString(ItemValue.strFileGid.c_str(), ItemValue.strFileGid.length(), sendJson.GetAllocator());
sendItemObj.AddMember(rapidjson::StringRef("gid"), Gid, sendJson.GetAllocator());
rapidjson::Value Downloadpercentage(rapidjson::kNumberType);//当前下载的百分百
Downloadpercentage.SetUint(ItemValue.Downloadpercentage);
sendItemObj.AddMember(rapidjson::StringRef("progress"), Downloadpercentage, sendJson.GetAllocator());
rapidjson::Value nErrCode(rapidjson::kNumberType);//下载错误代码
nErrCode.SetUint(ItemValue.nErrCode);
sendItemObj.AddMember(rapidjson::StringRef("errorCode"), nErrCode, sendJson.GetAllocator());
rapidjson::Value ErrMessage(rapidjson::kStringType);//下载错误原因
ErrMessage.SetString(ItemValue.strErrMessage.c_str(), ItemValue.strErrMessage.length(), sendJson.GetAllocator());
sendItemObj.AddMember(rapidjson::StringRef("errorMessage"), ErrMessage, sendJson.GetAllocator());
rapidjson::Value status(rapidjson::kStringType);//下载文件状态
status.SetString(ItemValue.strStatus.c_str(), ItemValue.strStatus.length(), sendJson.GetAllocator());
sendItemObj.AddMember(rapidjson::StringRef("status"), status, sendJson.GetAllocator());
rapidjson::Value strPath(rapidjson::kStringType);//下载文件路径
strPath.SetString(ItemValue.strPath.c_str(), ItemValue.strPath.length(), sendJson.GetAllocator());
sendItemObj.AddMember(rapidjson::StringRef("path"), strPath, sendJson.GetAllocator());
arrlist.PushBack(sendItemObj, sendJson.GetAllocator());
}
//发送给UI线程
sendJson.AddMember(rapidjson::StringRef("data"), arrlist, sendJson.GetAllocator());
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
sendJson.Accept(writer);
std::string strResultJson = buffer.GetString();
strResultJson = m_BaiduPare.Gbk_To_Utf8(strResultJson.c_str());
PVOID pSendDataPtr = AlloclocalHeap(strResultJson);
if (!nErrorcount)
{
::PostMessage(m_hwnd, ARIA2_UPDATE_TELLACTIVE_LIST_MSG, NULL, (LPARAM)pSendDataPtr);
}
}
if (dc.HasMember("result") && dc["result"].IsObject())
{
rapidjson::Value itemObj = dc["result"].GetObjectW();
if (itemObj.HasMember("numActive") && itemObj["numActive"].IsString())
numActive = atol(itemObj["numActive"].GetString());
if (itemObj.HasMember("numStopped") && itemObj["numStopped"].IsString())
numStopped = atol(itemObj["numStopped"].GetString());
if (itemObj.HasMember("numWaiting") && itemObj["numWaiting"].IsString())
numWaiting = atol(itemObj["numWaiting"].GetString());
}
}
#endif
DOWNLOADSPEEDINFO CWkeWindow::GetFileSizeType(double dSize)
{
DOWNLOADSPEEDINFO szFileSize;
ZeroMemory(&szFileSize, sizeof(DOWNLOADSPEEDINFO));
if (dSize <1024)
{
szFileSize.dwSize = m_BaiduPare.roundEx(dSize);
szFileSize.strUnit = "B";
}
else if (dSize >1024 && dSize < 1024 * 1024 * 1024 && dSize <1024 * 1024)
{
szFileSize.dwSize = m_BaiduPare.roundEx(dSize / 1024);
szFileSize.strUnit = "KB";
}
else if (dSize >1024 * 1024 && dSize <1024 * 1024 * 1024)
{
szFileSize.dwSize = m_BaiduPare.roundEx(dSize / 1024 / 1024);
szFileSize.strUnit = "MB";
}
else if (dSize >1024 * 1024 * 1024)
{
szFileSize.dwSize = m_BaiduPare.roundEx(dSize / 1024 / 1024 / 1024);
szFileSize.strUnit = "GB";
}
return szFileSize;
}
double CWkeWindow::Getpercentage(double completedLength, double totalLength)
{
return completedLength / totalLength * 100;
}
LRESULT CALLBACK CWkeWindow::MainProc(_In_ HWND hwnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam)
{
static int index = 0;
switch (uMsg)
{
case ARIA2_UPDATE_TELLACTIVE_LIST_MSG: //更新当前正在下载的任务列表
{
if (lParam)
{
const char* pbuffer = (const char*)lParam;
std::string strJsonData(pbuffer);
delete pbuffer;
GetInstance()->UpdateDownloadList(strJsonData);
}
}
break;
case ARIA2_PURGEDOWNLOAD_MSG: //清除下载错误的内存缓存
{
if (lParam)
{
const char* pbuffer = (const char*)lParam;
std::string strJsonData(pbuffer);
LOG(INFO) << "清除下载错误内存缓存" << strJsonData.c_str();
delete pbuffer;
GetInstance()->SendText(GetInstance()->m_BaiduPare.Gbk_To_Utf8(strJsonData.c_str()));
}
}
break;
case ARIA2_RETRYADDURL_MSG: //从新下载添加
{
if (lParam)
{
const char* pbuffer = (const char*)lParam;
std::string strJsonData(pbuffer);
delete pbuffer;
LOG(INFO) << "重新下载添加" << strJsonData.c_str();
GetInstance()->SendText(strJsonData);
}
}
break;
case ARIA2_UPDATE_TELLERROR_LIST_MSG://更新下载失败的文件任务列表
{
if (lParam)
{
const char* pbuffer = (const char*)lParam;
std::string strJsonData(pbuffer);
delete pbuffer;
static auto updateErrorList = [](const std::string strJosn) {
jsExecState es = wkeGlobalExec(app.window);
jsValue thisObject = jsGetGlobal(es, "app");
jsValue func = jsGet(es, thisObject, "updatedownloadErrorList");
jsValue jsArg[1] = { jsString(es, strJosn.c_str()) };
jsCall(es, func, thisObject, jsArg, 1);
};
LOG(INFO) << "更新下载失败的文件任务列表" << strJsonData.c_str();
updateErrorList(strJsonData);
}
}
break;
case ARIA2_DOWNLOAD_COMPLATE_MSG: //某个任务下载完成
{
if (lParam)
{
const char* pbuffer = (const char*)lParam;
std::string strGID(pbuffer);
delete pbuffer;
HttpRequest aria2_http;
std::string strformat = str(boost::format(ARIA2_TELLSTATUS_SENDDATA) % strGID);
aria2_http.Send(POST, ARIA2_HTTP_REQUESTURL, strformat);
std::string strResult = aria2_http.GetResponseText();
DOWNFILELISTINFO strFileName = GetInstance()->GetTellStatusFileName(strResult);
//更新数据到已下载完成列表
static auto addSussedList = [](const DOWNFILELISTINFO Gid) {
std::string buffer = str(boost::format("{\"name\":\"%1%\",\"ChangeTime\":\"%2%\",\"path\":\"%3%\"}") % Gid.strFileName % GetInstance()->m_BaiduPare.timestampToDate((ULONGLONG)time(NULL)) % Gid.strPath);
buffer = GetInstance()->m_BaiduPare.Gbk_To_Utf8(buffer.c_str());
jsExecState es = wkeGlobalExec(app.window);
jsValue thisObject = jsGetGlobal(es, "app");
jsValue func = jsGet(es, thisObject, "updatedownloadSussedList");
jsValue jsArg[1] = { jsString(es, buffer.c_str()) };
jsCall(es, func, thisObject, jsArg, 1);
};
LOG(INFO) << "某个任务下载完成" << strFileName.strFileName.c_str();
addSussedList(strFileName);
}
}
break;
case ARIA2_DOWNLOAD_START_MSG: //某个任务开始下载
{
if (lParam)
{
const char* pbuffer = (const char*)lParam;
std::string strGID(pbuffer);
delete pbuffer;
LOG(INFO) << "某个任务开始下载" << strGID.c_str();
}
}
break;
case ARIA2_DOWNLOAD_STOP_MSG: //某个任务停止下载 用户手动删除
{
LOG(INFO) << "某个任务停止下载";
if (lParam)
{
const char* pbuffer = (const char*)lParam;
std::string strGID(pbuffer);
delete pbuffer;
HttpRequest aria2_http;
std::string strformat = str(boost::format(ARIA2_TELLSTATUS_SENDDATA) % strGID);
aria2_http.Send(POST, ARIA2_HTTP_REQUESTURL, strformat);
std::string strResult = aria2_http.GetResponseText();
DOWNFILELISTINFO strFileName = GetInstance()->GetTellStatusFileName(strResult);
if (_access(strFileName.strPath.c_str(),0)!=-1)
{
DeleteFileA(strFileName.strPath.c_str());
DeleteFileA((strFileName.strPath+".aria2").c_str());
}
}
}
break;
case ARIA2_DOWNLOAD_PAUSE_MSG: //某个任务 暂停下载
{
LOG(INFO) << "某个任务 暂停下载";
}
break;
case ARIA2_DOWNLOAD_ERROR_MSG: //某个任务下载出错
{
if (lParam)
{
const char* pbuffer = (const char*)lParam;
std::string strGID(pbuffer);
delete pbuffer;
std::string strformat = str(boost::format(ARIA2_TELLSTATUS_SENDDATA) % strGID);
HttpRequest aria2_http;
aria2_http.Send(POST, ARIA2_HTTP_REQUESTURL, strformat);
std::string strResult = GetInstance()->m_BaiduPare.Utf8_To_Gbk(aria2_http.GetResponseText().c_str());
LOG(INFO) << "某个任务下载出错 这里会重新添加下载" << strformat.c_str();
static auto updateErrorList = [](const std::string strJosn) {
jsExecState es = wkeGlobalExec(app.window);
jsValue thisObject = jsGetGlobal(es, "app");
jsValue func = jsGet(es, thisObject, "updatedownloadErrorList");
jsValue jsArg[1] = { jsString(es, strJosn.c_str()) };
jsCall(es, func, thisObject, jsArg, 1);
};
rapidjson::Document dc;
dc.Parse(strResult.c_str());
if (!dc.IsObject())
break;
if (dc.HasMember("result") && dc["result"].IsObject())
{
rapidjson::Value itemObj = dc["result"].GetObjectW();
if (itemObj.HasMember("errorCode") && itemObj["errorCode"].IsString())
{
//开始组装json发送给UI线程处理渲染到界面
rapidjson::Document sendJson;
std::string strRetryUrl;
sendJson.SetObject();
rapidjson::Value sendItemObj(rapidjson::kObjectType);
DOWNFILELISTINFO ItemValue;
ZeroMemory(&ItemValue, sizeof(DOWNFILELISTINFO));
ULONGLONG totalLength, completedLength, downloadSpeed;
if (itemObj.HasMember("totalLength") && itemObj["totalLength"].IsString())
sscanf_s(itemObj["totalLength"].GetString(), "%I64d", &totalLength);
if (itemObj.HasMember("completedLength") && itemObj["completedLength"].IsString())
sscanf_s(itemObj["completedLength"].GetString(), "%I64d", &completedLength);
if (itemObj.HasMember("downloadSpeed") && itemObj["downloadSpeed"].IsString())
sscanf_s(itemObj["downloadSpeed"].GetString(), "%I64d", &downloadSpeed);
if (itemObj.HasMember("connections") && itemObj["connections"].IsString())
ItemValue.connections = itemObj["connections"].GetString();
if (itemObj.HasMember("gid") && itemObj["gid"].IsString())
ItemValue.strFileGid = itemObj["gid"].GetString();
ItemValue.nErrCode = atoi(itemObj["errorCode"].GetString());
ItemValue.strErrMessage = itemObj["errorMessage"].GetString();
if (itemObj.HasMember("files") && itemObj["files"].IsArray())
{
for (auto& keyval : itemObj["files"].GetArray())
{
if (keyval.HasMember("path") && keyval["path"].IsString())
{
char szName[MAX_PATH];
ZeroMemory(szName, MAX_PATH);
std::string szFileName = keyval["path"].GetString();
ItemValue.strPath = szFileName;
CopyMemory(szName, szFileName.c_str(), szFileName.length());
PathStripPathA(szName);
ItemValue.strFileName = szName;
}
if (keyval.HasMember("uris") && keyval["uris"].IsArray())
{
rapidjson::Value urisArr = keyval["uris"].GetArray();
if (urisArr.Size())
{
if (urisArr[0].HasMember("uri") && urisArr[0]["uri"].IsString())
{
strRetryUrl = urisArr[0]["uri"].GetString();
}
}
}
}
}
ItemValue.Downloadpercentage = (size_t)GetInstance()->Getpercentage(completedLength, totalLength);
DOWNLOADSPEEDINFO szFileSize = GetInstance()->GetFileSizeType(downloadSpeed);
int isRate = 0;
if (szFileSize.strUnit == "B")
{
ItemValue.DownloadSpeed = str(boost::format("%.1f B") % szFileSize.dwSize);
isRate = 1;
}
else if (szFileSize.strUnit == "KB")
{
ItemValue.DownloadSpeed = str(boost::format("%.1f KB") % szFileSize.dwSize);
if (szFileSize.dwSize < 100)
isRate = 1;
}
else if (szFileSize.strUnit == "MB")
{
ItemValue.DownloadSpeed = str(boost::format("%.1f MB") % szFileSize.dwSize);
}
else if (szFileSize.strUnit == "GB")
{
ItemValue.DownloadSpeed = str(boost::format("%.1f GB") % szFileSize.dwSize);
}
rapidjson::Value isRateLimiting(rapidjson::kNumberType); //是否限速
isRateLimiting.SetInt(isRate);
sendItemObj.AddMember(rapidjson::StringRef("isRateLimiting"), isRateLimiting, sendJson.GetAllocator());
rapidjson::Value connections(rapidjson::kStringType);//当前服务器下载链接数量
connections.SetString(ItemValue.connections.c_str(), ItemValue.connections.length(), sendJson.GetAllocator());
sendItemObj.AddMember(rapidjson::StringRef("connections"), connections, sendJson.GetAllocator());
rapidjson::Value downloadSpeedItem(rapidjson::kStringType);//下载速度每秒
downloadSpeedItem.SetString(ItemValue.DownloadSpeed.c_str(), ItemValue.DownloadSpeed.length(), sendJson.GetAllocator());
sendItemObj.AddMember(rapidjson::StringRef("downloadSpeed"), downloadSpeedItem, sendJson.GetAllocator());
rapidjson::Value FileName(rapidjson::kStringType);//当前任务的文件名
FileName.SetString(ItemValue.strFileName.c_str(), ItemValue.strFileName.length(), sendJson.GetAllocator());
sendItemObj.AddMember(rapidjson::StringRef("name"), FileName, sendJson.GetAllocator());
rapidjson::Value Gid(rapidjson::kStringType);//当前任务GID唯一标识符
Gid.SetString(ItemValue.strFileGid.c_str(), ItemValue.strFileGid.length(), sendJson.GetAllocator());
sendItemObj.AddMember(rapidjson::StringRef("gid"), Gid, sendJson.GetAllocator());
rapidjson::Value Downloadpercentage(rapidjson::kNumberType);//当前下载的百分百
Downloadpercentage.SetUint(ItemValue.Downloadpercentage);
sendItemObj.AddMember(rapidjson::StringRef("progress"), Downloadpercentage, sendJson.GetAllocator());
rapidjson::Value nErrCode(rapidjson::kNumberType);//下载错误代码
nErrCode.SetUint(ItemValue.nErrCode);
sendItemObj.AddMember(rapidjson::StringRef("errorCode"), nErrCode, sendJson.GetAllocator());
rapidjson::Value ErrMessage(rapidjson::kStringType);//下载错误原因
ErrMessage.SetString(ItemValue.strErrMessage.c_str(), ItemValue.strErrMessage.length(), sendJson.GetAllocator());
sendItemObj.AddMember(rapidjson::StringRef("errorMessage"), ErrMessage, sendJson.GetAllocator());
rapidjson::Value strPath(rapidjson::kStringType);//下载文件路径
strPath.SetString(ItemValue.strPath.c_str(), ItemValue.strPath.length(), sendJson.GetAllocator());
sendItemObj.AddMember(rapidjson::StringRef("path"), strPath, sendJson.GetAllocator());
//发送给UI线程
sendJson.AddMember(rapidjson::StringRef("data"), sendItemObj, sendJson.GetAllocator());
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
sendJson.Accept(writer);
std::string strResultJson = buffer.GetString();
strResultJson = GetInstance()->m_BaiduPare.Gbk_To_Utf8(strResultJson.c_str());
updateErrorList(strResultJson);
if (_access(ItemValue.strPath.c_str(), 0) != -1 && _access((ItemValue.strPath + ".aria2").c_str(), 0) != -1)
{
DeleteFileA(ItemValue.strPath.c_str());
DeleteFileA((ItemValue.strPath + ".aria2").c_str());
}
}
}
}
}
break;
case UI_DOWNLOAD_SHARE_UPDATE_LIST:
{
static auto updateDownloadShareListdata = [](const std::string strJosn) {
jsExecState es = wkeGlobalExec(app.window);
jsValue thisObject = jsGetGlobal(es, "app");
jsValue func = jsGet(es, thisObject, "updateDownloadShare");
jsValue jsArg[1] = { jsString(es, strJosn.c_str()) };
jsCall(es, func, thisObject, jsArg, 1);
};
if (lParam)
{
const char* pbuffer = (const char*)lParam;
std::string strGID(pbuffer);
delete pbuffer;
updateDownloadShareListdata(strGID);
}
}
break;
case UI_UPDATE_FOLODER_LIST_MSG:
{
if (lParam)
{
const char* pbuffer = (const char*)lParam;
std::string strResultJson(pbuffer);
delete pbuffer;
jsExecState es = wkeGlobalExec(app.window);
jsValue thisObject = jsGetGlobal(es, "app");
bool b = jsIsObject(thisObject);
jsValue func = jsGet(es, thisObject, "updateTreeListData");
strResultJson = GetInstance()->m_BaiduPare.Gbk_To_Utf8(strResultJson.c_str());
jsValue jsArg[1] = { jsString(es, strResultJson.c_str()) };
jsCall(es, func, thisObject, jsArg, 1);
}
}
break;
case UI_UPDATE_OFF_LINE_LIST_MSG:
{
if (lParam)
{
const char* pbuffer = (const char*)lParam;
std::string strResultJson(pbuffer);
delete pbuffer;
jsExecState es = wkeGlobalExec(app.window);
jsValue thisObject = jsGetGlobal(es, "app");
bool b = jsIsObject(thisObject);
jsValue func = jsGet(es, thisObject, "updateOfflineTableList");
//strResultJson = GetInstance()->m_BaiduPare.Gbk_To_Utf8(strResultJson.c_str());
jsValue jsArg[1] = { jsString(es, strResultJson.c_str()) };
jsCall(es, func, thisObject, jsArg, 1);
}
}
break;
case UI_UPDATE_USER_FILE_DATA_MSG:
{
if (lParam)
{
const char* pbuffer = (const char*)lParam;
std::string strResultJson(pbuffer);
delete pbuffer;
jsExecState es = wkeGlobalExec(app.window);
jsValue thisObject = jsGetGlobal(es, "app");
bool b = jsIsObject(thisObject);
jsValue func = jsGet(es, thisObject, "updateBaiduList");
jsValue jsArg[1] = { jsString(es, strResultJson.c_str()) };
jsCall(es, func, thisObject, jsArg, 1);
}
}
break;
case UI_QUIT_MSG:
{
::PostQuitMessage(0);
}
break;
case UI_SHOW_ERROR_MSG:
{
static auto showErrormsg = [](std::string& Strmsg) {
std::string buffer = Strmsg;
buffer = GetInstance()->m_BaiduPare.Gbk_To_Utf8(buffer.c_str());
jsExecState es = wkeGlobalExec(app.window);
jsValue thisObject = jsGetGlobal(es, "app");
jsValue func = jsGet(es, thisObject, "showErrorMessage");
jsValue jsArg[1] = { jsString(es, buffer.c_str()) };
jsCall(es, func, thisObject, jsArg, 1);
};
if (lParam)
{
const char* pbuffer = (const char*)lParam;
std::string strResultJson(pbuffer);
delete pbuffer;
showErrormsg(strResultJson);
}
}
default:
break;
}
return CallWindowProc(m_oldProc, hwnd, uMsg, wParam, lParam);
}
void CWkeWindow::AddShareFileItem(REQUESTINFO item)
{
bool bResult = false;
for (size_t i =0;i<m_ShareFileArray.size();i++)
{
auto & value = m_ShareFileArray.at(i);
if (value.strFileName == item.strFileName)
{
bResult = true;
break;
}
}
if (!bResult)
m_ShareFileArray.push_back(item);
}
void CWkeWindow::GetShareFileItem(const std::string& strFileName,REQUESTINFO& Result)
{
for (size_t i=0;i<m_ShareFileArray.size();i++)
{
auto & value = m_ShareFileArray.at(i);
if (value.strFileName == strFileName)
{
Result.strCookies = value.strCookies;
Result.strDownloadUrl = value.strDownloadUrl;
Result.strFileName = value.strFileName;
Result.strSavePath = value.strSavePath;
break;
}
}
}
bool CWkeWindow::IsRetryCountFinish(const std::string& strFileName)
{
bool bResult = false;
for (size_t i =0;i<m_RetryArray.size();i++)
{
auto & value = m_RetryArray.at(i);
if (value.strFileName == strFileName && value.nCount > 10)
{
bResult = true;
break;
}
}
return bResult;
}
bool CWkeWindow::IsRetryExist(const std::string& strFileName)
{
bool bResult = false;
RETRYCOUNT item;
ZeroMemory(&item, sizeof(RETRYCOUNT));
for (size_t i = 0; i < m_RetryArray.size(); i++)
{
auto & value = m_RetryArray.at(i);
if (value.strFileName == strFileName)
{
bResult = true;
break;
}
}
if (!bResult)
{
item.strFileName = strFileName;
m_RetryArray.push_back(item);
}
return bResult;
}
void CWkeWindow::addRetryCount(const std::string& strFileName)
{
for (size_t i = 0; i < m_RetryArray.size(); i++)
{
auto & value = m_RetryArray.at(i);
if (value.strFileName == strFileName)
{
value.nCount++;
break;
}
}
}
DOWNFILELISTINFO CWkeWindow::GetFileCompletedInfo(const std::string& strGid)
{
std::string StrJson="{\"data\":";
DOWNFILELISTINFO strResult;
ZeroMemory(&strResult, sizeof(DOWNFILELISTINFO));
jsExecState es = wkeGlobalExec(app.window);
jsValue thisObject = jsGetGlobal(es, "app");
jsValue func = jsGet(es, thisObject, "GetBackupListString");
jsValue rString = jsCall(es, func, thisObject, nullptr, 0);
jsType Type = jsTypeOf(rString);
StrJson += jsToTempString(es, rString);
StrJson += "}";
rapidjson::Document dc;
dc.Parse(StrJson.c_str());
if (!dc.IsObject())
return strResult;
if (dc.HasMember("data") && dc["data"].IsArray())
{
for (auto& v:dc["data"].GetArray())
{
if (v.HasMember("gid") && v["gid"].IsString())
{
if (strGid == v["gid"].GetString())
{
if (v.HasMember("name") && v["name"].IsString())
strResult.strFileName = m_BaiduPare.Utf8_To_Gbk(v["name"].GetString());
if (v.HasMember("path") && v["path"].IsString())
strResult.strPath = m_BaiduPare.Utf8_To_Gbk(v["path"].GetString());
}
}
}
}
return strResult;
}
DOWNFILELISTINFO CWkeWindow::GetTellStatusFileName(const std::string& strJSon)
{
DOWNFILELISTINFO strResult;
rapidjson::Document dc;
dc.Parse(strJSon.c_str());
if (!dc.IsObject())
{
return strResult;
}
if (dc.HasMember("result") && dc["result"].IsObject())
{
rapidjson::Value itemObj = dc["result"].GetObjectW();
if (itemObj.HasMember("files") && itemObj["files"].IsArray())
{
for (auto& keyval : itemObj["files"].GetArray())
{
if (keyval.HasMember("path") && keyval["path"].IsString())
{
char szName[MAX_PATH];
ZeroMemory(szName, MAX_PATH);
std::string szFileName = m_BaiduPare.Utf8_To_Gbk(keyval["path"].GetString());
strResult.strPath = szFileName;
CopyMemory(szName, szFileName.c_str(), szFileName.length());
PathStripPathA(szName);
strResult.strFileName = szName;
}
}
}
}
return strResult;
}
#if 1
void CWkeWindow::on_socket_init(websocketpp::connection_hdl hdl)
{
}
void CWkeWindow::on_message(websocketpp::connection_hdl hdl, message_ptr msg)
{
DWORD dwThread = ::GetThreadId(::GetCurrentThread());
websocketpp::frame::opcode::value opcodes = msg->get_opcode();
if (opcodes == websocketpp::frame::opcode::text)
{
std::string strMsgText = msg->get_payload();
ParseAria2JsonInfo(strMsgText);
}
}
void CWkeWindow::on_open(websocketpp::connection_hdl hdl)
{
m_hdl = hdl;
}
void CWkeWindow::on_close(websocketpp::connection_hdl hdl)
{
hdl.reset();
}
void CWkeWindow::on_fail(websocketpp::connection_hdl hdl)
{
LOG(ERROR) << "websoket启动失败";
::PostMessage(m_hwnd, UI_SHOW_ERROR_MSG, NULL, (LPARAM)AlloclocalHeap("websoket启动失败,请右键管理员身份运行"));
hdl.reset();
}
void CWkeWindow::start(std::string uri)
{
websocketpp::lib::error_code ec;
client::connection_ptr con = m_WssClient.get_connection(uri, ec);
if (ec) {
LOG(ERROR) << "启动wss环境失败";
return;
}
m_WssClient.connect(con);
m_WssClient.run();
}
void CWkeWindow::Connect()
{
try{
start("ws://127.0.0.1:6810/jsonrpc");
}
catch (websocketpp::exception const & e) {
//std::cout << e.what() << std::endl;
LOG(ERROR) << e.what();
}
catch (std::exception const & e) {
//std::cout << e.what() << std::endl;
LOG(ERROR) << e.what();
}
catch (...) {
LOG(ERROR) <<"void CWkeWindow::Connect() 未知的异常";
}
}
void CWkeWindow::SendText(std::string& strText)
{
if (m_hdl.lock().get())
{
//m_BaiduPare.WriteFileBuffer(".\\1.txt",(char*)strText.c_str(), strText.length());
m_WssClient.send(m_hdl, strText, websocketpp::frame::opcode::text);
}
}
#endif
BOOL CWkeWindow::RunAria2()
{
STARTUPINFOA si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
si.dwFlags = STARTF_USESHOWWINDOW; // 指定wShowWindow成员有效
#if !_DEBUG
si.wShowWindow = false; // 此成员设为TRUE的话则显示新建进程的主窗口,
std::string strCommandlineArg = str(boost::format("aria2c.exe --check-certificate=false --disable-ipv6=true --enable-rpc=true --quiet=true --file-allocation=falloc --max-concurrent-downloads=5 --rpc-allow-origin-all=true --rpc-listen-all=true --rpc-listen-port=6810 --rpc-secret=CDP --stop-with-process=%1%")\
% std::to_string(GetCurrentProcessId()));
#else
si.wShowWindow = true; // 此成员设为TRUE的话则显示新建进程的主窗口,
std::string strCommandlineArg = str(boost::format("aria2c.exe --check-certificate=false --disable-ipv6=true --enable-rpc=true --quiet=false --file-allocation=falloc --max-concurrent-downloads=5 --rpc-allow-origin-all=true --rpc-listen-all=true --rpc-listen-port=6810 --rpc-secret=CDP --stop-with-process=%1%")\
% std::to_string(GetCurrentProcessId()));
#endif
BOOL bRet = ::CreateProcessA(NULL, // 不在此指定可执行文件的文件名
const_cast<char*>(strCommandlineArg.c_str()), // 命令行参数
NULL, // 默认进程安全性
NULL, // 默认线程安全性
FALSE, // 指定当前进程内的句柄不可以被子进程继承
CREATE_NEW_CONSOLE, // 为新进程创建一个新的控制台窗口
NULL, // 使用本进程的环境变量
NULL, // 使用本进程的驱动器和目录
&si,
&pi);
::CloseHandle(pi.hProcess);
return bRet;
}
void CALLBACK CWkeWindow::TimeProc(HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime)
{
#if 1
GetInstance()->SendText(GetInstance()->m_BaiduPare.Gbk_To_Utf8(ARIA2_GETGLOBAL_STATUS));
if (GetInstance()->numActive > 0 || GetInstance()->numWaiting > 0)
{
std::string strWaiting;
GetInstance()->SendText(GetInstance()->m_BaiduPare.Gbk_To_Utf8(ARIA2_TELLACTICE_SENDDATA));
strWaiting = str(boost::format(ARIA2_TELLSTOPPED) % GetInstance()->numStopped);
GetInstance()->SendText(GetInstance()->m_BaiduPare.Gbk_To_Utf8(strWaiting.c_str()));
strWaiting = str(boost::format(ARIA2_TELLWAITING) % GetInstance()->numWaiting);
GetInstance()->SendText(GetInstance()->m_BaiduPare.Gbk_To_Utf8(strWaiting.c_str()));
wkeRunJS(app.window, "app.backupdownloadListinfo = app.downloadListinfo;");
}
if (GetInstance()->numActive == 0 && GetInstance()->numWaiting == 0)
{
GetInstance()->UpdateDownloadList("{\"data\":[]}");
}
#endif
}
void CWkeWindow::runApp(Application* app)
{
DWORD dwThread = ::GetThreadId(::GetCurrentThread());
memset(app, 0, sizeof(Application));
app->url = L"http://baiducdp.com/ui/element.html"; // 使用hook的方式加载资源
if (!createWebWindow(app)) {
PostQuitMessage(0);
return;
}
runMessageLoop(app);
}
std::string CWkeWindow::CarkUrl(const char* url)
{
std::string result = "http://";
URL_COMPONENTSA uc;
char Scheme[1000];
char HostName[1000];
char UserName[1000];
char Password[1000];
char UrlPath[1000];
char ExtraInfo[1000];
uc.dwStructSize = sizeof(uc);
uc.lpszScheme = Scheme;
uc.lpszHostName = HostName;
uc.lpszUserName = UserName;
uc.lpszPassword = Password;
uc.lpszUrlPath = UrlPath;
uc.lpszExtraInfo = ExtraInfo;
uc.dwSchemeLength = 1000;
uc.dwHostNameLength = 1000;
uc.dwUserNameLength = 1000;
uc.dwPasswordLength = 1000;
uc.dwUrlPathLength = 1000;
uc.dwExtraInfoLength = 1000;
InternetCrackUrlA(url, 0, 0, &uc);
return (result += HostName);
}
bool CWkeWindow::InintMiniBlink()
{
bool bResult = false;
std::vector<wchar_t> mbPath;
mbPath.resize(MAX_PATH);
::GetModuleFileName(nullptr, mbPath.data(), MAX_PATH);
if (!::PathRemoveFileSpec(mbPath.data())) return bResult;
if (!PathAppendW(mbPath.data(), MBDLL_NAME))return bResult;
if (!::PathFileExists(mbPath.data()))
{
::MessageBox(NULL, L"缺少miniblink 核心 node.dll文件!", L"错误", NULL);
return bResult;
}
wkeSetWkeDllPath(mbPath.data());
wkeInitialize();
bResult = true;
return bResult;
}
void CWkeWindow::quitApplication(Application* app)
{
if (app->window) {
wkeDestroyWebWindow(app->window);
app->window = NULL;
}
}
void CWkeWindow::runMessageLoop(Application* app)
{
MSG msg = { 0 };
while (GetMessageW(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
bool CWkeWindow::createWebWindow(Application* app)
{
app->window = wkeCreateWebWindow(WKE_WINDOW_TYPE_POPUP, NULL, 0, 0, 1024, 630);
if (!app->window)
return false;
//设置全局cookies/缓存路径
TCHAR szCookiePath[MAX_PATH];
ZeroMemory(szCookiePath, MAX_PATH);
::GetTempPath(MAX_PATH, szCookiePath);
std::wstring szRootPath(szCookiePath);
wcscat_s(szCookiePath, _T("cookie.tmp"));
wkeSetCookieJarFullPath(app->window, szCookiePath);
wkeSetLocalStorageFullPath(app->window, szRootPath.c_str());
//保存主窗口的窗口句柄
m_hwnd = wkeGetWindowHandle(app->window);
HICON hicon = ::LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_ICON1));
::SendMessage(m_hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hicon);
::SendMessage(m_hwnd, WM_SETICON, ICON_BIG, (LPARAM)hicon);
LONG styleValue = ::GetWindowLong(m_hwnd, GWL_STYLE);
styleValue &= ~WS_CAPTION;
styleValue &= ~WS_MAXIMIZEBOX;
styleValue &= ~WS_MINIMIZEBOX;
styleValue &= ~WS_THICKFRAME;
styleValue &= ~WS_BORDER;
styleValue &= ~WS_CAPTION;
::SetWindowLong(m_hwnd, GWL_STYLE, styleValue | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
DWORD dwExStyle = ::GetWindowLong(m_hwnd, GWL_EXSTYLE);
::SetWindowLong(m_hwnd, GWL_EXSTYLE, dwExStyle | WS_EX_LAYERED);
m_oldProc = (WNDPROC)::SetWindowLongPtr(m_hwnd, GWL_WNDPROC, (DWORD)MainProc);
m_ShadowWnd = BindShadowWindow(m_hwnd);
if (m_ShadowWnd)
m_ShadowWnd->Setup(5, 8, 192, 0);
::SetTimer(m_hwnd, UPDTAE_UI_TIMEID, 1000, TimeProc);
//设置窗口的标题