csharp: Download SVN source

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;
using System.Threading;
using System.Xml;
 
namespace DownloadSVN
{
 
 
    /// <summary>
    /// SVN 2016-05-13
    /// Geovin Du edit
    /// </summary>
    public partial class MainForm : Form
    {
        ManualResetEvent _waitingForStop;
        ManualResetEvent _finishedReadingTree;
        List<FileDownloadData> _filesToDownload;
        Thread _readingThread;
        String _selectedSourceType;
 
        public MainForm()
        {
            InitializeComponent();
 
            this.comboBoxSourceType.SelectedIndex = 0;
        }
 
        private void buttonBrowseTargetFolder_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog fbd = new FolderBrowserDialog())
            {
                if (fbd.ShowDialog() == DialogResult.OK)
                    this.textBoxTargetFolder.Text = fbd.SelectedPath;
            }
        }
 
        private void buttonGo_Click(object sender, EventArgs e)
        {
            if (_readingThread == null)
            {
                _selectedSourceType = this.comboBoxSourceType.Text;
 
                Thread t = new Thread(new ThreadStart(Run));
                t.Start();
                _readingThread = t;
                SetButtonGoText("Stop");
            }
            else
            {
                Stop();
            }
        }
 
        void Run()
        {           
            // Start downloading threads
            _finishedReadingTree = new ManualResetEvent(false);
            _waitingForStop = new ManualResetEvent(false);
            _filesToDownload = new List<FileDownloadData>();
 
            List<Thread> downloadThreads = new List<Thread>();
            for (int i = 0; i < 5; i++)
            {
                Thread t = new Thread(new ThreadStart(DownloadFilesThread));
                t.Start();
                downloadThreads.Add(t);
            }
 
            try
            {
                if ((this.textBoxTargetFolder.Text != "") && (this.textBoxSourceSvnUrl.Text != ""))
                {
                    string url = this.textBoxSourceSvnUrl.Text;
 
                    if (_selectedSourceType == "GIT")
                        RunSvn(this.textBoxTargetFolder.Text, this.textBoxSourceSvnUrl.Text, RepositoryType.GIT);
                    else // "SVN"
                        RunSvn(this.textBoxTargetFolder.Text, this.textBoxSourceSvnUrl.Text, RepositoryType.SVN);
                }
                else
                    WriteToScreen("Parameters not set.");
            }
            catch (Exception ex)
            {
                WriteToScreen("Failed: " + ex);
                lock (_filesToDownload)
                {
                    _filesToDownload.Clear();
                }
            }
            finally
            {
                _finishedReadingTree.Set();
            }
 
            // Wait for downloading threads
            WriteToScreen("Waiting for file downloading threads to finish");
            for (int i = 0; i < downloadThreads.Count; i++)
                downloadThreads[i].Join();
 
            WriteToScreen("Done.");
            MessageBox.Show("Done", "Done");
            _readingThread = null;
 
            SetButtonGoText("Start");
        }
 
        delegate void SetButtonGoTextDelegate(string text);
        /// <summary>
        ///
        /// </summary>
        /// <param name="text"></param>
        void SetButtonGoText(string text)
        {
            if (InvokeRequired == true)
            {
                this.Invoke(new SetButtonGoTextDelegate(SetButtonGoText), text);
                return;
            }
 
            buttonGo.Text = text;
        }
        /// <summary>
        ///
        /// </summary>
        void DownloadFilesThread()
        {
            while (true)
            {
                FileDownloadData fileDownloadData  = null;
                lock (_filesToDownload)
                {
                    if (_filesToDownload.Count > 0)
                    {
                        fileDownloadData = _filesToDownload[0];
                        _filesToDownload.RemoveAt(0);
                    }
                }
 
                if ((fileDownloadData == null) && (_finishedReadingTree.WaitOne(0, false) == true))
                    return;
 
                if (fileDownloadData != null)
                {
                    bool retry = true;
                    while (retry == true)
                    {
                        if (_waitingForStop.WaitOne(0, false) == true)
                            return;
 
                        try
                        {
                            DownloadFile(fileDownloadData.Url, fileDownloadData.FileName);
                            retry = false;
                        }
                        catch (Exception ex)
                        {
                            WriteToScreen("Failed to download: " + ex.Message);
                        }
                    }
                }
                else
                {
                    Thread.Sleep(100);
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        public enum RepositoryType
        {
            SVN,
            GIT
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="baseFolder"></param>
        /// <param name="baseUrl"></param>
        /// <param name="repositoryType"></param>
        void RunSvn(string baseFolder, string baseUrl, RepositoryType repositoryType)
        {
            if (repositoryType == RepositoryType.SVN)
            {
                if (baseUrl.EndsWith("/") == false)
                    baseUrl += "/";
            }
 
            if (baseFolder.EndsWith("\\") == false)
                baseFolder += "\\";
 
            List<FolderLinkData> urls = new List<FolderLinkData>();
            urls.Add(new FolderLinkData(baseUrl, ""));
 
            while (urls.Count > 0)
            {
                if (_waitingForStop.WaitOne(0, false) == true)
                {
                    WriteToScreen("Stopping...");
                    lock (_filesToDownload)
                    {
                        _filesToDownload.Clear();
                    }
                    break;
                }
 
                FolderLinkData targetUrlData = urls[0];
                string targetUrl = targetUrlData.Url;
                urls.RemoveAt(0);
 
                // Create the folder
                string relative;
                if (targetUrlData.RelativePath == null)
                    relative = targetUrl.Substring(baseUrl.Length);
                else
                    relative = targetUrlData.RelativePath;
 
                relative = relative.Replace("/", "\\");
                string targetFolder = Path.Combine(baseFolder, relative);
                if (Directory.Exists(targetFolder) == false)
                    Directory.CreateDirectory(targetFolder);
 
                // Download target page
                string page = null;
                bool retry = true;
                while (retry == true)
                {
                    if (_waitingForStop.WaitOne(0, false) == true)
                        return;
 
                    try
                    {
                        page = DownloadUrl(targetUrl);
                        retry = false;
                    }
                    catch (Exception ex)
                    {
                        WriteToScreen("Failed to download: " + ex.Message);
                    }
                }
 
                if (repositoryType == RepositoryType.SVN)
                {
                    List<string> links = ParseLinks(page);
 
                    foreach (string link in links)
                    {
                        string linkFullUrl = targetUrl + link;
                        if (linkFullUrl.EndsWith("/") == true)
                        {
                            urls.Add(new FolderLinkData(linkFullUrl, null));
                        }
                        else // file - download
                        {
                            string fileName = targetFolder + link;
                            lock (_filesToDownload)
                            {
                                _filesToDownload.Add(new FileDownloadData(linkFullUrl, fileName));
                            }
                        }
                    }
                }
                else if (repositoryType == RepositoryType.GIT)
                {
                    List<PageLink> links = ParseGitLinks(page);
                    int pos = targetUrl.IndexOf("/?");
                    string serverUrl = targetUrl.Substring(0, pos);
 
                    foreach (PageLink link in links)
                    {
                        string linkFullUrl = serverUrl + link.Url;
                        if (link.IsFolder == true)
                            urls.Add(new FolderLinkData(linkFullUrl, targetUrlData.RelativePath + link.Name + "\\"));
                        else
                        {
                            string fileName = targetFolder + link.Name;
 
                            lock (_filesToDownload)
                            {
                                _filesToDownload.Add(new FileDownloadData(linkFullUrl, fileName));
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        List<string> ParseLinks(string page)
        {
            try
            {
                return ParseLinksFromXml(page);
            }
            catch
            {
                return ParseLinksFromHtml(page);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        List<string> ParseLinksFromXml(string page)
        {
            List<string> list = new List<string>();
 
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(page);
 
            XmlNode svnNode = doc.SelectSingleNode("/svn");
            if (svnNode == null)
                throw new Exception("Not a valid SVN xml");
 
            foreach (XmlNode node in doc.SelectNodes("/svn/index/dir"))
            {
                string dir = node.Attributes["href"].Value;
                list.Add(dir);
            }
 
            foreach (XmlNode node in doc.SelectNodes("/svn/index/file"))
            {
                string file = node.Attributes["href"].Value;
                list.Add(file);
            }
 
            return list;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        List<string> ParseLinksFromHtml(string page)
        {
            List<string> links = new List<string>();
            string listArea = null;
 
            // Find list area: <ul> ... </ul>
            int pos = page.IndexOf("<ul>");
            if (pos >= 0)
            {
                int lastPos = page.IndexOf("</ul>", pos);
                if (lastPos >= 0)
                    listArea = page.Substring(pos + 4, lastPos - (pos + 4));
            }
 
            if (listArea != null)
            {
                string[] lines = listArea.Split('\n');
                string linePattern = "<a [^>]*>([^<]*)<";
                for (int i = 0; i < lines.Length; i++)
                {
                    Match match = Regex.Match(lines[i], linePattern);
                    if (match.Success == true)
                    {
                        string linkRelUrl = match.Groups[1].Value;
                        if (linkRelUrl != "..")
                            links.Add(linkRelUrl);
                    }
                }
            }
 
            return links;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        List<PageLink> ParseGitLinks(string page)       
        {
            List<PageLink> links = new List<PageLink>();
 
            string dataStartMarker = "<td class=\"mode\">";
            string nameMarker = "hb=HEAD\">";
 
            using (StringReader sr = new StringReader(page))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.StartsWith(dataStartMarker) == false)
                        continue;
 
                    bool isFolder = false;
                    if (line[dataStartMarker.Length] == 'd')
                        isFolder = true;
 
                    line = sr.ReadLine();
 
                    // Get name
                    int pos = line.IndexOf(nameMarker);
                    int endPos = line.IndexOf("<", pos);
                    pos += nameMarker.Length;
 
                    string name = line.Substring(pos, endPos - pos);
 
                    if ((name == "..") || (name == "."))
                        continue;
 
                    // Get URL
                    pos = line.IndexOf("href=\"");
                    endPos = line.IndexOf("\">", pos);
                    pos += "href=\"".Length;
                    string url = line.Substring(pos, endPos - pos);
                    if (isFolder == false)
                    {
                        url = url.Replace(";a=blob;", ";a=blob_plain;");
 
                        pos = url.IndexOf(";h=");
                        url = url.Substring(0, pos);
                        url = url + ";hb=HEAD";
                    }
 
                    if (url.Contains(";a=tree;"))
                        isFolder = true;
 
                    links.Add(new PageLink(name, url, isFolder));
                }
            }
 
            return links;
        }
 
        #region Download helper functions
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <param name="fileName"></param>
        void DownloadFile(string url, string fileName)
        {
            WriteToScreen("Downloading File: " + url);
 
            WebRequest webRequest = WebRequest.Create(url);
            webRequest.ContentType = "text/html; charset=utf-8"; //考虑乱码问题
            webRequest.Timeout = 50000;
            WebResponse webResponse = null;
            Stream responseStream = null;
            try
            {
                webResponse = webRequest.GetResponse();
                responseStream = webResponse.GetResponseStream();
                //  string  page = new StreamReader(responseStream, Encoding.UTF8, true).ReadToEnd();
                using (FileStream fs = new FileStream(fileName, FileMode.Create))
                {
                    byte[] buffer = new byte[1024];
                    int readSize;
                    while ((readSize = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fs.Write(buffer, 0, readSize);
                    }
                }
            }
            finally
            {
                if (responseStream != null)
                    responseStream.Close();
 
                if (webResponse != null)
                    webResponse.Close();
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        string DownloadUrl(string url)
        {
            WriteToScreen("Downloading: " + url);
            using (WebClient client = new WebClient())
            {
                client.Encoding = System.Text.Encoding.UTF8; //GetEncoding("utf-8"); //考虑乱码问题
                string data = client.DownloadString(url);
 
                return data;
            }
        }
        #endregion
 
        delegate void WriteToScreenDelegate(string str);
        /// <summary>
        ///
        /// </summary>
        /// <param name="str"></param>
        void WriteToScreen(string str)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new WriteToScreenDelegate(WriteToScreen), str);
                return;
            }
 
            this.richTextBox1.AppendText(str + "\n");
            this.richTextBox1.ScrollToCaret();
        }
 
        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
 
        private void Stop()
        {
            _waitingForStop.Set();
        }
 
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_readingThread != null)
            {
                Stop();
                e.Cancel = true;
            }
        }
    }
 
    public class PageLink
    {
        string _name;
        string _url;
        bool _isFolder;
 
        public string Name { get { return _name; } }
        public string Url { get { return _url; } }
        public bool IsFolder { get { return _isFolder; } }
 
        public PageLink(string name, string url, bool isFolder)
        {
            _name = name;
            _url = url;
            _isFolder = isFolder;
        }
    }
    /// <summary>
    ///
    /// </summary>
    public class FolderLinkData
    {
        string _url;
        string _relativePath;
 
        public string Url { get { return _url; } }
        public string RelativePath { get { return _relativePath; } }
 
        public FolderLinkData(string url, string relativePath)
        {
            _url = url;
            _relativePath = relativePath;
        }
    }
    /// <summary>
    ///
    /// </summary>
    public class FileDownloadData
    {
        string _url;
        string _fileName;
 
        public string Url
        {
            get { return _url; }
        }
 
        public string FileName
        {
            get { return _fileName; }
        }
 
        public FileDownloadData(string url, string fileName)
        {
            _url = url;
            _fileName = fileName;
        }
    }
}

  

posted @   ®Geovin Du Dream Park™  阅读(432)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示