Kavita/API/Services/DownloadService.cs
Joe Milazzo a8f48a6e9d
OPDS Flattening (#1904)
* Flattening OPDS Structure

# Changed
- Flattened OPDS structure to reduce user taps.

* Fixing format

* Fixing book series titles

* Optimized file size to use pre-calculated data to avoid an I/O touch.

* Fixes #1898 by aligning all content headers to the correct MIME types

* Remove dead code

* Fixed a bug with continue point where it fails on chapters or volumes tagged with a range

---------

Co-authored-by: Robbie Davis <robbie@therobbiedavis.com>
2023-03-30 16:45:46 -07:00

59 lines
2 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using API.Entities;
using Microsoft.AspNetCore.StaticFiles;
using MimeTypes;
namespace API.Services;
public interface IDownloadService
{
Tuple<string, string, string> GetFirstFileDownload(IEnumerable<MangaFile> files);
string GetContentTypeFromFile(string filepath);
}
public class DownloadService : IDownloadService
{
private readonly FileExtensionContentTypeProvider _fileTypeProvider = new FileExtensionContentTypeProvider();
public DownloadService() { }
/// <summary>
/// Downloads the first file in the file enumerable for download
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
public Tuple<string, string, string> GetFirstFileDownload(IEnumerable<MangaFile> files)
{
var firstFile = files.Select(c => c.FilePath).First();
return Tuple.Create(firstFile, GetContentTypeFromFile(firstFile), Path.GetFileName(firstFile));
}
public string GetContentTypeFromFile(string filepath)
{
// Figures out what the content type should be based on the file name.
if (!_fileTypeProvider.TryGetContentType(filepath, out var contentType))
{
contentType = Path.GetExtension(filepath).ToLowerInvariant() switch
{
".cbz" => "application/x-cbz",
".cbr" => "application/x-cbr",
".cb7" => "application/x-cb7",
".cbt" => "application/x-cbt",
".epub" => "application/epub+zip",
".7z" => "application/x-7z-compressed",
".7zip" => "application/x-7z-compressed",
".rar" => "application/vnd.rar",
".zip" => "application/zip",
".tar.gz" => "application/gzip",
".pdf" => "application/pdf",
_ => MimeTypeMap.GetMimeType(contentType)
};
}
return contentType!;
}
}