Advertisement
Guest User

Untitled

a guest
Aug 3rd, 2018
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.70 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Threading.Tasks.Dataflow;
  12.  
  13. namespace Get_Links
  14. {
  15.     class Files
  16.     {
  17.         IEnumerable<Uri> items;
  18.         int parallel;
  19.         HttpClient http;
  20.  
  21.         public Files(IEnumerable<Uri> items, int parallel)
  22.         {
  23.             this.items = items;
  24.             this.parallel = parallel;
  25.             http = new HttpClient();
  26.         }
  27.  
  28.         public Task CopyTo(string path, CancellationToken cancel = default)
  29.         {
  30.             if (!Directory.Exists(path))
  31.                 Directory.CreateDirectory(path);
  32.             var action = new ActionBlock<Uri>(
  33.                 async x => File.WriteAllBytes($"{Path.Combine(path, x.Host)}.txt", await http.GetByteArrayAsync(x)),
  34.                 new ExecutionDataflowBlockOptions { CancellationToken = cancel, MaxDegreeOfParallelism = parallel });
  35.             foreach (var item in items)
  36.                 action.Post(item);
  37.             action.Complete();
  38.             return action.Completion;
  39.         }
  40.     }
  41.  
  42.     class Links : IEnumerable<Uri>
  43.     {
  44.         const string URL_REGEX = @"(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?";
  45.  
  46.         readonly IEnumerable<Uri> e;
  47.  
  48.         public Links(string input)
  49.         {
  50.             e = Regex
  51.                 .Matches(input, URL_REGEX)
  52.                 .Cast<Match>()
  53.                 .Select(x => new Uri(x.Value));
  54.         }
  55.  
  56.         public IEnumerator<Uri> GetEnumerator() => e.GetEnumerator();
  57.  
  58.         IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  59.     }
  60.  
  61.     class Program
  62.     {
  63.         static async Task Main(string[] args)
  64.         {
  65.             var files = new Files(new Links("https://2ch.hk https://www.yandex.ru"), 4);
  66.             await files.CopyTo("files");
  67.         }
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement