File size: 2,405 Bytes
fab29d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using VersOne.Epub.Environment;
using VersOne.Epub.Options;

namespace VersOne.Epub.Internal
{
    internal class EpubRemoteContentLoader : EpubContentLoader
    {
        private readonly ContentDownloaderOptions contentDownloaderOptions;
        private readonly IContentDownloader contentDownloader;
        private readonly string userAgent;

        public EpubRemoteContentLoader(IEnvironmentDependencies environmentDependencies, ContentDownloaderOptions? contentDownloaderOptions = null)
            : base(environmentDependencies)
        {
            this.contentDownloaderOptions = contentDownloaderOptions ?? new ContentDownloaderOptions();
            contentDownloader = this.contentDownloaderOptions.CustomContentDownloader ?? EnvironmentDependencies.ContentDownloader;
            userAgent = this.contentDownloaderOptions.DownloaderUserAgent ??
                "EpubReader/" + typeof(EpubRemoteContentLoader).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
        }

        public override async Task<byte[]> LoadContentAsBytesAsync(EpubContentFileRefMetadata contentFileRefMetadata)
        {
            using Stream contentStream = await GetContentStreamAsync(contentFileRefMetadata);
            using MemoryStream memoryStream = new();
            await contentStream.CopyToAsync(memoryStream).ConfigureAwait(false);
            return memoryStream.ToArray();
        }

        public override async Task<string> LoadContentAsTextAsync(EpubContentFileRefMetadata contentFileRefMetadata)
        {
            using Stream contentStream = await GetContentStreamAsync(contentFileRefMetadata);
            using StreamReader streamReader = new(contentStream);
            return await streamReader.ReadToEndAsync().ConfigureAwait(false);
        }

        public override Task<Stream> GetContentStreamAsync(EpubContentFileRefMetadata contentFileRefMetadata)
        {
            if (!contentDownloaderOptions.DownloadContent)
            {
                throw new EpubContentDownloaderException("Downloading remote content is prohibited by the ContentDownloaderOptions.DownloadContent option.", contentFileRefMetadata.Key);
            }
            return contentDownloader.DownloadAsync(contentFileRefMetadata.Key, userAgent);
        }
    }
}