-
Notifications
You must be signed in to change notification settings - Fork 2
/
PMUDownloaderForm.cs
2325 lines (2135 loc) · 106 KB
/
PMUDownloaderForm.cs
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
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml;
using System.Text;
using Microsoft.WindowsAPICodePack.Taskbar;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualBasic.Devices;
namespace M3U8_Downloader
{
public partial class PMUDownloaderForm : Form
{
//public const string VideoRootPath = "\\\\cheeky\\data\\RaceData\\VideoFinish\\Temp\\";
public const string VideoRootPath = "\\\\diskstation\\web\\videos\\PMU\\";
//\\diskstation\web\videos
private bool DownloadAtRandomInterval = false;
private bool stopApp;
private Random RandomGen = new Random();
public bool CurDownloaded = false;
public DownLoadQueue myDownLoadQueue;
public int defaultTimeout = 1800000;
public MySqlHelper mySqlHelper;
//任务栏进度条的实现。
private TaskbarManager windowsTaskbar = TaskbarManager.Instance;
//拖动窗口
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
public const int WM_SYSCOMMAND = 0x0112;
private const int WM_SETREDRAW = 0xB;
public const int SC_MOVE = 0xF010;
public const int HTCAPTION = 0x0002;
[DllImport("kernel32.dll")]
static extern bool GenerateConsoleCtrlEvent(int dwCtrlEvent, int dwProcessGroupId);
[DllImport("kernel32.dll")]
static extern bool SetConsoleCtrlHandler(IntPtr handlerRoutine, bool add);
[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll")]
static extern bool FreeConsole();
[DllImport("user32.dll")]
public static extern bool FlashWindow(IntPtr hWnd, bool bInvert);
[DllImport("kernel32.dll")]
static extern int SetProcessWorkingSetSize(IntPtr process, int minimumWorkingSetSize, int maximumWorkingSetSize);
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref System.UInt32 pcchCookieData, int dwFlags, IntPtr lpReserved);
private static string GetCookies(string url)
{
uint datasize = 1024;
StringBuilder cookieData = new StringBuilder((int)datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x2000, IntPtr.Zero))
{
if (datasize < 0)
return null;
cookieData = new StringBuilder((int)datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, IntPtr.Zero))
return null;
}
//Clipboard.SetDataObject(cookieData.ToString() + "-----" + url);
return cookieData.ToString();
}
public string GetCookieString(WebBrowser webBrowser)
{
if (webBrowser.Url == null)
return null;
string dir = webBrowser.Url.Host;
FileStream fr = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Cookies) + "\\index.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
byte[] __dat = new byte[(int)fr.Length];
fr.Read(__dat, 0, __dat.Length);
fr.Close();
fr.Dispose();
string __datstream = Encoding.Default.GetString(__dat);
int p1 = 0;
p1 = __datstream.IndexOf("@" + dir, p1);
if (p1 == -1)
p1 = __datstream.IndexOf("@" + dir.Substring(dir.IndexOf('.') + 1));
if (p1 == -1)
return webBrowser.Document.Cookie;
int p2 = __datstream.IndexOf(".txt", p1 + 1);
p1 = __datstream.LastIndexOf('@', p2);
string dm = __datstream.Substring(p1 + 1, p2 - p1 + 3).TrimStart('?');
p1 = __datstream.LastIndexOf(":", p1);
p2 = __datstream.IndexOf('@', ++p1);
__datstream = string.Format("{0}@{1}", __datstream.Substring(p1, p2 - p1), dm);
Dictionary<string, string> __cookiedicts = new Dictionary<string, string>();
string __n;
StringBuilder __cookies = new StringBuilder();
__datstream = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.Cookies) + "\\" + __datstream, Encoding.Default);
p1 = -2;
do
{
p1 += 2;
p2 = __datstream.IndexOf('\n', p1);
if (p2 == -1)
break;
__n = __datstream.Substring(p1, p2 - p1);
p1 = p2 + 1;
p2 = __datstream.IndexOf('\n', p1);
if (!__cookiedicts.ContainsKey(__n))
__cookiedicts.Add(__n, __datstream.Substring(p1, p2 - p1));
}
while ((p1 = __datstream.IndexOf("*\n", p1)) > -1);
if (webBrowser.Document.Cookie != null && webBrowser.Document.Cookie.Length > 0)
{
foreach (string s in webBrowser.Document.Cookie.Split(';'))
{
p1 = s.IndexOf('=');
if (p1 == -1)
continue;
__datstream = s.Substring(0, p1).TrimStart();
if (__cookiedicts.ContainsKey(__datstream))
__cookiedicts[__datstream] = s.Substring(p1 + 1);
else
__cookiedicts.Add(__datstream, s.Substring(p1 + 1));
}
}
foreach (string s in __cookiedicts.Keys)
{
if (__cookies.Length > 0)
__cookies.Append(';');
__cookies.Append(s);
__cookies.Append('=');
__cookies.Append(__cookiedicts[s]);
}
return __cookies.ToString();
}
private SQLiteHelper mySQLiteHelper;
//private void RefreshTextBoxControl()
//{
// SendMessage(textBox_Info.Handle, WM_SETREDRAW, 0, IntPtr.Zero);//禁止重绘
// // 重新布局
// SendMessage(textBox_Info.Handle, WM_SETREDRAW, 1, IntPtr.Zero);//取消禁止
// textBox_Info.Refresh();
//}
int ffmpegid = -1;
Double big = 0;
Double small = 0;
private WebBrowser myWebBrowser;
private String SESSIONID;
//不影响点击任务栏图标最大最小化
protected override CreateParams CreateParams
{
get
{
const int WS_MINIMIZEBOX = 0x00020000; // Winuser.h中定义
CreateParams cp = base.CreateParams;
cp.Style = cp.Style | WS_MINIMIZEBOX; // 允许最小化操作
return cp;
}
}
public PMUDownloaderForm()
{
InitializeComponent();
Init();
mySqlHelper = new MySqlHelper();
myDownLoadQueue = new DownLoadQueue();
//禁止编译器对跨线程访问做检查
Control.CheckForIllegalCrossThreadCalls = false;
mySQLiteHelper = new SQLiteHelper();
SQLiteHelper.SetConnectionString(System.AppDomain.CurrentDomain.BaseDirectory + "Data.db3", "");
myWebBrowser = NewBrowser();
}
private void textBox_Adress_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.All;
}
private void textBox_Adress_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.All;
}
private void textBox_Adress_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
{
//获取拖拽的文件地址
var filenames = (string[])e.Data.GetData(DataFormats.FileDrop);
var hz = filenames[0].LastIndexOf('.') + 1;
var houzhui = filenames[0].Substring(hz);//文件后缀名
if (houzhui == "m3u8" || houzhui == "mkv" || houzhui == "avi" || houzhui == "mp4" || houzhui == "ts" || houzhui == "flv" || houzhui == "f4v" ||
houzhui == "wmv" || houzhui == "wm" || houzhui == "mpeg" || houzhui == "mpg" || houzhui == "m4v" || houzhui == "3gp" || houzhui == "rm" ||
houzhui == "rmvb" || houzhui == "mov" || houzhui == "qt" || houzhui == "m2ts" || houzhui == "m3u" || houzhui == "mts" || houzhui == "txt") //只允许拖入部分文件
{
e.Effect = DragDropEffects.All;
string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
textBox_Adress.Text = path; //将获取到的完整路径赋值到textBox1
}
}
}
private void button_Quit_Click(object sender, EventArgs e)
{
SaveSettings();
try
{
if (Process.GetProcessById(ffmpegid) != null)
{
if (MessageBox.Show("已启动下载进程,确认退出吗?\n(这有可能是强制的)", "请确认您的操作", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
{
Stop();
MessageBox.Show("已经发送命令!\n若进程仍然存在则强制结束!", "请确认");
try
{
if (Process.GetProcessById(ffmpegid) != null) //如果进程还存在就强制结束它
{
Process.GetProcessById(ffmpegid).Kill();
Dispose();
Application.Exit();
}
}
catch
{
Dispose();
Application.Exit();
}
}
else
{
}
}
}
catch
{
Dispose();
Application.Exit();
}
}
private void button_ChangePath_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox_DownloadPath.Text = folderBrowserDialog1.SelectedPath;
}
}
private void button_OpenPath_Click(object sender, EventArgs e)
{
Process.Start(textBox_DownloadPath.Text);
}
private void linkLabel_Stop_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Stop();
}
//格式化大小输出
public static String FormatFileSize(Double fileSize)
{
if (fileSize < 0)
{
throw new ArgumentOutOfRangeException("fileSize");
}
else if (fileSize >= 1024 * 1024 * 1024)
{
return string.Format("{0:########0.00} GB", ((Double)fileSize) / (1024 * 1024 * 1024));
}
else if (fileSize >= 1024 * 1024)
{
return string.Format("{0:####0.00} MB", ((Double)fileSize) / (1024 * 1024));
}
else if (fileSize >= 1024)
{
return string.Format("{0:####0.00} KB", ((Double)fileSize) / 1024);
}
else
{
return string.Format("{0} bytes", fileSize);
}
}
private void textBox_Info_TextChanged(object sender, EventArgs e)
{
if (textBox_Info.GetLineFromCharIndex(textBox_Info.TextLength) + 1 > 14)
textBox_Info.ScrollBars = ScrollBars.Vertical;
if (textBox_Info.GetLineFromCharIndex(textBox_Info.TextLength) + 1 <= 14)
textBox_Info.ScrollBars = ScrollBars.None;
Regex duration = new Regex(@"Duration: (\d\d[.:]){3}\d\d", RegexOptions.Compiled | RegexOptions.Singleline);//取总视频时长
label5.Text = "[TotalTime:" + duration.Match(textBox_Info.Text).Value.Replace("Duration: ", "") + "]";
Regex regex = new Regex(@"(\d\d[.:]){3}\d\d", RegexOptions.Compiled | RegexOptions.Singleline);//取视频时长以及Time属性
var time = regex.Matches(textBox_forRegex.Text);
//取已下载大小
Regex size = new Regex(@"[1-9][0-9]{0,}kB time", RegexOptions.Compiled | RegexOptions.Singleline);
var sizekb = size.Matches(textBox_forRegex.Text);
if (time.Count > 0 && sizekb.Count > 0)
{
try
{
label6.Text = "[Downloaded:" + time.OfType<Match>().Last() + "," + FormatFileSize(Convert.ToDouble(sizekb.OfType<Match>().Last().ToString().Replace("kB time", "")) * 1024) + "]";
}
catch (Exception ex)
{ }
}
Regex fps = new Regex(@", (\S+)\sfps", RegexOptions.Compiled | RegexOptions.Singleline);//取视频帧数
Regex resolution = new Regex(@", \d{2,}x\d{2,}", RegexOptions.Compiled | RegexOptions.Singleline);//取视频分辨率
label7.Text = "[Video information:" + resolution.Match(textBox_Info.Text).Value.Replace(", ", "") + "," + fps.Match(textBox_Info.Text).Value.Replace(", ", "") + "]";
//防止程序太快 无法截取
if (time.Count > 0 && sizekb.Count > 0)
{
try
{
//"[TotalTime:00:04:40.00]"
var time1 = label5.Text.Substring(11, 2);
var time2 = label5.Text.Substring(14, 2);
var time3 = label5.Text.Substring(17, 2);
var time4 = label5.Text.Substring(20, 2);
Double All = Convert.ToDouble(Convert.ToDouble(time1) * 60 * 60 + Convert.ToDouble(time2) * 60
+ Convert.ToDouble(time3) + Convert.ToDouble(time4) / 100);
//"[Downloaded:00:00:02.98,45.84 MB]"
var time5 = label6.Text.Substring(12, 2);
var time6 = label6.Text.Substring(15, 2);
var time7 = label6.Text.Substring(18, 2);
var time8 = label6.Text.Substring(21, 2);
Double Downloaded = Convert.ToDouble(Convert.ToDouble(time5) * 60 * 60 + Convert.ToDouble(time6) * 60
+ Convert.ToDouble(time7) + Convert.ToDouble(time8) / 100);
if (All == 0) All = 1; //防止被除数为零导致程序崩溃
Double Progress = (Downloaded / All) * 100;
if (Progress > 100) //防止进度条超过百分之百
Progress = 100;
if (Progress < 0) //防止进度条小于零……
Progress = 0;
ProgressBar.Value = Convert.ToInt32(Progress);
windowsTaskbar.SetProgressValue(Convert.ToInt32(Progress), 100, this.Handle);
label_Progress.Visible = true;
label_Progress.Text = "Completed:" + String.Format("{0:F}", Progress) + "%";
double fileSize = (big - small) * 1024;
this.Text = "Completed:" + String.Format("{0:F}", Progress) + "%" + " [" + FormatFileSize(fileSize > 0 ? fileSize : 0) + "/s]";
}
catch (Exception ex)
{
try
{
label5.Text = "[TotalTime:NULL]";
var time5 = label6.Text.Substring(12, 2);
var time6 = label6.Text.Substring(15, 2);
var time7 = label6.Text.Substring(18, 2);
var time8 = label6.Text.Substring(21, 2);
Double Downloaded = Convert.ToDouble(Convert.ToDouble(time5) * 60 * 60 + Convert.ToDouble(time6) * 60
+ Convert.ToDouble(time7) + Convert.ToDouble(time8) / 100);
Double Progress = 100;
if (Progress > 100) //防止进度条超过百分之百
Progress = 100;
if (Progress < 0) //防止进度条小于零……
Progress = 0;
ProgressBar.Value = Convert.ToInt32(Progress);
windowsTaskbar.SetProgressValue(Convert.ToInt32(Progress), 100, this.Handle);
label_Progress.Visible = true;
label_Progress.Text = "Completed:" + String.Format("{0:F}", Progress) + "%";
double fileSize = (big - small) * 1024;
this.Text = "Completed:" + String.Format("{0:F}", Progress) + "%" + " [" + FormatFileSize(fileSize > 0 ? fileSize : 0) + "/s]";
}
catch (Exception exs)
{
CommonHelper.WriteLog(exs.Message, "SetProgressValue");
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
myWebBrowser.ScriptErrorsSuppressed = true;
this.panel1.Controls.Add(myWebBrowser);
////初始化进度条
windowsTaskbar.SetProgressState(TaskbarProgressBarState.Normal, this.Handle);
windowsTaskbar.SetProgressValue(0, 100, this.Handle);
if (!File.Exists(@"Tools\ffmpeg.exe")) //判断程序目录有无ffmpeg.exe
{
MessageBox.Show("Could not find Tools\\ffmpeg.exe", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Dispose();
Application.Exit();
}
if (File.Exists(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\M3u8_Downloader_Settings.xml")) //判断程序目录有无配置文件,并读取文件
{
XmlDocument doc = new XmlDocument();
doc.Load(@System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "\\M3u8_Downloader_Settings.xml"); //加载Xml文件
XmlNodeList topM = doc.SelectNodes("Settings");
foreach (XmlElement element in topM)
{
textBox_DownloadPath.Text = element.GetElementsByTagName("DownPath")[0].InnerText;
if (element.GetElementsByTagName("ExtendName")[0].InnerText == "MP4") { radioButton1.Checked = true; }
if (element.GetElementsByTagName("ExtendName")[0].InnerText == "MKV") { radioButton2.Checked = true; }
if (element.GetElementsByTagName("ExtendName")[0].InnerText == "TS") { radioButton3.Checked = true; }
if (element.GetElementsByTagName("ExtendName")[0].InnerText == "FLV") { radioButton4.Checked = true; }
}
}
else //若无配置文件,获取当前程序运行路径,即为默认下载路径
{
string lujing = System.Environment.CurrentDirectory;
textBox_DownloadPath.Text = lujing;
}
//
this.BeginInvoke(new Action(() => {
WriteToLable(label9, "Loading page for infocentre.pmu.fr...");
LoginSite();
WriteToLable(label9, "Logged in");
}));
}
internal void WriteToLable(Label label, String message)
{
if (label.InvokeRequired)
{
this.Invoke((Action)(() =>
WriteToLable(label, message)
));
return;
}
label.Text = string.Format("{0}", message);
Application.DoEvents();
}
//webBrowser1
internal void InitWebBrowser(WebBrowser webBrowser)
{
if (webBrowser.InvokeRequired)
{
this.Invoke((Action)(() =>
this.myWebBrowser = webBrowser
));
return;
}
this.myWebBrowser = webBrowser;
Application.DoEvents();
}
private void textBox_Adress_KeyPress(object sender, KeyPressEventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox == null)
return;
if (e.KeyChar == (char)1) // Ctrl-A 相当于输入了AscII=1的控制字符
{
textBox.SelectAll();
e.Handled = true; // 不再发出“噔”的声音
}
}
private void button4_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void button_Exit_Click(object sender, EventArgs e)
{
SaveSettings();
try
{
if (this.myWebBrowser != null)
{
this.myWebBrowser.Stop();
this.myWebBrowser.Dispose();
}
stopApp = true;
if (Process.GetProcessById(ffmpegid) != null)
{
if (MessageBox.Show("已启动下载进程,确认退出吗?\n(这有可能是强制的)", "请确认您的操作", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
{
Stop();
MessageBox.Show("已经发送命令!\n若进程仍然存在则强制结束!", "请确认");
try
{
if (Process.GetProcessById(ffmpegid) != null) //如果进程还存在就强制结束它
{
Process.GetProcessById(ffmpegid).Kill();
Dispose();
Application.Exit();
}
}
catch
{
Dispose();
Application.Exit();
}
}
else
{
}
}
}
catch
{
Dispose();
Application.Exit();
}
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
MoveFrom();
}
private void label8_MouseDown(object sender, MouseEventArgs e)
{
MoveFrom();
}
private void label14_Click(object sender, EventArgs e)
{
Process.Start("https://ffmpeg.zeranoe.com/builds/win32/static/");
}
private void Label_Monitor_Click(object sender, EventArgs e)
{
Exist_Run(@"Tools\HttpFileMonitor.exe");
}
private void Label_WriteLog_Click(object sender, EventArgs e)
{
String LogName = "日志-" + System.DateTime.Now.ToString("yyyy.MM.dd-HH.mm.ss") + ".txt";
StreamWriter log = new StreamWriter(LogName);
log.WriteLine("━━━━━━━━━━━━━━\r\n"
+ "■M3U8 Downloader 用户日志\r\n\r\n"
+ "■" + System.DateTime.Now.ToString("F") + "\r\n\r\n"
+ "■输入:" + textBox_Adress.Text + "\r\n\r\n"
+ "■输出:" + textBox_DownloadPath.Text + "\\" + textBox_Name.Text + houzhui.Text + "\r\n\r\n"
+ "■FFmpeg命令:ffmpeg " + Command.Text + "\r\n"
+ "━━━━━━━━━━━━━━"
+ "\r\n\r\n"
+ textBox_Info.Text);
log.Close();
MessageBox.Show("日志已生成到程序目录!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void label_Update_Click(object sender, EventArgs e)
{
Process.Start("http://pan.baidu.com/s/1dF4uDuL");
}
private void label_OpenTool_Click(object sender, EventArgs e)
{
Exist_Run(@"Tools\Batch Download.exe");
}
private void label_Progress_MouseDown(object sender, MouseEventArgs e)
{
MoveFrom();
}
private void timer1_Tick(object sender, EventArgs e)
{
try
{
//取已下载大小
Regex size = new Regex(@"[1-9][0-9]{0,}kB time", RegexOptions.Compiled | RegexOptions.Singleline);
var sizekb = size.Matches(textBox_forRegex.Text);
big = Convert.ToDouble(sizekb.OfType<Match>().Last().ToString().Replace("kB time", ""));
double fileSize = (big - small) * 1024;
label8.Text = "[" + FormatFileSize(fileSize > 0 ? fileSize : 0) + "/s]";
}
catch (Exception) { }
}
private void timer2_Tick(object sender, EventArgs e)
{
small = big;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
SaveSettings();
try
{
if (Process.GetProcessById(ffmpegid) != null)
{
if (MessageBox.Show("已启动下载进程,确认退出吗?\n(这有可能是强制的)", "请确认您的操作", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
{
Stop();
MessageBox.Show("已经发送命令!\n若进程仍然存在则强制结束!", "请确认");
try
{
if (Process.GetProcessById(ffmpegid) != null) //如果进程还存在就强制结束它
{
Process.GetProcessById(ffmpegid).Kill();
Dispose();
Application.Exit();
}
}
catch
{
Dispose();
Application.Exit();
}
}
else
{
e.Cancel = true;
}
}
}
catch
{
Dispose();
Application.Exit();
}
}
private void button1_Click(object sender, EventArgs e)
{
//DateTime viewTimer = new DateTime();
//myProgressBar1.Value = 0;
Application.DoEvents();
//string racedatafile = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Files\\RaceData.txt";
string rsRacedatafile = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Files\\RSRaceData.txt";
var raceLists = new List<RaceInfo>();
//var fileInfo = new FileInfo(racedatafile);
var fileInfo = new FileInfo(rsRacedatafile);
if (fileInfo.Exists)
{
//raceLists = ReadLineFile(racedatafile);
//RDate,RCourse, RRaceNo
raceLists = ReadRSLineFile(rsRacedatafile).Select(r => r).Where(r => r.MeetingDiscipline == "T").OrderBy(r => r.MeetingDate).ThenBy(r => r.MeetingCourseCode).ThenBy(r => r.RaceNumber).ToList();
raceLists.ForEach(r =>
{
string sql = "select id from raceinfo where MeetingId='" + r.MeetingId + "' and MeetingCourseCode='" + r.MeetingCourseCode + "' and MeetingDiscipline='" + r.MeetingDiscipline + "' and MeetingDate='" + r.MeetingDate.ToString("yyyy-MM-dd") + "' and RaceId='" + r.RaceId + "' and RaceNumber=" + Convert.ToInt32(r.RaceNumber) + "";
try
{
var exist = mySQLiteHelper.ExecuteScalar(sql);
if (Convert.ToInt32(exist) == 0)
{
sql = "insert into raceinfo (MeetingId,MeetingCourse,MeetingCourseID,MeetingCourseCode,MeetingDiscipline,MeetingDate,RaceId,RaceName,RaceNumber,PlayerUrl) values (" + r.MeetingId + ",'" + r.MeetingCourse.Replace("'", "''") + "',0,'" + r.MeetingCourseCode + "','" + r.MeetingDiscipline + "','" + r.MeetingDate.ToString("yyyy-MM-dd") + "'," + r.RaceId + ",'" + r.RaceName.Replace("'", "''") + "'," + Convert.ToInt32(r.RaceNumber) + ",'" + r.PlayerUrl + "')";
mySQLiteHelper.ExecuteNonQuery(sql);
}
}
catch (Exception ex)
{
CommonHelper.WriteFile(sql, "InsertRaceInfo-Error");
}
});
myProgressBar1.Value = 0;
Application.DoEvents();
if (this.myWebBrowser.Document != null)
{
bool newBrowser = false;
int index = 0;
string mycookies = "";
mycookies = GetCookies(myWebBrowser.Url.ToString());
SESSIONID = RequestVerificationToken(mycookies, "JSESSIONID").TrimStart().TrimEnd();
foreach (var race in raceLists)
{
index++;
if (myWebBrowser == null)
{
myWebBrowser = NewBrowser();
this.panel1.Controls.Add(myWebBrowser);
LoginSite();
mycookies = GetCookies(myWebBrowser.Url.ToString());
SESSIONID = RequestVerificationToken(mycookies, "JSESSIONID").TrimStart().TrimEnd();
newBrowser = true;
}
//=======================================================
mycookies = GetCookies(myWebBrowser.Url.ToString());
if (SESSIONID != RequestVerificationToken(mycookies, "JSESSIONID").TrimStart().TrimEnd())
{
LoginSite();
mycookies = GetCookies(myWebBrowser.Url.ToString());
SESSIONID = RequestVerificationToken(mycookies, "JSESSIONID").TrimStart().TrimEnd();
}
InvokeDownLoadVidedoFile(myWebBrowser, raceLists, race, index);
//=======================================================
InvokeProgressChanged(index, raceLists.Count);
if (newBrowser && myWebBrowser.Document != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(myWebBrowser.ActiveXInstance);
myWebBrowser.Dispose();
myWebBrowser = null;
}
}
}
}
}
public void AddFieldDownload(RaceInfo r)
{
string sql = "select id from RaceFailed where MeetingId='" + r.MeetingId + "' and MeetingCourseCode='" + r.MeetingCourseCode + "' and MeetingDiscipline='" + r.MeetingDiscipline + "' and MeetingDate='" + r.MeetingDate.ToString("yyyy-MM-dd") + "' and RaceId='" + r.RaceId + "' and RaceNumber=" + Convert.ToInt32(r.RaceNumber) + "";
try
{
var exist = mySQLiteHelper.ExecuteScalar(sql);
if (Convert.ToInt32(exist) == 0)
{
sql = "insert into RaceFailed (MeetingId,MeetingCourse,MeetingCourseID,MeetingCourseCode,MeetingDiscipline,MeetingDate,RaceId,RaceName,RaceNumber,PlayerUrl) values (" + r.MeetingId + ",'" + r.MeetingCourse.Replace("'", "''") + "',0,'" + r.MeetingCourseCode + "','" + r.MeetingDiscipline + "','" + r.MeetingDate.ToString("yyyy-MM-dd") + "'," + r.RaceId + ",'" + r.RaceName.Replace("'", "''") + "'," + Convert.ToInt32(r.RaceNumber) + ",'" + r.PlayerUrl + "')";
mySQLiteHelper.ExecuteNonQuery(sql);
CommonHelper.WriteFile(sql, "InsertRaceFailed");
}
}
catch (Exception ex)
{
CommonHelper.WriteFile(sql, "InsertRaceFailed-Error");
}
}
public WebBrowser NewBrowser()
{
var webBrowser = new WebBrowser();
webBrowser.Dock = System.Windows.Forms.DockStyle.Fill;
webBrowser.Location = new System.Drawing.Point(0, 0);
webBrowser.MinimumSize = new System.Drawing.Size(20, 20);
webBrowser.Name = "webBrowser1";
webBrowser.Size = new System.Drawing.Size(995, 248);
webBrowser.TabIndex = 0;
return webBrowser;
}
public void InvokeDownLoadVidedoFile(WebBrowser webBrowser, List<RaceInfo> raceLists, RaceInfo race, int index)
{
WriteToLable(label9, "[" + index + "/" + raceLists.Count + "] Matching video address for " + race.PlayerUrl);
string fileName = String.Format("{0}-{1}{2}-race{3}", race.MeetingDate.ToString("yyyyMMdd"), race.MeetingCourseCode, race.MeetingDiscipline, race.RaceNumber);
string savePath = VideoRootPath + race.MeetingDate.ToString("yyyy") + "\\" + race.MeetingDate.ToString("MM") + "\\" + race.MeetingDate.ToString("dd");
string filePath = savePath + "\\" + fileName + ".mp4";
FileInfo videoFile = new FileInfo(filePath);
if (!videoFile.Exists)
{
try
{
string mycookies = webBrowser.Document.Cookie;
string frameHtml = "";
string videoLink = "";
webBrowser.Navigate(new Uri(race.PlayerUrl));
mycookies = webBrowser.Document.Cookie;
//Waiting
var viewTimer = DateTime.Now.AddMinutes(2);
while (webBrowser.ReadyState != WebBrowserReadyState.Complete || webBrowser.IsBusy)
{
Application.DoEvents();
if (DateTime.Compare(DateTime.Now, viewTimer) >= 0 || stopApp)
{
break;
}
}
int retry = 5;
frameHtml = GetFrameHtml(webBrowser);
while (string.IsNullOrEmpty(frameHtml) && retry >= 1)
{
frameHtml = GetFrameHtml(webBrowser);
retry--;
}
string pattern = "Clappr.HTML5Video.canPlay(\"[URL]\");";
videoLink = FigureURL(frameHtml, pattern, false);
if (!string.IsNullOrEmpty(videoLink))
{
WriteToLable(label1, "[" + index + "/" + raceLists.Count + "] DownLoading..." + videoLink);
this.textBox_DownloadPath.Text = savePath;
this.textBox_Adress.Text = videoLink;
this.textBox_Name.Text = fileName;
//
this.CurDownloaded = false;
#region
var downloadFile = new DownloadFile();
downloadFile.FileAddress = textBox_Adress.Text;
downloadFile.DownLoadPath = textBox_DownloadPath.Text;
downloadFile.FileName = textBox_Name.Text;
this.textBox_Name.Text = downloadFile.FileName;
if (radioButton1.Checked == true)
{
downloadFile.FileFormat = ".mp4";
downloadFile.CommandText = "-threads 0 -i " + "\"" + downloadFile.FileAddress + "\"" + " -c copy -y -bsf:a aac_adtstoasc -movflags +faststart " + "\"" + downloadFile.DownLoadPath + "\\" + downloadFile.FileName + downloadFile.FileFormat + "\"";
}
if (radioButton2.Checked == true)
{
downloadFile.FileFormat = ".mkv";
downloadFile.CommandText = "-threads 0 -i " + "\"" + downloadFile.FileAddress + "\"" + " -c copy -y -bsf:a aac_adtstoasc " + "\"" + downloadFile.DownLoadPath + "\\" + downloadFile.FileName + downloadFile.FileFormat + "\"";
}
if (radioButton3.Checked == true)
{
downloadFile.FileFormat = ".ts";
downloadFile.CommandText = "-threads 0 -i " + "\"" + downloadFile.FileAddress + "\"" + " -c copy -y -f mpegts " + "\"" + downloadFile.DownLoadPath + "\\" + downloadFile.FileName + downloadFile.FileFormat + "\"";
}
if (radioButton4.Checked == true)
{
downloadFile.FileFormat = ".flv";
downloadFile.CommandText = "-threads 0 -i " + "\"" + downloadFile.FileAddress + "\"" + " -c copy -y -f f4v -bsf:a aac_adtstoasc " + "\"" + downloadFile.DownLoadPath + "\\" + downloadFile.FileName + downloadFile.FileFormat + "\"";
}
if (!Directory.Exists(downloadFile.DownLoadPath))
{
Directory.CreateDirectory(downloadFile.DownLoadPath);
}
else
{
SetTextBox(textBox_Info, "");
SetTextBox(textBox_forRegex, "");
InitComponent();
//===================
//Download(downloadFile);
// 启动进程执行相应命令,此例中以执行ffmpeg.exe为例
//RealActionAsync(@"Tools\ffmpeg.exe", downloadFile.CommandText);
IAsyncResult asyncResult = this.BeginInvoke(new Func<DownloadFile, bool, ApplicationOutput>(DownLoadDoWorkAsync), downloadFile, false);
viewTimer = DateTime.Now.AddMinutes(30);
while ((!asyncResult.IsCompleted && !CurDownloaded) || DateTime.Compare(DateTime.Now, viewTimer) >= 0)
{
Application.DoEvents();
}
var downloadResult = (ApplicationOutput)this.EndInvoke(asyncResult);
////下载完成时
if (downloadResult.IsCompleted)
{
WriteToLable(label1, "[" + index + "/" + raceLists.Count + "] DownLoad Completed");
}
else
{
WriteToLable(label1, "[" + index + "/" + raceLists.Count + "] DownLoad failed:" + downloadResult.OutPut);
AddFieldDownload(race);
}
}
#endregion
}
else
{
videoLink = "NULL";
WriteToLable(label1, "[" + index + "/" + raceLists.Count + "] DownLoading failed, videoLink is Null:" + videoLink);
AddFieldDownload(race);
}
}
catch (Exception ex)
{
CommonHelper.WriteLog(ex.Message, "Error");
}
}
else
{
WriteToLable(label1, "[" + index + "/" + raceLists.Count + "] File is Exists:" + filePath);
}
}
public string GetFrameHtml(WebBrowser webBrowser)
{
DateTime viewTimer = new DateTime();
string frameHtml = "";
string videoLink = "";
if (webBrowser.Document != null)
{
HtmlElementCollection iframes = webBrowser.Document.GetElementsByTagName("iframe");
foreach (HtmlElement iframe in iframes)
{
if (iframe != null)
{
videoLink = iframe.GetAttribute("src");
break;
}
}
if (!String.IsNullOrEmpty(videoLink))
{
webBrowser.Navigate(new Uri(videoLink));
//Waiting
viewTimer = DateTime.Now.AddMinutes(2);
while (webBrowser.ReadyState != WebBrowserReadyState.Complete || webBrowser.IsBusy)
{
Application.DoEvents();
if (DateTime.Compare(DateTime.Now, viewTimer) >= 0 || stopApp)
{
break;
}
}
if (webBrowser.Document != null)
{
HtmlElement frameBody = webBrowser.Document.GetElementsByTagName("body")[0];
if (frameBody != null)
{
frameHtml = frameBody.InnerHtml;
}
}
}
}
return frameHtml;
}
public string FigureURL(string Doc, string pattern, bool settled)
{
string retString = "";
if (!settled && pattern.IndexOf("[URL]") >= 0)
{
Match m = GetMatchRigid(Doc, pattern, "[URL]");
if (m.Success)
{
retString = m.Groups["TARGET"].Value;
}
}
else
retString = pattern;
return retString;
}
/// <summary>
/// 按严格的匹配方式获取一个目标的匹配结果
/// </summary>
/// <param name="input"></param>
/// <param name="pattern"></param>
/// <param name="find"></param>
/// <returns></returns>
public static Match GetMatchRigid(string input, string pattern, string find)
{
string _pattn = Regex.Escape(pattern);
_pattn = _pattn.Replace(@"\[VARIABLE]", @"[\s\S]*?");
if (Regex.Match(pattern.TrimEnd(), Regex.Escape(find) + "$", RegexOptions.Compiled).Success)
_pattn = _pattn.Replace(@"\" + find, @"(?<TARGET>[\s\S]+)");
else
_pattn = _pattn.Replace(@"\" + find, @"(?<TARGET>[\s\S]+?)");
Regex r = new Regex(_pattn, RegexOptions.IgnoreCase | RegexOptions.Compiled);
Match m = r.Match(input);
return m;
}
private string RequestVerificationToken(string cookies, string key = "SessionId")
{
Dictionary<string, string> siteCookies = new Dictionary<string, string>();
var tempArry = cookies.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
foreach (var temp in tempArry)
{
var tempKeyArry = temp.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries).ToList();
if (tempKeyArry.Count > 1)
{
siteCookies.Add(tempKeyArry[0].TrimStart().TrimEnd(), tempKeyArry[1]);
}
}
//return keyValue;
var session = siteCookies.Select(c => c).Where(c => c.Key.Trim().ToUpper() == key.Trim().ToUpper()).FirstOrDefault();
if (!string.IsNullOrEmpty(session.Value))
return session.Value;
else
return "";
}
public void LoginSite()
{
DateTime viewTimer = new DateTime();
WebBrowserNavigate(this.myWebBrowser, "https://www.infocentre.pmu.fr/PMU/Phantoms/PhantomDemarrage");
if (myWebBrowser.Document != null)
{
HtmlElement formLogin = myWebBrowser.Document.GetElementById("formLogin");
if (formLogin != null)
{
var codeContact = formLogin.Document.GetElementById("codeContact");
if (codeContact != null)
{
codeContact.SetAttribute("value", "Callen");
}
HtmlElement submitButton = null;
HtmlElementCollection mdpContacts = formLogin.Document.GetElementsByTagName("input");