using Extreme.Net;
using RuriLib.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RuriLib.Functions.Download
{
///
/// Provides methods to download files from the internet.
///
public static class Download
{
///
/// Downloads a remote file.
///
/// The destination file on disk
/// The URL of the remote file
/// Whether to use proxies for the request
/// The proxy, if needed
/// The cookies to use in the request
/// The new cookie dictionary containing the new cookies too
/// The request timeout in milliseconds
/// The user agent to use
public static void RemoteFile(
string fileName, string url, bool useProxies, CProxy proxy, Dictionary cookies, out Dictionary newCookies, int timeout, string userAgent = "")
{
HttpRequest request = new HttpRequest();
if (userAgent != "") request.UserAgent = userAgent;
request.Cookies = new CookieDictionary();
foreach (var cookie in cookies)
request.Cookies.Add(cookie.Key, cookie.Value);
// Set proxy
if (useProxies)
{
request.Proxy = proxy.GetClient();
request.Proxy.ReadWriteTimeout = timeout;
request.Proxy.ConnectTimeout = timeout;
request.Proxy.Username = proxy.Username;
request.Proxy.Password = proxy.Password;
}
HttpResponse response = request.Get(url);
using (Stream inputStream = response.ToMemoryStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
newCookies = response.Cookies;
}
}
}