Skip to content

Commit

Permalink
Small changes
Browse files Browse the repository at this point in the history
  • Loading branch information
pudingus committed Apr 2, 2018
1 parent 00c17ee commit fc920a7
Show file tree
Hide file tree
Showing 12 changed files with 197 additions and 156 deletions.
13 changes: 6 additions & 7 deletions downloader3/AddWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Collections.Specialized;
using System.IO;
using System.Collections.Generic;
using System.Windows.Media;

namespace downloader3
{
Expand All @@ -27,16 +28,14 @@ public AddWindow()
/// <summary>
/// Představuje seznam zadaných odkazů bez nadbytečných mezer nebo prázdných řádků
/// </summary>
public List<string> urlList;

private List<string> badLines;
public List<string> UrlList { get; private set; }

private void buttonSave_Click(object sender, RoutedEventArgs e)
{
if (Util.IsValidPath(pathTextBox.Text))
{
urlList = new List<string>();
badLines = new List<string>();
UrlList = new List<string>();
List<string> badLines = new List<string>();

for (int i = 0; i < linksTextBox.LineCount; i++)
{
Expand All @@ -45,7 +44,7 @@ private void buttonSave_Click(object sender, RoutedEventArgs e)
if (Util.IsValidURL(url))
{
url = Regex.Replace(url, @"\r\n?|\n", "");
urlList.Add(url);
UrlList.Add(url);
}
else if (!String.IsNullOrWhiteSpace(url)) badLines.Add(url);
}
Expand All @@ -62,7 +61,7 @@ private void buttonSave_Click(object sender, RoutedEventArgs e)
}
}
}
else if (urlList.Count < 1)
else if (UrlList.Count < 1)
{
MessageBox.Show(Lang.Translate("lang_no_valid_links"), Lang.Translate("lang_error"), MessageBoxButton.OK, MessageBoxImage.Error);
}
Expand Down
127 changes: 65 additions & 62 deletions downloader3/DownloadClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,24 +30,27 @@ public enum Providers { DirectLink, Zippyshare, Openload }
public class DownloadClient
{
public delegate void DownloadError(DownloadClient client, LvData item, string message);
public delegate void DownloadCompleted(DownloadClient client, LvData item);

public delegate void DownloadInit(DownloadClient client, LvData item);

public delegate void DownloadStateChanged(DownloadClient client, LvData item, States oldState, States newState);

/// <summary>
/// Nastane když stahovaní přeruší chyba
/// </summary>
public event DownloadError OnDownloadError;

public delegate void DownloadCompleted(DownloadClient client, LvData item);

/// <summary>
/// Nastane když se stahování úspěšně dokončí
/// </summary>
public event DownloadCompleted OnDownloadCompleted;

public delegate void DownloadInit(DownloadClient client, LvData item);

/// <summary>
/// Nastane když se zahají stahování, po tom, co je soubor vytvořen na disku
/// </summary>
public event DownloadInit OnDownloadInit;

public delegate void DownloadStateChanged(DownloadClient client, LvData item, States oldState, States newState);

/// <summary>
/// Nastane když se změní stav stahování
/// </summary>
Expand Down Expand Up @@ -134,7 +137,6 @@ private set {

private LvData Item { get; set; }


private Thread downloadThread;
private int processed = 0;
private DispatcherTimer timer = new DispatcherTimer();
Expand All @@ -145,14 +147,31 @@ private set {
private DispatcherTimer wbTimer = new DispatcherTimer();
private Providers provider;

private const int chunkSize = 1024;
private const int bufferSize = 1024;
private const int maxRenameCount = 999;
private const int requestTimeout = 6000; //v milisekundách
private const int browserTimeout = 6000;
private const int updateInterval = 1000;
private const int pauseSleep = 100;
private const int speedlimitSleep = 200;

/// <summary>
/// Vytvoří novou instanci třídy <see cref="DownloadClient"/>.
/// </summary>
/// <param name="url">Odkaz ze kterého se soubor stáhne.</param>
/// <param name="directory">Úplná cesta ke složce, kde se soubor uloží.</param>
/// <param name="item">Reference na položku v listview, která obsahuje tento objekt.</param>
public DownloadClient(string url, string directory, LvData item)
{
append = false;
Url = WebUtility.UrlDecode(url);
Directory = directory;
Item = item;

timer.Tick += Timer_Tick;
timer.Interval = new TimeSpan(0, 0, 0, 0, updateInterval);
}


/// <summary>
/// Vytvoří novou instanci třídy <see cref="DownloadClient"/> a načte informace o předchozím stahování.
Expand All @@ -162,10 +181,11 @@ private set {
/// <param name="item">Reference na položku v listview, která obsahuje tento objekt.</param>
/// <param name="cachedTotalBytes">Očekávaná celková velikost soubor. Slouží ke kontrole, jestli nebyl soubor na serveru změněn.</param>
/// <param name="cachedFileName">Název souboru, na který se má navázat</param>
public DownloadClient(string url, string directory, LvData item, long cachedTotalBytes, string cachedFileName)
public DownloadClient(string url, string directory, LvData item,
long cachedTotalBytes, string cachedFileName)
{
append = true;
Url = url;
Url = WebUtility.UrlDecode(url);
Directory = directory;
TotalBytes = cachedTotalBytes;
Item = item;
Expand All @@ -179,28 +199,10 @@ public DownloadClient(string url, string directory, LvData item, long cachedTota
FileInfo file = new FileInfo(FullPath);
BytesDownloaded = file.Length;
}

if (BytesDownloaded == TotalBytes && TotalBytes > 0) State = States.Completed;
else State = States.Paused;
}

/// <summary>
/// Vytvoří novou instanci třídy <see cref="DownloadClient"/>.
/// </summary>
/// <param name="url">Odkaz ze kterého se soubor stáhne.</param>
/// <param name="directory">Úplná cesta ke složce, kde se soubor uloží.</param>
/// <param name="item">Reference na položku v listview, která obsahuje tento objekt.</param>
public DownloadClient(string url, string directory, LvData item)
{
append = false;
Url = url;
Directory = directory;
Item = item;

timer.Tick += Timer_Tick;
timer.Interval = new TimeSpan(0, 0, 0, 0, updateInterval);
}


/// <summary>
/// Zahájí stahování bez blokování současného vlákna
/// </summary>
Expand Down Expand Up @@ -230,7 +232,7 @@ public void Start()
}
}

if (provider == Providers.DirectLink) //pokud se jedná o přímých odkaz, rovnou se vytvoří vlákno a spustí stahování
if (provider == Providers.DirectLink) //pokud se jedná o přímý odkaz, rovnou se vytvoří vlákno a spustí stahování
{
if (downloadThread == null || !downloadThread.IsAlive)
{
Expand All @@ -253,16 +255,14 @@ public void Start()
}

/// <summary>
/// Zruší současné stahování a smaže soubor, pokud existuje.
/// Zruší současné stahování a smaže soubor.
/// </summary>
public void Cancel()
{
State = States.Canceled;
if (downloadThread == null || !downloadThread.IsAlive)
{
if (File.Exists(Path.Combine(Directory, FileName)))
File.Delete(Path.Combine(Directory, FileName));
}
if (downloadThread == null || !downloadThread.IsAlive)
if (File.Exists(FullPath))
File.Delete(FullPath);
}

/// <summary>
Expand All @@ -282,7 +282,7 @@ public void Pause()
/// Zařadí stahování do fronty
/// </summary>
/// <remarks>
/// Funguje podobně jako pozastavení. Slouží pro rozlišení, jestli bylo stahování přerušeno uživatelem
/// Funguje podobně jako pozastavení. Slouží pro rozlišení stavu, jestli bylo stahování přerušeno uživatelem
/// nebo programem, který spravuje položky ve frontě.
/// </remarks>
public void Queue()
Expand Down Expand Up @@ -310,11 +310,12 @@ public void Rename(string newName)
if (File.Exists(oldPath)) File.Move(oldPath, newPath);
if (downloadThread != null)
{
if (downloadThread.IsAlive) fs = new FileStream(newPath, FileMode.Append, FileAccess.Write, FileShare.Read);
if (downloadThread.IsAlive)
fs = new FileStream(newPath, FileMode.Append, FileAccess.Write, FileShare.Read);
}
FileName = newName;
}
}
}

//Nastane po úplném načtení stránky
private void WebBrowser_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
Expand All @@ -334,17 +335,7 @@ private void WbTimer_Tick(object sender, EventArgs e)
ResolveLink();
webBrowser.Dispose();
}
}

//Zkratka pro vyvolání údalosti při chybě
private void CallError(string message)
{
State = States.Error;
operation.Post(new SendOrPostCallback(delegate (object state)
{
OnDownloadError?.Invoke(this, Item, message);
}), null);
}
}

//Má na starosti extrakci přímých odkazů z podporovaných stránek
private void ResolveLink()
Expand All @@ -362,7 +353,6 @@ private void ResolveLink()
CallError(Lang.Translate("lang_unable_to_extract"));
return;
}

}
else if (provider == Providers.Openload)
{
Expand All @@ -383,7 +373,17 @@ private void ResolveLink()

downloadThread = new Thread(DownloadWorker);
downloadThread.Start();
}
}

//Zkratka pro vyvolání údalosti při chybě
private void CallError(string message)
{
State = States.Error;
operation.Post(new SendOrPostCallback(delegate (object state)
{
OnDownloadError?.Invoke(this, Item, message);
}), null);
}

//Obsluhuje čtení dat ze serveru a zápis na disk. Běží v samostatném vlákně.
private void DownloadWorker()
Expand All @@ -409,19 +409,23 @@ private void DownloadWorker()

response = (HttpWebResponse)request.GetResponse();

//když je FileName prázdný, ještě jsme nezískali jméno ze serveru, jinak použít stávající
//když je FileName prázdný, ještě nebyl získan název souboru ze serveru, jinak se použije stávající
if (FileName == "")
{
string header = response.Headers["Content-Disposition"];
if (header != null)
{
string s = header.Replace("attachment; ", "").Replace("attachment;", "").Replace("filename=", "").Replace("filename*=UTF-8''", "").Replace("\"", "");
FileName = WebUtility.UrlDecode(s);

// z: form%c3%a1ln%c3%ad%20%c3%baprava%20podle%20norem.docx
// na: formální úprava podle norem.docx

FileName = WebUtility.UrlDecode(s);
}
else
{
Uri uri = new Uri(Url);
FileName = Path.GetFileName(uri.LocalPath);
FileName = Path.GetFileName(uri.LocalPath);
}

//pokud již existuje soubor se stejným jménem, přidá se číslo
Expand Down Expand Up @@ -460,14 +464,13 @@ private void DownloadWorker()
OnDownloadInit?.Invoke(this, Item);
}), null);

byte[] read = new byte[chunkSize];
int count;

while ((count = receiveStream.Read(read, 0, chunkSize)) > 0 && State != States.Canceled) //dokud není přečten celý stream
byte[] buffer = new byte[bufferSize];
int receivedCount;
while ((receivedCount = receiveStream.Read(buffer, 0, bufferSize)) > 0 && State != States.Canceled) //dokud není přečten celý stream
{
fs.Write(read, 0, count);
BytesDownloaded += count;
processed += count;
fs.Write(buffer, 0, receivedCount);
BytesDownloaded += receivedCount;
processed += receivedCount;

while (State == States.Paused || State == States.Queue) Thread.Sleep(pauseSleep);
if (State == States.Starting) State = States.Downloading;
Expand Down
4 changes: 2 additions & 2 deletions downloader3/Lang.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace downloader3
/// <summary>
/// Poskytuje možnost měnit jazyk programu a překládat
/// </summary>
public class Lang
public static class Lang
{
/// <summary>
/// Nastaví jazyk programu
Expand Down Expand Up @@ -47,7 +47,7 @@ public static string Translate(string resource)
string result = (string)Application.Current.TryFindResource(resource);
if (result == null)
{
MessageBox.Show("Language resource \"" + resource + "\" is invalid", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show($"Language resource \"{resource}\" is invalid", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return resource;
}
return result;
Expand Down
1 change: 0 additions & 1 deletion downloader3/LinksStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ public class Link
public string Url { get; set; }
public long TotalBytes { get; set; }
public long SpeedLimit { get; set; }
public bool Completed { get; set; }
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion downloader3/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
xmlns:local="clr-namespace:downloader3"
x:Class="downloader3.MainWindow"
mc:Ignorable="d"
Title="wyDownloader" Height="546" Width="903" Closing="Window_Closing" Loaded="Window_Loaded" Icon="favicon.ico" Background="#FFF0F0F0" MinHeight="160" MinWidth="490">
Title="mDownloader" Height="546" Width="903" Closing="Window_Closing" Loaded="Window_Loaded" Background="#FFF0F0F0" MinHeight="160" MinWidth="490">
<Window.Resources>

<LinearGradientBrush x:Key="ProgressBarBackground" EndPoint="1,0" StartPoint="0,0">
Expand Down
Loading

0 comments on commit fc920a7

Please sign in to comment.