Example #1
0
        private async Task ProcessUrl(DownloadManagerItem item, CancellationToken cancelToken)
        {
            try
            {
                using var response = await HttpClient.GetAsync(item.Url, HttpCompletionOption.ResponseHeadersRead, cancelToken);

                item.StatusCode = response.StatusCode;

                if (response.IsSuccessStatusCode)
                {
                    if (item.MimeType.IsEmpty())
                    {
                        item.MimeType = MimeTypes.MapNameToMimeType(item.FileName);
                    }

                    var contentType = response.Content.Headers.ContentType?.MediaType;
                    if (contentType.HasValue() && !contentType.EqualsNoCase(item.MimeType))
                    {
                        // Update mime type and local path.
                        var extension = MimeTypes.MapMimeTypeToExtension(contentType).NullEmpty() ?? "jpg";

                        item.MimeType = contentType;
                        item.Path     = Path.ChangeExtension(item.Path, extension.EnsureStartsWith('.'));
                    }

                    using var source = await response.Content.ReadAsStreamAsync(cancelToken);

                    using var target = File.Open(item.Path, FileMode.Create);

                    await source.CopyToAsync(target, cancelToken);

                    item.Success = true;
                }
                else
                {
                    item.Success      = false;
                    item.ErrorMessage = response.ReasonPhrase.HasValue()
                        ? $"{response.StatusCode} ({response.ReasonPhrase})"
                        : response.StatusCode.ToString();
                }
            }
            catch (Exception ex)
            {
                item.Success      = false;
                item.ErrorMessage = ex.ToAllMessages();

                if (ex.InnerException is WebException webExc)
                {
                    item.ExceptionStatus = webExc.Status;
                }
            }
        }
Example #2
0
        private async Task ProcessUrl(DownloadManagerContext context, HttpClient client, DownloadManagerItem item)
        {
            try
            {
                var count    = 0;
                var canceled = false;
                var bytes    = new byte[_bufferSize];

                using var response = await client.GetAsync(item.Url);

                if (response.IsSuccessStatusCode)
                {
                    if (response.Content.Headers.ContentType != null)
                    {
                        var contentType = response.Content.Headers.ContentType.MediaType;
                        if (contentType.HasValue() && !contentType.EqualsNoCase(item.MimeType))
                        {
                            // Update mime type and local path.
                            var extension = MimeTypes.MapMimeTypeToExtension(contentType).NullEmpty() ?? "jpg";

                            item.MimeType = contentType;
                            item.Path     = Path.ChangeExtension(item.Path, extension.EnsureStartsWith('.'));
                        }
                    }

                    //Task <Stream> task = client.GetStreamAsync(item.Url);
                    Task <Stream> task = response.Content.ReadAsStreamAsync();
                    await         task;

                    using (var srcStream = task.Result)
                        using (var dstStream = File.Open(item.Path, FileMode.Create))
                        {
                            while ((count = srcStream.Read(bytes, 0, bytes.Length)) != 0 && !canceled)
                            {
                                dstStream.Write(bytes, 0, count);

                                if (context.CancellationToken.IsCancellationRequested)
                                {
                                    canceled = true;
                                }
                            }
                        }

                    item.Success = !task.IsFaulted && !canceled;
                }
                else
                {
                    item.Success      = false;
                    item.ErrorMessage = response.StatusCode.ToString();
                }
            }
            catch (Exception ex)
            {
                try
                {
                    item.Success      = false;
                    item.ErrorMessage = ex.ToAllMessages();

                    var webExc = ex.InnerException as WebException;
                    if (webExc != null)
                    {
                        item.ExceptionStatus = webExc.Status;
                    }

                    if (context.Logger != null)
                    {
                        context.Logger.Error(ex, item.ToString());
                    }
                }
                catch { }
            }
        }
Example #3
0
 /// <summary>
 /// Downloads a file asynchronously and saves it to disk.
 /// </summary>
 /// <param name="item">Information about the file to download.</param>
 /// <param name="cancelToken">A <see cref="CancellationToken"/> to observe while waiting for the task to complete.</param>
 public Task DownloadFileAsync(DownloadManagerItem item, CancellationToken cancelToken = default)
 {
     return(ProcessUrl(item, cancelToken));
 }