Skip to content

Kavita is a fast, feature rich, cross platform reading server. Built with the goal of being a full solution for all your reading needs. Setup your own server and share your reading collection with your friends and family.

v0.4.6 Release (#599)

Joseph Milazzo9aa6c87b72eb
diff --git a/.gitignore b/.gitignore
index 9f28eec22..928e1ee53 100644
--- a/.gitignore
+++ b/.gitignore
@@ -500,3 +500,4 @@ _output/
API/stats/
UI/Web/dist/
/API.Tests/Extensions/Test Data/modified on run.txt
+/API/covers/
diff --git a/API.Benchmark/ArchiveSerivceBenchmark.cs b/API.Benchmark/ArchiveSerivceBenchmark.cs
new file mode 100644
index 000000000..c60a4271f
--- /dev/null
+++ b/API.Benchmark/ArchiveSerivceBenchmark.cs
@@ -0,0 +1,8 @@
+namespace API.Benchmark
+{
+ public class ArchiveSerivceBenchmark
+ {
+ // Benchmark to test default GetNumberOfPages from archive
+ // vs a new method where I try to open the archive and return said stream
+ }
+}
diff --git a/API.Benchmark/ParseScannedFilesBenchmarks.cs b/API.Benchmark/ParseScannedFilesBenchmarks.cs
index bc0c810ce..d3fd19a4e 100644
--- a/API.Benchmark/ParseScannedFilesBenchmarks.cs
+++ b/API.Benchmark/ParseScannedFilesBenchmarks.cs
@@ -1,7 +1,9 @@
using System;
using System.IO;
+using API.Data;
using API.Entities.Enums;
using API.Interfaces.Services;
+using API.Parser;
using API.Services;
using API.Services.Tasks.Scanner;
using BenchmarkDotNet.Attributes;
@@ -14,7 +16,7 @@ namespace API.Benchmark
[MemoryDiagnoser]
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
[RankColumn]
- [SimpleJob(launchCount: 1, warmupCount: 3, targetCount: 5, invocationCount: 100, id: "Test"), ShortRunJob]
+ //[SimpleJob(launchCount: 1, warmupCount: 3, targetCount: 5, invocationCount: 100, id: "Test"), ShortRunJob]
public class ParseScannedFilesBenchmarks
{
private readonly ParseScannedFiles _parseScannedFiles;
@@ -27,14 +29,37 @@ namespace API.Benchmark
_parseScannedFiles = new ParseScannedFiles(bookService, _logger);
}
+ // [Benchmark]
+ // public void Test()
+ // {
+ // var libraryPath = Path.Join(Directory.GetCurrentDirectory(),
+ // "../../../Services/Test Data/ScannerService/Manga");
+ // var parsedSeries = _parseScannedFiles.ScanLibrariesForSeries(LibraryType.Manga, new string[] {libraryPath},
+ // out var totalFiles, out var scanElapsedTime);
+ // }
+
+ /// <summary>
+ /// Generate a list of Series and another list with
+ /// </summary>
[Benchmark]
- public void Test()
+ public void MergeName()
{
var libraryPath = Path.Join(Directory.GetCurrentDirectory(),
"../../../Services/Test Data/ScannerService/Manga");
+ var p1 = new ParserInfo()
+ {
+ Chapters = "0",
+ Edition = "",
+ Format = MangaFormat.Archive,
+ FullFilePath = Path.Join(libraryPath, "A Town Where You Live", "A_Town_Where_You_Live_v01.zip"),
+ IsSpecial = false,
+ Series = "A Town Where You Live",
+ Title = "A Town Where You Live",
+ Volumes = "1"
+ };
var parsedSeries = _parseScannedFiles.ScanLibrariesForSeries(LibraryType.Manga, new string[] {libraryPath},
out var totalFiles, out var scanElapsedTime);
+ _parseScannedFiles.MergeName(p1);
}
-
}
}
diff --git a/API.Benchmark/Program.cs b/API.Benchmark/Program.cs
index 05c296f8b..b308a07b7 100644
--- a/API.Benchmark/Program.cs
+++ b/API.Benchmark/Program.cs
@@ -13,6 +13,7 @@ namespace API.Benchmark
static void Main(string[] args)
{
BenchmarkRunner.Run<ParseScannedFilesBenchmarks>();
+ //BenchmarkRunner.Run<TestBenchmark>();
}
}
}
diff --git a/API.Benchmark/TestBenchmark.cs b/API.Benchmark/TestBenchmark.cs
new file mode 100644
index 000000000..a2aabdd8a
--- /dev/null
+++ b/API.Benchmark/TestBenchmark.cs
@@ -0,0 +1,69 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using API.Comparators;
+using API.DTOs;
+using BenchmarkDotNet.Attributes;
+using BenchmarkDotNet.Order;
+
+namespace API.Benchmark
+{
+ /// <summary>
+ /// This is used as a scratchpad for testing
+ /// </summary>
+ [MemoryDiagnoser]
+ [Orderer(SummaryOrderPolicy.FastestToSlowest)]
+ [RankColumn]
+ public class TestBenchmark
+ {
+ private readonly NaturalSortComparer _naturalSortComparer = new ();
+
+
+ private static IEnumerable<VolumeDto> GenerateVolumes(int max)
+ {
+ var random = new Random();
+ var maxIterations = random.Next(max) + 1;
+ var list = new List<VolumeDto>();
+ for (var i = 0; i < maxIterations; i++)
+ {
+ list.Add(new VolumeDto()
+ {
+ Number = random.Next(10) > 5 ? 1 : 0,
+ Chapters = GenerateChapters()
+ });
+ }
+
+ return list;
+ }
+
+ private static List<ChapterDto> GenerateChapters()
+ {
+ var list = new List<ChapterDto>();
+ for (var i = 1; i < 40; i++)
+ {
+ list.Add(new ChapterDto()
+ {
+ Range = i + string.Empty
+ });
+ }
+
+ return list;
+ }
+
+ private void SortSpecialChapters(IEnumerable<VolumeDto> volumes)
+ {
+ foreach (var v in volumes.Where(vDto => vDto.Number == 0))
+ {
+ v.Chapters = v.Chapters.OrderBy(x => x.Range, _naturalSortComparer).ToList();
+ }
+ }
+
+ [Benchmark]
+ public void TestSortSpecialChapters()
+ {
+ var volumes = GenerateVolumes(10);
+ SortSpecialChapters(volumes);
+ }
+
+ }
+}
diff --git a/API.Tests/API.Tests.csproj b/API.Tests/API.Tests.csproj
index 73a19fd5d..e01bab216 100644
--- a/API.Tests/API.Tests.csproj
+++ b/API.Tests/API.Tests.csproj
@@ -30,4 +30,8 @@
<Folder Include="Services\Test Data\ScannerService\Manga" />
</ItemGroup>
+ <ItemGroup>
+ <None Remove="Extensions\Test Data\modified on run.txt" />
+ </ItemGroup>
+
</Project>
diff --git a/API.Tests/Extensions/Test Data/modified on run.txt b/API.Tests/Extensions/Test Data/modified on run.txt
deleted file mode 100644
index d6a609edc..000000000
--- a/API.Tests/Extensions/Test Data/modified on run.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-This file should be modified by the unit test08/20/2021 10:26:03
-08/20/2021 10:26:29
-08/22/2021 12:39:58
diff --git a/API.Tests/Parser/ComicParserTests.cs b/API.Tests/Parser/ComicParserTests.cs
index a18ea21c9..8d25661ff 100644
--- a/API.Tests/Parser/ComicParserTests.cs
+++ b/API.Tests/Parser/ComicParserTests.cs
@@ -23,49 +23,63 @@ namespace API.Tests.Parser
[InlineData("Amazing Man Comics chapter 25", "Amazing Man Comics")]
[InlineData("Amazing Man Comics issue #25", "Amazing Man Comics")]
[InlineData("Teen Titans v1 038 (1972) (c2c).cbr", "Teen Titans")]
+ [InlineData("Batman Beyond 02 (of 6) (1999)", "Batman Beyond")]
+ [InlineData("Batman Beyond - Return of the Joker (2001)", "Batman Beyond - Return of the Joker")]
+ [InlineData("Invincible 033.5 - Marvel Team-Up 14 (2006) (digital) (Minutemen-Slayer)", "Invincible")]
+ [InlineData("Batman Wayne Family Adventures - Ep. 001 - Moving In", "Batman Wayne Family Adventures")]
+ [InlineData("Saga 001 (2012) (Digital) (Empire-Zone).cbr", "Saga")]
+ [InlineData("Batman Beyond 04 (of 6) (1999)", "Batman Beyond")]
public void ParseComicSeriesTest(string filename, string expected)
{
Assert.Equal(expected, API.Parser.Parser.ParseComicSeries(filename));
}
[Theory]
- [InlineData("01 Spider-Man & Wolverine 01.cbr", "1")]
- [InlineData("04 - Asterix the Gladiator (1964) (Digital-Empire) (WebP by Doc MaKS)", "4")]
+ [InlineData("01 Spider-Man & Wolverine 01.cbr", "0")]
+ [InlineData("04 - Asterix the Gladiator (1964) (Digital-Empire) (WebP by Doc MaKS)", "0")]
[InlineData("The First Asterix Frieze (WebP by Doc MaKS)", "0")]
- [InlineData("Batman & Catwoman - Trail of the Gun 01", "1")]
+ [InlineData("Batman & Catwoman - Trail of the Gun 01", "0")]
[InlineData("Batman & Daredevil - King of New York", "0")]
- [InlineData("Batman & Grendel (1996) 01 - Devil's Bones", "1")]
+ [InlineData("Batman & Grendel (1996) 01 - Devil's Bones", "0")]
[InlineData("Batman & Robin the Teen Wonder #0", "0")]
[InlineData("Batman & Wildcat (1 of 3)", "0")]
- [InlineData("Batman And Superman World's Finest #01", "1")]
- [InlineData("Babe 01", "1")]
- [InlineData("Scott Pilgrim 01 - Scott Pilgrim's Precious Little Life (2004)", "1")]
+ [InlineData("Batman And Superman World's Finest #01", "0")]
+ [InlineData("Babe 01", "0")]
+ [InlineData("Scott Pilgrim 01 - Scott Pilgrim's Precious Little Life (2004)", "0")]
[InlineData("Teen Titans v1 001 (1966-02) (digital) (OkC.O.M.P.U.T.O.-Novus)", "1")]
- [InlineData("Scott Pilgrim 02 - Scott Pilgrim vs. The World (2005)", "2")]
+ [InlineData("Scott Pilgrim 02 - Scott Pilgrim vs. The World (2005)", "0")]
[InlineData("Superman v1 024 (09-10 1943)", "1")]
[InlineData("Amazing Man Comics chapter 25", "0")]
+ [InlineData("Invincible 033.5 - Marvel Team-Up 14 (2006) (digital) (Minutemen-Slayer)", "0")]
+ [InlineData("Cyberpunk 2077 - Trauma Team 04.cbz", "0")]
public void ParseComicVolumeTest(string filename, string expected)
{
Assert.Equal(expected, API.Parser.Parser.ParseComicVolume(filename));
}
[Theory]
- [InlineData("01 Spider-Man & Wolverine 01.cbr", "0")]
+ [InlineData("01 Spider-Man & Wolverine 01.cbr", "1")]
[InlineData("04 - Asterix the Gladiator (1964) (Digital-Empire) (WebP by Doc MaKS)", "0")]
[InlineData("The First Asterix Frieze (WebP by Doc MaKS)", "0")]
- [InlineData("Batman & Catwoman - Trail of the Gun 01", "0")]
+ [InlineData("Batman & Catwoman - Trail of the Gun 01", "1")]
[InlineData("Batman & Daredevil - King of New York", "0")]
[InlineData("Batman & Grendel (1996) 01 - Devil's Bones", "1")]
[InlineData("Batman & Robin the Teen Wonder #0", "0")]
[InlineData("Batman & Wildcat (1 of 3)", "1")]
[InlineData("Batman & Wildcat (2 of 3)", "2")]
- [InlineData("Batman And Superman World's Finest #01", "0")]
- [InlineData("Babe 01", "0")]
+ [InlineData("Batman And Superman World's Finest #01", "1")]
+ [InlineData("Babe 01", "1")]
[InlineData("Scott Pilgrim 01 - Scott Pilgrim's Precious Little Life (2004)", "1")]
[InlineData("Teen Titans v1 001 (1966-02) (digital) (OkC.O.M.P.U.T.O.-Novus)", "1")]
[InlineData("Superman v1 024 (09-10 1943)", "24")]
[InlineData("Invincible 070.5 - Invincible Returns 1 (2010) (digital) (Minutemen-InnerDemons).cbr", "70.5")]
[InlineData("Amazing Man Comics chapter 25", "25")]
+ [InlineData("Invincible 033.5 - Marvel Team-Up 14 (2006) (digital) (Minutemen-Slayer)", "33.5")]
+ [InlineData("Batman Wayne Family Adventures - Ep. 014 - Moving In", "14")]
+ [InlineData("Saga 001 (2012) (Digital) (Empire-Zone)", "1")]
+ [InlineData("Batman Beyond 04 (of 6) (1999)", "4")]
+ [InlineData("Invincible 052 (c2c) (2008) (Minutemen-TheCouple)", "52")]
+ [InlineData("Y - The Last Man #001", "1")]
public void ParseComicChapterTest(string filename, string expected)
{
Assert.Equal(expected, API.Parser.Parser.ParseComicChapter(filename));
diff --git a/API.Tests/Parser/MangaParserTests.cs b/API.Tests/Parser/MangaParserTests.cs
index d27f22dd9..917d1f467 100644
--- a/API.Tests/Parser/MangaParserTests.cs
+++ b/API.Tests/Parser/MangaParserTests.cs
@@ -66,6 +66,7 @@ namespace API.Tests.Parser
[InlineData("Noblesse - Episode 406 (52 Pages).7z", "0")]
[InlineData("X-Men v1 #201 (September 2007).cbz", "1")]
[InlineData("Hentai Ouji to Warawanai Neko. - Vol. 06 Ch. 034.5", "6")]
+ [InlineData("The 100 Girlfriends Who Really, Really, Really, Really, Really Love You - Vol. 03 Ch. 023.5 - Volume 3 Extras.cbz", "3")]
public void ParseVolumeTest(string filename, string expected)
{
Assert.Equal(expected, API.Parser.Parser.ParseVolume(filename));
@@ -128,7 +129,6 @@ namespace API.Tests.Parser
[InlineData("Fullmetal Alchemist chapters 101-108.cbz", "Fullmetal Alchemist")]
[InlineData("To Love Ru v09 Uncensored (Ch.071-079).cbz", "To Love Ru")]
[InlineData("[dmntsf.net] One Piece - Digital Colored Comics Vol. 20 Ch. 177 - 30 Million vs 81 Million.cbz", "One Piece - Digital Colored Comics")]
- //[InlineData("Corpse Party -The Anthology- Sachikos game of love Hysteric Birthday 2U Extra Chapter", "Corpse Party -The Anthology- Sachikos game of love Hysteric Birthday 2U")]
[InlineData("Corpse Party -The Anthology- Sachikos game of love Hysteric Birthday 2U Chapter 01", "Corpse Party -The Anthology- Sachikos game of love Hysteric Birthday 2U")]
[InlineData("Vol03_ch15-22.rar", "")]
[InlineData("Love Hina - Special.cbz", "")] // This has to be a fallback case
@@ -157,6 +157,15 @@ namespace API.Tests.Parser
[InlineData("Killing Bites - Vol 11 Chapter 050 Save Me, Nunupi!.cbz", "Killing Bites")]
[InlineData("Mad Chimera World - Volume 005 - Chapter 026.cbz", "Mad Chimera World")]
[InlineData("Hentai Ouji to Warawanai Neko. - Vol. 06 Ch. 034.5", "Hentai Ouji to Warawanai Neko.")]
+ [InlineData("The 100 Girlfriends Who Really, Really, Really, Really, Really Love You - Vol. 03 Ch. 023.5 - Volume 3 Extras.cbz", "The 100 Girlfriends Who Really, Really, Really, Really, Really Love You")]
+ [InlineData("Kimi no Koto ga Daidaidaidaidaisuki na 100-nin no Kanojo Chapter 1-10", "Kimi no Koto ga Daidaidaidaidaisuki na 100-nin no Kanojo")]
+ [InlineData("The Duke of Death and His Black Maid - Ch. 177 - The Ball (3).cbz", "The Duke of Death and His Black Maid")]
+ [InlineData("A Compendium of Ghosts - 031 - The Third Story_ Part 12 (Digital) (Cobalt001)", "A Compendium of Ghosts")]
+ [InlineData("The Duke of Death and His Black Maid - Vol. 04 Ch. 054.5 - V4 Omake", "The Duke of Death and His Black Maid")]
+ [InlineData("Vol. 04 Ch. 054.5", "")]
+ [InlineData("Great_Teacher_Onizuka_v16[TheSpectrum]", "Great Teacher Onizuka")]
+ [InlineData("[Renzokusei]_Kimi_wa_Midara_na_Boku_no_Joou_Ch5_Final_Chapter", "Kimi wa Midara na Boku no Joou")]
+ [InlineData("Battle Royale, v01 (2000) [TokyoPop] [Manga-Sketchbook]", "Battle Royale")]
public void ParseSeriesTest(string filename, string expected)
{
Assert.Equal(expected, API.Parser.Parser.ParseSeries(filename));
@@ -226,6 +235,9 @@ namespace API.Tests.Parser
[InlineData("Ijousha No Ai - Vol.01 Chapter 029 8 Years Ago", "29")]
[InlineData("Kedouin Makoto - Corpse Party Musume, Chapter 09.cbz", "9")]
[InlineData("Hentai Ouji to Warawanai Neko. - Vol. 06 Ch. 034.5", "34.5")]
+ [InlineData("Kimi no Koto ga Daidaidaidaidaisuki na 100-nin no Kanojo Chapter 1-10", "1-10")]
+ [InlineData("Deku_&_Bakugo_-_Rising_v1_c1.1.cbz", "1.1")]
+ [InlineData("Chapter 63 - The Promise Made for 520 Cenz.cbr", "63")]
public void ParseChaptersTest(string filename, string expected)
{
Assert.Equal(expected, API.Parser.Parser.ParseChapter(filename));
@@ -408,6 +420,22 @@ namespace API.Tests.Parser
FullFilePath = filepath, IsSpecial = false
});
+ filepath = @"E:\Manga\Kono Subarashii Sekai ni Bakuen wo!\Vol. 00 Ch. 000.cbz";
+ expected.Add(filepath, new ParserInfo
+ {
+ Series = "Kono Subarashii Sekai ni Bakuen wo!", Volumes = "0", Edition = "",
+ Chapters = "0", Filename = "Vol. 00 Ch. 000.cbz", Format = MangaFormat.Archive,
+ FullFilePath = filepath, IsSpecial = false
+ });
+
+ filepath = @"E:\Manga\Toukyou Akazukin\Vol. 01 Ch. 001.cbz";
+ expected.Add(filepath, new ParserInfo
+ {
+ Series = "Toukyou Akazukin", Volumes = "1", Edition = "",
+ Chapters = "1", Filename = "Vol. 01 Ch. 001.cbz", Format = MangaFormat.Archive,
+ FullFilePath = filepath, IsSpecial = false
+ });
+
// If an image is cover exclusively, ignore it
filepath = @"E:\Manga\Seraph of the End\cover.png";
expected.Add(filepath, null);
diff --git a/API.Tests/Parser/ParserTest.cs b/API.Tests/Parser/ParserTest.cs
index 5857a50c9..6830cde0d 100644
--- a/API.Tests/Parser/ParserTest.cs
+++ b/API.Tests/Parser/ParserTest.cs
@@ -156,6 +156,7 @@ namespace API.Tests.Parser
[InlineData("test.png", true)]
[InlineData(".test.jpg", false)]
[InlineData("!test.jpg", false)]
+ [InlineData("test.webp", true)]
public void IsImageTest(string filename, bool expected)
{
Assert.Equal(expected, IsImage(filename));
diff --git a/API.Tests/Services/ArchiveServiceTests.cs b/API.Tests/Services/ArchiveServiceTests.cs
index 50d2d0673..80f09a144 100644
--- a/API.Tests/Services/ArchiveServiceTests.cs
+++ b/API.Tests/Services/ArchiveServiceTests.cs
@@ -2,6 +2,7 @@
using System.IO;
using System.IO.Compression;
using API.Archive;
+using API.Interfaces.Services;
using API.Services;
using Microsoft.Extensions.Logging;
using NSubstitute;
@@ -17,11 +18,12 @@ namespace API.Tests.Services
private readonly ArchiveService _archiveService;
private readonly ILogger<ArchiveService> _logger = Substitute.For<ILogger<ArchiveService>>();
private readonly ILogger<DirectoryService> _directoryServiceLogger = Substitute.For<ILogger<DirectoryService>>();
+ private readonly IDirectoryService _directoryService = new DirectoryService(Substitute.For<ILogger<DirectoryService>>());
public ArchiveServiceTests(ITestOutputHelper testOutputHelper)
{
_testOutputHelper = testOutputHelper;
- _archiveService = new ArchiveService(_logger, new DirectoryService(_directoryServiceLogger));
+ _archiveService = new ArchiveService(_logger, _directoryService);
}
[Theory]
@@ -50,7 +52,7 @@ namespace API.Tests.Services
var testDirectory = Path.Join(Directory.GetCurrentDirectory(), "../../../Services/Test Data/ArchiveService/Archives");
Assert.Equal(expected, _archiveService.IsValidArchive(Path.Join(testDirectory, archivePath)));
}
-
+
[Theory]
[InlineData("non existent file.zip", 0)]
[InlineData("winrar.rar", 0)]
@@ -69,7 +71,7 @@ namespace API.Tests.Services
Assert.Equal(expected, _archiveService.GetNumberOfPagesFromArchive(Path.Join(testDirectory, archivePath)));
_testOutputHelper.WriteLine($"Processed Original in {sw.ElapsedMilliseconds} ms");
}
-
+
[Theory]
@@ -84,12 +86,12 @@ namespace API.Tests.Services
{
var sw = Stopwatch.StartNew();
var testDirectory = Path.Join(Directory.GetCurrentDirectory(), "../../../Services/Test Data/ArchiveService/Archives");
-
+
Assert.Equal(expected, _archiveService.CanOpen(Path.Join(testDirectory, archivePath)));
_testOutputHelper.WriteLine($"Processed Original in {sw.ElapsedMilliseconds} ms");
}
-
-
+
+
[Theory]
[InlineData("non existent file.zip", 0)]
[InlineData("winrar.rar", 0)]
@@ -100,18 +102,18 @@ namespace API.Tests.Services
[InlineData("file in folder_alt.zip", 1)]
public void CanExtractArchive(string archivePath, int expectedFileCount)
{
-
+
var testDirectory = Path.Join(Directory.GetCurrentDirectory(), "../../../Services/Test Data/ArchiveService/Archives");
var extractDirectory = Path.Join(Directory.GetCurrentDirectory(), "../../../Services/Test Data/ArchiveService/Archives/Extraction");
DirectoryService.ClearAndDeleteDirectory(extractDirectory);
-
+
Stopwatch sw = Stopwatch.StartNew();
_archiveService.ExtractArchive(Path.Join(testDirectory, archivePath), extractDirectory);
var di1 = new DirectoryInfo(extractDirectory);
Assert.Equal(expectedFileCount, di1.Exists ? di1.GetFiles().Length : 0);
_testOutputHelper.WriteLine($"Processed in {sw.ElapsedMilliseconds} ms");
-
+
DirectoryService.ClearAndDeleteDirectory(extractDirectory);
}
@@ -142,14 +144,14 @@ namespace API.Tests.Services
var foundFile = _archiveService.FirstFileEntry(files);
Assert.Equal(expected, string.IsNullOrEmpty(foundFile) ? "" : foundFile);
}
-
-
-
- [Theory]
+
+
+
+ // TODO: This is broken on GA due to DirectoryService.CoverImageDirectory
+ //[Theory]
[InlineData("v10.cbz", "v10.expected.jpg")]
[InlineData("v10 - with folder.cbz", "v10 - with folder.expected.jpg")]
[InlineData("v10 - nested folder.cbz", "v10 - nested folder.expected.jpg")]
- //[InlineData("png.zip", "png.PNG")]
[InlineData("macos_native.zip", "macos_native.jpg")]
[InlineData("v10 - duplicate covers.cbz", "v10 - duplicate covers.expected.jpg")]
[InlineData("sorting.zip", "sorting.expected.jpg")]
@@ -159,17 +161,29 @@ namespace API.Tests.Services
var testDirectory = Path.Join(Directory.GetCurrentDirectory(), "../../../Services/Test Data/ArchiveService/CoverImages");
var expectedBytes = File.ReadAllBytes(Path.Join(testDirectory, expectedOutputFile));
archiveService.Configure().CanOpen(Path.Join(testDirectory, inputFile)).Returns(ArchiveLibrary.Default);
- Stopwatch sw = Stopwatch.StartNew();
- Assert.Equal(expectedBytes, archiveService.GetCoverImage(Path.Join(testDirectory, inputFile)));
+ var sw = Stopwatch.StartNew();
+
+ var outputDir = Path.Join(testDirectory, "output");
+ DirectoryService.ClearAndDeleteDirectory(outputDir);
+ DirectoryService.ExistOrCreate(outputDir);
+
+
+ var coverImagePath = archiveService.GetCoverImage(Path.Join(testDirectory, inputFile),
+ Path.GetFileNameWithoutExtension(inputFile) + "_output");
+ var actual = File.ReadAllBytes(coverImagePath);
+
+
+ Assert.Equal(expectedBytes, actual);
_testOutputHelper.WriteLine($"Processed in {sw.ElapsedMilliseconds} ms");
+ DirectoryService.ClearAndDeleteDirectory(outputDir);
}
-
-
- [Theory]
+
+
+ // TODO: This is broken on GA due to DirectoryService.CoverImageDirectory
+ //[Theory]
[InlineData("v10.cbz", "v10.expected.jpg")]
[InlineData("v10 - with folder.cbz", "v10 - with folder.expected.jpg")]
[InlineData("v10 - nested folder.cbz", "v10 - nested folder.expected.jpg")]
- //[InlineData("png.zip", "png.PNG")]
[InlineData("macos_native.zip", "macos_native.jpg")]
[InlineData("v10 - duplicate covers.cbz", "v10 - duplicate covers.expected.jpg")]
[InlineData("sorting.zip", "sorting.expected.jpg")]
@@ -178,20 +192,21 @@ namespace API.Tests.Services
var archiveService = Substitute.For<ArchiveService>(_logger, new DirectoryService(_directoryServiceLogger));
var testDirectory = Path.Join(Directory.GetCurrentDirectory(), "../../../Services/Test Data/ArchiveService/CoverImages");
var expectedBytes = File.ReadAllBytes(Path.Join(testDirectory, expectedOutputFile));
-
+
archiveService.Configure().CanOpen(Path.Join(testDirectory, inputFile)).Returns(ArchiveLibrary.SharpCompress);
Stopwatch sw = Stopwatch.StartNew();
- Assert.Equal(expectedBytes, archiveService.GetCoverImage(Path.Join(testDirectory, inputFile)));
+ Assert.Equal(expectedBytes, File.ReadAllBytes(archiveService.GetCoverImage(Path.Join(testDirectory, inputFile), Path.GetFileNameWithoutExtension(inputFile) + "_output")));
_testOutputHelper.WriteLine($"Processed in {sw.ElapsedMilliseconds} ms");
}
- [Theory]
+ // TODO: This is broken on GA due to DirectoryService.CoverImageDirectory
+ //[Theory]
[InlineData("Archives/macos_native.zip")]
[InlineData("Formats/One File with DB_Supported.zip")]
public void CanParseCoverImage(string inputFile)
{
var testDirectory = Path.Join(Directory.GetCurrentDirectory(), "../../../Services/Test Data/ArchiveService/");
- Assert.NotEmpty(_archiveService.GetCoverImage(Path.Join(testDirectory, inputFile)));
+ Assert.NotEmpty(File.ReadAllBytes(_archiveService.GetCoverImage(Path.Join(testDirectory, inputFile), Path.GetFileNameWithoutExtension(inputFile) + "_output")));
}
[Fact]
@@ -200,9 +215,9 @@ namespace API.Tests.Services
var testDirectory = Path.Join(Directory.GetCurrentDirectory(), "../../../Services/Test Data/ArchiveService/ComicInfos");
var archive = Path.Join(testDirectory, "file in folder.zip");
var summaryInfo = "By all counts, Ryouta Sakamoto is a loser when he's not holed up in his room, bombing things into oblivion in his favorite online action RPG. But his very own uneventful life is blown to pieces when he's abducted and taken to an uninhabited island, where he soon learns the hard way that he's being pitted against others just like him in a explosives-riddled death match! How could this be happening? Who's putting them up to this? And why!? The name, not to mention the objective, of this very real survival game is eerily familiar to Ryouta, who has mastered its virtual counterpart-BTOOOM! Can Ryouta still come out on top when he's playing for his life!?";
-
+
Assert.Equal(summaryInfo, _archiveService.GetSummaryInfo(archive));
}
}
-}
\ No newline at end of file
+}
diff --git a/API.Tests/Services/DirectoryServiceTests.cs b/API.Tests/Services/DirectoryServiceTests.cs
index 4dcb77dec..db756ebab 100644
--- a/API.Tests/Services/DirectoryServiceTests.cs
+++ b/API.Tests/Services/DirectoryServiceTests.cs
@@ -89,6 +89,15 @@ namespace API.Tests.Services
}
+ [Theory]
+ [InlineData(new string[] {"C:/Manga/"}, new string[] {"C:/Manga/Love Hina/Vol. 01.cbz"}, "C:/Manga/Love Hina")]
+ public void FindHighestDirectoriesFromFilesTest(string[] rootDirectories, string[] folders, string expectedDirectory)
+ {
+ var actual = DirectoryService.FindHighestDirectoriesFromFiles(rootDirectories, folders);
+ var expected = new Dictionary<string, string> {{expectedDirectory, ""}};
+ Assert.Equal(expected, actual);
+ }
+
[Theory]
[InlineData("C:/Manga/", "C:/Manga/Love Hina/Specials/Omake/", "Omake,Specials,Love Hina")]
[InlineData("C:/Manga/", "C:/Manga/Love Hina/Specials/Omake", "Omake,Specials,Love Hina")]
@@ -102,6 +111,7 @@ namespace API.Tests.Services
[InlineData(@"C:/", @"C://Btooom!/Vol.1 Chapter 2/1.cbz", "Vol.1 Chapter 2,Btooom!")]
[InlineData(@"C:\\", @"C://Btooom!/Vol.1 Chapter 2/1.cbz", "Vol.1 Chapter 2,Btooom!")]
[InlineData(@"C://mount/gdrive/Library/Test Library/Comics", @"C://mount/gdrive/Library/Test Library/Comics/Dragon Age/Test", "Test,Dragon Age")]
+ [InlineData(@"M:\", @"M:\Toukyou Akazukin\Vol. 01 Ch. 005.cbz", @"Toukyou Akazukin")]
public void GetFoldersTillRoot_Test(string rootPath, string fullpath, string expectedArray)
{
var expected = expectedArray.Split(",");
diff --git a/API.Tests/Services/MetadataServiceTests.cs b/API.Tests/Services/MetadataServiceTests.cs
index 796201538..b921f74b7 100644
--- a/API.Tests/Services/MetadataServiceTests.cs
+++ b/API.Tests/Services/MetadataServiceTests.cs
@@ -4,6 +4,8 @@ using API.Entities;
using API.Interfaces;
using API.Interfaces.Services;
using API.Services;
+using API.SignalR;
+using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Xunit;
@@ -13,16 +15,19 @@ namespace API.Tests.Services
public class MetadataServiceTests
{
private readonly string _testDirectory = Path.Join(Directory.GetCurrentDirectory(), "../../../Services/Test Data/ArchiveService/Archives");
- private readonly MetadataService _metadataService;
- private readonly IUnitOfWork _unitOfWork = Substitute.For<IUnitOfWork>();
- private readonly IImageService _imageService = Substitute.For<IImageService>();
- private readonly IBookService _bookService = Substitute.For<IBookService>();
- private readonly IArchiveService _archiveService = Substitute.For<IArchiveService>();
- private readonly ILogger<MetadataService> _logger = Substitute.For<ILogger<MetadataService>>();
+ private const string TestCoverImageFile = "thumbnail.jpg";
+ private readonly string _testCoverImageDirectory = Path.Join(Directory.GetCurrentDirectory(), @"../../../Services/Test Data/ArchiveService/CoverImages");
+ //private readonly MetadataService _metadataService;
+ // private readonly IUnitOfWork _unitOfWork = Substitute.For<IUnitOfWork>();
+ // private readonly IImageService _imageService = Substitute.For<IImageService>();
+ // private readonly IBookService _bookService = Substitute.For<IBookService>();
+ // private readonly IArchiveService _archiveService = Substitute.For<IArchiveService>();
+ // private readonly ILogger<MetadataService> _logger = Substitute.For<ILogger<MetadataService>>();
+ // private readonly IHubContext<MessageHub> _messageHub = Substitute.For<IHubContext<MessageHub>>();
public MetadataServiceTests()
{
- _metadataService = new MetadataService(_unitOfWork, _logger, _archiveService, _bookService, _imageService);
+ //_metadataService = new MetadataService(_unitOfWork, _logger, _archiveService, _bookService, _imageService, _messageHub);
}
[Fact]
@@ -44,7 +49,7 @@ namespace API.Tests.Services
}
[Fact]
- public void ShouldUpdateCoverImage_OnSecondRun_FileModified()
+ public void ShouldUpdateCoverImage_OnFirstRun_FileModified()
{
// Represents first run
Assert.True(MetadataService.ShouldUpdateCoverImage(null, new MangaFile()
@@ -55,10 +60,10 @@ namespace API.Tests.Services
}
[Fact]
- public void ShouldUpdateCoverImage_OnSecondRun_CoverImageLocked()
+ public void ShouldUpdateCoverImage_OnFirstRun_CoverImageLocked()
{
// Represents first run
- Assert.False(MetadataService.ShouldUpdateCoverImage(null, new MangaFile()
+ Assert.True(MetadataService.ShouldUpdateCoverImage(null, new MangaFile()
{
FilePath = Path.Join(_testDirectory, "file in folder.zip"),
LastModified = new FileInfo(Path.Join(_testDirectory, "file in folder.zip")).LastWriteTime
@@ -99,14 +104,36 @@ namespace API.Tests.Services
}
[Fact]
- public void ShouldUpdateCoverImage_OnSecondRun_CoverImageSet()
+ public void ShouldNotUpdateCoverImage_OnSecondRun_CoverImageSet()
{
// Represents first run
- Assert.False(MetadataService.ShouldUpdateCoverImage(new byte[] {1}, new MangaFile()
+ Assert.False(MetadataService.ShouldUpdateCoverImage(TestCoverImageFile, new MangaFile()
{
FilePath = Path.Join(_testDirectory, "file in folder.zip"),
LastModified = new FileInfo(Path.Join(_testDirectory, "file in folder.zip")).LastWriteTime
- }, false, false));
+ }, false, false, _testCoverImageDirectory));
+ }
+
+ [Fact]
+ public void ShouldNotUpdateCoverImage_OnSecondRun_HasCoverImage_NoForceUpdate_NoLock()
+ {
+
+ Assert.False(MetadataService.ShouldUpdateCoverImage(TestCoverImageFile, new MangaFile()
+ {
+ FilePath = Path.Join(_testDirectory, "file in folder.zip"),
+ LastModified = DateTime.Now
+ }, false, false, _testCoverImageDirectory));
+ }
+
+ [Fact]
+ public void ShouldUpdateCoverImage_OnSecondRun_HasCoverImage_NoForceUpdate_HasLock_CoverImageDoesntExist()
+ {
+
+ Assert.True(MetadataService.ShouldUpdateCoverImage(@"doesn't_exist.jpg", new MangaFile()
+ {
+ FilePath = Path.Join(_testDirectory, "file in folder.zip"),
+ LastModified = DateTime.Now
+ }, false, true, _testCoverImageDirectory));
}
}
}
diff --git a/API.Tests/Services/ScannerServiceTests.cs b/API.Tests/Services/ScannerServiceTests.cs
index 2c7a999f0..93b254c8e 100644
--- a/API.Tests/Services/ScannerServiceTests.cs
+++ b/API.Tests/Services/ScannerServiceTests.cs
@@ -14,8 +14,10 @@ using API.Parser;
using API.Services;
using API.Services.Tasks;
using API.Services.Tasks.Scanner;
+using API.SignalR;
using API.Tests.Helpers;
using AutoMapper;
+using Microsoft.AspNetCore.SignalR;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
@@ -34,6 +36,7 @@ namespace API.Tests.Services
private readonly IImageService _imageService = Substitute.For<IImageService>();
private readonly ILogger<MetadataService> _metadataLogger = Substitute.For<ILogger<MetadataService>>();
private readonly ICacheService _cacheService = Substitute.For<ICacheService>();
+ private readonly IHubContext<MessageHub> _messageHub = Substitute.For<IHubContext<MessageHub>>();
private readonly DbConnection _connection;
private readonly DataContext _context;
@@ -52,8 +55,8 @@ namespace API.Tests.Services
IUnitOfWork unitOfWork = new UnitOfWork(_context, Substitute.For<IMapper>(), null);
- IMetadataService metadataService = Substitute.For<MetadataService>(unitOfWork, _metadataLogger, _archiveService, _bookService, _imageService);
- _scannerService = new ScannerService(unitOfWork, _logger, _archiveService, metadataService, _bookService, _cacheService);
+ IMetadataService metadataService = Substitute.For<MetadataService>(unitOfWork, _metadataLogger, _archiveService, _bookService, _imageService, _messageHub);
+ _scannerService = new ScannerService(unitOfWork, _logger, _archiveService, metadataService, _bookService, _cacheService, _messageHub);
}
private async Task<bool> SeedDb()
@@ -111,6 +114,7 @@ namespace API.Tests.Services
Assert.Empty(_scannerService.FindSeriesNotOnDisk(existingSeries, infos));
}
+
// TODO: Figure out how to do this with ParseScannedFiles
// [Theory]
// [InlineData(new [] {"Darker than Black"}, "Darker than Black", "Darker than Black")]
diff --git a/API.Tests/Services/Test Data/ImageService/cover.expected.jpg b/API.Tests/Services/Test Data/ImageService/cover.expected.jpg
new file mode 100644
index 000000000..73da78f50
Binary files /dev/null and b/API.Tests/Services/Test Data/ImageService/cover.expected.jpg differ
diff --git a/API/API.csproj b/API/API.csproj
index 74bf6fbbc..fa1bcdfec 100644
--- a/API/API.csproj
+++ b/API/API.csproj
@@ -22,8 +22,6 @@
<Company>kareadita.github.io</Company>
<Copyright>Copyright 2020-$([System.DateTime]::Now.ToString('yyyy')) kavitareader.com (GNU General Public v3)</Copyright>
- <!-- Should be replaced by CI -->
- <AssemblyVersion>0.4.1</AssemblyVersion>
<AssemblyConfiguration>$(Configuration)-dev</AssemblyConfiguration>
<GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
@@ -60,7 +58,7 @@
<PackageReference Include="NetVips.Native" Version="8.11.0" />
<PackageReference Include="NReco.Logging.File" Version="1.1.2" />
<PackageReference Include="Sentry.AspNetCore" Version="3.8.3" />
- <PackageReference Include="SharpCompress" Version="0.28.3" />
+ <PackageReference Include="SharpCompress" Version="0.29.0" />
<PackageReference Include="SonarAnalyzer.CSharp" Version="8.27.0.35380">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -75,42 +73,41 @@
<ProjectReference Include="..\Kavita.Common\Kavita.Common.csproj" />
</ItemGroup>
-
+
<ItemGroup>
<None Remove="Hangfire-log.db" />
<None Remove="obj\**" />
- <None Remove="wwwroot\**" />
<None Remove="cache\**" />
<None Remove="backups\**" />
<None Remove="logs\**" />
<None Remove="temp\**" />
<None Remove="kavita.log" />
<None Remove="kavita.db" />
+ <None Remove="covers\**" />
</ItemGroup>
<ItemGroup>
<Compile Remove="Interfaces\IMetadataService.cs" />
<Compile Remove="obj\**" />
- <Compile Remove="wwwroot\**" />
<Compile Remove="cache\**" />
<Compile Remove="backups\**" />
<Compile Remove="logs\**" />
<Compile Remove="temp\**" />
+ <Compile Remove="covers\**" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Remove="obj\**" />
- <EmbeddedResource Remove="wwwroot\**" />
<EmbeddedResource Remove="cache\**" />
<EmbeddedResource Remove="backups\**" />
<EmbeddedResource Remove="logs\**" />
<EmbeddedResource Remove="temp\**" />
+ <EmbeddedResource Remove="covers\**" />
</ItemGroup>
<ItemGroup>
<Content Remove="obj\**" />
- <Content Remove="wwwroot\**" />
<Content Remove="cache\**" />
<Content Remove="backups\**" />
<Content Remove="logs\**" />
@@ -120,6 +117,7 @@
<Content Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
+ <Content Remove="covers\**" />
</ItemGroup>
<ItemGroup>
@@ -244,6 +242,48 @@
<_ContentIncludedByDefault Remove="wwwroot\styles.4bd902bb3037f36f2c64.css.map" />
<_ContentIncludedByDefault Remove="wwwroot\vendor.6b2a0912ae80e6fd297f.js" />
<_ContentIncludedByDefault Remove="wwwroot\vendor.6b2a0912ae80e6fd297f.js.map" />
+ <_ContentIncludedByDefault Remove="wwwroot\10.b727db78581442412e9a.js" />
+ <_ContentIncludedByDefault Remove="wwwroot\10.b727db78581442412e9a.js.map" />
+ <_ContentIncludedByDefault Remove="wwwroot\2.fcc031071e80d6837012.js" />
+ <_ContentIncludedByDefault Remove="wwwroot\2.fcc031071e80d6837012.js.map" />
+ <_ContentIncludedByDefault Remove="wwwroot\7.c30da7d2e809fa05d1e3.js" />
+ <_ContentIncludedByDefault Remove="wwwroot\7.c30da7d2e809fa05d1e3.js.map" />
+ <_ContentIncludedByDefault Remove="wwwroot\8.d4c77a90c95e9861656a.js" />
+ <_ContentIncludedByDefault Remove="wwwroot\8.d4c77a90c95e9861656a.js.map" />
+ <_ContentIncludedByDefault Remove="wwwroot\9.489b177dd1a6beeb35ad.js" />
+ <_ContentIncludedByDefault Remove="wwwroot\9.489b177dd1a6beeb35ad.js.map" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\fonts\Spartan\OFL.txt" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\fonts\Spartan\Spartan-VariableFont_wght.ttf" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\icons\android-chrome-192x192.png" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\icons\android-chrome-256x256.png" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\icons\apple-touch-icon.png" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\icons\browserconfig.xml" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\icons\favicon-16x16.png" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\icons\favicon-32x32.png" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\icons\favicon.ico" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\icons\mstile-150x150.png" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\images\image-reset-cover-min.png" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\images\image-reset-cover.png" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\images\kavita-book-cropped.png" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\images\login-bg.jpg" />
+ <_ContentIncludedByDefault Remove="wwwroot\assets\images\logo.png" />
+ <_ContentIncludedByDefault Remove="wwwroot\common.fbf71de364f5a1f37413.js" />
+ <_ContentIncludedByDefault Remove="wwwroot\common.fbf71de364f5a1f37413.js.map" />
+ <_ContentIncludedByDefault Remove="wwwroot\login-bg.8860e6ff9d2a3598539c.jpg" />
+ <_ContentIncludedByDefault Remove="wwwroot\main.a3a1e647a39145accff3.js" />
+ <_ContentIncludedByDefault Remove="wwwroot\main.a3a1e647a39145accff3.js.map" />
+ <_ContentIncludedByDefault Remove="wwwroot\polyfills.3dda3bf3d087e5d131ba.js" />
+ <_ContentIncludedByDefault Remove="wwwroot\polyfills.3dda3bf3d087e5d131ba.js.map" />
+ <_ContentIncludedByDefault Remove="wwwroot\runtime.b9818dfc90f418b3f0a7.js" />
+ <_ContentIncludedByDefault Remove="wwwroot\runtime.b9818dfc90f418b3f0a7.js.map" />
+ <_ContentIncludedByDefault Remove="wwwroot\scripts.7d1c78b2763c483bb699.js" />
+ <_ContentIncludedByDefault Remove="wwwroot\scripts.7d1c78b2763c483bb699.js.map" />
+ <_ContentIncludedByDefault Remove="wwwroot\site.webmanifest" />
+ <_ContentIncludedByDefault Remove="wwwroot\Spartan-VariableFont_wght.0427aac0d980a12ae8ba.ttf" />
+ <_ContentIncludedByDefault Remove="wwwroot\styles.85a58cb3e4a4b1add864.css" />
+ <_ContentIncludedByDefault Remove="wwwroot\styles.85a58cb3e4a4b1add864.css.map" />
+ <_ContentIncludedByDefault Remove="wwwroot\vendor.54bf44a9aa720ff8881d.js" />
+ <_ContentIncludedByDefault Remove="wwwroot\vendor.54bf44a9aa720ff8881d.js.map" />
</ItemGroup>
<ItemGroup>
diff --git a/API/API.csproj.DotSettings b/API/API.csproj.DotSettings
new file mode 100644
index 000000000..80aad93c5
--- /dev/null
+++ b/API/API.csproj.DotSettings
@@ -0,0 +1,2 @@
+<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
+ <s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=covers/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
\ No newline at end of file
diff --git a/API/Comparators/ChapterSortComparer.cs b/API/Comparators/ChapterSortComparer.cs
index a56693fca..3791e05ff 100644
--- a/API/Comparators/ChapterSortComparer.cs
+++ b/API/Comparators/ChapterSortComparer.cs
@@ -2,8 +2,17 @@
namespace API.Comparators
{
+ /// <summary>
+ /// Sorts chapters based on their Number. Uses natural ordering of doubles.
+ /// </summary>
public class ChapterSortComparer : IComparer<double>
{
+ /// <summary>
+ /// Normal sort for 2 doubles. 0 always comes before anything else
+ /// </summary>
+ /// <param name="x"></param>
+ /// <param name="y"></param>
+ /// <returns></returns>
public int Compare(double x, double y)
{
if (x == 0.0 && y == 0.0) return 0;
diff --git a/API/Comparators/NaturalSortComparer.cs b/API/Comparators/NaturalSortComparer.cs
index ac10e09ae..9bf79db81 100644
--- a/API/Comparators/NaturalSortComparer.cs
+++ b/API/Comparators/NaturalSortComparer.cs
@@ -10,7 +10,7 @@ namespace API.Comparators
{
private readonly bool _isAscending;
private Dictionary<string, string[]> _table = new();
-
+
private bool _disposed;
@@ -23,9 +23,9 @@ namespace API.Comparators
{
if (x == y) return 0;
+ // Should be fixed: Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.
if (!_table.TryGetValue(x ?? Empty, out var x1))
{
- // .Replace(" ", Empty)
x1 = Regex.Split(x ?? Empty, "([0-9]+)");
_table.Add(x ?? Empty, x1);
}
@@ -33,6 +33,7 @@ namespace API.Comparators
if (!_table.TryGetValue(y ?? Empty, out var y1))
{
y1 = Regex.Split(y ?? Empty, "([0-9]+)");
+ // Should be fixed: EXCEPTION: An item with the same key has already been added. Key: M:\Girls of the Wild's\Girls of the Wild's - Ep. 083 (Season 1) [LINE Webtoon].cbz
_table.Add(y ?? Empty, y1);
}
@@ -50,8 +51,8 @@ namespace API.Comparators
returnVal = 1;
}
else if (x1.Length > y1.Length)
- {
- returnVal = -1;
+ {
+ returnVal = -1;
}
else
{
@@ -78,12 +79,12 @@ namespace API.Comparators
{
if (disposing)
{
- // called via myClass.Dispose().
+ // called via myClass.Dispose().
_table.Clear();
_table = null;
}
// Release unmanaged resources.
- // Set large fields to null.
+ // Set large fields to null.
_disposed = true;
}
}
@@ -93,10 +94,10 @@ namespace API.Comparators
Dispose(true);
SuppressFinalize(this);
}
-
+
~NaturalSortComparer() // the finalizer
{
Dispose(false);
}
}
-}
\ No newline at end of file
+}
diff --git a/API/Controllers/AccountController.cs b/API/Controllers/AccountController.cs
index 8e108cd28..58478e2f8 100644
--- a/API/Controllers/AccountController.cs
+++ b/API/Controllers/AccountController.cs
@@ -5,6 +5,7 @@ using System.Reflection;
using System.Threading.Tasks;
using API.Constants;
using API.DTOs;
+using API.DTOs.Account;
using API.Entities;
using API.Errors;
using API.Extensions;
diff --git a/API/Controllers/BookController.cs b/API/Controllers/BookController.cs
index d48b75707..448d45c02 100644
--- a/API/Controllers/BookController.cs
+++ b/API/Controllers/BookController.cs
@@ -2,6 +2,8 @@
using System.Linq;
using System.Threading.Tasks;
using API.DTOs;
+using API.DTOs.Reader;
+using API.Entities.Enums;
using API.Extensions;
using API.Interfaces;
using API.Interfaces.Services;
@@ -31,18 +33,36 @@ namespace API.Controllers
}
[HttpGet("{chapterId}/book-info")]
- public async Task<ActionResult<string>> GetBookInfo(int chapterId)
+ public async Task<ActionResult<BookInfoDto>> GetBookInfo(int chapterId)
{
- var chapter = await _unitOfWork.VolumeRepository.GetChapterAsync(chapterId);
- using var book = await EpubReader.OpenBookAsync(chapter.Files.ElementAt(0).FilePath);
+ var dto = await _unitOfWork.ChapterRepository.GetChapterInfoDtoAsync(chapterId);
+ var bookTitle = string.Empty;
+ if (dto.SeriesFormat == MangaFormat.Epub)
+ {
+ var mangaFile = (await _unitOfWork.ChapterRepository.GetFilesForChapterAsync(chapterId)).First();
+ using var book = await EpubReader.OpenBookAsync(mangaFile.FilePath);
+ bookTitle = book.Title;
+ }
- return book.Title;
+ return Ok(new BookInfoDto()
+ {
+ ChapterNumber = dto.ChapterNumber,
+ VolumeNumber = dto.VolumeNumber,
+ VolumeId = dto.VolumeId,
+ BookTitle = bookTitle,
+ SeriesName = dto.SeriesName,
+ SeriesFormat = dto.SeriesFormat,
+ SeriesId = dto.SeriesId,
+ LibraryId = dto.LibraryId,
+ IsSpecial = dto.IsSpecial,
+ Pages = dto.Pages,
+ });
}
[HttpGet("{chapterId}/book-resources")]
public async Task<ActionResult> GetBookPageResources(int chapterId, [FromQuery] string file)
{
- var chapter = await _unitOfWork.VolumeRepository.GetChapterAsync(chapterId);
+ var chapter = await _unitOfWork.ChapterRepository.GetChapterAsync(chapterId);
var book = await EpubReader.OpenBookAsync(chapter.Files.ElementAt(0).FilePath);
var key = BookService.CleanContentKeys(file);
@@ -61,7 +81,7 @@ namespace API.Controllers
{
// This will return a list of mappings from ID -> pagenum. ID will be the xhtml key and pagenum will be the reading order
// this is used to rewrite anchors in the book text so that we always load properly in FE
- var chapter = await _unitOfWork.VolumeRepository.GetChapterAsync(chapterId);
+ var chapter = await _unitOfWork.ChapterRepository.GetChapterAsync(chapterId);
using var book = await EpubReader.OpenBookAsync(chapter.Files.ElementAt(0).FilePath);
var mappings = await _bookService.CreateKeyToPageMappingAsync(book);
diff --git a/API/Controllers/CollectionController.cs b/API/Controllers/CollectionController.cs
index 8bf10c09a..6081f7d58 100644
--- a/API/Controllers/CollectionController.cs
+++ b/API/Controllers/CollectionController.cs
@@ -121,7 +121,7 @@ namespace API.Controllers
if (!updateSeriesForTagDto.Tag.CoverImageLocked)
{
tag.CoverImageLocked = false;
- tag.CoverImage = Array.Empty<byte>();
+ tag.CoverImage = string.Empty;
_unitOfWork.CollectionTagRepository.Update(tag);
}
diff --git a/API/Controllers/DownloadController.cs b/API/Controllers/DownloadController.cs
index 416ffbfc5..3000e1f22 100644
--- a/API/Controllers/DownloadController.cs
+++ b/API/Controllers/DownloadController.cs
@@ -14,7 +14,6 @@ using API.Services;
using Kavita.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.StaticFiles;
namespace API.Controllers
{
@@ -49,7 +48,7 @@ namespace API.Controllers
[HttpGet("chapter-size")]
public async Task<ActionResult<long>> GetChapterSize(int chapterId)
{
- var files = await _unitOfWork.VolumeRepository.GetFilesForChapterAsync(chapterId);
+ var files = await _unitOfWork.ChapterRepository.GetFilesForChapterAsync(chapterId);
return Ok(DirectoryService.GetTotalSize(files.Select(c => c.FilePath)));
}
@@ -91,8 +90,8 @@ namespace API.Controllers
[HttpGet("chapter")]
public async Task<ActionResult> DownloadChapter(int chapterId)
{
- var files = await _unitOfWork.VolumeRepository.GetFilesForChapterAsync(chapterId);
- var chapter = await _unitOfWork.VolumeRepository.GetChapterAsync(chapterId);
+ var files = await _unitOfWork.ChapterRepository.GetFilesForChapterAsync(chapterId);
+ var chapter = await _unitOfWork.ChapterRepository.GetChapterAsync(chapterId);
var volume = await _unitOfWork.SeriesRepository.GetVolumeByIdAsync(chapter.VolumeId);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(volume.SeriesId);
try
@@ -155,7 +154,7 @@ namespace API.Controllers
var chapterExtractPath = Path.Join(fullExtractPath, $"{series.Id}_bookmark_{chapterId}");
var chapterPages = downloadBookmarkDto.Bookmarks.Where(b => b.ChapterId == chapterId)
.Select(b => b.Page).ToList();
- var mangaFiles = await _unitOfWork.VolumeRepository.GetFilesForChapterAsync(chapterId);
+ var mangaFiles = await _unitOfWork.ChapterRepository.GetFilesForChapterAsync(chapterId);
switch (series.Format)
{
case MangaFormat.Image:
diff --git a/API/Controllers/ImageController.cs b/API/Controllers/ImageController.cs
index 31da9c54b..f1ddb770e 100644
--- a/API/Controllers/ImageController.cs
+++ b/API/Controllers/ImageController.cs
@@ -1,7 +1,12 @@
-using System.Threading.Tasks;
+using System;
+using System.IO;
+using System.Net;
+using System.Threading.Tasks;
using API.Extensions;
using API.Interfaces;
+using API.Services;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.Net.Http.Headers;
namespace API.Controllers
{
@@ -10,7 +15,6 @@ namespace API.Controllers
/// </summary>
public class ImageController : BaseApiController
{
- private const string Format = "jpeg";
private readonly IUnitOfWork _unitOfWork;
/// <inheritdoc />
@@ -27,11 +31,12 @@ namespace API.Controllers
[HttpGet("chapter-cover")]
public async Task<ActionResult> GetChapterCoverImage(int chapterId)
{
- var content = await _unitOfWork.VolumeRepository.GetChapterCoverImageAsync(chapterId);
- if (content == null) return BadRequest("No cover image");
+ var path = Path.Join(DirectoryService.CoverImageDirectory, await _unitOfWork.ChapterRepository.GetChapterCoverImageAsync(chapterId));
+ if (string.IsNullOrEmpty(path) || !System.IO.File.Exists(path)) return BadRequest($"No cover image");
+ var format = Path.GetExtension(path).Replace(".", "");
- Response.AddCacheHeader(content);
- return File(content, "image/" + Format, $"{chapterId}");
+ Response.AddCacheHeader(path);
+ return PhysicalFile(path, "image/" + format, Path.GetFileName(path));
}
/// <summary>
@@ -42,11 +47,12 @@ namespace API.Controllers
[HttpGet("volume-cover")]
public async Task<ActionResult> GetVolumeCoverImage(int volumeId)
{
- var content = await _unitOfWork.SeriesRepository.GetVolumeCoverImageAsync(volumeId);
- if (content == null) return BadRequest("No cover image");
+ var path = Path.Join(DirectoryService.CoverImageDirectory, await _unitOfWork.VolumeRepository.GetVolumeCoverImageAsync(volumeId));
+ if (string.IsNullOrEmpty(path) || !System.IO.File.Exists(path)) return BadRequest($"No cover image");
+ var format = Path.GetExtension(path).Replace(".", "");
- Response.AddCacheHeader(content);
- return File(content, "image/" + Format, $"{volumeId}");
+ Response.AddCacheHeader(path);
+ return PhysicalFile(path, "image/" + format, Path.GetFileName(path));
}
/// <summary>
@@ -57,11 +63,12 @@ namespace API.Controllers
[HttpGet("series-cover")]
public async Task<ActionResult> GetSeriesCoverImage(int seriesId)
{
- var content = await _unitOfWork.SeriesRepository.GetSeriesCoverImageAsync(seriesId);
- if (content == null) return BadRequest("No cover image");
+ var path = Path.Join(DirectoryService.CoverImageDirectory, await _unitOfWork.SeriesRepository.GetSeriesCoverImageAsync(seriesId));
+ if (string.IsNullOrEmpty(path) || !System.IO.File.Exists(path)) return BadRequest($"No cover image");
+ var format = Path.GetExtension(path).Replace(".", "");
- Response.AddCacheHeader(content);
- return File(content, "image/" + Format, $"{seriesId}");
+ Response.AddCacheHeader(path);
+ return PhysicalFile(path, "image/" + format, Path.GetFileName(path));
}
/// <summary>
@@ -72,11 +79,12 @@ namespace API.Controllers
[HttpGet("collection-cover")]
public async Task<ActionResult> GetCollectionCoverImage(int collectionTagId)
{
- var content = await _unitOfWork.CollectionTagRepository.GetCoverImageAsync(collectionTagId);
- if (content == null) return BadRequest("No cover image");
+ var path = Path.Join(DirectoryService.CoverImageDirectory, await _unitOfWork.CollectionTagRepository.GetCoverImageAsync(collectionTagId));
+ if (string.IsNullOrEmpty(path) || !System.IO.File.Exists(path)) return BadRequest($"No cover image");
+ var format = Path.GetExtension(path).Replace(".", "");
- Response.AddCacheHeader(content);
- return File(content, "image/" + Format, $"{collectionTagId}");
+ Response.AddCacheHeader(path);
+ return PhysicalFile(path, "image/" + format, Path.GetFileName(path));
}
}
}
diff --git a/API/Controllers/LibraryController.cs b/API/Controllers/LibraryController.cs
index 53c3953ac..25f224a28 100644
--- a/API/Controllers/LibraryController.cs
+++ b/API/Controllers/LibraryController.cs
@@ -225,11 +225,11 @@ namespace API.Controllers
[HttpGet("search")]
public async Task<ActionResult<IEnumerable<SearchResultDto>>> Search(string queryString)
{
- queryString = queryString.Replace(@"%", "");
+ queryString = queryString.Trim().Replace(@"%", "");
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
// Get libraries user has access to
- var libraries = (await _unitOfWork.LibraryRepository.GetLibrariesForUserIdAsync(user.Id)).ToList();
+ var libraries = (await _unitOfWork.LibraryRepository.GetLibrariesForUserIdAsync(userId)).ToList();
if (!libraries.Any()) return BadRequest("User does not have access to any libraries");
diff --git a/API/Controllers/OPDSController.cs b/API/Controllers/OPDSController.cs
index 438dfac77..ef83c2a69 100644
--- a/API/Controllers/OPDSController.cs
+++ b/API/Controllers/OPDSController.cs
@@ -93,6 +93,19 @@ namespace API.Controllers
}
});
feed.Entries.Add(new FeedEntry()
+ {
+ Id = "readingList",
+ Title = "Reading Lists",
+ Content = new FeedEntryContent()
+ {
+ Text = "Browse by Reading Lists"
+ },
+ Links = new List<FeedLink>()
+ {
+ CreateLink(FeedLinkRelation.SubSection, FeedLinkType.AtomNavigation, Prefix + $"{apiKey}/reading-list"),
+ }
+ });
+ feed.Entries.Add(new FeedEntry()
{
Id = "allLibraries",
Title = "All Libraries",
@@ -128,8 +141,8 @@ namespace API.Controllers
{
if (!(await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).EnableOpds)
return BadRequest("OPDS is not enabled on this server");
- var user = await GetUser(apiKey);
- var libraries = await _unitOfWork.LibraryRepository.GetLibrariesForUserIdAsync(user.Id);
+ var userId = await GetUser(apiKey);
+ var libraries = await _unitOfWork.LibraryRepository.GetLibrariesForUserIdAsync(userId);
var feed = CreateFeed("All Libraries", $"{apiKey}/libraries", apiKey);
@@ -155,7 +168,8 @@ namespace API.Controllers
{
if (!(await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).EnableOpds)
return BadRequest("OPDS is not enabled on this server");
- var user = await GetUser(apiKey);
+ var userId = await GetUser(apiKey);
+ var user = await _unitOfWork.UserRepository.GetUserByIdAsync(userId);
var isAdmin = await _userManager.IsInRoleAsync(user, PolicyConstants.AdminRole);
IEnumerable <CollectionTagDto> tags;
@@ -190,13 +204,15 @@ namespace API.Controllers
return CreateXmlResult(SerializeXml(feed));
}
+
[HttpGet("{apiKey}/collections/{collectionId}")]
[Produces("application/xml")]
public async Task<IActionResult> GetCollection(int collectionId, string apiKey, [FromQuery] int pageNumber = 0)
{
if (!(await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).EnableOpds)
return BadRequest("OPDS is not enabled on this server");
- var user = await GetUser(apiKey);
+ var userId = await GetUser(apiKey);
+ var user = await _unitOfWork.UserRepository.GetUserByIdAsync(userId);
var isAdmin = await _userManager.IsInRoleAsync(user, PolicyConstants.AdminRole);
IEnumerable <CollectionTagDto> tags;
@@ -215,7 +231,7 @@ namespace API.Controllers
return BadRequest("Collection does not exist or you don't have access");
}
- var series = await _unitOfWork.SeriesRepository.GetSeriesDtoForCollectionAsync(collectionId, user.Id, new UserParams()
+ var series = await _unitOfWork.SeriesRepository.GetSeriesDtoForCollectionAsync(collectionId, userId, new UserParams()
{
PageNumber = pageNumber,
PageSize = 20
@@ -230,6 +246,77 @@ namespace API.Controllers
}
+ return CreateXmlResult(SerializeXml(feed));
+ }
+
+ [HttpGet("{apiKey}/reading-list")]
+ [Produces("application/xml")]
+ public async Task<IActionResult> GetReadingLists(string apiKey, [FromQuery] int pageNumber = 0)
+ {
+ if (!(await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).EnableOpds)
+ return BadRequest("OPDS is not enabled on this server");
+ var userId = await GetUser(apiKey);
+
+ var readingLists = await _unitOfWork.ReadingListRepository.GetReadingListDtosForUserAsync(userId, true, new UserParams()
+ {
+ PageNumber = pageNumber
+ });
+
+
+ var feed = CreateFeed("All Reading Lists", $"{apiKey}/reading-list", apiKey);
+
+ foreach (var readingListDto in readingLists)
+ {
+ feed.Entries.Add(new FeedEntry()
+ {
+ Id = readingListDto.Id.ToString(),
+ Title = readingListDto.Title,
+ Summary = readingListDto.Summary,
+ Links = new List<FeedLink>()
+ {
+ CreateLink(FeedLinkRelation.SubSection, FeedLinkType.AtomNavigation, Prefix + $"{apiKey}/reading-list/{readingListDto.Id}"),
+ }
+ });
+ }
+
+ return CreateXmlResult(SerializeXml(feed));
+ }
+
+ [HttpGet("{apiKey}/reading-list/{readingListId}")]
+ [Produces("application/xml")]
+ public async Task<IActionResult> GetReadingListItems(int readingListId, string apiKey)
+ {
+ if (!(await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).EnableOpds)
+ return BadRequest("OPDS is not enabled on this server");
+ var userId = await GetUser(apiKey);
+ var user = await _unitOfWork.UserRepository.GetUserByIdAsync(userId);
+
+ var userWithLists = await _unitOfWork.UserRepository.GetUserWithReadingListsByUsernameAsync(user.UserName);
+ var readingList = userWithLists.ReadingLists.SingleOrDefault(t => t.Id == readingListId);
+ if (readingList == null)
+ {
+ return BadRequest("Reading list does not exist or you don't have access");
+ }
+
+ var feed = CreateFeed(readingList.Title + " Reading List", $"{apiKey}/reading-list/{readingListId}", apiKey);
+
+ var items = await _unitOfWork.ReadingListRepository.GetReadingListItemDtosByIdAsync(readingListId, userId);
+ foreach (var item in items)
+ {
+ feed.Entries.Add(new FeedEntry()
+ {
+ Id = item.ChapterId.ToString(),
+ Title = "Chapter " + item.ChapterNumber,
+ Links = new List<FeedLink>()
+ {
+ CreateLink(FeedLinkRelation.SubSection, FeedLinkType.AtomNavigation, Prefix + $"{apiKey}/series/{item.SeriesId}/volume/{item.VolumeId}/chapter/{item.ChapterId}"),
+ CreateLink(FeedLinkRelation.Image, FeedLinkType.Image, $"/api/image/chapter-cover?chapterId={item.ChapterId}")
+ }
+ });
+ }
+
+
+
return CreateXmlResult(SerializeXml(feed));
}
@@ -239,16 +326,16 @@ namespace API.Controllers
{
if (!(await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).EnableOpds)
return BadRequest("OPDS is not enabled on this server");
- var user = await GetUser(apiKey);
+ var userId = await GetUser(apiKey);
var library =
- (await _unitOfWork.LibraryRepository.GetLibrariesForUserIdAsync(user.Id)).SingleOrDefault(l =>
+ (await _unitOfWork.LibraryRepository.GetLibrariesForUserIdAsync(userId)).SingleOrDefault(l =>
l.Id == libraryId);
if (library == null)
{
return BadRequest("User does not have access to this library");
}
- var series = await _unitOfWork.SeriesRepository.GetSeriesDtoForLibraryIdAsync(libraryId, user.Id, new UserParams()
+ var series = await _unitOfWork.SeriesRepository.GetSeriesDtoForLibraryIdAsync(libraryId, userId, new UserParams()
{
PageNumber = pageNumber,
PageSize = 20
@@ -271,8 +358,8 @@ namespace API.Controllers
{
if (!(await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).EnableOpds)
return BadRequest("OPDS is not enabled on this server");
- var user = await GetUser(apiKey);
- var recentlyAdded = await _unitOfWork.SeriesRepository.GetRecentlyAdded(0, user.Id, new UserParams()
+ var userId = await GetUser(apiKey);
+ var recentlyAdded = await _unitOfWork.SeriesRepository.GetRecentlyAdded(0, userId, new UserParams()
{
PageNumber = pageNumber,
PageSize = 20
@@ -296,13 +383,13 @@ namespace API.Controllers
{
if (!(await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).EnableOpds)
return BadRequest("OPDS is not enabled on this server");
- var user = await GetUser(apiKey);
+ var userId = await GetUser(apiKey);
var userParams = new UserParams()
{
PageNumber = pageNumber,
PageSize = 20
};
- var results = await _unitOfWork.SeriesRepository.GetInProgress(user.Id, 0, userParams, _filterDto);
+ var results = await _unitOfWork.SeriesRepository.GetInProgress(userId, 0, userParams, _filterDto);
var listResults = results.DistinctBy(s => s.Name).Skip((userParams.PageNumber - 1) * userParams.PageSize)
.Take(userParams.PageSize).ToList();
var pagedList = new PagedList<SeriesDto>(listResults, listResults.Count, userParams.PageNumber, userParams.PageSize);
@@ -326,14 +413,14 @@ namespace API.Controllers
{
if (!(await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).EnableOpds)
return BadRequest("OPDS is not enabled on this server");
- var user = await GetUser(apiKey);
+ var userId = await GetUser(apiKey);
if (string.IsNullOrEmpty(query))
{
return BadRequest("You must pass a query parameter");
}
query = query.Replace(@"%", "");
// Get libraries user has access to
- var libraries = (await _unitOfWork.LibraryRepository.GetLibrariesForUserIdAsync(user.Id)).ToList();
+ var libraries = (await _unitOfWork.LibraryRepository.GetLibrariesForUserIdAsync(userId)).ToList();
if (!libraries.Any()) return BadRequest("User does not have access to any libraries");
@@ -378,9 +465,9 @@ namespace API.Controllers
{
if (!(await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).EnableOpds)
return BadRequest("OPDS is not enabled on this server");
- var user = await GetUser(apiKey);
- var series = await _unitOfWork.SeriesRepository.GetSeriesDtoByIdAsync(seriesId, user.Id);
- var volumes = await _unitOfWork.SeriesRepository.GetVolumesDtoAsync(seriesId, user.Id);
+ var userId = await GetUser(apiKey);
+ var series = await _unitOfWork.SeriesRepository.GetSeriesDtoByIdAsync(seriesId, userId);
+ var volumes = await _unitOfWork.SeriesRepository.GetVolumesDtoAsync(seriesId, userId);
var feed = CreateFeed(series.Name + " - Volumes", $"{apiKey}/series/{series.Id}", apiKey);
feed.Links.Add(CreateLink(FeedLinkRelation.Image, FeedLinkType.Image, $"/api/image/series-cover?seriesId={seriesId}"));
foreach (var volumeDto in volumes)
@@ -397,11 +484,11 @@ namespace API.Controllers
{
if (!(await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).EnableOpds)
return BadRequest("OPDS is not enabled on this server");
- var user = await GetUser(apiKey);
- var series = await _unitOfWork.SeriesRepository.GetSeriesDtoByIdAsync(seriesId, user.Id);
+ var userId = await GetUser(apiKey);
+ var series = await _unitOfWork.SeriesRepository.GetSeriesDtoByIdAsync(seriesId, userId);
var volume = await _unitOfWork.SeriesRepository.GetVolumeAsync(volumeId);
var chapters =
- (await _unitOfWork.VolumeRepository.GetChaptersAsync(volumeId)).OrderBy(x => double.Parse(x.Number),
+ (await _unitOfWork.ChapterRepository.GetChaptersAsync(volumeId)).OrderBy(x => double.Parse(x.Number),
_chapterSortComparer);
var feed = CreateFeed(series.Name + " - Volume " + volume.Name + " - Chapters ", $"{apiKey}/series/{seriesId}/volume/{volumeId}", apiKey);
@@ -428,11 +515,11 @@ namespace API.Controllers
{
if (!(await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).EnableOpds)
return BadRequest("OPDS is not enabled on this server");
- var user = await GetUser(apiKey);
- var series = await _unitOfWork.SeriesRepository.GetSeriesDtoByIdAsync(seriesId, user.Id);
+ var userId = await GetUser(apiKey);
+ var series = await _unitOfWork.SeriesRepository.GetSeriesDtoByIdAsync(seriesId, userId);
var volume = await _unitOfWork.SeriesRepository.GetVolumeAsync(volumeId);
- var chapter = await _unitOfWork.VolumeRepository.GetChapterDtoAsync(chapterId);
- var files = await _unitOfWork.VolumeRepository.GetFilesForChapterAsync(chapterId);
+ var chapter = await _unitOfWork.ChapterRepository.GetChapterDtoAsync(chapterId);
+ var files = await _unitOfWork.ChapterRepository.GetFilesForChapterAsync(chapterId);
var feed = CreateFeed(series.Name + " - Volume " + volume.Name + " - Chapters ", $"{apiKey}/series/{seriesId}/volume/{volumeId}/chapter/{chapterId}", apiKey);
foreach (var mangaFile in files)
@@ -456,7 +543,7 @@ namespace API.Controllers
{
if (!(await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).EnableOpds)
return BadRequest("OPDS is not enabled on this server");
- var files = await _unitOfWork.VolumeRepository.GetFilesForChapterAsync(chapterId);
+ var files = await _unitOfWork.ChapterRepository.GetFilesForChapterAsync(chapterId);
var (bytes, contentType, fileDownloadName) = await _downloadService.GetFirstFileDownload(files);
return File(bytes, contentType, fileDownloadName);
}
@@ -544,7 +631,7 @@ namespace API.Controllers
return new FeedEntry()
{
Id = volumeDto.Id.ToString(),
- Title = volumeDto.IsSpecial ? "Specials" : "Volume " + volumeDto.Name,
+ Title = "Volume " + volumeDto.Name,
Links = new List<FeedLink>()
{
CreateLink(FeedLinkRelation.SubSection, FeedLinkType.AtomNavigation, Prefix + $"{apiKey}/series/{seriesId}/volume/{volumeDto.Id}"),
@@ -639,15 +726,18 @@ namespace API.Controllers
/// Gets the user from the API key
/// </summary>
/// <returns></returns>
- private async Task<AppUser> GetUser(string apiKey)
+ private async Task<int> GetUser(string apiKey)
{
- var user = await _unitOfWork.UserRepository.GetUserByApiKeyAsync(apiKey);
- if (user == null)
+ try
{
- throw new KavitaException("User does not exist");
+ var user = await _unitOfWork.UserRepository.GetUserIdByApiKeyAsync(apiKey);
+ return user;
}
-
- return user;
+ catch
+ {
+ /* Do nothing */
+ }
+ throw new KavitaException("User does not exist");
}
private static FeedLink CreatePageStreamLink(int seriesId, int volumeId, int chapterId, MangaFile mangaFile, string apiKey)
diff --git a/API/Controllers/PluginController.cs b/API/Controllers/PluginController.cs
new file mode 100644
index 000000000..b176c0628
--- /dev/null
+++ b/API/Controllers/PluginController.cs
@@ -0,0 +1,45 @@
+using System.Threading.Tasks;
+using API.DTOs;
+using API.Interfaces;
+using API.Interfaces.Services;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+namespace API.Controllers
+{
+ public class PluginController : BaseApiController
+ {
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ITokenService _tokenService;
+ private readonly ILogger<PluginController> _logger;
+
+ public PluginController(IUnitOfWork unitOfWork, ITokenService tokenService, ILogger<PluginController> logger)
+ {
+ _unitOfWork = unitOfWork;
+ _tokenService = tokenService;
+ _logger = logger;
+ }
+
+ /// <summary>
+ /// Authenticate with the Server given an apiKey. This will log you in by returning the user object and the JWT token.
+ /// </summary>
+ /// <param name="apiKey"></param>
+ /// <param name="pluginName">Name of the Plugin</param>
+ /// <returns></returns>
+ [HttpPost("authenticate")]
+ public async Task<ActionResult<UserDto>> Authenticate(string apiKey, string pluginName)
+ {
+ // NOTE: In order to log information about plugins, we need some Plugin Description information for each request
+ // Should log into access table so we can tell the user
+ var userId = await _unitOfWork.UserRepository.GetUserIdByApiKeyAsync(apiKey);
+ var user = await _unitOfWork.UserRepository.GetUserByIdAsync(userId);
+ _logger.LogInformation("Plugin {PluginName} has authenticated with {UserName} ({UserId})'s API Key", pluginName, user.UserName, userId);
+ return new UserDto
+ {
+ Username = user.UserName,
+ Token = await _tokenService.CreateToken(user),
+ ApiKey = user.ApiKey,
+ };
+ }
+ }
+}
diff --git a/API/Controllers/ReaderController.cs b/API/Controllers/ReaderController.cs
index 9b112e5da..d1314674e 100644
--- a/API/Controllers/ReaderController.cs
+++ b/API/Controllers/ReaderController.cs
@@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
-using API.Comparators;
+using API.Data.Repositories;
using API.DTOs;
using API.DTOs.Reader;
using API.Entities;
@@ -20,20 +20,15 @@ namespace API.Controllers
/// </summary>
public class ReaderController : BaseApiController
{
- private readonly IDirectoryService _directoryService;
private readonly ICacheService _cacheService;
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<ReaderController> _logger;
private readonly IReaderService _readerService;
- private readonly ChapterSortComparer _chapterSortComparer = new ChapterSortComparer();
- private readonly ChapterSortComparerZeroFirst _chapterSortComparerForInChapterSorting = new ChapterSortComparerZeroFirst();
- private readonly NaturalSortComparer _naturalSortComparer = new NaturalSortComparer();
/// <inheritdoc />
- public ReaderController(IDirectoryService directoryService, ICacheService cacheService,
+ public ReaderController(ICacheService cacheService,
IUnitOfWork unitOfWork, ILogger<ReaderController> logger, IReaderService readerService)
{
- _directoryService = directoryService;
_cacheService = cacheService;
_unitOfWork = unitOfWork;
_logger = logger;
@@ -49,7 +44,7 @@ namespace API.Controllers
[HttpGet("image")]
public async Task<ActionResult> GetImage(int chapterId, int page)
{
- if (page < 0) return BadRequest("Page cannot be less than 0");
+ if (page < 0) page = 0;
var chapter = await _cacheService.Ensure(chapterId);
if (chapter == null) return BadRequest("There was an issue finding image file for reading");
@@ -57,14 +52,9 @@ namespace API.Controllers
{
var (path, _) = await _cacheService.GetCachedPagePath(chapter, page);
if (string.IsNullOrEmpty(path) || !System.IO.File.Exists(path)) return BadRequest($"No such image for page {page}");
-
- var content = await _directoryService.ReadFileAsync(path);
var format = Path.GetExtension(path).Replace(".", "");
- // Calculates SHA1 Hash for byte[]
- Response.AddCacheHeader(content);
-
- return File(content, "image/" + format);
+ return PhysicalFile(path, "image/" + format, Path.GetFileName(path));
}
catch (Exception)
{
@@ -76,30 +66,29 @@ namespace API.Controllers
/// <summary>
/// Returns various information about a Chapter. Side effect: This will cache the chapter images for reading.
/// </summary>
- /// <param name="seriesId"></param>
/// <param name="chapterId"></param>
/// <returns></returns>
[HttpGet("chapter-info")]
- public async Task<ActionResult<ChapterInfoDto>> GetChapterInfo(int seriesId, int chapterId)
+ public async Task<ActionResult<ChapterInfoDto>> GetChapterInfo(int chapterId)
{
- // PERF: Write this in one DB call
var chapter = await _cacheService.Ensure(chapterId);
if (chapter == null) return BadRequest("Could not find Chapter");
- var volume = await _unitOfWork.SeriesRepository.GetVolumeDtoAsync(chapter.VolumeId);
- if (volume == null) return BadRequest("Could not find Volume");
- var mangaFile = (await _unitOfWork.VolumeRepository.GetFilesForChapterAsync(chapterId)).First();
- var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId);
+ var dto = await _unitOfWork.ChapterRepository.GetChapterInfoDtoAsync(chapterId);
+ var mangaFile = (await _unitOfWork.ChapterRepository.GetFilesForChapterAsync(chapterId)).First();
return Ok(new ChapterInfoDto()
{
- ChapterNumber = chapter.Range,
- VolumeNumber = volume.Number + string.Empty,
- VolumeId = volume.Id,
+ ChapterNumber = dto.ChapterNumber,
+ VolumeNumber = dto.VolumeNumber,
+ VolumeId = dto.VolumeId,
FileName = Path.GetFileName(mangaFile.FilePath),
- SeriesName = series?.Name,
- IsSpecial = chapter.IsSpecial,
- Pages = chapter.Pages,
+ SeriesName = dto.SeriesName,
+ SeriesFormat = dto.SeriesFormat,
+ SeriesId = dto.SeriesId,
+ LibraryId = dto.LibraryId,
+ IsSpecial = dto.IsSpecial,
+ Pages = dto.Pages,
});
}
@@ -107,32 +96,12 @@ namespace API.Controllers
[HttpPost("mark-read")]
public async Task<ActionResult> MarkRead(MarkReadDto markReadDto)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
var volumes = await _unitOfWork.SeriesRepository.GetVolumes(markReadDto.SeriesId);
user.Progresses ??= new List<AppUserProgress>();
foreach (var volume in volumes)
{
- foreach (var chapter in volume.Chapters)
- {
- var userProgress = GetUserProgressForChapter(user, chapter);
-
- if (userProgress == null)
- {
- user.Progresses.Add(new AppUserProgress
- {
- PagesRead = chapter.Pages,
- VolumeId = volume.Id,
- SeriesId = markReadDto.SeriesId,
- ChapterId = chapter.Id
- });
- }
- else
- {
- userProgress.PagesRead = chapter.Pages;
- userProgress.SeriesId = markReadDto.SeriesId;
- userProgress.VolumeId = volume.Id;
- }
- }
+ _readerService.MarkChaptersAsRead(user, markReadDto.SeriesId, volume.Chapters);
}
_unitOfWork.UserRepository.Update(user);
@@ -146,47 +115,23 @@ namespace API.Controllers
return BadRequest("There was an issue saving progress");
}
- private static AppUserProgress GetUserProgressForChapter(AppUser user, Chapter chapter)
- {
- AppUserProgress userProgress = null;
- try
- {
- userProgress =
- user.Progresses.SingleOrDefault(x => x.ChapterId == chapter.Id && x.AppUserId == user.Id);
- }
- catch (Exception)
- {
- // There is a very rare chance that user progress will duplicate current row. If that happens delete one with less pages
- var progresses = user.Progresses.Where(x => x.ChapterId == chapter.Id && x.AppUserId == user.Id).ToList();
- if (progresses.Count > 1)
- {
- user.Progresses = new List<AppUserProgress>()
- {
- user.Progresses.First()
- };
- userProgress = user.Progresses.First();
- }
- }
-
- return userProgress;
- }
/// <summary>
- /// Marks a Chapter as Unread (progress)
+ /// Marks a Series as Unread (progress)
/// </summary>
/// <param name="markReadDto"></param>
/// <returns></returns>
[HttpPost("mark-unread")]
public async Task<ActionResult> MarkUnread(MarkReadDto markReadDto)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
var volumes = await _unitOfWork.SeriesRepository.GetVolumes(markReadDto.SeriesId);
user.Progresses ??= new List<AppUserProgress>();
foreach (var volume in volumes)
{
foreach (var chapter in volume.Chapters)
{
- var userProgress = GetUserProgressForChapter(user, chapter);
+ var userProgress = ReaderService.GetUserProgressForChapter(user, chapter);
if (userProgress == null) continue;
userProgress.PagesRead = 0;
@@ -206,6 +151,29 @@ namespace API.Controllers
return BadRequest("There was an issue saving progress");
}
+ /// <summary>
+ /// Marks all chapters within a volume as unread
+ /// </summary>
+ /// <param name="markVolumeReadDto"></param>
+ /// <returns></returns>
+ [HttpPost("mark-volume-unread")]
+ public async Task<ActionResult> MarkVolumeAsUnread(MarkVolumeReadDto markVolumeReadDto)
+ {
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
+
+ var chapters = await _unitOfWork.ChapterRepository.GetChaptersAsync(markVolumeReadDto.VolumeId);
+ _readerService.MarkChaptersAsUnread(user, markVolumeReadDto.SeriesId, chapters);
+
+ _unitOfWork.UserRepository.Update(user);
+
+ if (await _unitOfWork.CommitAsync())
+ {
+ return Ok();
+ }
+
+ return BadRequest("Could not save progress");
+ }
+
/// <summary>
/// Marks all chapters within a volume as Read
/// </summary>
@@ -214,30 +182,122 @@ namespace API.Controllers
[HttpPost("mark-volume-read")]
public async Task<ActionResult> MarkVolumeAsRead(MarkVolumeReadDto markVolumeReadDto)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
+
+ var chapters = await _unitOfWork.ChapterRepository.GetChaptersAsync(markVolumeReadDto.VolumeId);
+ _readerService.MarkChaptersAsRead(user, markVolumeReadDto.SeriesId, chapters);
- var chapters = await _unitOfWork.VolumeRepository.GetChaptersAsync(markVolumeReadDto.VolumeId);
- foreach (var chapter in chapters)
+ _unitOfWork.UserRepository.Update(user);
+
+ if (await _unitOfWork.CommitAsync())
{
- user.Progresses ??= new List<AppUserProgress>();
- var userProgress = user.Progresses.FirstOrDefault(x => x.ChapterId == chapter.Id && x.AppUserId == user.Id);
+ return Ok();
+ }
- if (userProgress == null)
- {
- user.Progresses.Add(new AppUserProgress
- {
- PagesRead = chapter.Pages,
- VolumeId = markVolumeReadDto.VolumeId,
- SeriesId = markVolumeReadDto.SeriesId,
- ChapterId = chapter.Id
- });
- }
- else
- {
- userProgress.PagesRead = chapter.Pages;
- userProgress.SeriesId = markVolumeReadDto.SeriesId;
- userProgress.VolumeId = markVolumeReadDto.VolumeId;
- }
+ return BadRequest("Could not save progress");
+ }
+
+
+ /// <summary>
+ /// Marks all chapters within a list of volumes as Read. All volumes must belong to the same Series.
+ /// </summary>
+ /// <param name="dto"></param>
+ /// <returns></returns>
+ [HttpPost("mark-multiple-read")]
+ public async Task<ActionResult> MarkMultipleAsRead(MarkVolumesReadDto dto)
+ {
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
+ user.Progresses ??= new List<AppUserProgress>();
+
+ var chapterIds = await _unitOfWork.VolumeRepository.GetChapterIdsByVolumeIds(dto.VolumeIds);
+ foreach (var chapterId in dto.ChapterIds)
+ {
+ chapterIds.Add(chapterId);
+ }
+ var chapters = await _unitOfWork.ChapterRepository.GetChaptersByIdsAsync(chapterIds);
+ _readerService.MarkChaptersAsRead(user, dto.SeriesId, chapters);
+
+ _unitOfWork.UserRepository.Update(user);
+
+ if (await _unitOfWork.CommitAsync())
+ {
+ return Ok();
+ }
+
+ return BadRequest("Could not save progress");
+ }
+
+ /// <summary>
+ /// Marks all chapters within a list of volumes as Unread. All volumes must belong to the same Series.
+ /// </summary>
+ /// <param name="dto"></param>
+ /// <returns></returns>
+ [HttpPost("mark-multiple-unread")]
+ public async Task<ActionResult> MarkMultipleAsUnread(MarkVolumesReadDto dto)
+ {
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
+ user.Progresses ??= new List<AppUserProgress>();
+
+ var chapterIds = await _unitOfWork.VolumeRepository.GetChapterIdsByVolumeIds(dto.VolumeIds);
+ foreach (var chapterId in dto.ChapterIds)
+ {
+ chapterIds.Add(chapterId);
+ }
+ var chapters = await _unitOfWork.ChapterRepository.GetChaptersByIdsAsync(chapterIds);
+ _readerService.MarkChaptersAsUnread(user, dto.SeriesId, chapters);
+
+ _unitOfWork.UserRepository.Update(user);
+
+ if (await _unitOfWork.CommitAsync())
+ {
+ return Ok();
+ }
+
+ return BadRequest("Could not save progress");
+ }
+
+ /// <summary>
+ /// Marks all chapters within a list of series as Read.
+ /// </summary>
+ /// <param name="dto"></param>
+ /// <returns></returns>
+ [HttpPost("mark-multiple-series-read")]
+ public async Task<ActionResult> MarkMultipleSeriesAsRead(MarkMultipleSeriesAsReadDto dto)
+ {
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
+ user.Progresses ??= new List<AppUserProgress>();
+
+ var volumes = await _unitOfWork.SeriesRepository.GetVolumesForSeriesAsync(dto.SeriesIds.ToArray(), true);
+ foreach (var volume in volumes)
+ {
+ _readerService.MarkChaptersAsRead(user, volume.SeriesId, volume.Chapters);
+ }
+
+ _unitOfWork.UserRepository.Update(user);
+
+ if (await _unitOfWork.CommitAsync())
+ {
+ return Ok();
+ }
+
+ return BadRequest("Could not save progress");
+ }
+
+ /// <summary>
+ /// Marks all chapters within a list of series as Unread.
+ /// </summary>
+ /// <param name="dto"></param>
+ /// <returns></returns>
+ [HttpPost("mark-multiple-series-unread")]
+ public async Task<ActionResult> MarkMultipleSeriesAsUnread(MarkMultipleSeriesAsReadDto dto)
+ {
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
+ user.Progresses ??= new List<AppUserProgress>();
+
+ var volumes = await _unitOfWork.SeriesRepository.GetVolumesForSeriesAsync(dto.SeriesIds.ToArray(), true);
+ foreach (var volume in volumes)
+ {
+ _readerService.MarkChaptersAsUnread(user, volume.SeriesId, volume.Chapters);
}
_unitOfWork.UserRepository.Update(user);
@@ -258,7 +318,7 @@ namespace API.Controllers
[HttpGet("get-progress")]
public async Task<ActionResult<ProgressDto>> GetProgress(int chapterId)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Progress);
var progressBookmark = new ProgressDto()
{
PageNum = 0,
@@ -267,7 +327,7 @@ namespace API.Controllers
SeriesId = 0
};
if (user.Progresses == null) return Ok(progressBookmark);
- var progress = user.Progresses.SingleOrDefault(x => x.AppUserId == user.Id && x.ChapterId == chapterId);
+ var progress = user.Progresses.FirstOrDefault(x => x.AppUserId == user.Id && x.ChapterId == chapterId);
if (progress != null)
{
@@ -288,7 +348,8 @@ namespace API.Controllers
public async Task<ActionResult> BookmarkProgress(ProgressDto progressDto)
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
- if (await _readerService.SaveReadingProgress(progressDto, user)) return Ok(true);
+
+ if (await _readerService.SaveReadingProgress(progressDto, user.Id)) return Ok(true);
return BadRequest("Could not save progress");
}
@@ -301,7 +362,7 @@ namespace API.Controllers
[HttpGet("get-bookmarks")]
public async Task<ActionResult<IEnumerable<BookmarkDto>>> GetBookmarks(int chapterId)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
if (user.Bookmarks == null) return Ok(Array.Empty<BookmarkDto>());
return Ok(await _unitOfWork.UserRepository.GetBookmarkDtosForChapter(user.Id, chapterId));
}
@@ -313,7 +374,7 @@ namespace API.Controllers
[HttpGet("get-all-bookmarks")]
public async Task<ActionResult<IEnumerable<BookmarkDto>>> GetAllBookmarks()
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
if (user.Bookmarks == null) return Ok(Array.Empty<BookmarkDto>());
return Ok(await _unitOfWork.UserRepository.GetAllBookmarkDtos(user.Id));
}
@@ -326,7 +387,7 @@ namespace API.Controllers
[HttpPost("remove-bookmarks")]
public async Task<ActionResult> RemoveBookmarks(RemoveBookmarkForSeriesDto dto)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
if (user.Bookmarks == null) return Ok("Nothing to remove");
try
{
@@ -356,7 +417,7 @@ namespace API.Controllers
[HttpGet("get-volume-bookmarks")]
public async Task<ActionResult<IEnumerable<BookmarkDto>>> GetBookmarksForVolume(int volumeId)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
if (user.Bookmarks == null) return Ok(Array.Empty<BookmarkDto>());
return Ok(await _unitOfWork.UserRepository.GetBookmarkDtosForVolume(user.Id, volumeId));
}
@@ -369,7 +430,7 @@ namespace API.Controllers
[HttpGet("get-series-bookmarks")]
public async Task<ActionResult<IEnumerable<BookmarkDto>>> GetBookmarksForSeries(int seriesId)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
if (user.Bookmarks == null) return Ok(Array.Empty<BookmarkDto>());
return Ok(await _unitOfWork.UserRepository.GetBookmarkDtosForSeries(user.Id, seriesId));
@@ -383,45 +444,28 @@ namespace API.Controllers
[HttpPost("bookmark")]
public async Task<ActionResult> BookmarkPage(BookmarkDto bookmarkDto)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
-
// Don't let user save past total pages.
- var chapter = await _unitOfWork.VolumeRepository.GetChapterAsync(bookmarkDto.ChapterId);
- if (bookmarkDto.Page > chapter.Pages)
- {
- bookmarkDto.Page = chapter.Pages;
- }
-
- if (bookmarkDto.Page < 0)
- {
- bookmarkDto.Page = 0;
- }
-
+ bookmarkDto.Page = await _readerService.CapPageToChapter(bookmarkDto.ChapterId, bookmarkDto.Page);
try
{
- user.Bookmarks ??= new List<AppUserBookmark>();
- var userBookmark =
- user.Bookmarks.SingleOrDefault(x => x.ChapterId == bookmarkDto.ChapterId && x.AppUserId == user.Id && x.Page == bookmarkDto.Page);
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
+ var userBookmark =
+ await _unitOfWork.UserRepository.GetBookmarkForPage(bookmarkDto.Page, bookmarkDto.ChapterId, user.Id);
if (userBookmark == null)
{
- user.Bookmarks.Add(new AppUserBookmark()
- {
- Page = bookmarkDto.Page,
- VolumeId = bookmarkDto.VolumeId,
- SeriesId = bookmarkDto.SeriesId,
- ChapterId = bookmarkDto.ChapterId,
- });
- }
- else
- {
- userBookmark.Page = bookmarkDto.Page;
- userBookmark.SeriesId = bookmarkDto.SeriesId;
- userBookmark.VolumeId = bookmarkDto.VolumeId;
+ user.Bookmarks ??= new List<AppUserBookmark>();
+ user.Bookmarks.Add(new AppUserBookmark()
+ {
+ Page = bookmarkDto.Page,
+ VolumeId = bookmarkDto.VolumeId,
+ SeriesId = bookmarkDto.SeriesId,
+ ChapterId = bookmarkDto.ChapterId,
+ });
+ _unitOfWork.UserRepository.Update(user);
}
- _unitOfWork.UserRepository.Update(user);
if (await _unitOfWork.CommitAsync())
{
@@ -444,7 +488,7 @@ namespace API.Controllers
[HttpPost("unbookmark")]
public async Task<ActionResult> UnBookmarkPage(BookmarkDto bookmarkDto)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Bookmarks);
if (user.Bookmarks == null) return Ok();
try {
@@ -453,7 +497,6 @@ namespace API.Controllers
&& x.AppUserId == user.Id
&& x.Page != bookmarkDto.Page).ToList();
-
_unitOfWork.UserRepository.Update(user);
if (await _unitOfWork.CommitAsync())
@@ -482,58 +525,10 @@ namespace API.Controllers
[HttpGet("next-chapter")]
public async Task<ActionResult<int>> GetNextChapter(int seriesId, int volumeId, int currentChapterId)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
- var volumes = await _unitOfWork.SeriesRepository.GetVolumesDtoAsync(seriesId, user.Id);
- var currentVolume = await _unitOfWork.SeriesRepository.GetVolumeAsync(volumeId);
- var currentChapter = await _unitOfWork.VolumeRepository.GetChapterAsync(currentChapterId);
- if (currentVolume.Number == 0)
- {
- // Handle specials by sorting on their Filename aka Range
- var chapterId = GetNextChapterId(currentVolume.Chapters.OrderBy(x => x.Range, _naturalSortComparer), currentChapter.Number);
- if (chapterId > 0) return Ok(chapterId);
- }
-
- foreach (var volume in volumes)
- {
- if (volume.Number == currentVolume.Number && volume.Chapters.Count > 1)
- {
- // Handle Chapters within current Volume
- // In this case, i need 0 first because 0 represents a full volume file.
- var chapterId = GetNextChapterId(currentVolume.Chapters.OrderBy(x => double.Parse(x.Number), _chapterSortComparerForInChapterSorting), currentChapter.Number);
- if (chapterId > 0) return Ok(chapterId);
- }
-
- if (volume.Number == currentVolume.Number + 1)
- {
- // Handle Chapters within next Volume
- // ! When selecting the chapter for the next volume, we need to make sure a c0 comes before a c1+
- var chapters = volume.Chapters.OrderBy(x => double.Parse(x.Number), _chapterSortComparer).ToList();
- if (currentChapter.Number.Equals("0") && chapters.Last().Number.Equals("0"))
- {
- return chapters.Last().Id;
- }
-
- return Ok(chapters.FirstOrDefault()?.Id);
- }
- }
- return Ok(-1);
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
+ return await _readerService.GetNextChapterIdAsync(seriesId, volumeId, currentChapterId, userId);
}
- private static int GetNextChapterId(IEnumerable<Chapter> chapters, string currentChapterNumber)
- {
- var next = false;
- var chaptersList = chapters.ToList();
- foreach (var chapter in chaptersList)
- {
- if (next)
- {
- return chapter.Id;
- }
- if (currentChapterNumber.Equals(chapter.Number)) next = true;
- }
-
- return -1;
- }
/// <summary>
/// Returns the previous logical chapter from the series.
@@ -548,30 +543,8 @@ namespace API.Controllers
[HttpGet("prev-chapter")]
public async Task<ActionResult<int>> GetPreviousChapter(int seriesId, int volumeId, int currentChapterId)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
- var volumes = await _unitOfWork.SeriesRepository.GetVolumesDtoAsync(seriesId, user.Id);
- var currentVolume = await _unitOfWork.SeriesRepository.GetVolumeAsync(volumeId);
- var currentChapter = await _unitOfWork.VolumeRepository.GetChapterAsync(currentChapterId);
-
- if (currentVolume.Number == 0)
- {
- var chapterId = GetNextChapterId(currentVolume.Chapters.OrderBy(x => x.Range, _naturalSortComparer).Reverse(), currentChapter.Number);
- if (chapterId > 0) return Ok(chapterId);
- }
-
- foreach (var volume in volumes.Reverse())
- {
- if (volume.Number == currentVolume.Number)
- {
- var chapterId = GetNextChapterId(currentVolume.Chapters.OrderBy(x => double.Parse(x.Number), _chapterSortComparerForInChapterSorting).Reverse(), currentChapter.Number);
- if (chapterId > 0) return Ok(chapterId);
- }
- if (volume.Number == currentVolume.Number - 1)
- {
- return Ok(volume.Chapters.OrderBy(x => double.Parse(x.Number), _chapterSortComparerForInChapterSorting).LastOrDefault()?.Id);
- }
- }
- return Ok(-1);
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
+ return await _readerService.GetPrevChapterIdAsync(seriesId, volumeId, currentChapterId, userId);
}
}
diff --git a/API/Controllers/ReadingListController.cs b/API/Controllers/ReadingListController.cs
new file mode 100644
index 000000000..1f22263c7
--- /dev/null
+++ b/API/Controllers/ReadingListController.cs
@@ -0,0 +1,503 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using API.Comparators;
+using API.DTOs.ReadingLists;
+using API.Entities;
+using API.Extensions;
+using API.Helpers;
+using API.Interfaces;
+using Microsoft.AspNetCore.Mvc;
+
+namespace API.Controllers
+{
+ public class ReadingListController : BaseApiController
+ {
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ChapterSortComparerZeroFirst _chapterSortComparerForInChapterSorting = new ChapterSortComparerZeroFirst();
+
+ public ReadingListController(IUnitOfWork unitOfWork)
+ {
+ _unitOfWork = unitOfWork;
+ }
+
+ /// <summary>
+ /// Fetches a single Reading List
+ /// </summary>
+ /// <param name="readingListId"></param>
+ /// <returns></returns>
+ [HttpGet]
+ public async Task<ActionResult<IEnumerable<ReadingListDto>>> GetList(int readingListId)
+ {
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
+ return Ok(await _unitOfWork.ReadingListRepository.GetReadingListDtoByIdAsync(readingListId, userId));
+ }
+
+ /// <summary>
+ /// Returns reading lists (paginated) for a given user.
+ /// </summary>
+ /// <param name="includePromoted">Defaults to true</param>
+ /// <returns></returns>
+ [HttpPost("lists")]
+ public async Task<ActionResult<IEnumerable<ReadingListDto>>> GetListsForUser([FromQuery] UserParams userParams, [FromQuery] bool includePromoted = true)
+ {
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
+ var items = await _unitOfWork.ReadingListRepository.GetReadingListDtosForUserAsync(userId, includePromoted,
+ userParams);
+ Response.AddPaginationHeader(items.CurrentPage, items.PageSize, items.TotalCount, items.TotalPages);
+
+ return Ok(items);
+ }
+
+ /// <summary>
+ /// Fetches all reading list items for a given list including rich metadata around series, volume, chapters, and progress
+ /// </summary>
+ /// <remarks>This call is expensive</remarks>
+ /// <param name="readingListId"></param>
+ /// <returns></returns>
+ [HttpGet("items")]
+ public async Task<ActionResult<IEnumerable<ReadingListItemDto>>> GetListForUser(int readingListId)
+ {
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
+ var items = await _unitOfWork.ReadingListRepository.GetReadingListItemDtosByIdAsync(readingListId, userId);
+
+ return Ok(await _unitOfWork.ReadingListRepository.AddReadingProgressModifiers(userId, items.ToList()));
+ }
+
+ /// <summary>
+ /// Updates an items position
+ /// </summary>
+ /// <param name="dto"></param>
+ /// <returns></returns>
+ [HttpPost("update-position")]
+ public async Task<ActionResult> UpdateListItemPosition(UpdateReadingListPosition dto)
+ {
+ // Make sure UI buffers events
+ var items = (await _unitOfWork.ReadingListRepository.GetReadingListItemsByIdAsync(dto.ReadingListId)).ToList();
+ var item = items.Find(r => r.Id == dto.ReadingListItemId);
+ items.Remove(item);
+ items.Insert(dto.ToPosition, item);
+
+ for (var i = 0; i < items.Count; i++)
+ {
+ items[i].Order = i;
+ }
+
+ if (_unitOfWork.HasChanges() && await _unitOfWork.CommitAsync())
+ {
+ return Ok("Updated");
+ }
+
+ return BadRequest("Couldn't update position");
+ }
+
+ /// <summary>
+ /// Deletes a list item from the list. Will reorder all item positions afterwards
+ /// </summary>
+ /// <param name="dto"></param>
+ /// <returns></returns>
+ [HttpPost("delete-item")]
+ public async Task<ActionResult> DeleteListItem(UpdateReadingListPosition dto)
+ {
+ var items = (await _unitOfWork.ReadingListRepository.GetReadingListItemsByIdAsync(dto.ReadingListId)).ToList();
+ var item = items.Find(r => r.Id == dto.ReadingListItemId);
+ items.Remove(item);
+
+ for (var i = 0; i < items.Count; i++)
+ {
+ items[i].Order = i;
+ }
+
+ if (_unitOfWork.HasChanges() && await _unitOfWork.CommitAsync())
+ {
+ return Ok("Updated");
+ }
+
+ return BadRequest("Couldn't delete item");
+ }
+
+ /// <summary>
+ /// Removes all entries that are fully read from the reading list
+ /// </summary>
+ /// <param name="readingListId"></param>
+ /// <returns></returns>
+ [HttpPost("remove-read")]
+ public async Task<ActionResult> DeleteReadFromList([FromQuery] int readingListId)
+ {
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
+ var items = await _unitOfWork.ReadingListRepository.GetReadingListItemDtosByIdAsync(readingListId, userId);
+ items = await _unitOfWork.ReadingListRepository.AddReadingProgressModifiers(userId, items.ToList());
+
+ // Collect all Ids to remove
+ var itemIdsToRemove = items.Where(item => item.PagesRead == item.PagesTotal).Select(item => item.Id);
+
+ try
+ {
+ var listItems =
+ (await _unitOfWork.ReadingListRepository.GetReadingListItemsByIdAsync(readingListId)).Where(r =>
+ itemIdsToRemove.Contains(r.Id));
+ _unitOfWork.ReadingListRepository.BulkRemove(listItems);
+
+ if (_unitOfWork.HasChanges())
+ {
+ await _unitOfWork.CommitAsync();
+ return Ok("Updated");
+ }
+ else
+ {
+ return Ok("Nothing to remove");
+ }
+ }
+ catch
+ {
+ await _unitOfWork.RollbackAsync();
+ }
+
+ return BadRequest("Could not remove read items");
+ }
+
+ /// <summary>
+ /// Deletes a reading list
+ /// </summary>
+ /// <param name="readingListId"></param>
+ /// <returns></returns>
+ [HttpDelete]
+ public async Task<ActionResult> DeleteList([FromQuery] int readingListId)
+ {
+ var user = await _unitOfWork.UserRepository.GetUserWithReadingListsByUsernameAsync(User.GetUsername());
+ var readingList = user.ReadingLists.SingleOrDefault(r => r.Id == readingListId);
+ if (readingList == null)
+ {
+ return BadRequest("User is not associated with this reading list");
+ }
+
+ user.ReadingLists.Remove(readingList);
+
+ if (_unitOfWork.HasChanges() && await _unitOfWork.CommitAsync())
+ {
+ return Ok("Deleted");
+ }
+
+ return BadRequest("There was an issue deleting reading list");
+ }
+
+ /// <summary>
+ /// Creates a new List with a unique title. Returns the new ReadingList back
+ /// </summary>
+ /// <param name="dto"></param>
+ /// <returns></returns>
+ [HttpPost("create")]
+ public async Task<ActionResult<ReadingListDto>> CreateList(CreateReadingListDto dto)
+ {
+ var user = await _unitOfWork.UserRepository.GetUserWithReadingListsByUsernameAsync(User.GetUsername());
+
+ // When creating, we need to make sure Title is unique
+ var hasExisting = user.ReadingLists.Any(l => l.Title.Equals(dto.Title));
+ if (hasExisting)
+ {
+ return BadRequest("A list of this name already exists");
+ }
+ user.ReadingLists.Add(new ReadingList()
+ {
+ Promoted = false,
+ Title = dto.Title,
+ Summary = string.Empty
+ });
+
+ if (!_unitOfWork.HasChanges()) return BadRequest("There was a problem creating list");
+
+ await _unitOfWork.CommitAsync();
+
+ return Ok(await _unitOfWork.ReadingListRepository.GetReadingListDtoByTitleAsync(dto.Title));
+ }
+
+ /// <summary>
+ /// Update the properites (title, summary) of a reading list
+ /// </summary>
+ /// <param name="dto"></param>
+ /// <returns></returns>
+ [HttpPost("update")]
+ public async Task<ActionResult> UpdateList(UpdateReadingListDto dto)
+ {
+ var readingList = await _unitOfWork.ReadingListRepository.GetReadingListByIdAsync(dto.ReadingListId);
+ if (readingList == null) return BadRequest("List does not exist");
+
+ if (!string.IsNullOrEmpty(dto.Title))
+ {
+ readingList.Title = dto.Title; // Should I check if this is unique?
+ }
+ if (!string.IsNullOrEmpty(dto.Title))
+ {
+ readingList.Summary = dto.Summary;
+ }
+
+ readingList.Promoted = dto.Promoted;
+
+ _unitOfWork.ReadingListRepository.Update(readingList);
+
+ if (await _unitOfWork.CommitAsync())
+ {
+ return Ok("Updated");
+ }
+ return BadRequest("Could not update reading list");
+ }
+
+ /// <summary>
+ /// Adds all chapters from a Series to a reading list
+ /// </summary>
+ /// <param name="dto"></param>
+ /// <returns></returns>
+ [HttpPost("update-by-series")]
+ public async Task<ActionResult> UpdateListBySeries(UpdateReadingListBySeriesDto dto)
+ {
+ var user = await _unitOfWork.UserRepository.GetUserWithReadingListsByUsernameAsync(User.GetUsername());
+ var readingList = user.ReadingLists.SingleOrDefault(l => l.Id == dto.ReadingListId);
+ if (readingList == null) return BadRequest("Reading List does not exist");
+ var chapterIdsForSeries =
+ await _unitOfWork.SeriesRepository.GetChapterIdsForSeriesAsync(new [] {dto.SeriesId});
+
+ // If there are adds, tell tracking this has been modified
+ if (await AddChaptersToReadingList(dto.SeriesId, chapterIdsForSeries, readingList))
+ {
+ _unitOfWork.ReadingListRepository.Update(readingList);
+ }
+
+ try
+ {
+ if (_unitOfWork.HasChanges())
+ {
+ await _unitOfWork.CommitAsync();
+ return Ok("Updated");
+ }
+ }
+ catch
+ {
+ await _unitOfWork.RollbackAsync();
+ }
+
+ return Ok("Nothing to do");
+ }
+
+
+ /// <summary>
+ /// Adds all chapters from a list of volumes and chapters to a reading list
+ /// </summary>
+ /// <param name="dto"></param>
+ /// <returns></returns>
+ [HttpPost("update-by-multiple")]
+ public async Task<ActionResult> UpdateListByMultiple(UpdateReadingListByMultipleDto dto)
+ {
+ var user = await _unitOfWork.UserRepository.GetUserWithReadingListsByUsernameAsync(User.GetUsername());
+ var readingList = user.ReadingLists.SingleOrDefault(l => l.Id == dto.ReadingListId);
+ if (readingList == null) return BadRequest("Reading List does not exist");
+
+ var chapterIds = await _unitOfWork.VolumeRepository.GetChapterIdsByVolumeIds(dto.VolumeIds);
+ foreach (var chapterId in dto.ChapterIds)
+ {
+ chapterIds.Add(chapterId);
+ }
+
+ // If there are adds, tell tracking this has been modified
+ if (await AddChaptersToReadingList(dto.SeriesId, chapterIds, readingList))
+ {
+ _unitOfWork.ReadingListRepository.Update(readingList);
+ }
+
+ try
+ {
+ if (_unitOfWork.HasChanges())
+ {
+ await _unitOfWork.CommitAsync();
+ return Ok("Updated");
+ }
+ }
+ catch
+ {
+ await _unitOfWork.RollbackAsync();
+ }
+
+ return Ok("Nothing to do");
+ }
+
+ /// <summary>
+ /// Adds all chapters from a list of series to a reading list
+ /// </summary>
+ /// <param name="dto"></param>
+ /// <returns></returns>
+ [HttpPost("update-by-multiple-series")]
+ public async Task<ActionResult> UpdateListByMultipleSeries(UpdateReadingListByMultipleSeriesDto dto)
+ {
+ var user = await _unitOfWork.UserRepository.GetUserWithReadingListsByUsernameAsync(User.GetUsername());
+ var readingList = user.ReadingLists.SingleOrDefault(l => l.Id == dto.ReadingListId);
+ if (readingList == null) return BadRequest("Reading List does not exist");
+
+ var ids = await _unitOfWork.SeriesRepository.GetChapterIdWithSeriesIdForSeriesAsync(dto.SeriesIds.ToArray());
+
+ foreach (var seriesId in ids.Keys)
+ {
+ // If there are adds, tell tracking this has been modified
+ if (await AddChaptersToReadingList(seriesId, ids[seriesId], readingList))
+ {
+ _unitOfWork.ReadingListRepository.Update(readingList);
+ }
+ }
+
+ try
+ {
+ if (_unitOfWork.HasChanges())
+ {
+ await _unitOfWork.CommitAsync();
+ return Ok("Updated");
+ }
+ }
+ catch
+ {
+ await _unitOfWork.RollbackAsync();
+ }
+
+ return Ok("Nothing to do");
+ }
+
+ [HttpPost("update-by-volume")]
+ public async Task<ActionResult> UpdateListByVolume(UpdateReadingListByVolumeDto dto)
+ {
+ var user = await _unitOfWork.UserRepository.GetUserWithReadingListsByUsernameAsync(User.GetUsername());
+ var readingList = user.ReadingLists.SingleOrDefault(l => l.Id == dto.ReadingListId);
+ if (readingList == null) return BadRequest("Reading List does not exist");
+ var chapterIdsForVolume =
+ (await _unitOfWork.ChapterRepository.GetChaptersAsync(dto.VolumeId)).Select(c => c.Id).ToList();
+
+ // If there are adds, tell tracking this has been modified
+ if (await AddChaptersToReadingList(dto.SeriesId, chapterIdsForVolume, readingList))
+ {
+ _unitOfWork.ReadingListRepository.Update(readingList);
+ }
+
+ try
+ {
+ if (_unitOfWork.HasChanges())
+ {
+ await _unitOfWork.CommitAsync();
+ return Ok("Updated");
+ }
+ }
+ catch
+ {
+ await _unitOfWork.RollbackAsync();
+ }
+
+ return Ok("Nothing to do");
+ }
+
+ [HttpPost("update-by-chapter")]
+ public async Task<ActionResult> UpdateListByChapter(UpdateReadingListByChapterDto dto)
+ {
+ var user = await _unitOfWork.UserRepository.GetUserWithReadingListsByUsernameAsync(User.GetUsername());
+ var readingList = user.ReadingLists.SingleOrDefault(l => l.Id == dto.ReadingListId);
+ if (readingList == null) return BadRequest("Reading List does not exist");
+
+ // If there are adds, tell tracking this has been modified
+ if (await AddChaptersToReadingList(dto.SeriesId, new List<int>() { dto.ChapterId }, readingList))
+ {
+ _unitOfWork.ReadingListRepository.Update(readingList);
+ }
+
+ try
+ {
+ if (_unitOfWork.HasChanges())
+ {
+ await _unitOfWork.CommitAsync();
+ return Ok("Updated");
+ }
+ }
+ catch
+ {
+ await _unitOfWork.RollbackAsync();
+ }
+
+ return Ok("Nothing to do");
+ }
+
+ /// <summary>
+ /// Adds a list of Chapters as reading list items to the passed reading list.
+ /// </summary>
+ /// <param name="seriesId"></param>
+ /// <param name="chapterIds"></param>
+ /// <param name="readingList"></param>
+ /// <returns>True if new chapters were added</returns>
+ private async Task<bool> AddChaptersToReadingList(int seriesId, IList<int> chapterIds,
+ ReadingList readingList)
+ {
+ readingList.Items ??= new List<ReadingListItem>();
+ var lastOrder = 0;
+ if (readingList.Items.Any())
+ {
+ lastOrder = readingList.Items.DefaultIfEmpty().Max(rli => rli.Order);
+ }
+
+ var existingChapterExists = readingList.Items.Select(rli => rli.ChapterId).ToHashSet();
+ var chaptersForSeries = (await _unitOfWork.ChapterRepository.GetChaptersByIdsAsync(chapterIds))
+ .OrderBy(c => int.Parse(c.Volume.Name))
+ .ThenBy(x => double.Parse(x.Number), _chapterSortComparerForInChapterSorting);
+
+ var index = lastOrder + 1;
+ foreach (var chapter in chaptersForSeries)
+ {
+ if (existingChapterExists.Contains(chapter.Id)) continue;
+
+ readingList.Items.Add(new ReadingListItem()
+ {
+ Order = index,
+ ChapterId = chapter.Id,
+ SeriesId = seriesId,
+ VolumeId = chapter.VolumeId
+ });
+ index += 1;
+ }
+
+ return index > lastOrder + 1;
+ }
+
+ /// <summary>
+ /// Returns the next chapter within the reading list
+ /// </summary>
+ /// <param name="currentChapterId"></param>
+ /// <param name="readingListId"></param>
+ /// <returns>Chapter Id for next item, -1 if nothing exists</returns>
+ [HttpGet("next-chapter")]
+ public async Task<ActionResult<int>> GetNextChapter(int currentChapterId, int readingListId)
+ {
+ var items = (await _unitOfWork.ReadingListRepository.GetReadingListItemsByIdAsync(readingListId)).ToList();
+ var readingListItem = items.SingleOrDefault(rl => rl.ChapterId == currentChapterId);
+ if (readingListItem == null) return BadRequest("Id does not exist");
+ var index = items.IndexOf(readingListItem) + 1;
+ if (items.Count > index)
+ {
+ return items[index].ChapterId;
+ }
+
+ return Ok(-1);
+ }
+
+ /// <summary>
+ /// Returns the prev chapter within the reading list
+ /// </summary>
+ /// <param name="currentChapterId"></param>
+ /// <param name="readingListId"></param>
+ /// <returns>Chapter Id for next item, -1 if nothing exists</returns>
+ [HttpGet("prev-chapter")]
+ public async Task<ActionResult<int>> GetPrevChapter(int currentChapterId, int readingListId)
+ {
+ var items = (await _unitOfWork.ReadingListRepository.GetReadingListItemsByIdAsync(readingListId)).ToList();
+ var readingListItem = items.SingleOrDefault(rl => rl.ChapterId == currentChapterId);
+ if (readingListItem == null) return BadRequest("Id does not exist");
+ var index = items.IndexOf(readingListItem) - 1;
+ if (0 <= index)
+ {
+ return items[index].ChapterId;
+ }
+
+ return Ok(-1);
+ }
+ }
+}
diff --git a/API/Controllers/SeriesController.cs b/API/Controllers/SeriesController.cs
index cce70de6d..ff0fa7587 100644
--- a/API/Controllers/SeriesController.cs
+++ b/API/Controllers/SeriesController.cs
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API.Data;
+using API.Data.Repositories;
using API.DTOs;
using API.DTOs.Filtering;
using API.Entities;
@@ -32,14 +33,14 @@ namespace API.Controllers
[HttpPost]
public async Task<ActionResult<IEnumerable<Series>>> GetSeriesForLibrary(int libraryId, [FromQuery] UserParams userParams, [FromBody] FilterDto filterDto)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
var series =
- await _unitOfWork.SeriesRepository.GetSeriesDtoForLibraryIdAsync(libraryId, user.Id, userParams, filterDto);
+ await _unitOfWork.SeriesRepository.GetSeriesDtoForLibraryIdAsync(libraryId, userId, userParams, filterDto);
// Apply progress/rating information (I can't work out how to do this in initial query)
if (series == null) return BadRequest("Could not get series for library");
- await _unitOfWork.SeriesRepository.AddSeriesModifiers(user.Id, series);
+ await _unitOfWork.SeriesRepository.AddSeriesModifiers(userId, series);
Response.AddPaginationHeader(series.CurrentPage, series.PageSize, series.TotalCount, series.TotalPages);
@@ -55,10 +56,10 @@ namespace API.Controllers
[HttpGet("{seriesId}")]
public async Task<ActionResult<SeriesDto>> GetSeries(int seriesId)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
try
{
- return Ok(await _unitOfWork.SeriesRepository.GetSeriesDtoByIdAsync(seriesId, user.Id));
+ return Ok(await _unitOfWork.SeriesRepository.GetSeriesDtoByIdAsync(seriesId, userId));
}
catch (Exception e)
{
@@ -95,30 +96,28 @@ namespace API.Controllers
[HttpGet("volumes")]
public async Task<ActionResult<IEnumerable<VolumeDto>>> GetVolumes(int seriesId)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
- return Ok(await _unitOfWork.SeriesRepository.GetVolumesDtoAsync(seriesId, user.Id));
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
+ return Ok(await _unitOfWork.SeriesRepository.GetVolumesDtoAsync(seriesId, userId));
}
[HttpGet("volume")]
public async Task<ActionResult<VolumeDto>> GetVolume(int volumeId)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
- return Ok(await _unitOfWork.SeriesRepository.GetVolumeDtoAsync(volumeId, user.Id));
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
+ return Ok(await _unitOfWork.SeriesRepository.GetVolumeDtoAsync(volumeId, userId));
}
[HttpGet("chapter")]
public async Task<ActionResult<VolumeDto>> GetChapter(int chapterId)
{
- return Ok(await _unitOfWork.VolumeRepository.GetChapterDtoAsync(chapterId));
+ return Ok(await _unitOfWork.ChapterRepository.GetChapterDtoAsync(chapterId));
}
-
-
[HttpPost("update-rating")]
public async Task<ActionResult> UpdateSeriesRating(UpdateSeriesRatingDto updateSeriesRatingDto)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername(), AppUserIncludes.Ratings);
var userRating = await _unitOfWork.UserRepository.GetUserRating(updateSeriesRatingDto.SeriesId, user.Id) ??
new AppUserRating();
@@ -158,10 +157,12 @@ namespace API.Controllers
series.Summary = updateSeries.Summary?.Trim();
var needsRefreshMetadata = false;
+ // This is when you hit Reset
if (series.CoverImageLocked && !updateSeries.CoverImageLocked)
{
// Trigger a refresh when we are moving from a locked image to a non-locked
needsRefreshMetadata = true;
+ series.CoverImage = string.Empty;
series.CoverImageLocked = updateSeries.CoverImageLocked;
}
@@ -182,14 +183,14 @@ namespace API.Controllers
[HttpPost("recently-added")]
public async Task<ActionResult<IEnumerable<SeriesDto>>> GetRecentlyAdded(FilterDto filterDto, [FromQuery] UserParams userParams, [FromQuery] int libraryId = 0)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
var series =
- await _unitOfWork.SeriesRepository.GetRecentlyAdded(libraryId, user.Id, userParams, filterDto);
+ await _unitOfWork.SeriesRepository.GetRecentlyAdded(libraryId, userId, userParams, filterDto);
// Apply progress/rating information (I can't work out how to do this in initial query)
if (series == null) return BadRequest("Could not get series");
- await _unitOfWork.SeriesRepository.AddSeriesModifiers(user.Id, series);
+ await _unitOfWork.SeriesRepository.AddSeriesModifiers(userId, series);
Response.AddPaginationHeader(series.CurrentPage, series.PageSize, series.TotalCount, series.TotalPages);
@@ -200,8 +201,8 @@ namespace API.Controllers
public async Task<ActionResult<IEnumerable<SeriesDto>>> GetInProgress(FilterDto filterDto, [FromQuery] UserParams userParams, [FromQuery] int libraryId = 0)
{
// NOTE: This has to be done manually like this due to the DistinctBy requirement
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
- var results = await _unitOfWork.SeriesRepository.GetInProgress(user.Id, libraryId, userParams, filterDto);
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
+ var results = await _unitOfWork.SeriesRepository.GetInProgress(userId, libraryId, userParams, filterDto);
var listResults = results.DistinctBy(s => s.Name).Skip((userParams.PageNumber - 1) * userParams.PageSize)
.Take(userParams.PageSize).ToList();
@@ -316,14 +317,14 @@ namespace API.Controllers
[HttpGet("series-by-collection")]
public async Task<ActionResult<IEnumerable<SeriesDto>>> GetSeriesByCollectionTag(int collectionId, [FromQuery] UserParams userParams)
{
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
var series =
- await _unitOfWork.SeriesRepository.GetSeriesDtoForCollectionAsync(collectionId, user.Id, userParams);
+ await _unitOfWork.SeriesRepository.GetSeriesDtoForCollectionAsync(collectionId, userId, userParams);
// Apply progress/rating information (I can't work out how to do this in initial query)
if (series == null) return BadRequest("Could not get series for collection");
- await _unitOfWork.SeriesRepository.AddSeriesModifiers(user.Id, series);
+ await _unitOfWork.SeriesRepository.AddSeriesModifiers(userId, series);
Response.AddPaginationHeader(series.CurrentPage, series.PageSize, series.TotalCount, series.TotalPages);
@@ -339,8 +340,8 @@ namespace API.Controllers
public async Task<ActionResult<IEnumerable<SeriesDto>>> GetAllSeriesById(SeriesByIdsDto dto)
{
if (dto.SeriesIds == null) return BadRequest("Must pass seriesIds");
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
- return Ok(await _unitOfWork.SeriesRepository.GetSeriesDtoForIdsAsync(dto.SeriesIds, user.Id));
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
+ return Ok(await _unitOfWork.SeriesRepository.GetSeriesDtoForIdsAsync(dto.SeriesIds, userId));
}
diff --git a/API/Controllers/SettingsController.cs b/API/Controllers/SettingsController.cs
index 4d81eb22d..acd1b61e8 100644
--- a/API/Controllers/SettingsController.cs
+++ b/API/Controllers/SettingsController.cs
@@ -103,7 +103,7 @@ namespace API.Controllers
}
else
{
- _taskScheduler.ScheduleStatsTasks();
+ await _taskScheduler.ScheduleStatsTasks();
}
}
}
diff --git a/API/Controllers/UploadController.cs b/API/Controllers/UploadController.cs
index 0d924c66d..4241a8bc6 100644
--- a/API/Controllers/UploadController.cs
+++ b/API/Controllers/UploadController.cs
@@ -3,9 +3,11 @@ using System.Threading.Tasks;
using API.DTOs.Uploads;
using API.Interfaces;
using API.Interfaces.Services;
+using API.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
+using NetVips;
namespace API.Controllers
{
@@ -48,12 +50,12 @@ namespace API.Controllers
try
{
- var bytes = _imageService.CreateThumbnailFromBase64(uploadFileDto.Url);
+ var filePath = _imageService.CreateThumbnailFromBase64(uploadFileDto.Url, ImageService.GetSeriesFormat(uploadFileDto.Id));
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(uploadFileDto.Id);
- if (bytes.Length > 0)
+ if (!string.IsNullOrEmpty(filePath))
{
- series.CoverImage = bytes;
+ series.CoverImage = filePath;
series.CoverImageLocked = true;
_unitOfWork.SeriesRepository.Update(series);
}
@@ -93,12 +95,12 @@ namespace API.Controllers
try
{
- var bytes = _imageService.CreateThumbnailFromBase64(uploadFileDto.Url);
+ var filePath = _imageService.CreateThumbnailFromBase64(uploadFileDto.Url, $"{ImageService.GetCollectionTagFormat(uploadFileDto.Id)}");
var tag = await _unitOfWork.CollectionTagRepository.GetTagAsync(uploadFileDto.Id);
- if (bytes.Length > 0)
+ if (!string.IsNullOrEmpty(filePath))
{
- tag.CoverImage = bytes;
+ tag.CoverImage = filePath;
tag.CoverImageLocked = true;
_unitOfWork.CollectionTagRepository.Update(tag);
}
@@ -138,12 +140,12 @@ namespace API.Controllers
try
{
- var bytes = _imageService.CreateThumbnailFromBase64(uploadFileDto.Url);
+ var chapter = await _unitOfWork.ChapterRepository.GetChapterAsync(uploadFileDto.Id);
+ var filePath = _imageService.CreateThumbnailFromBase64(uploadFileDto.Url, $"{ImageService.GetChapterFormat(uploadFileDto.Id, chapter.VolumeId)}");
- if (bytes.Length > 0)
+ if (!string.IsNullOrEmpty(filePath))
{
- var chapter = await _unitOfWork.VolumeRepository.GetChapterAsync(uploadFileDto.Id);
- chapter.CoverImage = bytes;
+ chapter.CoverImage = filePath;
chapter.CoverImageLocked = true;
_unitOfWork.ChapterRepository.Update(chapter);
var volume = await _unitOfWork.SeriesRepository.GetVolumeAsync(chapter.VolumeId);
@@ -178,8 +180,9 @@ namespace API.Controllers
{
try
{
- var chapter = await _unitOfWork.VolumeRepository.GetChapterAsync(uploadFileDto.Id);
- chapter.CoverImage = Array.Empty<byte>();
+ var chapter = await _unitOfWork.ChapterRepository.GetChapterAsync(uploadFileDto.Id);
+ var originalFile = chapter.CoverImage;
+ chapter.CoverImage = string.Empty;
chapter.CoverImageLocked = false;
_unitOfWork.ChapterRepository.Update(chapter);
var volume = await _unitOfWork.SeriesRepository.GetVolumeAsync(chapter.VolumeId);
@@ -190,7 +193,8 @@ namespace API.Controllers
if (_unitOfWork.HasChanges())
{
await _unitOfWork.CommitAsync();
- _taskScheduler.RefreshSeriesMetadata(series.LibraryId, series.Id);
+ System.IO.File.Delete(originalFile);
+ _taskScheduler.RefreshSeriesMetadata(series.LibraryId, series.Id, true);
return Ok();
}
diff --git a/API/Controllers/UsersController.cs b/API/Controllers/UsersController.cs
index ee4c9ac66..c35e368cc 100644
--- a/API/Controllers/UsersController.cs
+++ b/API/Controllers/UsersController.cs
@@ -18,7 +18,7 @@ namespace API.Controllers
{
_unitOfWork = unitOfWork;
}
-
+
[Authorize(Policy = "RequireAdminRole")]
[HttpDelete("delete-user")]
public async Task<ActionResult> DeleteUser(string username)
@@ -30,7 +30,7 @@ namespace API.Controllers
return BadRequest("Could not delete the user.");
}
-
+
[Authorize(Policy = "RequireAdminRole")]
[HttpGet]
public async Task<ActionResult<IEnumerable<MemberDto>>> GetUsers()
@@ -42,8 +42,8 @@ namespace API.Controllers
public async Task<ActionResult<bool>> HasReadingProgress(int libraryId)
{
var library = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(libraryId);
- var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
- return Ok(await _unitOfWork.AppUserProgressRepository.UserHasProgress(library.Type, user.Id));
+ var userId = await _unitOfWork.UserRepository.GetUserIdByUsernameAsync(User.GetUsername());
+ return Ok(await _unitOfWork.AppUserProgressRepository.UserHasProgress(library.Type, userId));
}
[HttpGet("has-library-access")]
@@ -77,8 +77,8 @@ namespace API.Controllers
{
return Ok(preferencesDto);
}
-
+
return BadRequest("There was an issue saving preferences.");
}
}
-}
\ No newline at end of file
+}
diff --git a/API/DTOs/LoginDto.cs b/API/DTOs/Account/LoginDto.cs
similarity index 100%
rename from API/DTOs/LoginDto.cs
rename to API/DTOs/Account/LoginDto.cs
diff --git a/API/DTOs/ResetPasswordDto.cs b/API/DTOs/Account/ResetPasswordDto.cs
similarity index 90%
rename from API/DTOs/ResetPasswordDto.cs
rename to API/DTOs/Account/ResetPasswordDto.cs
index 4b3ee3580..2e7ef4d66 100644
--- a/API/DTOs/ResetPasswordDto.cs
+++ b/API/DTOs/Account/ResetPasswordDto.cs
@@ -1,6 +1,6 @@
using System.ComponentModel.DataAnnotations;
-namespace API.DTOs
+namespace API.DTOs.Account
{
public class ResetPasswordDto
{
@@ -10,4 +10,4 @@ namespace API.DTOs
[StringLength(32, MinimumLength = 6)]
public string Password { get; init; }
}
-}
\ No newline at end of file
+}
diff --git a/API/DTOs/Downloads/DownloadBookmarkDto.cs b/API/DTOs/Downloads/DownloadBookmarkDto.cs
index 5239b4aae..b7ccf9569 100644
--- a/API/DTOs/Downloads/DownloadBookmarkDto.cs
+++ b/API/DTOs/Downloads/DownloadBookmarkDto.cs
@@ -1,4 +1,5 @@
using System.Collections.Generic;
+using API.DTOs.Reader;
namespace API.DTOs.Downloads
{
diff --git a/API/DTOs/ImageDto.cs b/API/DTOs/ImageDto.cs
deleted file mode 100644
index e66591001..000000000
--- a/API/DTOs/ImageDto.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-namespace API.DTOs
-{
- public class ImageDto
- {
- public int Page { get; init; }
- public string Filename { get; init; }
- public string FullPath { get; init; }
- public int Width { get; init; }
- public int Height { get; init; }
- public string Format { get; init; }
- public byte[] Content { get; init; }
- public string MangaFileName { get; init; }
- public bool NeedsSplitting { get; init; }
- }
-}
\ No newline at end of file
diff --git a/API/DTOs/InProgressChapterDto.cs b/API/DTOs/InProgressChapterDto.cs
deleted file mode 100644
index 08bce3fc6..000000000
--- a/API/DTOs/InProgressChapterDto.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-namespace API.DTOs
-{
- public class InProgressChapterDto
- {
- public int Id { get; init; }
- /// <summary>
- /// Range of chapters. Chapter 2-4 -> "2-4". Chapter 2 -> "2".
- /// </summary>
- public string Range { get; init; }
- /// <summary>
- /// Smallest number of the Range.
- /// </summary>
- public string Number { get; init; }
- /// <summary>
- /// Total number of pages in all MangaFiles
- /// </summary>
- public int Pages { get; init; }
- public int SeriesId { get; init; }
- public int LibraryId { get; init; }
- public string SeriesName { get; init; }
- public int VolumeId { get; init; }
-
- }
-}
\ No newline at end of file
diff --git a/API/DTOs/Reader/BookInfoDto.cs b/API/DTOs/Reader/BookInfoDto.cs
new file mode 100644
index 000000000..6705c9647
--- /dev/null
+++ b/API/DTOs/Reader/BookInfoDto.cs
@@ -0,0 +1,18 @@
+using API.Entities.Enums;
+
+namespace API.DTOs.Reader
+{
+ public class BookInfoDto : IChapterInfoDto
+ {
+ public string BookTitle { get; set; }
+ public int SeriesId { get; set; }
+ public int VolumeId { get; set; }
+ public MangaFormat SeriesFormat { get; set; }
+ public string SeriesName { get; set; }
+ public string ChapterNumber { get; set; }
+ public string VolumeNumber { get; set; }
+ public int LibraryId { get; set; }
+ public int Pages { get; set; }
+ public bool IsSpecial { get; set; }
+ }
+}
diff --git a/API/DTOs/BookmarkDto.cs b/API/DTOs/Reader/BookmarkDto.cs
similarity index 89%
rename from API/DTOs/BookmarkDto.cs
rename to API/DTOs/Reader/BookmarkDto.cs
index c45a183c3..3653bcaa0 100644
--- a/API/DTOs/BookmarkDto.cs
+++ b/API/DTOs/Reader/BookmarkDto.cs
@@ -1,4 +1,4 @@
-namespace API.DTOs
+namespace API.DTOs.Reader
{
public class BookmarkDto
{
diff --git a/API/DTOs/Reader/ChapterInfoDto.cs b/API/DTOs/Reader/ChapterInfoDto.cs
index 850149016..ec512670d 100644
--- a/API/DTOs/Reader/ChapterInfoDto.cs
+++ b/API/DTOs/Reader/ChapterInfoDto.cs
@@ -1,16 +1,21 @@
-namespace API.DTOs.Reader
+using API.Entities.Enums;
+
+namespace API.DTOs.Reader
{
- public class ChapterInfoDto
+ public class ChapterInfoDto : IChapterInfoDto
{
-
+
public string ChapterNumber { get; set; }
public string VolumeNumber { get; set; }
public int VolumeId { get; set; }
public string SeriesName { get; set; }
+ public MangaFormat SeriesFormat { get; set; }
+ public int SeriesId { get; set; }
+ public int LibraryId { get; set; }
public string ChapterTitle { get; set; } = "";
public int Pages { get; set; }
public string FileName { get; set; }
public bool IsSpecial { get; set; }
-
+
}
-}
\ No newline at end of file
+}
diff --git a/API/DTOs/Reader/IChapterInfoDto.cs b/API/DTOs/Reader/IChapterInfoDto.cs
new file mode 100644
index 000000000..63b5c9a62
--- /dev/null
+++ b/API/DTOs/Reader/IChapterInfoDto.cs
@@ -0,0 +1,19 @@
+using API.Entities.Enums;
+using Newtonsoft.Json;
+
+namespace API.DTOs.Reader
+{
+ public interface IChapterInfoDto
+ {
+ public int SeriesId { get; set; }
+ public int VolumeId { get; set; }
+ public MangaFormat SeriesFormat { get; set; }
+ public string SeriesName { get; set; }
+ public string ChapterNumber { get; set; }
+ public string VolumeNumber { get; set; }
+ public int LibraryId { get; set; }
+ public int Pages { get; set; }
+ public bool IsSpecial { get; set; }
+
+ }
+}
diff --git a/API/DTOs/Reader/MarkMultipleSeriesAsReadDto.cs b/API/DTOs/Reader/MarkMultipleSeriesAsReadDto.cs
new file mode 100644
index 000000000..7201658fa
--- /dev/null
+++ b/API/DTOs/Reader/MarkMultipleSeriesAsReadDto.cs
@@ -0,0 +1,9 @@
+using System.Collections.Generic;
+
+namespace API.DTOs.Reader
+{
+ public class MarkMultipleSeriesAsReadDto
+ {
+ public IReadOnlyList<int> SeriesIds { get; init; }
+ }
+}
diff --git a/API/DTOs/MarkReadDto.cs b/API/DTOs/Reader/MarkReadDto.cs
similarity index 73%
rename from API/DTOs/MarkReadDto.cs
rename to API/DTOs/Reader/MarkReadDto.cs
index 1b39df2a8..3d94e3a9d 100644
--- a/API/DTOs/MarkReadDto.cs
+++ b/API/DTOs/Reader/MarkReadDto.cs
@@ -1,7 +1,7 @@
-namespace API.DTOs
+namespace API.DTOs.Reader
{
public class MarkReadDto
{
public int SeriesId { get; init; }
}
-}
\ No newline at end of file
+}
diff --git a/API/DTOs/MarkVolumeReadDto.cs b/API/DTOs/Reader/MarkVolumeReadDto.cs
similarity index 81%
rename from API/DTOs/MarkVolumeReadDto.cs
rename to API/DTOs/Reader/MarkVolumeReadDto.cs
index ffae155a2..757f23aee 100644
--- a/API/DTOs/MarkVolumeReadDto.cs
+++ b/API/DTOs/Reader/MarkVolumeReadDto.cs
@@ -1,8 +1,8 @@
-namespace API.DTOs
+namespace API.DTOs.Reader
{
public class MarkVolumeReadDto
{
public int SeriesId { get; init; }
public int VolumeId { get; init; }
}
-}
\ No newline at end of file
+}
diff --git a/API/DTOs/Reader/MarkVolumesReadDto.cs b/API/DTOs/Reader/MarkVolumesReadDto.cs
new file mode 100644
index 000000000..7e23e721a
--- /dev/null
+++ b/API/DTOs/Reader/MarkVolumesReadDto.cs
@@ -0,0 +1,20 @@
+using System.Collections.Generic;
+
+namespace API.DTOs.Reader
+{
+ /// <summary>
+ /// This is used for bulk updating a set of volume and or chapters in one go
+ /// </summary>
+ public class MarkVolumesReadDto
+ {
+ public int SeriesId { get; set; }
+ /// <summary>
+ /// A list of Volumes to mark read
+ /// </summary>
+ public IReadOnlyList<int> VolumeIds { get; set; }
+ /// <summary>
+ /// A list of additional Chapters to mark as read
+ /// </summary>
+ public IReadOnlyList<int> ChapterIds { get; set; }
+ }
+}
diff --git a/API/DTOs/RemoveBookmarkForSeriesDto.cs b/API/DTOs/Reader/RemoveBookmarkForSeriesDto.cs
similarity index 78%
rename from API/DTOs/RemoveBookmarkForSeriesDto.cs
rename to API/DTOs/Reader/RemoveBookmarkForSeriesDto.cs
index 7ec76b081..a269b7095 100644
--- a/API/DTOs/RemoveBookmarkForSeriesDto.cs
+++ b/API/DTOs/Reader/RemoveBookmarkForSeriesDto.cs
@@ -1,4 +1,4 @@
-namespace API.DTOs
+namespace API.DTOs.Reader
{
public class RemoveBookmarkForSeriesDto
{
diff --git a/API/DTOs/ReadingLists/CreateReadingListDto.cs b/API/DTOs/ReadingLists/CreateReadingListDto.cs
new file mode 100644
index 000000000..c32b62bea
--- /dev/null
+++ b/API/DTOs/ReadingLists/CreateReadingListDto.cs
@@ -0,0 +1,7 @@
+namespace API.DTOs.ReadingLists
+{
+ public class CreateReadingListDto
+ {
+ public string Title { get; init; }
+ }
+}
diff --git a/API/DTOs/ReadingLists/ReadingListDto.cs b/API/DTOs/ReadingLists/ReadingListDto.cs
new file mode 100644
index 000000000..e3837a2e3
--- /dev/null
+++ b/API/DTOs/ReadingLists/ReadingListDto.cs
@@ -0,0 +1,13 @@
+namespace API.DTOs.ReadingLists
+{
+ public class ReadingListDto
+ {
+ public int Id { get; init; }
+ public string Title { get; set; }
+ public string Summary { get; set; }
+ /// <summary>
+ /// Reading lists that are promoted are only done by admins
+ /// </summary>
+ public bool Promoted { get; set; }
+ }
+}
diff --git a/API/DTOs/ReadingLists/ReadingListItemDto.cs b/API/DTOs/ReadingLists/ReadingListItemDto.cs
new file mode 100644
index 000000000..b58fdcf80
--- /dev/null
+++ b/API/DTOs/ReadingLists/ReadingListItemDto.cs
@@ -0,0 +1,25 @@
+using API.Entities.Enums;
+
+namespace API.DTOs.ReadingLists
+{
+ public class ReadingListItemDto
+ {
+ public int Id { get; init; }
+ public int Order { get; init; }
+ public int ChapterId { get; init; }
+ public int SeriesId { get; init; }
+ public string SeriesName { get; set; }
+ public MangaFormat SeriesFormat { get; set; }
+ public int PagesRead { get; set; }
+ public int PagesTotal { get; set; }
+ public string ChapterNumber { get; set; }
+ public string VolumeNumber { get; set; }
+ public int VolumeId { get; set; }
+ public int LibraryId { get; set; }
+ public string Title { get; set; }
+ /// <summary>
+ /// Used internally only
+ /// </summary>
+ public int ReadingListId { get; set; }
+ }
+}
diff --git a/API/DTOs/ReadingLists/UpdateReadingListByChapterDto.cs b/API/DTOs/ReadingLists/UpdateReadingListByChapterDto.cs
new file mode 100644
index 000000000..887850755
--- /dev/null
+++ b/API/DTOs/ReadingLists/UpdateReadingListByChapterDto.cs
@@ -0,0 +1,9 @@
+namespace API.DTOs.ReadingLists
+{
+ public class UpdateReadingListByChapterDto
+ {
+ public int ChapterId { get; init; }
+ public int SeriesId { get; init; }
+ public int ReadingListId { get; init; }
+ }
+}
diff --git a/API/DTOs/ReadingLists/UpdateReadingListByMultipleDto.cs b/API/DTOs/ReadingLists/UpdateReadingListByMultipleDto.cs
new file mode 100644
index 000000000..02a41a767
--- /dev/null
+++ b/API/DTOs/ReadingLists/UpdateReadingListByMultipleDto.cs
@@ -0,0 +1,12 @@
+using System.Collections.Generic;
+
+namespace API.DTOs.ReadingLists
+{
+ public class UpdateReadingListByMultipleDto
+ {
+ public int SeriesId { get; init; }
+ public int ReadingListId { get; init; }
+ public IReadOnlyList<int> VolumeIds { get; init; }
+ public IReadOnlyList<int> ChapterIds { get; init; }
+ }
+}
diff --git a/API/DTOs/ReadingLists/UpdateReadingListByMultipleSeriesDto.cs b/API/DTOs/ReadingLists/UpdateReadingListByMultipleSeriesDto.cs
new file mode 100644
index 000000000..4b08f95bc
--- /dev/null
+++ b/API/DTOs/ReadingLists/UpdateReadingListByMultipleSeriesDto.cs
@@ -0,0 +1,10 @@
+using System.Collections.Generic;
+
+namespace API.DTOs.ReadingLists
+{
+ public class UpdateReadingListByMultipleSeriesDto
+ {
+ public int ReadingListId { get; init; }
+ public IReadOnlyList<int> SeriesIds { get; init; }
+ }
+}
diff --git a/API/DTOs/ReadingLists/UpdateReadingListBySeriesDto.cs b/API/DTOs/ReadingLists/UpdateReadingListBySeriesDto.cs
new file mode 100644
index 000000000..1040a9218
--- /dev/null
+++ b/API/DTOs/ReadingLists/UpdateReadingListBySeriesDto.cs
@@ -0,0 +1,8 @@
+namespace API.DTOs.ReadingLists
+{
+ public class UpdateReadingListBySeriesDto
+ {
+ public int SeriesId { get; init; }
+ public int ReadingListId { get; init; }
+ }
+}
diff --git a/API/DTOs/ReadingLists/UpdateReadingListByVolumeDto.cs b/API/DTOs/ReadingLists/UpdateReadingListByVolumeDto.cs
new file mode 100644
index 000000000..0d903d48e
--- /dev/null
+++ b/API/DTOs/ReadingLists/UpdateReadingListByVolumeDto.cs
@@ -0,0 +1,9 @@
+namespace API.DTOs.ReadingLists
+{
+ public class UpdateReadingListByVolumeDto
+ {
+ public int VolumeId { get; init; }
+ public int SeriesId { get; init; }
+ public int ReadingListId { get; init; }
+ }
+}
diff --git a/API/DTOs/ReadingLists/UpdateReadingListDto.cs b/API/DTOs/ReadingLists/UpdateReadingListDto.cs
new file mode 100644
index 000000000..a9f6f0d59
--- /dev/null
+++ b/API/DTOs/ReadingLists/UpdateReadingListDto.cs
@@ -0,0 +1,10 @@
+namespace API.DTOs.ReadingLists
+{
+ public class UpdateReadingListDto
+ {
+ public int ReadingListId { get; set; }
+ public string Title { get; set; }
+ public string Summary { get; set; }
+ public bool Promoted { get; set; }
+ }
+}
diff --git a/API/DTOs/ReadingLists/UpdateReadingListPosition.cs b/API/DTOs/ReadingLists/UpdateReadingListPosition.cs
new file mode 100644
index 000000000..023849024
--- /dev/null
+++ b/API/DTOs/ReadingLists/UpdateReadingListPosition.cs
@@ -0,0 +1,10 @@
+namespace API.DTOs.ReadingLists
+{
+ public class UpdateReadingListPosition
+ {
+ public int ReadingListId { get; set; }
+ public int ReadingListItemId { get; set; }
+ public int FromPosition { get; set; }
+ public int ToPosition { get; set; }
+ }
+}
diff --git a/API/DTOs/ServerSettingDTO.cs b/API/DTOs/Settings/ServerSettingDTO.cs
similarity index 100%
rename from API/DTOs/ServerSettingDTO.cs
rename to API/DTOs/Settings/ServerSettingDTO.cs
diff --git a/API/DTOs/VolumeDto.cs b/API/DTOs/VolumeDto.cs
index 3fc165a6d..3e719346f 100644
--- a/API/DTOs/VolumeDto.cs
+++ b/API/DTOs/VolumeDto.cs
@@ -13,7 +13,7 @@ namespace API.DTOs
public int PagesRead { get; set; }
public DateTime LastModified { get; set; }
public DateTime Created { get; set; }
- public bool IsSpecial { get; set; }
+ public int SeriesId { get; set; }
public ICollection<ChapterDto> Chapters { get; set; }
}
-}
\ No newline at end of file
+}
diff --git a/API/Data/BookmarkRepository.cs b/API/Data/BookmarkRepository.cs
deleted file mode 100644
index af212bc72..000000000
--- a/API/Data/BookmarkRepository.cs
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace API.Data
-{
- public class BookmarkRepository
- {
-
- }
-}
diff --git a/API/Data/ChapterRepository.cs b/API/Data/ChapterRepository.cs
deleted file mode 100644
index e3510adc4..000000000
--- a/API/Data/ChapterRepository.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using API.Entities;
-using API.Interfaces.Repositories;
-using Microsoft.EntityFrameworkCore;
-
-namespace API.Data
-{
- public class ChapterRepository : IChapterRepository
- {
- private readonly DataContext _context;
-
- public ChapterRepository(DataContext context)
- {
- _context = context;
- }
-
- public void Update(Chapter chapter)
- {
- _context.Entry(chapter).State = EntityState.Modified;
- }
-
- // TODO: Move over Chapter based queries here
- }
-}
diff --git a/API/Data/DataContext.cs b/API/Data/DataContext.cs
index 62765f607..8e4dc263e 100644
--- a/API/Data/DataContext.cs
+++ b/API/Data/DataContext.cs
@@ -35,6 +35,9 @@ namespace API.Data
public DbSet<SeriesMetadata> SeriesMetadata { get; set; }
public DbSet<CollectionTag> CollectionTag { get; set; }
public DbSet<AppUserBookmark> AppUserBookmark { get; set; }
+ public DbSet<ReadingList> ReadingList { get; set; }
+ public DbSet<ReadingListItem> ReadingListItem { get; set; }
+
protected override void OnModelCreating(ModelBuilder builder)
{
diff --git a/API/Data/MigrateCoverImages.cs b/API/Data/MigrateCoverImages.cs
new file mode 100644
index 000000000..87e65cb81
--- /dev/null
+++ b/API/Data/MigrateCoverImages.cs
@@ -0,0 +1,180 @@
+using System;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using API.Comparators;
+using API.Helpers;
+using API.Services;
+using Microsoft.EntityFrameworkCore;
+
+namespace API.Data
+{
+ /// <summary>
+ /// A data structure to migrate Cover Images from byte[] to files.
+ /// </summary>
+ internal class CoverMigration
+ {
+ public string Id { get; set; }
+ public byte[] CoverImage { get; set; }
+ public string ParentId { get; set; }
+ }
+
+ /// <summary>
+ /// In v0.4.6, Cover Images were migrated from byte[] in the DB to external files. This migration handles that work.
+ /// </summary>
+ public static class MigrateCoverImages
+ {
+ private static readonly ChapterSortComparerZeroFirst ChapterSortComparerForInChapterSorting = new ();
+
+ /// <summary>
+ /// Run first. Will extract byte[]s from DB and write them to the cover directory.
+ /// </summary>
+ public static void ExtractToImages(DbContext context)
+ {
+ Console.WriteLine("Migrating Cover Images to disk. Expect delay.");
+ DirectoryService.ExistOrCreate(DirectoryService.CoverImageDirectory);
+
+ Console.WriteLine("Extracting cover images for Series");
+ var lockedSeries = SqlHelper.RawSqlQuery(context, "Select Id, CoverImage From Series Where CoverImage IS NOT NULL", x =>
+ new CoverMigration()
+ {
+ Id = x[0] + string.Empty,
+ CoverImage = (byte[]) x[1],
+ ParentId = "0"
+ });
+ foreach (var series in lockedSeries)
+ {
+ if (series.CoverImage == null || !series.CoverImage.Any()) continue;
+ if (File.Exists(Path.Join(DirectoryService.CoverImageDirectory,
+ $"{ImageService.GetSeriesFormat(int.Parse(series.Id))}.png"))) continue;
+
+ try
+ {
+ var stream = new MemoryStream(series.CoverImage);
+ stream.Position = 0;
+ ImageService.WriteCoverThumbnail(stream, ImageService.GetSeriesFormat(int.Parse(series.Id)));
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine(e);
+ }
+ }
+
+ Console.WriteLine("Extracting cover images for Chapters");
+ var chapters = SqlHelper.RawSqlQuery(context, "Select Id, CoverImage, VolumeId From Chapter Where CoverImage IS NOT NULL;", x =>
+ new CoverMigration()
+ {
+ Id = x[0] + string.Empty,
+ CoverImage = (byte[]) x[1],
+ ParentId = x[2] + string.Empty
+ });
+ foreach (var chapter in chapters)
+ {
+ if (chapter.CoverImage == null || !chapter.CoverImage.Any()) continue;
+ if (File.Exists(Path.Join(DirectoryService.CoverImageDirectory,
+ $"{ImageService.GetChapterFormat(int.Parse(chapter.Id), int.Parse(chapter.ParentId))}.png"))) continue;
+
+ try
+ {
+ var stream = new MemoryStream(chapter.CoverImage);
+ stream.Position = 0;
+ ImageService.WriteCoverThumbnail(stream, $"{ImageService.GetChapterFormat(int.Parse(chapter.Id), int.Parse(chapter.ParentId))}");
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine(e);
+ }
+ }
+
+ Console.WriteLine("Extracting cover images for Collection Tags");
+ var tags = SqlHelper.RawSqlQuery(context, "Select Id, CoverImage From CollectionTag Where CoverImage IS NOT NULL;", x =>
+ new CoverMigration()
+ {
+ Id = x[0] + string.Empty,
+ CoverImage = (byte[]) x[1] ,
+ ParentId = "0"
+ });
+ foreach (var tag in tags)
+ {
+ if (tag.CoverImage == null || !tag.CoverImage.Any()) continue;
+ if (File.Exists(Path.Join(DirectoryService.CoverImageDirectory,
+ $"{ImageService.GetCollectionTagFormat(int.Parse(tag.Id))}.png"))) continue;
+ try
+ {
+ var stream = new MemoryStream(tag.CoverImage);
+ stream.Position = 0;
+ ImageService.WriteCoverThumbnail(stream, $"{ImageService.GetCollectionTagFormat(int.Parse(tag.Id))}");
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine(e);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Run after <see cref="ExtractToImages"/>. Will update the DB with names of files that were extracted.
+ /// </summary>
+ /// <param name="context"></param>
+ public static async Task UpdateDatabaseWithImages(DataContext context)
+ {
+ Console.WriteLine("Updating Series entities");
+ var seriesCovers = await context.Series.Where(s => !string.IsNullOrEmpty(s.CoverImage)).ToListAsync();
+ foreach (var series in seriesCovers)
+ {
+ if (!File.Exists(Path.Join(DirectoryService.CoverImageDirectory,
+ $"{ImageService.GetSeriesFormat(series.Id)}.png"))) continue;
+ series.CoverImage = $"{ImageService.GetSeriesFormat(series.Id)}.png";
+ }
+
+ await context.SaveChangesAsync();
+
+ Console.WriteLine("Updating Chapter entities");
+ var chapters = await context.Chapter.ToListAsync();
+ foreach (var chapter in chapters)
+ {
+ if (File.Exists(Path.Join(DirectoryService.CoverImageDirectory,
+ $"{ImageService.GetChapterFormat(chapter.Id, chapter.VolumeId)}.png")))
+ {
+ chapter.CoverImage = $"{ImageService.GetChapterFormat(chapter.Id, chapter.VolumeId)}.png";
+ }
+
+ }
+
+ await context.SaveChangesAsync();
+
+ Console.WriteLine("Updating Volume entities");
+ var volumes = await context.Volume.Include(v => v.Chapters).ToListAsync();
+ foreach (var volume in volumes)
+ {
+ var firstChapter = volume.Chapters.OrderBy(x => double.Parse(x.Number), ChapterSortComparerForInChapterSorting).FirstOrDefault();
+ if (firstChapter == null) continue;
+ if (File.Exists(Path.Join(DirectoryService.CoverImageDirectory,
+ $"{ImageService.GetChapterFormat(firstChapter.Id, firstChapter.VolumeId)}.png")))
+ {
+ volume.CoverImage = $"{ImageService.GetChapterFormat(firstChapter.Id, firstChapter.VolumeId)}.png";
+ }
+
+ }
+
+ await context.SaveChangesAsync();
+
+ Console.WriteLine("Updating Collection Tag entities");
+ var tags = await context.CollectionTag.ToListAsync();
+ foreach (var tag in tags)
+ {
+ if (File.Exists(Path.Join(DirectoryService.CoverImageDirectory,
+ $"{ImageService.GetCollectionTagFormat(tag.Id)}.png")))
+ {
+ tag.CoverImage = $"{ImageService.GetCollectionTagFormat(tag.Id)}.png";
+ }
+
+ }
+
+ await context.SaveChangesAsync();
+
+ Console.WriteLine("Cover Image Migration completed");
+ }
+
+ }
+}
diff --git a/API/Data/Migrations/20210901150310_ReadingLists.Designer.cs b/API/Data/Migrations/20210901150310_ReadingLists.Designer.cs
new file mode 100644
index 000000000..fef65fdcf
--- /dev/null
+++ b/API/Data/Migrations/20210901150310_ReadingLists.Designer.cs
@@ -0,0 +1,1018 @@
+// <auto-generated />
+using System;
+using API.Data;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace API.Data.Migrations
+{
+ [DbContext(typeof(DataContext))]
+ [Migration("20210901150310_ReadingLists")]
+ partial class ReadingLists
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "5.0.8");
+
+ modelBuilder.Entity("API.Entities.AppRole", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ConcurrencyStamp")
+ .IsConcurrencyToken()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("NormalizedName")
+ .IsUnique()
+ .HasDatabaseName("RoleNameIndex");
+
+ b.ToTable("AspNetRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUser", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AccessFailedCount")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ApiKey")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ConcurrencyStamp")
+ .IsConcurrencyToken()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Email")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("EmailConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastActive")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("LockoutEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTimeOffset?>("LockoutEnd")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedEmail")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedUserName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PasswordHash")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PhoneNumber")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("PhoneNumberConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("SecurityStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("TwoFactorEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("UserName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("NormalizedEmail")
+ .HasDatabaseName("EmailIndex");
+
+ b.HasIndex("NormalizedUserName")
+ .IsUnique()
+ .HasDatabaseName("UserNameIndex");
+
+ b.ToTable("AspNetUsers");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserBookmark", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Page")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserBookmark");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserPreferences", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("AutoCloseMenu")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("BookReaderDarkMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("BookReaderFontFamily")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("BookReaderFontSize")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderLineSpacing")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderMargin")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderReadingDirection")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("BookReaderTapToPaginate")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("PageSplitOption")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReaderMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReadingDirection")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ScalingOption")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("SiteDarkMode")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId")
+ .IsUnique();
+
+ b.ToTable("AppUserPreferences");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserProgress", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("BookScrollId")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("PagesRead")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserProgresses");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRating", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Rating")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Review")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserRating");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRole", b =>
+ {
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("RoleId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("UserId", "RoleId");
+
+ b.HasIndex("RoleId");
+
+ b.ToTable("AspNetUserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("IsSpecial")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Number")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Range")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("VolumeId");
+
+ b.ToTable("Chapter");
+ });
+
+ modelBuilder.Entity("API.Entities.CollectionTag", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("NormalizedTitle")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("Promoted")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Id", "Promoted")
+ .IsUnique();
+
+ b.ToTable("CollectionTag");
+ });
+
+ modelBuilder.Entity("API.Entities.FolderPath", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastScanned")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("LibraryId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Path")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("LibraryId");
+
+ b.ToTable("FolderPath");
+ });
+
+ modelBuilder.Entity("API.Entities.Library", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("CoverImage")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Type")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.ToTable("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.MangaFile", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("FilePath")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Format")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ChapterId");
+
+ b.ToTable("MangaFile");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("Promoted")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("ReadingList");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingListItem", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("LibraryId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Order")
+ .HasColumnType("INTEGER");
+
+ b.Property<int?>("ReadingListId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ReadingListId");
+
+ b.HasIndex("SeriesId", "VolumeId", "ChapterId", "LibraryId")
+ .IsUnique();
+
+ b.ToTable("ReadingListItem");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Format")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("LibraryId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("LocalizedName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("OriginalName")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("SortName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("LibraryId");
+
+ b.HasIndex("Name", "NormalizedName", "LocalizedName", "LibraryId", "Format")
+ .IsUnique();
+
+ b.ToTable("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.SeriesMetadata", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("SeriesId")
+ .IsUnique();
+
+ b.HasIndex("Id", "SeriesId")
+ .IsUnique();
+
+ b.ToTable("SeriesMetadata");
+ });
+
+ modelBuilder.Entity("API.Entities.ServerSetting", b =>
+ {
+ b.Property<int>("Key")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Value")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Key");
+
+ b.ToTable("ServerSetting");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Number")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("SeriesId");
+
+ b.ToTable("Volume");
+ });
+
+ modelBuilder.Entity("AppUserLibrary", b =>
+ {
+ b.Property<int>("AppUsersId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("LibrariesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("AppUsersId", "LibrariesId");
+
+ b.HasIndex("LibrariesId");
+
+ b.ToTable("AppUserLibrary");
+ });
+
+ modelBuilder.Entity("CollectionTagSeriesMetadata", b =>
+ {
+ b.Property<int>("CollectionTagsId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesMetadatasId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("CollectionTagsId", "SeriesMetadatasId");
+
+ b.HasIndex("SeriesMetadatasId");
+
+ b.ToTable("CollectionTagSeriesMetadata");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("RoleId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("RoleId");
+
+ b.ToTable("AspNetRoleClaims");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AspNetUserClaims");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
+ {
+ b.Property<string>("LoginProvider")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderKey")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderDisplayName")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("LoginProvider", "ProviderKey");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AspNetUserLogins");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
+ {
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("LoginProvider")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Value")
+ .HasColumnType("TEXT");
+
+ b.HasKey("UserId", "LoginProvider", "Name");
+
+ b.ToTable("AspNetUserTokens");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserBookmark", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Bookmarks")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserPreferences", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithOne("UserPreferences")
+ .HasForeignKey("API.Entities.AppUserPreferences", "AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserProgress", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Progresses")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRating", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Ratings")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRole", b =>
+ {
+ b.HasOne("API.Entities.AppRole", "Role")
+ .WithMany("UserRoles")
+ .HasForeignKey("RoleId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.AppUser", "User")
+ .WithMany("UserRoles")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Role");
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.HasOne("API.Entities.Volume", "Volume")
+ .WithMany("Chapters")
+ .HasForeignKey("VolumeId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Volume");
+ });
+
+ modelBuilder.Entity("API.Entities.FolderPath", b =>
+ {
+ b.HasOne("API.Entities.Library", "Library")
+ .WithMany("Folders")
+ .HasForeignKey("LibraryId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.MangaFile", b =>
+ {
+ b.HasOne("API.Entities.Chapter", "Chapter")
+ .WithMany("Files")
+ .HasForeignKey("ChapterId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Chapter");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("ReadingLists")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingListItem", b =>
+ {
+ b.HasOne("API.Entities.ReadingList", null)
+ .WithMany("Items")
+ .HasForeignKey("ReadingListId");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.HasOne("API.Entities.Library", "Library")
+ .WithMany("Series")
+ .HasForeignKey("LibraryId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.SeriesMetadata", b =>
+ {
+ b.HasOne("API.Entities.Series", "Series")
+ .WithOne("Metadata")
+ .HasForeignKey("API.Entities.SeriesMetadata", "SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.HasOne("API.Entities.Series", "Series")
+ .WithMany("Volumes")
+ .HasForeignKey("SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("AppUserLibrary", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("AppUsersId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.Library", null)
+ .WithMany()
+ .HasForeignKey("LibrariesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("CollectionTagSeriesMetadata", b =>
+ {
+ b.HasOne("API.Entities.CollectionTag", null)
+ .WithMany()
+ .HasForeignKey("CollectionTagsId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.SeriesMetadata", null)
+ .WithMany()
+ .HasForeignKey("SeriesMetadatasId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
+ {
+ b.HasOne("API.Entities.AppRole", null)
+ .WithMany()
+ .HasForeignKey("RoleId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("API.Entities.AppRole", b =>
+ {
+ b.Navigation("UserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUser", b =>
+ {
+ b.Navigation("Bookmarks");
+
+ b.Navigation("Progresses");
+
+ b.Navigation("Ratings");
+
+ b.Navigation("ReadingLists");
+
+ b.Navigation("UserPreferences");
+
+ b.Navigation("UserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.Navigation("Files");
+ });
+
+ modelBuilder.Entity("API.Entities.Library", b =>
+ {
+ b.Navigation("Folders");
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.Navigation("Items");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.Navigation("Metadata");
+
+ b.Navigation("Volumes");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.Navigation("Chapters");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/API/Data/Migrations/20210901150310_ReadingLists.cs b/API/Data/Migrations/20210901150310_ReadingLists.cs
new file mode 100644
index 000000000..709d3e17a
--- /dev/null
+++ b/API/Data/Migrations/20210901150310_ReadingLists.cs
@@ -0,0 +1,84 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace API.Data.Migrations
+{
+ public partial class ReadingLists : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "ReadingList",
+ columns: table => new
+ {
+ Id = table.Column<int>(type: "INTEGER", nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ Title = table.Column<string>(type: "TEXT", nullable: true),
+ Summary = table.Column<string>(type: "TEXT", nullable: true),
+ Promoted = table.Column<bool>(type: "INTEGER", nullable: false),
+ Created = table.Column<DateTime>(type: "TEXT", nullable: false),
+ LastModified = table.Column<DateTime>(type: "TEXT", nullable: false),
+ AppUserId = table.Column<int>(type: "INTEGER", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_ReadingList", x => x.Id);
+ table.ForeignKey(
+ name: "FK_ReadingList_AspNetUsers_AppUserId",
+ column: x => x.AppUserId,
+ principalTable: "AspNetUsers",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "ReadingListItem",
+ columns: table => new
+ {
+ Id = table.Column<int>(type: "INTEGER", nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ LibraryId = table.Column<int>(type: "INTEGER", nullable: false),
+ SeriesId = table.Column<int>(type: "INTEGER", nullable: false),
+ VolumeId = table.Column<int>(type: "INTEGER", nullable: false),
+ ChapterId = table.Column<int>(type: "INTEGER", nullable: false),
+ Order = table.Column<int>(type: "INTEGER", nullable: false),
+ ReadingListId = table.Column<int>(type: "INTEGER", nullable: true)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_ReadingListItem", x => x.Id);
+ table.ForeignKey(
+ name: "FK_ReadingListItem_ReadingList_ReadingListId",
+ column: x => x.ReadingListId,
+ principalTable: "ReadingList",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Restrict);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_ReadingList_AppUserId",
+ table: "ReadingList",
+ column: "AppUserId");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_ReadingListItem_ReadingListId",
+ table: "ReadingListItem",
+ column: "ReadingListId");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_ReadingListItem_SeriesId_VolumeId_ChapterId_LibraryId",
+ table: "ReadingListItem",
+ columns: new[] { "SeriesId", "VolumeId", "ChapterId", "LibraryId" },
+ unique: true);
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "ReadingListItem");
+
+ migrationBuilder.DropTable(
+ name: "ReadingList");
+ }
+ }
+}
diff --git a/API/Data/Migrations/20210901200442_ReadingListsAdditions.Designer.cs b/API/Data/Migrations/20210901200442_ReadingListsAdditions.Designer.cs
new file mode 100644
index 000000000..8ee5bdec8
--- /dev/null
+++ b/API/Data/Migrations/20210901200442_ReadingListsAdditions.Designer.cs
@@ -0,0 +1,1022 @@
+// <auto-generated />
+using System;
+using API.Data;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace API.Data.Migrations
+{
+ [DbContext(typeof(DataContext))]
+ [Migration("20210901200442_ReadingListsAdditions")]
+ partial class ReadingListsAdditions
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "5.0.8");
+
+ modelBuilder.Entity("API.Entities.AppRole", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ConcurrencyStamp")
+ .IsConcurrencyToken()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("NormalizedName")
+ .IsUnique()
+ .HasDatabaseName("RoleNameIndex");
+
+ b.ToTable("AspNetRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUser", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AccessFailedCount")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ApiKey")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ConcurrencyStamp")
+ .IsConcurrencyToken()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Email")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("EmailConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastActive")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("LockoutEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTimeOffset?>("LockoutEnd")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedEmail")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedUserName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PasswordHash")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PhoneNumber")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("PhoneNumberConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("SecurityStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("TwoFactorEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("UserName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("NormalizedEmail")
+ .HasDatabaseName("EmailIndex");
+
+ b.HasIndex("NormalizedUserName")
+ .IsUnique()
+ .HasDatabaseName("UserNameIndex");
+
+ b.ToTable("AspNetUsers");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserBookmark", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Page")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserBookmark");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserPreferences", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("AutoCloseMenu")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("BookReaderDarkMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("BookReaderFontFamily")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("BookReaderFontSize")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderLineSpacing")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderMargin")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderReadingDirection")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("BookReaderTapToPaginate")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("PageSplitOption")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReaderMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReadingDirection")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ScalingOption")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("SiteDarkMode")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId")
+ .IsUnique();
+
+ b.ToTable("AppUserPreferences");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserProgress", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("BookScrollId")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("PagesRead")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserProgresses");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRating", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Rating")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Review")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserRating");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRole", b =>
+ {
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("RoleId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("UserId", "RoleId");
+
+ b.HasIndex("RoleId");
+
+ b.ToTable("AspNetUserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("IsSpecial")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Number")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Range")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("VolumeId");
+
+ b.ToTable("Chapter");
+ });
+
+ modelBuilder.Entity("API.Entities.CollectionTag", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("NormalizedTitle")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("Promoted")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Id", "Promoted")
+ .IsUnique();
+
+ b.ToTable("CollectionTag");
+ });
+
+ modelBuilder.Entity("API.Entities.FolderPath", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastScanned")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("LibraryId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Path")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("LibraryId");
+
+ b.ToTable("FolderPath");
+ });
+
+ modelBuilder.Entity("API.Entities.Library", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("CoverImage")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Type")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.ToTable("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.MangaFile", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("FilePath")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Format")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ChapterId");
+
+ b.ToTable("MangaFile");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("Promoted")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("ReadingList");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingListItem", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("LibraryId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Order")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReadingListId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ReadingListId");
+
+ b.HasIndex("SeriesId", "VolumeId", "ChapterId", "LibraryId")
+ .IsUnique();
+
+ b.ToTable("ReadingListItem");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Format")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("LibraryId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("LocalizedName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("OriginalName")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("SortName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("LibraryId");
+
+ b.HasIndex("Name", "NormalizedName", "LocalizedName", "LibraryId", "Format")
+ .IsUnique();
+
+ b.ToTable("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.SeriesMetadata", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("SeriesId")
+ .IsUnique();
+
+ b.HasIndex("Id", "SeriesId")
+ .IsUnique();
+
+ b.ToTable("SeriesMetadata");
+ });
+
+ modelBuilder.Entity("API.Entities.ServerSetting", b =>
+ {
+ b.Property<int>("Key")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Value")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Key");
+
+ b.ToTable("ServerSetting");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Number")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("SeriesId");
+
+ b.ToTable("Volume");
+ });
+
+ modelBuilder.Entity("AppUserLibrary", b =>
+ {
+ b.Property<int>("AppUsersId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("LibrariesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("AppUsersId", "LibrariesId");
+
+ b.HasIndex("LibrariesId");
+
+ b.ToTable("AppUserLibrary");
+ });
+
+ modelBuilder.Entity("CollectionTagSeriesMetadata", b =>
+ {
+ b.Property<int>("CollectionTagsId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesMetadatasId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("CollectionTagsId", "SeriesMetadatasId");
+
+ b.HasIndex("SeriesMetadatasId");
+
+ b.ToTable("CollectionTagSeriesMetadata");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("RoleId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("RoleId");
+
+ b.ToTable("AspNetRoleClaims");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AspNetUserClaims");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
+ {
+ b.Property<string>("LoginProvider")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderKey")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderDisplayName")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("LoginProvider", "ProviderKey");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AspNetUserLogins");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
+ {
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("LoginProvider")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Value")
+ .HasColumnType("TEXT");
+
+ b.HasKey("UserId", "LoginProvider", "Name");
+
+ b.ToTable("AspNetUserTokens");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserBookmark", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Bookmarks")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserPreferences", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithOne("UserPreferences")
+ .HasForeignKey("API.Entities.AppUserPreferences", "AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserProgress", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Progresses")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRating", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Ratings")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRole", b =>
+ {
+ b.HasOne("API.Entities.AppRole", "Role")
+ .WithMany("UserRoles")
+ .HasForeignKey("RoleId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.AppUser", "User")
+ .WithMany("UserRoles")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Role");
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.HasOne("API.Entities.Volume", "Volume")
+ .WithMany("Chapters")
+ .HasForeignKey("VolumeId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Volume");
+ });
+
+ modelBuilder.Entity("API.Entities.FolderPath", b =>
+ {
+ b.HasOne("API.Entities.Library", "Library")
+ .WithMany("Folders")
+ .HasForeignKey("LibraryId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.MangaFile", b =>
+ {
+ b.HasOne("API.Entities.Chapter", "Chapter")
+ .WithMany("Files")
+ .HasForeignKey("ChapterId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Chapter");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("ReadingLists")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingListItem", b =>
+ {
+ b.HasOne("API.Entities.ReadingList", "ReadingList")
+ .WithMany("Items")
+ .HasForeignKey("ReadingListId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("ReadingList");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.HasOne("API.Entities.Library", "Library")
+ .WithMany("Series")
+ .HasForeignKey("LibraryId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.SeriesMetadata", b =>
+ {
+ b.HasOne("API.Entities.Series", "Series")
+ .WithOne("Metadata")
+ .HasForeignKey("API.Entities.SeriesMetadata", "SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.HasOne("API.Entities.Series", "Series")
+ .WithMany("Volumes")
+ .HasForeignKey("SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("AppUserLibrary", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("AppUsersId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.Library", null)
+ .WithMany()
+ .HasForeignKey("LibrariesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("CollectionTagSeriesMetadata", b =>
+ {
+ b.HasOne("API.Entities.CollectionTag", null)
+ .WithMany()
+ .HasForeignKey("CollectionTagsId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.SeriesMetadata", null)
+ .WithMany()
+ .HasForeignKey("SeriesMetadatasId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
+ {
+ b.HasOne("API.Entities.AppRole", null)
+ .WithMany()
+ .HasForeignKey("RoleId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("API.Entities.AppRole", b =>
+ {
+ b.Navigation("UserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUser", b =>
+ {
+ b.Navigation("Bookmarks");
+
+ b.Navigation("Progresses");
+
+ b.Navigation("Ratings");
+
+ b.Navigation("ReadingLists");
+
+ b.Navigation("UserPreferences");
+
+ b.Navigation("UserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.Navigation("Files");
+ });
+
+ modelBuilder.Entity("API.Entities.Library", b =>
+ {
+ b.Navigation("Folders");
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.Navigation("Items");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.Navigation("Metadata");
+
+ b.Navigation("Volumes");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.Navigation("Chapters");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/API/Data/Migrations/20210901200442_ReadingListsAdditions.cs b/API/Data/Migrations/20210901200442_ReadingListsAdditions.cs
new file mode 100644
index 000000000..b44c2ac4d
--- /dev/null
+++ b/API/Data/Migrations/20210901200442_ReadingListsAdditions.cs
@@ -0,0 +1,55 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace API.Data.Migrations
+{
+ public partial class ReadingListsAdditions : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropForeignKey(
+ name: "FK_ReadingListItem_ReadingList_ReadingListId",
+ table: "ReadingListItem");
+
+ migrationBuilder.AlterColumn<int>(
+ name: "ReadingListId",
+ table: "ReadingListItem",
+ type: "INTEGER",
+ nullable: false,
+ defaultValue: 0,
+ oldClrType: typeof(int),
+ oldType: "INTEGER",
+ oldNullable: true);
+
+ migrationBuilder.AddForeignKey(
+ name: "FK_ReadingListItem_ReadingList_ReadingListId",
+ table: "ReadingListItem",
+ column: "ReadingListId",
+ principalTable: "ReadingList",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropForeignKey(
+ name: "FK_ReadingListItem_ReadingList_ReadingListId",
+ table: "ReadingListItem");
+
+ migrationBuilder.AlterColumn<int>(
+ name: "ReadingListId",
+ table: "ReadingListItem",
+ type: "INTEGER",
+ nullable: true,
+ oldClrType: typeof(int),
+ oldType: "INTEGER");
+
+ migrationBuilder.AddForeignKey(
+ name: "FK_ReadingListItem_ReadingList_ReadingListId",
+ table: "ReadingListItem",
+ column: "ReadingListId",
+ principalTable: "ReadingList",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Restrict);
+ }
+ }
+}
diff --git a/API/Data/Migrations/20210902110705_ReadingListsExtraRealationships.Designer.cs b/API/Data/Migrations/20210902110705_ReadingListsExtraRealationships.Designer.cs
new file mode 100644
index 000000000..566d2c5be
--- /dev/null
+++ b/API/Data/Migrations/20210902110705_ReadingListsExtraRealationships.Designer.cs
@@ -0,0 +1,1050 @@
+// <auto-generated />
+using System;
+using API.Data;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace API.Data.Migrations
+{
+ [DbContext(typeof(DataContext))]
+ [Migration("20210902110705_ReadingListsExtraRealationships")]
+ partial class ReadingListsExtraRealationships
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "5.0.8");
+
+ modelBuilder.Entity("API.Entities.AppRole", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ConcurrencyStamp")
+ .IsConcurrencyToken()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("NormalizedName")
+ .IsUnique()
+ .HasDatabaseName("RoleNameIndex");
+
+ b.ToTable("AspNetRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUser", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AccessFailedCount")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ApiKey")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ConcurrencyStamp")
+ .IsConcurrencyToken()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Email")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("EmailConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastActive")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("LockoutEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTimeOffset?>("LockoutEnd")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedEmail")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedUserName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PasswordHash")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PhoneNumber")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("PhoneNumberConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("SecurityStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("TwoFactorEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("UserName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("NormalizedEmail")
+ .HasDatabaseName("EmailIndex");
+
+ b.HasIndex("NormalizedUserName")
+ .IsUnique()
+ .HasDatabaseName("UserNameIndex");
+
+ b.ToTable("AspNetUsers");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserBookmark", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Page")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserBookmark");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserPreferences", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("AutoCloseMenu")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("BookReaderDarkMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("BookReaderFontFamily")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("BookReaderFontSize")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderLineSpacing")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderMargin")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderReadingDirection")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("BookReaderTapToPaginate")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("PageSplitOption")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReaderMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReadingDirection")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ScalingOption")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("SiteDarkMode")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId")
+ .IsUnique();
+
+ b.ToTable("AppUserPreferences");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserProgress", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("BookScrollId")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("PagesRead")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserProgresses");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRating", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Rating")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Review")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserRating");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRole", b =>
+ {
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("RoleId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("UserId", "RoleId");
+
+ b.HasIndex("RoleId");
+
+ b.ToTable("AspNetUserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("IsSpecial")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Number")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Range")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("VolumeId");
+
+ b.ToTable("Chapter");
+ });
+
+ modelBuilder.Entity("API.Entities.CollectionTag", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("NormalizedTitle")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("Promoted")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Id", "Promoted")
+ .IsUnique();
+
+ b.ToTable("CollectionTag");
+ });
+
+ modelBuilder.Entity("API.Entities.FolderPath", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastScanned")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("LibraryId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Path")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("LibraryId");
+
+ b.ToTable("FolderPath");
+ });
+
+ modelBuilder.Entity("API.Entities.Library", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("CoverImage")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Type")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.ToTable("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.MangaFile", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("FilePath")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Format")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ChapterId");
+
+ b.ToTable("MangaFile");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("Promoted")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("ReadingList");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingListItem", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("LibraryId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Order")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReadingListId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ChapterId");
+
+ b.HasIndex("ReadingListId");
+
+ b.HasIndex("VolumeId");
+
+ b.HasIndex("SeriesId", "VolumeId", "ChapterId", "LibraryId")
+ .IsUnique();
+
+ b.ToTable("ReadingListItem");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Format")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("LibraryId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("LocalizedName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("OriginalName")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("SortName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("LibraryId");
+
+ b.HasIndex("Name", "NormalizedName", "LocalizedName", "LibraryId", "Format")
+ .IsUnique();
+
+ b.ToTable("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.SeriesMetadata", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("SeriesId")
+ .IsUnique();
+
+ b.HasIndex("Id", "SeriesId")
+ .IsUnique();
+
+ b.ToTable("SeriesMetadata");
+ });
+
+ modelBuilder.Entity("API.Entities.ServerSetting", b =>
+ {
+ b.Property<int>("Key")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Value")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Key");
+
+ b.ToTable("ServerSetting");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Number")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("SeriesId");
+
+ b.ToTable("Volume");
+ });
+
+ modelBuilder.Entity("AppUserLibrary", b =>
+ {
+ b.Property<int>("AppUsersId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("LibrariesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("AppUsersId", "LibrariesId");
+
+ b.HasIndex("LibrariesId");
+
+ b.ToTable("AppUserLibrary");
+ });
+
+ modelBuilder.Entity("CollectionTagSeriesMetadata", b =>
+ {
+ b.Property<int>("CollectionTagsId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesMetadatasId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("CollectionTagsId", "SeriesMetadatasId");
+
+ b.HasIndex("SeriesMetadatasId");
+
+ b.ToTable("CollectionTagSeriesMetadata");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("RoleId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("RoleId");
+
+ b.ToTable("AspNetRoleClaims");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AspNetUserClaims");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
+ {
+ b.Property<string>("LoginProvider")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderKey")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderDisplayName")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("LoginProvider", "ProviderKey");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AspNetUserLogins");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
+ {
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("LoginProvider")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Value")
+ .HasColumnType("TEXT");
+
+ b.HasKey("UserId", "LoginProvider", "Name");
+
+ b.ToTable("AspNetUserTokens");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserBookmark", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Bookmarks")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserPreferences", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithOne("UserPreferences")
+ .HasForeignKey("API.Entities.AppUserPreferences", "AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserProgress", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Progresses")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRating", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Ratings")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRole", b =>
+ {
+ b.HasOne("API.Entities.AppRole", "Role")
+ .WithMany("UserRoles")
+ .HasForeignKey("RoleId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.AppUser", "User")
+ .WithMany("UserRoles")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Role");
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.HasOne("API.Entities.Volume", "Volume")
+ .WithMany("Chapters")
+ .HasForeignKey("VolumeId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Volume");
+ });
+
+ modelBuilder.Entity("API.Entities.FolderPath", b =>
+ {
+ b.HasOne("API.Entities.Library", "Library")
+ .WithMany("Folders")
+ .HasForeignKey("LibraryId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.MangaFile", b =>
+ {
+ b.HasOne("API.Entities.Chapter", "Chapter")
+ .WithMany("Files")
+ .HasForeignKey("ChapterId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Chapter");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("ReadingLists")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingListItem", b =>
+ {
+ b.HasOne("API.Entities.Chapter", "Chapter")
+ .WithMany()
+ .HasForeignKey("ChapterId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.ReadingList", "ReadingList")
+ .WithMany("Items")
+ .HasForeignKey("ReadingListId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.Series", "Series")
+ .WithMany()
+ .HasForeignKey("SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.Volume", "Volume")
+ .WithMany()
+ .HasForeignKey("VolumeId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Chapter");
+
+ b.Navigation("ReadingList");
+
+ b.Navigation("Series");
+
+ b.Navigation("Volume");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.HasOne("API.Entities.Library", "Library")
+ .WithMany("Series")
+ .HasForeignKey("LibraryId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.SeriesMetadata", b =>
+ {
+ b.HasOne("API.Entities.Series", "Series")
+ .WithOne("Metadata")
+ .HasForeignKey("API.Entities.SeriesMetadata", "SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.HasOne("API.Entities.Series", "Series")
+ .WithMany("Volumes")
+ .HasForeignKey("SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("AppUserLibrary", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("AppUsersId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.Library", null)
+ .WithMany()
+ .HasForeignKey("LibrariesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("CollectionTagSeriesMetadata", b =>
+ {
+ b.HasOne("API.Entities.CollectionTag", null)
+ .WithMany()
+ .HasForeignKey("CollectionTagsId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.SeriesMetadata", null)
+ .WithMany()
+ .HasForeignKey("SeriesMetadatasId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
+ {
+ b.HasOne("API.Entities.AppRole", null)
+ .WithMany()
+ .HasForeignKey("RoleId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("API.Entities.AppRole", b =>
+ {
+ b.Navigation("UserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUser", b =>
+ {
+ b.Navigation("Bookmarks");
+
+ b.Navigation("Progresses");
+
+ b.Navigation("Ratings");
+
+ b.Navigation("ReadingLists");
+
+ b.Navigation("UserPreferences");
+
+ b.Navigation("UserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.Navigation("Files");
+ });
+
+ modelBuilder.Entity("API.Entities.Library", b =>
+ {
+ b.Navigation("Folders");
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.Navigation("Items");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.Navigation("Metadata");
+
+ b.Navigation("Volumes");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.Navigation("Chapters");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/API/Data/Migrations/20210902110705_ReadingListsExtraRealationships.cs b/API/Data/Migrations/20210902110705_ReadingListsExtraRealationships.cs
new file mode 100644
index 000000000..9ddb1b5fc
--- /dev/null
+++ b/API/Data/Migrations/20210902110705_ReadingListsExtraRealationships.cs
@@ -0,0 +1,67 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace API.Data.Migrations
+{
+ public partial class ReadingListsExtraRealationships : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateIndex(
+ name: "IX_ReadingListItem_ChapterId",
+ table: "ReadingListItem",
+ column: "ChapterId");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_ReadingListItem_VolumeId",
+ table: "ReadingListItem",
+ column: "VolumeId");
+
+ migrationBuilder.AddForeignKey(
+ name: "FK_ReadingListItem_Chapter_ChapterId",
+ table: "ReadingListItem",
+ column: "ChapterId",
+ principalTable: "Chapter",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+
+ migrationBuilder.AddForeignKey(
+ name: "FK_ReadingListItem_Series_SeriesId",
+ table: "ReadingListItem",
+ column: "SeriesId",
+ principalTable: "Series",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+
+ migrationBuilder.AddForeignKey(
+ name: "FK_ReadingListItem_Volume_VolumeId",
+ table: "ReadingListItem",
+ column: "VolumeId",
+ principalTable: "Volume",
+ principalColumn: "Id",
+ onDelete: ReferentialAction.Cascade);
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropForeignKey(
+ name: "FK_ReadingListItem_Chapter_ChapterId",
+ table: "ReadingListItem");
+
+ migrationBuilder.DropForeignKey(
+ name: "FK_ReadingListItem_Series_SeriesId",
+ table: "ReadingListItem");
+
+ migrationBuilder.DropForeignKey(
+ name: "FK_ReadingListItem_Volume_VolumeId",
+ table: "ReadingListItem");
+
+ migrationBuilder.DropIndex(
+ name: "IX_ReadingListItem_ChapterId",
+ table: "ReadingListItem");
+
+ migrationBuilder.DropIndex(
+ name: "IX_ReadingListItem_VolumeId",
+ table: "ReadingListItem");
+ }
+ }
+}
diff --git a/API/Data/Migrations/20210906140845_ReadingListsChanges.Designer.cs b/API/Data/Migrations/20210906140845_ReadingListsChanges.Designer.cs
new file mode 100644
index 000000000..836a496e0
--- /dev/null
+++ b/API/Data/Migrations/20210906140845_ReadingListsChanges.Designer.cs
@@ -0,0 +1,1046 @@
+// <auto-generated />
+using System;
+using API.Data;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace API.Data.Migrations
+{
+ [DbContext(typeof(DataContext))]
+ [Migration("20210906140845_ReadingListsChanges")]
+ partial class ReadingListsChanges
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "5.0.8");
+
+ modelBuilder.Entity("API.Entities.AppRole", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ConcurrencyStamp")
+ .IsConcurrencyToken()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("NormalizedName")
+ .IsUnique()
+ .HasDatabaseName("RoleNameIndex");
+
+ b.ToTable("AspNetRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUser", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AccessFailedCount")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ApiKey")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ConcurrencyStamp")
+ .IsConcurrencyToken()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Email")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("EmailConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastActive")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("LockoutEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTimeOffset?>("LockoutEnd")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedEmail")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedUserName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PasswordHash")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PhoneNumber")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("PhoneNumberConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("SecurityStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("TwoFactorEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("UserName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("NormalizedEmail")
+ .HasDatabaseName("EmailIndex");
+
+ b.HasIndex("NormalizedUserName")
+ .IsUnique()
+ .HasDatabaseName("UserNameIndex");
+
+ b.ToTable("AspNetUsers");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserBookmark", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Page")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserBookmark");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserPreferences", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("AutoCloseMenu")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("BookReaderDarkMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("BookReaderFontFamily")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("BookReaderFontSize")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderLineSpacing")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderMargin")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderReadingDirection")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("BookReaderTapToPaginate")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("PageSplitOption")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReaderMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReadingDirection")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ScalingOption")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("SiteDarkMode")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId")
+ .IsUnique();
+
+ b.ToTable("AppUserPreferences");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserProgress", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("BookScrollId")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("PagesRead")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserProgresses");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRating", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Rating")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Review")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserRating");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRole", b =>
+ {
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("RoleId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("UserId", "RoleId");
+
+ b.HasIndex("RoleId");
+
+ b.ToTable("AspNetUserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("IsSpecial")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Number")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Range")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("VolumeId");
+
+ b.ToTable("Chapter");
+ });
+
+ modelBuilder.Entity("API.Entities.CollectionTag", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("NormalizedTitle")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("Promoted")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Id", "Promoted")
+ .IsUnique();
+
+ b.ToTable("CollectionTag");
+ });
+
+ modelBuilder.Entity("API.Entities.FolderPath", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastScanned")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("LibraryId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Path")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("LibraryId");
+
+ b.ToTable("FolderPath");
+ });
+
+ modelBuilder.Entity("API.Entities.Library", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("CoverImage")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Type")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.ToTable("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.MangaFile", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("FilePath")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Format")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ChapterId");
+
+ b.ToTable("MangaFile");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("Promoted")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("ReadingList");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingListItem", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Order")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReadingListId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ChapterId");
+
+ b.HasIndex("ReadingListId");
+
+ b.HasIndex("SeriesId");
+
+ b.HasIndex("VolumeId");
+
+ b.ToTable("ReadingListItem");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Format")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("LibraryId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("LocalizedName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("OriginalName")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("SortName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("LibraryId");
+
+ b.HasIndex("Name", "NormalizedName", "LocalizedName", "LibraryId", "Format")
+ .IsUnique();
+
+ b.ToTable("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.SeriesMetadata", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("SeriesId")
+ .IsUnique();
+
+ b.HasIndex("Id", "SeriesId")
+ .IsUnique();
+
+ b.ToTable("SeriesMetadata");
+ });
+
+ modelBuilder.Entity("API.Entities.ServerSetting", b =>
+ {
+ b.Property<int>("Key")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Value")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Key");
+
+ b.ToTable("ServerSetting");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("CoverImage")
+ .HasColumnType("BLOB");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Number")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("SeriesId");
+
+ b.ToTable("Volume");
+ });
+
+ modelBuilder.Entity("AppUserLibrary", b =>
+ {
+ b.Property<int>("AppUsersId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("LibrariesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("AppUsersId", "LibrariesId");
+
+ b.HasIndex("LibrariesId");
+
+ b.ToTable("AppUserLibrary");
+ });
+
+ modelBuilder.Entity("CollectionTagSeriesMetadata", b =>
+ {
+ b.Property<int>("CollectionTagsId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesMetadatasId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("CollectionTagsId", "SeriesMetadatasId");
+
+ b.HasIndex("SeriesMetadatasId");
+
+ b.ToTable("CollectionTagSeriesMetadata");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("RoleId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("RoleId");
+
+ b.ToTable("AspNetRoleClaims");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AspNetUserClaims");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
+ {
+ b.Property<string>("LoginProvider")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderKey")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderDisplayName")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("LoginProvider", "ProviderKey");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AspNetUserLogins");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
+ {
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("LoginProvider")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Value")
+ .HasColumnType("TEXT");
+
+ b.HasKey("UserId", "LoginProvider", "Name");
+
+ b.ToTable("AspNetUserTokens");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserBookmark", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Bookmarks")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserPreferences", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithOne("UserPreferences")
+ .HasForeignKey("API.Entities.AppUserPreferences", "AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserProgress", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Progresses")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRating", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Ratings")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRole", b =>
+ {
+ b.HasOne("API.Entities.AppRole", "Role")
+ .WithMany("UserRoles")
+ .HasForeignKey("RoleId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.AppUser", "User")
+ .WithMany("UserRoles")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Role");
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.HasOne("API.Entities.Volume", "Volume")
+ .WithMany("Chapters")
+ .HasForeignKey("VolumeId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Volume");
+ });
+
+ modelBuilder.Entity("API.Entities.FolderPath", b =>
+ {
+ b.HasOne("API.Entities.Library", "Library")
+ .WithMany("Folders")
+ .HasForeignKey("LibraryId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.MangaFile", b =>
+ {
+ b.HasOne("API.Entities.Chapter", "Chapter")
+ .WithMany("Files")
+ .HasForeignKey("ChapterId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Chapter");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("ReadingLists")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingListItem", b =>
+ {
+ b.HasOne("API.Entities.Chapter", "Chapter")
+ .WithMany()
+ .HasForeignKey("ChapterId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.ReadingList", "ReadingList")
+ .WithMany("Items")
+ .HasForeignKey("ReadingListId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.Series", "Series")
+ .WithMany()
+ .HasForeignKey("SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.Volume", "Volume")
+ .WithMany()
+ .HasForeignKey("VolumeId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Chapter");
+
+ b.Navigation("ReadingList");
+
+ b.Navigation("Series");
+
+ b.Navigation("Volume");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.HasOne("API.Entities.Library", "Library")
+ .WithMany("Series")
+ .HasForeignKey("LibraryId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.SeriesMetadata", b =>
+ {
+ b.HasOne("API.Entities.Series", "Series")
+ .WithOne("Metadata")
+ .HasForeignKey("API.Entities.SeriesMetadata", "SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.HasOne("API.Entities.Series", "Series")
+ .WithMany("Volumes")
+ .HasForeignKey("SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("AppUserLibrary", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("AppUsersId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.Library", null)
+ .WithMany()
+ .HasForeignKey("LibrariesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("CollectionTagSeriesMetadata", b =>
+ {
+ b.HasOne("API.Entities.CollectionTag", null)
+ .WithMany()
+ .HasForeignKey("CollectionTagsId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.SeriesMetadata", null)
+ .WithMany()
+ .HasForeignKey("SeriesMetadatasId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
+ {
+ b.HasOne("API.Entities.AppRole", null)
+ .WithMany()
+ .HasForeignKey("RoleId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("API.Entities.AppRole", b =>
+ {
+ b.Navigation("UserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUser", b =>
+ {
+ b.Navigation("Bookmarks");
+
+ b.Navigation("Progresses");
+
+ b.Navigation("Ratings");
+
+ b.Navigation("ReadingLists");
+
+ b.Navigation("UserPreferences");
+
+ b.Navigation("UserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.Navigation("Files");
+ });
+
+ modelBuilder.Entity("API.Entities.Library", b =>
+ {
+ b.Navigation("Folders");
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.Navigation("Items");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.Navigation("Metadata");
+
+ b.Navigation("Volumes");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.Navigation("Chapters");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/API/Data/Migrations/20210906140845_ReadingListsChanges.cs b/API/Data/Migrations/20210906140845_ReadingListsChanges.cs
new file mode 100644
index 000000000..e4ea07e2e
--- /dev/null
+++ b/API/Data/Migrations/20210906140845_ReadingListsChanges.cs
@@ -0,0 +1,43 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace API.Data.Migrations
+{
+ public partial class ReadingListsChanges : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropIndex(
+ name: "IX_ReadingListItem_SeriesId_VolumeId_ChapterId_LibraryId",
+ table: "ReadingListItem");
+
+ migrationBuilder.DropColumn(
+ name: "LibraryId",
+ table: "ReadingListItem");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_ReadingListItem_SeriesId",
+ table: "ReadingListItem",
+ column: "SeriesId");
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropIndex(
+ name: "IX_ReadingListItem_SeriesId",
+ table: "ReadingListItem");
+
+ migrationBuilder.AddColumn<int>(
+ name: "LibraryId",
+ table: "ReadingListItem",
+ type: "INTEGER",
+ nullable: false,
+ defaultValue: 0);
+
+ migrationBuilder.CreateIndex(
+ name: "IX_ReadingListItem_SeriesId_VolumeId_ChapterId_LibraryId",
+ table: "ReadingListItem",
+ columns: new[] { "SeriesId", "VolumeId", "ChapterId", "LibraryId" },
+ unique: true);
+ }
+ }
+}
diff --git a/API/Data/Migrations/20210916142418_EntityImageRefactor.Designer.cs b/API/Data/Migrations/20210916142418_EntityImageRefactor.Designer.cs
new file mode 100644
index 000000000..b4c6f62f1
--- /dev/null
+++ b/API/Data/Migrations/20210916142418_EntityImageRefactor.Designer.cs
@@ -0,0 +1,1042 @@
+// <auto-generated />
+using System;
+using API.Data;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+namespace API.Data.Migrations
+{
+ [DbContext(typeof(DataContext))]
+ [Migration("20210916142418_EntityImageRefactor")]
+ partial class EntityImageRefactor
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "5.0.8");
+
+ modelBuilder.Entity("API.Entities.AppRole", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ConcurrencyStamp")
+ .IsConcurrencyToken()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("NormalizedName")
+ .IsUnique()
+ .HasDatabaseName("RoleNameIndex");
+
+ b.ToTable("AspNetRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUser", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AccessFailedCount")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ApiKey")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ConcurrencyStamp")
+ .IsConcurrencyToken()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Email")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("EmailConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastActive")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("LockoutEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTimeOffset?>("LockoutEnd")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedEmail")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedUserName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PasswordHash")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PhoneNumber")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("PhoneNumberConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("SecurityStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("TwoFactorEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("UserName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("NormalizedEmail")
+ .HasDatabaseName("EmailIndex");
+
+ b.HasIndex("NormalizedUserName")
+ .IsUnique()
+ .HasDatabaseName("UserNameIndex");
+
+ b.ToTable("AspNetUsers");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserBookmark", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Page")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserBookmark");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserPreferences", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("AutoCloseMenu")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("BookReaderDarkMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("BookReaderFontFamily")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("BookReaderFontSize")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderLineSpacing")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderMargin")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("BookReaderReadingDirection")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("BookReaderTapToPaginate")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("PageSplitOption")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReaderMode")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReadingDirection")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ScalingOption")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("SiteDarkMode")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId")
+ .IsUnique();
+
+ b.ToTable("AppUserPreferences");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserProgress", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("BookScrollId")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("PagesRead")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserProgresses");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRating", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Rating")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Review")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("AppUserRating");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRole", b =>
+ {
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("RoleId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("UserId", "RoleId");
+
+ b.HasIndex("RoleId");
+
+ b.ToTable("AspNetUserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("CoverImage")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("IsSpecial")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Number")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Range")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("VolumeId");
+
+ b.ToTable("Chapter");
+ });
+
+ modelBuilder.Entity("API.Entities.CollectionTag", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("CoverImage")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("NormalizedTitle")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("Promoted")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Id", "Promoted")
+ .IsUnique();
+
+ b.ToTable("CollectionTag");
+ });
+
+ modelBuilder.Entity("API.Entities.FolderPath", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastScanned")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("LibraryId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Path")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("LibraryId");
+
+ b.ToTable("FolderPath");
+ });
+
+ modelBuilder.Entity("API.Entities.Library", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("CoverImage")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Type")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.ToTable("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.MangaFile", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("FilePath")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Format")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ChapterId");
+
+ b.ToTable("MangaFile");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("Promoted")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("ReadingList");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingListItem", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Order")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReadingListId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ChapterId");
+
+ b.HasIndex("ReadingListId");
+
+ b.HasIndex("SeriesId");
+
+ b.HasIndex("VolumeId");
+
+ b.ToTable("ReadingListItem");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("CoverImage")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("CoverImageLocked")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Format")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("LibraryId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("LocalizedName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("OriginalName")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("SortName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("LibraryId");
+
+ b.HasIndex("Name", "NormalizedName", "LocalizedName", "LibraryId", "Format")
+ .IsUnique();
+
+ b.ToTable("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.SeriesMetadata", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("SeriesId")
+ .IsUnique();
+
+ b.HasIndex("Id", "SeriesId")
+ .IsUnique();
+
+ b.ToTable("SeriesMetadata");
+ });
+
+ modelBuilder.Entity("API.Entities.ServerSetting", b =>
+ {
+ b.Property<int>("Key")
+ .HasColumnType("INTEGER");
+
+ b.Property<uint>("RowVersion")
+ .IsConcurrencyToken()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Value")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Key");
+
+ b.ToTable("ServerSetting");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("CoverImage")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Number")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Pages")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("SeriesId");
+
+ b.ToTable("Volume");
+ });
+
+ modelBuilder.Entity("AppUserLibrary", b =>
+ {
+ b.Property<int>("AppUsersId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("LibrariesId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("AppUsersId", "LibrariesId");
+
+ b.HasIndex("LibrariesId");
+
+ b.ToTable("AppUserLibrary");
+ });
+
+ modelBuilder.Entity("CollectionTagSeriesMetadata", b =>
+ {
+ b.Property<int>("CollectionTagsId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesMetadatasId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("CollectionTagsId", "SeriesMetadatasId");
+
+ b.HasIndex("SeriesMetadatasId");
+
+ b.ToTable("CollectionTagSeriesMetadata");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("RoleId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("RoleId");
+
+ b.ToTable("AspNetRoleClaims");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AspNetUserClaims");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
+ {
+ b.Property<string>("LoginProvider")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderKey")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderDisplayName")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("LoginProvider", "ProviderKey");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AspNetUserLogins");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
+ {
+ b.Property<int>("UserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("LoginProvider")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Value")
+ .HasColumnType("TEXT");
+
+ b.HasKey("UserId", "LoginProvider", "Name");
+
+ b.ToTable("AspNetUserTokens");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserBookmark", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Bookmarks")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserPreferences", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithOne("UserPreferences")
+ .HasForeignKey("API.Entities.AppUserPreferences", "AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserProgress", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Progresses")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRating", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("Ratings")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUserRole", b =>
+ {
+ b.HasOne("API.Entities.AppRole", "Role")
+ .WithMany("UserRoles")
+ .HasForeignKey("RoleId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.AppUser", "User")
+ .WithMany("UserRoles")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Role");
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.HasOne("API.Entities.Volume", "Volume")
+ .WithMany("Chapters")
+ .HasForeignKey("VolumeId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Volume");
+ });
+
+ modelBuilder.Entity("API.Entities.FolderPath", b =>
+ {
+ b.HasOne("API.Entities.Library", "Library")
+ .WithMany("Folders")
+ .HasForeignKey("LibraryId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.MangaFile", b =>
+ {
+ b.HasOne("API.Entities.Chapter", "Chapter")
+ .WithMany("Files")
+ .HasForeignKey("ChapterId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Chapter");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("ReadingLists")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingListItem", b =>
+ {
+ b.HasOne("API.Entities.Chapter", "Chapter")
+ .WithMany()
+ .HasForeignKey("ChapterId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.ReadingList", "ReadingList")
+ .WithMany("Items")
+ .HasForeignKey("ReadingListId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.Series", "Series")
+ .WithMany()
+ .HasForeignKey("SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.Volume", "Volume")
+ .WithMany()
+ .HasForeignKey("VolumeId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Chapter");
+
+ b.Navigation("ReadingList");
+
+ b.Navigation("Series");
+
+ b.Navigation("Volume");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.HasOne("API.Entities.Library", "Library")
+ .WithMany("Series")
+ .HasForeignKey("LibraryId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Library");
+ });
+
+ modelBuilder.Entity("API.Entities.SeriesMetadata", b =>
+ {
+ b.HasOne("API.Entities.Series", "Series")
+ .WithOne("Metadata")
+ .HasForeignKey("API.Entities.SeriesMetadata", "SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.HasOne("API.Entities.Series", "Series")
+ .WithMany("Volumes")
+ .HasForeignKey("SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("AppUserLibrary", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("AppUsersId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.Library", null)
+ .WithMany()
+ .HasForeignKey("LibrariesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("CollectionTagSeriesMetadata", b =>
+ {
+ b.HasOne("API.Entities.CollectionTag", null)
+ .WithMany()
+ .HasForeignKey("CollectionTagsId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.SeriesMetadata", null)
+ .WithMany()
+ .HasForeignKey("SeriesMetadatasId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b =>
+ {
+ b.HasOne("API.Entities.AppRole", null)
+ .WithMany()
+ .HasForeignKey("RoleId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b =>
+ {
+ b.HasOne("API.Entities.AppUser", null)
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("API.Entities.AppRole", b =>
+ {
+ b.Navigation("UserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.AppUser", b =>
+ {
+ b.Navigation("Bookmarks");
+
+ b.Navigation("Progresses");
+
+ b.Navigation("Ratings");
+
+ b.Navigation("ReadingLists");
+
+ b.Navigation("UserPreferences");
+
+ b.Navigation("UserRoles");
+ });
+
+ modelBuilder.Entity("API.Entities.Chapter", b =>
+ {
+ b.Navigation("Files");
+ });
+
+ modelBuilder.Entity("API.Entities.Library", b =>
+ {
+ b.Navigation("Folders");
+
+ b.Navigation("Series");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.Navigation("Items");
+ });
+
+ modelBuilder.Entity("API.Entities.Series", b =>
+ {
+ b.Navigation("Metadata");
+
+ b.Navigation("Volumes");
+ });
+
+ modelBuilder.Entity("API.Entities.Volume", b =>
+ {
+ b.Navigation("Chapters");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/API/Data/Migrations/20210916142418_EntityImageRefactor.cs b/API/Data/Migrations/20210916142418_EntityImageRefactor.cs
new file mode 100644
index 000000000..deafb134b
--- /dev/null
+++ b/API/Data/Migrations/20210916142418_EntityImageRefactor.cs
@@ -0,0 +1,97 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace API.Data.Migrations
+{
+ public partial class EntityImageRefactor : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropColumn(
+ name: "RowVersion",
+ table: "AppUserProgresses");
+
+ migrationBuilder.AlterColumn<string>(
+ name: "CoverImage",
+ table: "Volume",
+ type: "TEXT",
+ nullable: true,
+ oldClrType: typeof(byte[]),
+ oldType: "BLOB",
+ oldNullable: true);
+
+ migrationBuilder.AlterColumn<string>(
+ name: "CoverImage",
+ table: "Series",
+ type: "TEXT",
+ nullable: true,
+ oldClrType: typeof(byte[]),
+ oldType: "BLOB",
+ oldNullable: true);
+
+ migrationBuilder.AlterColumn<string>(
+ name: "CoverImage",
+ table: "CollectionTag",
+ type: "TEXT",
+ nullable: true,
+ oldClrType: typeof(byte[]),
+ oldType: "BLOB",
+ oldNullable: true);
+
+ migrationBuilder.AlterColumn<string>(
+ name: "CoverImage",
+ table: "Chapter",
+ type: "TEXT",
+ nullable: true,
+ oldClrType: typeof(byte[]),
+ oldType: "BLOB",
+ oldNullable: true);
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AlterColumn<byte[]>(
+ name: "CoverImage",
+ table: "Volume",
+ type: "BLOB",
+ nullable: true,
+ oldClrType: typeof(string),
+ oldType: "TEXT",
+ oldNullable: true);
+
+ migrationBuilder.AlterColumn<byte[]>(
+ name: "CoverImage",
+ table: "Series",
+ type: "BLOB",
+ nullable: true,
+ oldClrType: typeof(string),
+ oldType: "TEXT",
+ oldNullable: true);
+
+ migrationBuilder.AlterColumn<byte[]>(
+ name: "CoverImage",
+ table: "CollectionTag",
+ type: "BLOB",
+ nullable: true,
+ oldClrType: typeof(string),
+ oldType: "TEXT",
+ oldNullable: true);
+
+ migrationBuilder.AlterColumn<byte[]>(
+ name: "CoverImage",
+ table: "Chapter",
+ type: "BLOB",
+ nullable: true,
+ oldClrType: typeof(string),
+ oldType: "TEXT",
+ oldNullable: true);
+
+ migrationBuilder.AddColumn<uint>(
+ name: "RowVersion",
+ table: "AppUserProgresses",
+ type: "INTEGER",
+ nullable: false,
+ defaultValue: 0u);
+ }
+ }
+}
diff --git a/API/Data/Migrations/DataContextModelSnapshot.cs b/API/Data/Migrations/DataContextModelSnapshot.cs
index 9f763c03b..38a09633e 100644
--- a/API/Data/Migrations/DataContextModelSnapshot.cs
+++ b/API/Data/Migrations/DataContextModelSnapshot.cs
@@ -229,10 +229,6 @@ namespace API.Data.Migrations
b.Property<int>("PagesRead")
.HasColumnType("INTEGER");
- b.Property<uint>("RowVersion")
- .IsConcurrencyToken()
- .HasColumnType("INTEGER");
-
b.Property<int>("SeriesId")
.HasColumnType("INTEGER");
@@ -292,8 +288,8 @@ namespace API.Data.Migrations
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
- b.Property<byte[]>("CoverImage")
- .HasColumnType("BLOB");
+ b.Property<string>("CoverImage")
+ .HasColumnType("TEXT");
b.Property<bool>("CoverImageLocked")
.HasColumnType("INTEGER");
@@ -335,8 +331,8 @@ namespace API.Data.Migrations
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
- b.Property<byte[]>("CoverImage")
- .HasColumnType("BLOB");
+ b.Property<string>("CoverImage")
+ .HasColumnType("TEXT");
b.Property<bool>("CoverImageLocked")
.HasColumnType("INTEGER");
@@ -440,14 +436,79 @@ namespace API.Data.Migrations
b.ToTable("MangaFile");
});
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("AppUserId")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Created")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("Promoted")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Summary")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Title")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AppUserId");
+
+ b.ToTable("ReadingList");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingListItem", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ChapterId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Order")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("ReadingListId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("SeriesId")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("VolumeId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ChapterId");
+
+ b.HasIndex("ReadingListId");
+
+ b.HasIndex("SeriesId");
+
+ b.HasIndex("VolumeId");
+
+ b.ToTable("ReadingListItem");
+ });
+
modelBuilder.Entity("API.Entities.Series", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
- b.Property<byte[]>("CoverImage")
- .HasColumnType("BLOB");
+ b.Property<string>("CoverImage")
+ .HasColumnType("TEXT");
b.Property<bool>("CoverImageLocked")
.HasColumnType("INTEGER");
@@ -542,8 +603,8 @@ namespace API.Data.Migrations
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
- b.Property<byte[]>("CoverImage")
- .HasColumnType("BLOB");
+ b.Property<string>("CoverImage")
+ .HasColumnType("TEXT");
b.Property<DateTime>("Created")
.HasColumnType("TEXT");
@@ -780,6 +841,52 @@ namespace API.Data.Migrations
b.Navigation("Chapter");
});
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.HasOne("API.Entities.AppUser", "AppUser")
+ .WithMany("ReadingLists")
+ .HasForeignKey("AppUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("AppUser");
+ });
+
+ modelBuilder.Entity("API.Entities.ReadingListItem", b =>
+ {
+ b.HasOne("API.Entities.Chapter", "Chapter")
+ .WithMany()
+ .HasForeignKey("ChapterId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.ReadingList", "ReadingList")
+ .WithMany("Items")
+ .HasForeignKey("ReadingListId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.Series", "Series")
+ .WithMany()
+ .HasForeignKey("SeriesId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("API.Entities.Volume", "Volume")
+ .WithMany()
+ .HasForeignKey("VolumeId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Chapter");
+
+ b.Navigation("ReadingList");
+
+ b.Navigation("Series");
+
+ b.Navigation("Volume");
+ });
+
modelBuilder.Entity("API.Entities.Series", b =>
{
b.HasOne("API.Entities.Library", "Library")
@@ -892,6 +999,8 @@ namespace API.Data.Migrations
b.Navigation("Ratings");
+ b.Navigation("ReadingLists");
+
b.Navigation("UserPreferences");
b.Navigation("UserRoles");
@@ -909,6 +1018,11 @@ namespace API.Data.Migrations
b.Navigation("Series");
});
+ modelBuilder.Entity("API.Entities.ReadingList", b =>
+ {
+ b.Navigation("Items");
+ });
+
modelBuilder.Entity("API.Entities.Series", b =>
{
b.Navigation("Metadata");
diff --git a/API/Data/AppUserProgressRepository.cs b/API/Data/Repositories/AppUserProgressRepository.cs
similarity index 65%
rename from API/Data/AppUserProgressRepository.cs
rename to API/Data/Repositories/AppUserProgressRepository.cs
index 38912b589..c91e61cd0 100644
--- a/API/Data/AppUserProgressRepository.cs
+++ b/API/Data/Repositories/AppUserProgressRepository.cs
@@ -1,10 +1,11 @@
using System.Linq;
using System.Threading.Tasks;
+using API.Entities;
using API.Entities.Enums;
-using API.Interfaces;
+using API.Interfaces.Repositories;
using Microsoft.EntityFrameworkCore;
-namespace API.Data
+namespace API.Data.Repositories
{
public class AppUserProgressRepository : IAppUserProgressRepository
{
@@ -15,6 +16,11 @@ namespace API.Data
_context = context;
}
+ public void Update(AppUserProgress userProgress)
+ {
+ _context.Entry(userProgress).State = EntityState.Modified;
+ }
+
/// <summary>
/// This will remove any entries that have chapterIds that no longer exists. This will execute the save as well.
/// </summary>
@@ -25,8 +31,18 @@ namespace API.Data
var rowsToRemove = await _context.AppUserProgresses
.Where(progress => !chapterIds.Contains(progress.ChapterId))
.ToListAsync();
-
+
+ var rowsToRemoveBookmarks = await _context.AppUserBookmark
+ .Where(progress => !chapterIds.Contains(progress.ChapterId))
+ .ToListAsync();
+
+ var rowsToRemoveReadingLists = await _context.ReadingListItem
+ .Where(item => !chapterIds.Contains(item.ChapterId))
+ .ToListAsync();
+
_context.RemoveRange(rowsToRemove);
+ _context.RemoveRange(rowsToRemoveBookmarks);
+ _context.RemoveRange(rowsToRemoveReadingLists);
return await _context.SaveChangesAsync() > 0 ? rowsToRemove.Count : 0;
}
@@ -45,12 +61,19 @@ namespace API.Data
.ToListAsync();
if (seriesIds.Count == 0) return false;
-
+
return await _context.Series
.Include(s => s.Library)
.Where(s => seriesIds.Contains(s.Id) && s.Library.Type == libraryType)
.AsNoTracking()
.AnyAsync();
}
+
+ public async Task<AppUserProgress> GetUserProgressAsync(int chapterId, int userId)
+ {
+ return await _context.AppUserProgresses
+ .Where(p => p.ChapterId == chapterId && p.AppUserId == userId)
+ .FirstOrDefaultAsync();
+ }
}
-}
\ No newline at end of file
+}
diff --git a/API/Data/Repositories/ChapterRepository.cs b/API/Data/Repositories/ChapterRepository.cs
new file mode 100644
index 000000000..f1905eaa8
--- /dev/null
+++ b/API/Data/Repositories/ChapterRepository.cs
@@ -0,0 +1,191 @@
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using API.DTOs;
+using API.DTOs.Reader;
+using API.Entities;
+using API.Interfaces.Repositories;
+using AutoMapper;
+using AutoMapper.QueryableExtensions;
+using Microsoft.EntityFrameworkCore;
+
+namespace API.Data.Repositories
+{
+ public class ChapterRepository : IChapterRepository
+ {
+ private readonly DataContext _context;
+ private readonly IMapper _mapper;
+
+ public ChapterRepository(DataContext context, IMapper mapper)
+ {
+ _context = context;
+ _mapper = mapper;
+ }
+
+ public void Update(Chapter chapter)
+ {
+ _context.Entry(chapter).State = EntityState.Modified;
+ }
+
+ public async Task<IEnumerable<Chapter>> GetChaptersByIdsAsync(IList<int> chapterIds)
+ {
+ return await _context.Chapter
+ .Where(c => chapterIds.Contains(c.Id))
+ .Include(c => c.Volume)
+ .ToListAsync();
+ }
+
+ /// <summary>
+ /// Populates a partial IChapterInfoDto
+ /// </summary>
+ /// <returns></returns>
+ public async Task<IChapterInfoDto> GetChapterInfoDtoAsync(int chapterId)
+ {
+ return await _context.Chapter
+ .Where(c => c.Id == chapterId)
+ .Join(_context.Volume, c => c.VolumeId, v => v.Id, (chapter, volume) => new
+ {
+ ChapterNumber = chapter.Range,
+ VolumeNumber = volume.Number,
+ VolumeId = volume.Id,
+ chapter.IsSpecial,
+ volume.SeriesId,
+ chapter.Pages
+ })
+ .Join(_context.Series, data => data.SeriesId, series => series.Id, (data, series) => new
+ {
+ data.ChapterNumber,
+ data.VolumeNumber,
+ data.VolumeId,
+ data.IsSpecial,
+ data.SeriesId,
+ data.Pages,
+ SeriesFormat = series.Format,
+ SeriesName = series.Name,
+ series.LibraryId
+ })
+ .Select(data => new BookInfoDto()
+ {
+ ChapterNumber = data.ChapterNumber,
+ VolumeNumber = data.VolumeNumber + string.Empty,
+ VolumeId = data.VolumeId,
+ IsSpecial = data.IsSpecial,
+ SeriesId =data.SeriesId,
+ SeriesFormat = data.SeriesFormat,
+ SeriesName = data.SeriesName,
+ LibraryId = data.LibraryId,
+ Pages = data.Pages
+ })
+ .AsNoTracking()
+ .SingleAsync();
+ }
+
+ public Task<int> GetChapterTotalPagesAsync(int chapterId)
+ {
+ return _context.Chapter
+ .Where(c => c.Id == chapterId)
+ .Select(c => c.Pages)
+ .SingleOrDefaultAsync();
+ }
+ public async Task<ChapterDto> GetChapterDtoAsync(int chapterId)
+ {
+ var chapter = await _context.Chapter
+ .Include(c => c.Files)
+ .ProjectTo<ChapterDto>(_mapper.ConfigurationProvider)
+ .AsNoTracking()
+ .SingleOrDefaultAsync(c => c.Id == chapterId);
+
+ return chapter;
+ }
+
+ /// <summary>
+ /// Returns non-tracked files for a given chapterId
+ /// </summary>
+ /// <param name="chapterId"></param>
+ /// <returns></returns>
+ public async Task<IList<MangaFile>> GetFilesForChapterAsync(int chapterId)
+ {
+ return await _context.MangaFile
+ .Where(c => chapterId == c.ChapterId)
+ .AsNoTracking()
+ .ToListAsync();
+ }
+
+ /// <summary>
+ /// Returns a Chapter for an Id. Includes linked <see cref="MangaFile"/>s.
+ /// </summary>
+ /// <param name="chapterId"></param>
+ /// <returns></returns>
+ public async Task<Chapter> GetChapterAsync(int chapterId)
+ {
+ return await _context.Chapter
+ .Include(c => c.Files)
+ .SingleOrDefaultAsync(c => c.Id == chapterId);
+ }
+
+ /// <summary>
+ /// Returns Chapters for a volume id.
+ /// </summary>
+ /// <param name="volumeId"></param>
+ /// <returns></returns>
+ public async Task<IList<Chapter>> GetChaptersAsync(int volumeId)
+ {
+ return await _context.Chapter
+ .Where(c => c.VolumeId == volumeId)
+ .ToListAsync();
+ }
+
+ /// <summary>
+ /// Returns the cover image for a chapter id.
+ /// </summary>
+ /// <param name="chapterId"></param>
+ /// <returns></returns>
+ public async Task<string> GetChapterCoverImageAsync(int chapterId)
+ {
+
+ return await _context.Chapter
+ .Where(c => c.Id == chapterId)
+ .Select(c => c.CoverImage)
+ .AsNoTracking()
+ .SingleOrDefaultAsync();
+ }
+
+ public async Task<IList<string>> GetAllCoverImagesAsync()
+ {
+ return await _context.Chapter
+ .Select(c => c.CoverImage)
+ .Where(t => !string.IsNullOrEmpty(t))
+ .AsNoTracking()
+ .ToListAsync();
+ }
+
+ /// <summary>
+ /// Returns cover images for locked chapters
+ /// </summary>
+ /// <returns></returns>
+ public async Task<IEnumerable<string>> GetCoverImagesForLockedChaptersAsync()
+ {
+ return await _context.Chapter
+ .Where(c => c.CoverImageLocked)
+ .Select(c => c.CoverImage)
+ .Where(t => !string.IsNullOrEmpty(t))
+ .AsNoTracking()
+ .ToListAsync();
+ }
+
+ /// <summary>
+ /// Returns non-tracked files for a set of <paramref name="chapterIds"/>
+ /// </summary>
+ /// <param name="chapterIds">List of chapter Ids</param>
+ /// <returns></returns>
+ public async Task<IList<MangaFile>> GetFilesForChaptersAsync(IReadOnlyList<int> chapterIds)
+ {
+ return await _context.MangaFile
+ .Where(c => chapterIds.Contains(c.ChapterId))
+ .AsNoTracking()
+ .ToListAsync();
+ }
+ }
+}
diff --git a/API/Data/CollectionTagRepository.cs b/API/Data/Repositories/CollectionTagRepository.cs
similarity index 87%
rename from API/Data/CollectionTagRepository.cs
rename to API/Data/Repositories/CollectionTagRepository.cs
index b694b0bb8..777e82788 100644
--- a/API/Data/CollectionTagRepository.cs
+++ b/API/Data/Repositories/CollectionTagRepository.cs
@@ -1,14 +1,15 @@
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Threading.Tasks;
using API.DTOs;
using API.Entities;
-using API.Interfaces;
+using API.Interfaces.Repositories;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
-namespace API.Data
+namespace API.Data.Repositories
{
public class CollectionTagRepository : ICollectionTagRepository
{
@@ -48,11 +49,19 @@ namespace API.Data
public async Task<IEnumerable<CollectionTag>> GetAllTagsAsync()
{
return await _context.CollectionTag
- .Select(c => c)
.OrderBy(c => c.NormalizedTitle)
.ToListAsync();
}
+ public async Task<IList<string>> GetAllCoverImagesAsync()
+ {
+ return await _context.CollectionTag
+ .Select(t => t.CoverImage)
+ .Where(t => !string.IsNullOrEmpty(t))
+ .AsNoTracking()
+ .ToListAsync();
+ }
+
public async Task<IEnumerable<CollectionTagDto>> GetAllTagDtosAsync()
{
return await _context.CollectionTag
@@ -100,9 +109,9 @@ namespace API.Data
.ToListAsync();
}
- public Task<byte[]> GetCoverImageAsync(int collectionTagId)
+ public async Task<string> GetCoverImageAsync(int collectionTagId)
{
- return _context.CollectionTag
+ return await _context.CollectionTag
.Where(c => c.Id == collectionTagId)
.Select(c => c.CoverImage)
.AsNoTracking()
diff --git a/API/Data/FileRepository.cs b/API/Data/Repositories/FileRepository.cs
similarity index 92%
rename from API/Data/FileRepository.cs
rename to API/Data/Repositories/FileRepository.cs
index c3234abba..4665dac7e 100644
--- a/API/Data/FileRepository.cs
+++ b/API/Data/Repositories/FileRepository.cs
@@ -2,10 +2,10 @@
using System.IO;
using System.Linq;
using System.Threading.Tasks;
-using API.Interfaces;
+using API.Interfaces.Repositories;
using Microsoft.EntityFrameworkCore;
-namespace API.Data
+namespace API.Data.Repositories
{
public class FileRepository : IFileRepository
{
diff --git a/API/Data/LibraryRepository.cs b/API/Data/Repositories/LibraryRepository.cs
similarity index 98%
rename from API/Data/LibraryRepository.cs
rename to API/Data/Repositories/LibraryRepository.cs
index 23ad6ea76..7f3544aee 100644
--- a/API/Data/LibraryRepository.cs
+++ b/API/Data/Repositories/LibraryRepository.cs
@@ -4,12 +4,12 @@ using System.Threading.Tasks;
using API.DTOs;
using API.Entities;
using API.Entities.Enums;
-using API.Interfaces;
+using API.Interfaces.Repositories;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
-namespace API.Data
+namespace API.Data.Repositories
{
public class LibraryRepository : ILibraryRepository
{
diff --git a/API/Data/Repositories/ReadingListRepository.cs b/API/Data/Repositories/ReadingListRepository.cs
new file mode 100644
index 000000000..4f44bc943
--- /dev/null
+++ b/API/Data/Repositories/ReadingListRepository.cs
@@ -0,0 +1,178 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using API.DTOs.ReadingLists;
+using API.Entities;
+using API.Helpers;
+using API.Interfaces.Repositories;
+using AutoMapper;
+using AutoMapper.QueryableExtensions;
+using Microsoft.EntityFrameworkCore;
+
+namespace API.Data.Repositories
+{
+ public class ReadingListRepository : IReadingListRepository
+ {
+ private readonly DataContext _context;
+ private readonly IMapper _mapper;
+
+ public ReadingListRepository(DataContext context, IMapper mapper)
+ {
+ _context = context;
+ _mapper = mapper;
+ }
+
+ public void Update(ReadingList list)
+ {
+ _context.Entry(list).State = EntityState.Modified;
+ }
+
+ public void Remove(ReadingListItem item)
+ {
+ _context.ReadingListItem.Remove(item);
+ }
+
+ public void BulkRemove(IEnumerable<ReadingListItem> items)
+ {
+ _context.ReadingListItem.RemoveRange(items);
+ }
+
+
+ public async Task<PagedList<ReadingListDto>> GetReadingListDtosForUserAsync(int userId, bool includePromoted, UserParams userParams)
+ {
+ var query = _context.ReadingList
+ .Where(l => l.AppUserId == userId || (includePromoted && l.Promoted ))
+ .OrderBy(l => l.LastModified)
+ .ProjectTo<ReadingListDto>(_mapper.ConfigurationProvider)
+ .AsNoTracking();
+
+ return await PagedList<ReadingListDto>.CreateAsync(query, userParams.PageNumber, userParams.PageSize);
+ }
+
+ public async Task<ReadingList> GetReadingListByIdAsync(int readingListId)
+ {
+ return await _context.ReadingList
+ .Where(r => r.Id == readingListId)
+ .Include(r => r.Items)
+ .SingleOrDefaultAsync();
+ }
+
+ public async Task<IEnumerable<ReadingListItemDto>> GetReadingListItemDtosByIdAsync(int readingListId, int userId)
+ {
+ var userLibraries = _context.Library
+ .Include(l => l.AppUsers)
+ .Where(library => library.AppUsers.Any(user => user.Id == userId))
+ .AsNoTracking()
+ .Select(library => library.Id)
+ .ToList();
+
+ var items = await _context.ReadingListItem
+ .Where(s => s.ReadingListId == readingListId)
+ .Join(_context.Chapter, s => s.ChapterId, chapter => chapter.Id, (data, chapter) => new
+ {
+ TotalPages = chapter.Pages,
+ ChapterNumber = chapter.Range,
+ readingListItem = data
+ })
+ .Join(_context.Volume, s => s.readingListItem.VolumeId, volume => volume.Id, (data, volume) => new
+ {
+ data.readingListItem,
+ data.TotalPages,
+ data.ChapterNumber,
+ VolumeId = volume.Id,
+ VolumeNumber = volume.Name,
+ })
+ .Join(_context.Series, s => s.readingListItem.SeriesId, series => series.Id,
+ (data, s) => new
+ {
+ SeriesName = s.Name,
+ SeriesFormat = s.Format,
+ s.LibraryId,
+ data.readingListItem,
+ data.TotalPages,
+ data.ChapterNumber,
+ data.VolumeNumber,
+ data.VolumeId
+ })
+ .Select(data => new ReadingListItemDto()
+ {
+ Id = data.readingListItem.Id,
+ ChapterId = data.readingListItem.ChapterId,
+ Order = data.readingListItem.Order,
+ SeriesId = data.readingListItem.SeriesId,
+ SeriesName = data.SeriesName,
+ SeriesFormat = data.SeriesFormat,
+ PagesTotal = data.TotalPages,
+ ChapterNumber = data.ChapterNumber,
+ VolumeNumber = data.VolumeNumber,
+ LibraryId = data.LibraryId,
+ VolumeId = data.VolumeId,
+ ReadingListId = data.readingListItem.ReadingListId
+ })
+ .Where(o => userLibraries.Contains(o.LibraryId))
+ .OrderBy(rli => rli.Order)
+ .AsNoTracking()
+ .ToListAsync();
+
+ // Attach progress information
+ var fetchedChapterIds = items.Select(i => i.ChapterId);
+ var progresses = await _context.AppUserProgresses
+ .Where(p => fetchedChapterIds.Contains(p.ChapterId))
+ .AsNoTracking()
+ .ToListAsync();
+
+ foreach (var progress in progresses)
+ {
+ var progressItem = items.SingleOrDefault(i => i.ChapterId == progress.ChapterId && i.ReadingListId == readingListId);
+ if (progressItem == null) continue;
+
+ progressItem.PagesRead = progress.PagesRead;
+ }
+
+ return items;
+ }
+
+ public async Task<ReadingListDto> GetReadingListDtoByIdAsync(int readingListId, int userId)
+ {
+ return await _context.ReadingList
+ .Where(r => r.Id == readingListId && (r.AppUserId == userId || r.Promoted))
+ .ProjectTo<ReadingListDto>(_mapper.ConfigurationProvider)
+ .SingleOrDefaultAsync();
+ }
+
+ public async Task<IEnumerable<ReadingListItemDto>> AddReadingProgressModifiers(int userId, IList<ReadingListItemDto> items)
+ {
+ var chapterIds = items.Select(i => i.ChapterId).Distinct().ToList();
+ var userProgress = await _context.AppUserProgresses
+ .Where(p => p.AppUserId == userId && chapterIds.Contains(p.ChapterId))
+ .AsNoTracking()
+ .ToListAsync();
+
+ foreach (var item in items)
+ {
+ var progress = userProgress.Where(p => p.ChapterId == item.ChapterId);
+ item.PagesRead = progress.Sum(p => p.PagesRead);
+ }
+
+ return items;
+ }
+
+ public async Task<ReadingListDto> GetReadingListDtoByTitleAsync(string title)
+ {
+ return await _context.ReadingList
+ .Where(r => r.Title.Equals(title))
+ .ProjectTo<ReadingListDto>(_mapper.ConfigurationProvider)
+ .SingleOrDefaultAsync();
+ }
+
+ public async Task<IEnumerable<ReadingListItem>> GetReadingListItemsByIdAsync(int readingListId)
+ {
+ return await _context.ReadingListItem
+ .Where(r => r.ReadingListId == readingListId)
+ .OrderBy(r => r.Order)
+ .ToListAsync();
+ }
+
+
+ }
+}
diff --git a/API/Data/SeriesRepository.cs b/API/Data/Repositories/SeriesRepository.cs
similarity index 86%
rename from API/Data/SeriesRepository.cs
rename to API/Data/Repositories/SeriesRepository.cs
index b9e2f16cd..3ed415859 100644
--- a/API/Data/SeriesRepository.cs
+++ b/API/Data/Repositories/SeriesRepository.cs
@@ -1,4 +1,6 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Threading.Tasks;
using API.Comparators;
@@ -7,18 +9,17 @@ using API.DTOs.Filtering;
using API.Entities;
using API.Extensions;
using API.Helpers;
-using API.Interfaces;
+using API.Interfaces.Repositories;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
-namespace API.Data
+namespace API.Data.Repositories
{
public class SeriesRepository : ISeriesRepository
{
private readonly DataContext _context;
private readonly IMapper _mapper;
- private readonly NaturalSortComparer _naturalSortComparer = new ();
public SeriesRepository(DataContext context, IMapper mapper)
{
_context = context;
@@ -115,16 +116,15 @@ namespace API.Data
await AddVolumeModifiers(userId, volumes);
SortSpecialChapters(volumes);
-
-
return volumes;
}
- private void SortSpecialChapters(IEnumerable<VolumeDto> volumes)
+ private static void SortSpecialChapters(IEnumerable<VolumeDto> volumes)
{
+ var sorter = new NaturalSortComparer();
foreach (var v in volumes.Where(vDto => vDto.Number == 0))
{
- v.Chapters = v.Chapters.OrderBy(x => x.Range, _naturalSortComparer).ToList();
+ v.Chapters = v.Chapters.OrderBy(x => x.Range, sorter).ToList();
}
}
@@ -189,11 +189,16 @@ namespace API.Data
/// </summary>
/// <param name="seriesIds"></param>
/// <returns></returns>
- public async Task<IEnumerable<Volume>> GetVolumesForSeriesAsync(int[] seriesIds)
+ public async Task<IEnumerable<Volume>> GetVolumesForSeriesAsync(IList<int> seriesIds, bool includeChapters = false)
{
- return await _context.Volume
- .Where(v => seriesIds.Contains(v.SeriesId))
- .ToListAsync();
+ var query = _context.Volume
+ .Where(v => seriesIds.Contains(v.SeriesId));
+
+ if (includeChapters)
+ {
+ query = query.Include(v => v.Chapters);
+ }
+ return await query.ToListAsync();
}
public async Task<bool> DeleteSeriesAsync(int seriesId)
@@ -221,25 +226,50 @@ namespace API.Data
public async Task<int[]> GetChapterIdsForSeriesAsync(int[] seriesIds)
{
- var series = await _context.Series
- .Where(s => seriesIds.Contains(s.Id))
- .Include(s => s.Volumes)
- .ThenInclude(v => v.Chapters)
+ var volumes = await _context.Volume
+ .Where(v => seriesIds.Contains(v.SeriesId))
+ .Include(v => v.Chapters)
.ToListAsync();
IList<int> chapterIds = new List<int>();
- foreach (var s in series)
+ foreach (var v in volumes)
+ {
+ foreach (var c in v.Chapters)
+ {
+ chapterIds.Add(c.Id);
+ }
+ }
+
+ return chapterIds.ToArray();
+ }
+
+ /// <summary>
+ /// This returns a list of tuples<chapterId, seriesId> back for each series id passed
+ /// </summary>
+ /// <param name="seriesIds"></param>
+ /// <returns></returns>
+ public async Task<IDictionary<int, IList<int>>> GetChapterIdWithSeriesIdForSeriesAsync(int[] seriesIds)
+ {
+ var volumes = await _context.Volume
+ .Where(v => seriesIds.Contains(v.SeriesId))
+ .Include(v => v.Chapters)
+ .ToListAsync();
+
+ var seriesChapters = new Dictionary<int, IList<int>>();
+ foreach (var v in volumes)
{
- foreach (var v in s.Volumes)
+ foreach (var c in v.Chapters)
{
- foreach (var c in v.Chapters)
+ if (!seriesChapters.ContainsKey(v.SeriesId))
{
- chapterIds.Add(c.Id);
+ var list = new List<int>();
+ seriesChapters.Add(v.SeriesId, list);
}
+ seriesChapters[v.SeriesId].Add(c.Id);
}
}
- return chapterIds.ToArray();
+ return seriesChapters;
}
public async Task AddSeriesModifiers(int userId, List<SeriesDto> series)
@@ -262,16 +292,7 @@ namespace API.Data
}
}
- public async Task<byte[]> GetVolumeCoverImageAsync(int volumeId)
- {
- return await _context.Volume
- .Where(v => v.Id == volumeId)
- .Select(v => v.CoverImage)
- .AsNoTracking()
- .SingleOrDefaultAsync();
- }
-
- public async Task<byte[]> GetSeriesCoverImageAsync(int seriesId)
+ public async Task<string> GetSeriesCoverImageAsync(int seriesId)
{
return await _context.Series
.Where(s => s.Id == seriesId)
@@ -282,8 +303,9 @@ namespace API.Data
private async Task AddVolumeModifiers(int userId, IReadOnlyCollection<VolumeDto> volumes)
{
+ var volIds = volumes.Select(s => s.Id);
var userProgress = await _context.AppUserProgresses
- .Where(p => p.AppUserId == userId && volumes.Select(s => s.Id).Contains(p.VolumeId))
+ .Where(p => p.AppUserId == userId && volIds.Contains(p.VolumeId))
.AsNoTracking()
.ToListAsync();
@@ -457,5 +479,23 @@ namespace API.Data
.AsSplitQuery()
.ToListAsync();
}
+
+ public async Task<IList<string>> GetAllCoverImagesAsync()
+ {
+ return await _context.Series
+ .Select(s => s.CoverImage)
+ .Where(t => !string.IsNullOrEmpty(t))
+ .AsNoTracking()
+ .ToListAsync();
+ }
+
+ public async Task<IEnumerable<string>> GetLockedCoverImagesAsync()
+ {
+ return await _context.Series
+ .Where(s => s.CoverImageLocked && !string.IsNullOrEmpty(s.CoverImage))
+ .Select(s => s.CoverImage)
+ .AsNoTracking()
+ .ToListAsync();
+ }
}
}
diff --git a/API/Data/SettingsRepository.cs b/API/Data/Repositories/SettingsRepository.cs
similarity index 94%
rename from API/Data/SettingsRepository.cs
rename to API/Data/Repositories/SettingsRepository.cs
index ecacf0f87..1eb0165bb 100644
--- a/API/Data/SettingsRepository.cs
+++ b/API/Data/Repositories/SettingsRepository.cs
@@ -4,11 +4,11 @@ using System.Threading.Tasks;
using API.DTOs;
using API.Entities;
using API.Entities.Enums;
-using API.Interfaces;
+using API.Interfaces.Repositories;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
-namespace API.Data
+namespace API.Data.Repositories
{
public class SettingsRepository : ISettingsRepository
{
@@ -45,4 +45,4 @@ namespace API.Data
return await _context.ServerSetting.ToListAsync();
}
}
-}
\ No newline at end of file
+}
diff --git a/API/Data/UserRepository.cs b/API/Data/Repositories/UserRepository.cs
similarity index 56%
rename from API/Data/UserRepository.cs
rename to API/Data/Repositories/UserRepository.cs
index 2e0b9e7f3..4e20039c7 100644
--- a/API/Data/UserRepository.cs
+++ b/API/Data/Repositories/UserRepository.cs
@@ -1,17 +1,29 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API.Constants;
using API.DTOs;
+using API.DTOs.Reader;
using API.Entities;
-using API.Interfaces;
+using API.Interfaces.Repositories;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
-namespace API.Data
+namespace API.Data.Repositories
{
+ [Flags]
+ public enum AppUserIncludes
+ {
+ None = 1,
+ Progress = 2,
+ Bookmarks = 4,
+ ReadingLists = 8,
+ Ratings = 16
+ }
+
public class UserRepository : IUserRepository
{
private readonly DataContext _context;
@@ -35,35 +47,105 @@ namespace API.Data
_context.Entry(preferences).State = EntityState.Modified;
}
+ public void Update(AppUserBookmark bookmark)
+ {
+ _context.Entry(bookmark).State = EntityState.Modified;
+ }
+
public void Delete(AppUser user)
{
_context.AppUser.Remove(user);
}
/// <summary>
- /// Gets an AppUser by username. Returns back Progress information.
+ /// A one stop shop to get a tracked AppUser instance with any number of JOINs generated by passing bitwise flags.
+ /// </summary>
+ /// <param name="username"></param>
+ /// <param name="includeFlags">Includes() you want. Pass multiple with flag1 | flag2 </param>
+ /// <returns></returns>
+ public async Task<AppUser> GetUserByUsernameAsync(string username, AppUserIncludes includeFlags = AppUserIncludes.None)
+ {
+ var query = _context.Users
+ .Where(x => x.UserName == username);
+
+ query = AddIncludesToQuery(query, includeFlags);
+
+ return await query.SingleOrDefaultAsync();
+ }
+
+ /// <summary>
+ /// A one stop shop to get a tracked AppUser instance with any number of JOINs generated by passing bitwise flags.
+ /// </summary>
+ /// <param name="userId"></param>
+ /// <param name="includeFlags">Includes() you want. Pass multiple with flag1 | flag2 </param>
+ /// <returns></returns>
+ public async Task<AppUser> GetUserByIdAsync(int userId, AppUserIncludes includeFlags = AppUserIncludes.None)
+ {
+ var query = _context.Users
+ .Where(x => x.Id == userId);
+
+ query = AddIncludesToQuery(query, includeFlags);
+
+ return await query.SingleOrDefaultAsync();
+ }
+
+ public async Task<AppUserBookmark> GetBookmarkForPage(int page, int chapterId, int userId)
+ {
+ return await _context.AppUserBookmark
+ .Where(b => b.Page == page && b.ChapterId == chapterId && b.AppUserId == userId)
+ .SingleOrDefaultAsync();
+ }
+
+ private static IQueryable<AppUser> AddIncludesToQuery(IQueryable<AppUser> query, AppUserIncludes includeFlags)
+ {
+ if (includeFlags.HasFlag(AppUserIncludes.Bookmarks))
+ {
+ query = query.Include(u => u.Bookmarks);
+ }
+
+ if (includeFlags.HasFlag(AppUserIncludes.Progress))
+ {
+ query = query.Include(u => u.Progresses);
+ }
+
+ if (includeFlags.HasFlag(AppUserIncludes.ReadingLists))
+ {
+ query = query.Include(u => u.ReadingLists);
+ }
+
+ if (includeFlags.HasFlag(AppUserIncludes.Ratings))
+ {
+ query = query.Include(u => u.Ratings);
+ }
+
+ return query;
+ }
+
+
+ /// <summary>
+ /// This fetches the Id for a user. Use whenever you just need an ID.
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
- public async Task<AppUser> GetUserByUsernameAsync(string username)
+ public async Task<int> GetUserIdByUsernameAsync(string username)
{
return await _context.Users
- .Include(u => u.Progresses)
- .Include(u => u.Bookmarks)
- .SingleOrDefaultAsync(x => x.UserName == username);
+ .Where(x => x.UserName == username)
+ .Select(u => u.Id)
+ .SingleOrDefaultAsync();
}
/// <summary>
- /// Gets an AppUser by id. Returns back Progress information.
+ /// Gets an AppUser by username. Returns back Reading List and their Items.
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
- public async Task<AppUser> GetUserByIdAsync(int id)
+ public async Task<AppUser> GetUserWithReadingListsByUsernameAsync(string username)
{
return await _context.Users
- .Include(u => u.Progresses)
- .Include(u => u.Bookmarks)
- .SingleOrDefaultAsync(x => x.Id == id);
+ .Include(u => u.ReadingLists)
+ .ThenInclude(l => l.Items)
+ .SingleOrDefaultAsync(x => x.UserName == username);
}
public async Task<IEnumerable<AppUser>> GetAdminUsersAsync()
@@ -77,11 +159,6 @@ namespace API.Data
.SingleOrDefaultAsync();
}
- public void AddRatingTracking(AppUserRating userRating)
- {
- _context.AppUserRating.Add(userRating);
- }
-
public async Task<AppUserPreferences> GetPreferencesAsync(string username)
{
return await _context.AppUserPreferences
@@ -129,10 +206,17 @@ namespace API.Data
.ToListAsync();
}
- public async Task<AppUser> GetUserByApiKeyAsync(string apiKey)
+ /// <summary>
+ /// Fetches the UserId by API Key. This does not include any extra information
+ /// </summary>
+ /// <param name="apiKey"></param>
+ /// <returns></returns>
+ public async Task<int> GetUserIdByApiKeyAsync(string apiKey)
{
return await _context.AppUser
- .SingleOrDefaultAsync(u => u.ApiKey.Equals(apiKey));
+ .Where(u => u.ApiKey.Equals(apiKey))
+ .Select(u => u.Id)
+ .SingleOrDefaultAsync();
}
diff --git a/API/Data/Repositories/VolumeRepository.cs b/API/Data/Repositories/VolumeRepository.cs
new file mode 100644
index 000000000..d991a928c
--- /dev/null
+++ b/API/Data/Repositories/VolumeRepository.cs
@@ -0,0 +1,56 @@
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using API.DTOs;
+using API.DTOs.Reader;
+using API.Entities;
+using API.Interfaces.Repositories;
+using AutoMapper;
+using AutoMapper.QueryableExtensions;
+using Microsoft.EntityFrameworkCore;
+
+namespace API.Data.Repositories
+{
+ public class VolumeRepository : IVolumeRepository
+ {
+ private readonly DataContext _context;
+
+ public VolumeRepository(DataContext context)
+ {
+ _context = context;
+ }
+
+ public void Update(Volume volume)
+ {
+ _context.Entry(volume).State = EntityState.Modified;
+ }
+
+ public async Task<IList<MangaFile>> GetFilesForVolume(int volumeId)
+ {
+ return await _context.Chapter
+ .Where(c => volumeId == c.VolumeId)
+ .Include(c => c.Files)
+ .SelectMany(c => c.Files)
+ .AsNoTracking()
+ .ToListAsync();
+ }
+
+ public async Task<string> GetVolumeCoverImageAsync(int volumeId)
+ {
+ return await _context.Volume
+ .Where(v => v.Id == volumeId)
+ .Select(v => v.CoverImage)
+ .AsNoTracking()
+ .SingleOrDefaultAsync();
+ }
+
+ public async Task<IList<int>> GetChapterIdsByVolumeIds(IReadOnlyList<int> volumeIds)
+ {
+ return await _context.Chapter
+ .Where(c => volumeIds.Contains(c.VolumeId))
+ .Select(c => c.Id)
+ .ToListAsync();
+ }
+ }
+}
diff --git a/API/Data/UnitOfWork.cs b/API/Data/UnitOfWork.cs
index 25ac5654c..017293be0 100644
--- a/API/Data/UnitOfWork.cs
+++ b/API/Data/UnitOfWork.cs
@@ -1,4 +1,5 @@
using System.Threading.Tasks;
+using API.Data.Repositories;
using API.Entities;
using API.Interfaces;
using API.Interfaces.Repositories;
@@ -24,14 +25,15 @@ namespace API.Data
public IUserRepository UserRepository => new UserRepository(_context, _userManager, _mapper);
public ILibraryRepository LibraryRepository => new LibraryRepository(_context, _mapper);
- public IVolumeRepository VolumeRepository => new VolumeRepository(_context, _mapper);
+ public IVolumeRepository VolumeRepository => new VolumeRepository(_context);
public ISettingsRepository SettingsRepository => new SettingsRepository(_context, _mapper);
public IAppUserProgressRepository AppUserProgressRepository => new AppUserProgressRepository(_context);
public ICollectionTagRepository CollectionTagRepository => new CollectionTagRepository(_context, _mapper);
public IFileRepository FileRepository => new FileRepository(_context);
- public IChapterRepository ChapterRepository => new ChapterRepository(_context);
+ public IChapterRepository ChapterRepository => new ChapterRepository(_context, _mapper);
+ public IReadingListRepository ReadingListRepository => new ReadingListRepository(_context, _mapper);
/// <summary>
/// Commits changes to the DB. Completes the open transaction.
@@ -39,7 +41,6 @@ namespace API.Data
/// <returns></returns>
public bool Commit()
{
-
return _context.SaveChanges() > 0;
}
/// <summary>
diff --git a/API/Data/VolumeRepository.cs b/API/Data/VolumeRepository.cs
deleted file mode 100644
index c10a3a04e..000000000
--- a/API/Data/VolumeRepository.cs
+++ /dev/null
@@ -1,116 +0,0 @@
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using API.DTOs;
-using API.Entities;
-using API.Interfaces;
-using AutoMapper;
-using AutoMapper.QueryableExtensions;
-using Microsoft.EntityFrameworkCore;
-
-namespace API.Data
-{
- public class VolumeRepository : IVolumeRepository
- {
- private readonly DataContext _context;
- private readonly IMapper _mapper;
-
- public VolumeRepository(DataContext context, IMapper mapper)
- {
- _context = context;
- _mapper = mapper;
- }
-
- public void Update(Volume volume)
- {
- _context.Entry(volume).State = EntityState.Modified;
- }
-
- /// <summary>
- /// Returns a Chapter for an Id. Includes linked <see cref="MangaFile"/>s.
- /// </summary>
- /// <param name="chapterId"></param>
- /// <returns></returns>
- public async Task<Chapter> GetChapterAsync(int chapterId)
- {
- return await _context.Chapter
- .Include(c => c.Files)
- .SingleOrDefaultAsync(c => c.Id == chapterId);
- }
-
- /// <summary>
- /// Returns Chapters for a volume id.
- /// </summary>
- /// <param name="volumeId"></param>
- /// <returns></returns>
- public async Task<IList<Chapter>> GetChaptersAsync(int volumeId)
- {
- return await _context.Chapter
- .Where(c => c.VolumeId == volumeId)
- .ToListAsync();
- }
-
- /// <summary>
- /// Returns the cover image for a chapter id.
- /// </summary>
- /// <param name="chapterId"></param>
- /// <returns></returns>
- public async Task<byte[]> GetChapterCoverImageAsync(int chapterId)
- {
- return await _context.Chapter
- .Where(c => c.Id == chapterId)
- .Select(c => c.CoverImage)
- .AsNoTracking()
- .SingleOrDefaultAsync();
- }
-
-
-
-
- public async Task<ChapterDto> GetChapterDtoAsync(int chapterId)
- {
- var chapter = await _context.Chapter
- .Include(c => c.Files)
- .ProjectTo<ChapterDto>(_mapper.ConfigurationProvider)
- .AsNoTracking()
- .SingleOrDefaultAsync(c => c.Id == chapterId);
-
- return chapter;
- }
-
- /// <summary>
- /// Returns non-tracked files for a given chapterId
- /// </summary>
- /// <param name="chapterId"></param>
- /// <returns></returns>
- public async Task<IList<MangaFile>> GetFilesForChapterAsync(int chapterId)
- {
- return await _context.MangaFile
- .Where(c => chapterId == c.ChapterId)
- .AsNoTracking()
- .ToListAsync();
- }
- /// <summary>
- /// Returns non-tracked files for a set of chapterIds
- /// </summary>
- /// <param name="chapterIds"></param>
- /// <returns></returns>
- public async Task<IList<MangaFile>> GetFilesForChaptersAsync(IReadOnlyList<int> chapterIds)
- {
- return await _context.MangaFile
- .Where(c => chapterIds.Contains(c.ChapterId))
- .AsNoTracking()
- .ToListAsync();
- }
-
- public async Task<IList<MangaFile>> GetFilesForVolume(int volumeId)
- {
- return await _context.Chapter
- .Where(c => volumeId == c.VolumeId)
- .Include(c => c.Files)
- .SelectMany(c => c.Files)
- .AsNoTracking()
- .ToListAsync();
- }
- }
-}
diff --git a/API/Entities/AppUser.cs b/API/Entities/AppUser.cs
index c4a24e405..b959fac1a 100644
--- a/API/Entities/AppUser.cs
+++ b/API/Entities/AppUser.cs
@@ -18,6 +18,10 @@ namespace API.Entities
public AppUserPreferences UserPreferences { get; set; }
public ICollection<AppUserBookmark> Bookmarks { get; set; }
/// <summary>
+ /// Reading lists associated with this user
+ /// </summary>
+ public ICollection<ReadingList> ReadingLists { get; set; }
+ /// <summary>
/// An API Key to interact with external services, like OPDS
/// </summary>
public string ApiKey { get; set; }
diff --git a/API/Entities/AppUserProgress.cs b/API/Entities/AppUserProgress.cs
index cb3c1b33c..08fffa540 100644
--- a/API/Entities/AppUserProgress.cs
+++ b/API/Entities/AppUserProgress.cs
@@ -9,7 +9,7 @@ namespace API.Entities
/// Represents the progress a single user has on a given Chapter.
/// </summary>
//[Index(nameof(SeriesId), nameof(VolumeId), nameof(ChapterId), nameof(AppUserId), IsUnique = true)]
- public class AppUserProgress : IEntityDate, IHasConcurrencyToken
+ public class AppUserProgress : IEntityDate
{
/// <summary>
/// Id of Entity
@@ -55,16 +55,5 @@ namespace API.Entities
/// Last date this was updated
/// </summary>
public DateTime LastModified { get; set; }
-
- /// <inheritdoc />
- [ConcurrencyCheck]
- public uint RowVersion { get; private set; }
-
-
- /// <inheritdoc />
- public void OnSavingChanges()
- {
- RowVersion++;
- }
}
}
diff --git a/API/Entities/Chapter.cs b/API/Entities/Chapter.cs
index 4595ba048..ef12de8ce 100644
--- a/API/Entities/Chapter.cs
+++ b/API/Entities/Chapter.cs
@@ -23,7 +23,11 @@ namespace API.Entities
public ICollection<MangaFile> Files { get; set; }
public DateTime Created { get; set; }
public DateTime LastModified { get; set; }
- public byte[] CoverImage { get; set; }
+ /// <summary>
+ /// Absolute path to the (managed) image file
+ /// </summary>
+ /// <remarks>The file is managed internally to Kavita's APPDIR</remarks>
+ public string CoverImage { get; set; }
public bool CoverImageLocked { get; set; }
/// <summary>
/// Total number of pages in all MangaFiles
diff --git a/API/Entities/CollectionTag.cs b/API/Entities/CollectionTag.cs
index c9dd4fa92..ee966cafc 100644
--- a/API/Entities/CollectionTag.cs
+++ b/API/Entities/CollectionTag.cs
@@ -14,11 +14,11 @@ namespace API.Entities
/// Visible title of the Tag
/// </summary>
public string Title { get; set; }
-
/// <summary>
- /// Cover Image for the collection tag
+ /// Absolute path to the (managed) image file
/// </summary>
- public byte[] CoverImage { get; set; }
+ /// <remarks>The file is managed internally to Kavita's APPDIR</remarks>
+ public string CoverImage { get; set; }
/// <summary>
/// Denotes if the CoverImage has been overridden by the user. If so, it will not be updated during normal scan operations.
/// </summary>
diff --git a/API/Entities/MangaFile.cs b/API/Entities/MangaFile.cs
index 2376ec721..72c620ce9 100644
--- a/API/Entities/MangaFile.cs
+++ b/API/Entities/MangaFile.cs
@@ -30,9 +30,13 @@ namespace API.Entities
public int ChapterId { get; set; }
// Methods
+ /// <summary>
+ /// If the File on disk's last modified time is after what is stored in MangaFile
+ /// </summary>
+ /// <returns></returns>
public bool HasFileBeenModified()
{
- return !File.GetLastWriteTime(FilePath).Equals(LastModified);
+ return File.GetLastWriteTime(FilePath) > LastModified;
}
}
}
diff --git a/API/Entities/ReadingList.cs b/API/Entities/ReadingList.cs
new file mode 100644
index 000000000..ef0b4bd9c
--- /dev/null
+++ b/API/Entities/ReadingList.cs
@@ -0,0 +1,29 @@
+using System;
+using System.Collections.Generic;
+using API.Entities.Interfaces;
+
+namespace API.Entities
+{
+ /// <summary>
+ /// This is a collection of <see cref="ReadingListItem"/> which represent individual chapters and an order.
+ /// </summary>
+ public class ReadingList : IEntityDate
+ {
+ public int Id { get; init; }
+ public string Title { get; set; }
+ public string Summary { get; set; }
+ /// <summary>
+ /// Reading lists that are promoted are only done by admins
+ /// </summary>
+ public bool Promoted { get; set; }
+
+ public ICollection<ReadingListItem> Items { get; set; }
+ public DateTime Created { get; set; }
+ public DateTime LastModified { get; set; }
+
+ // Relationships
+ public int AppUserId { get; set; }
+ public AppUser AppUser { get; set; }
+
+ }
+}
diff --git a/API/Entities/ReadingListItem.cs b/API/Entities/ReadingListItem.cs
new file mode 100644
index 000000000..002911131
--- /dev/null
+++ b/API/Entities/ReadingListItem.cs
@@ -0,0 +1,25 @@
+namespace API.Entities
+{
+ //[Index(nameof(SeriesId), nameof(VolumeId), nameof(ChapterId), IsUnique = true)]
+ public class ReadingListItem
+ {
+ public int Id { get; init; }
+ public int SeriesId { get; set; }
+ public int VolumeId { get; set; }
+ public int ChapterId { get; set; }
+ /// <summary>
+ /// Order of the chapter within a Reading List
+ /// </summary>
+ public int Order { get; set; }
+
+ // Relationship
+ public ReadingList ReadingList { get; set; }
+ public int ReadingListId { get; set; }
+
+ // Idea, keep these for easy join statements
+ public Series Series { get; set; }
+ public Volume Volume { get; set; }
+ public Chapter Chapter { get; set; }
+
+ }
+}
diff --git a/API/Entities/Series.cs b/API/Entities/Series.cs
index b2d97751f..899e52bfd 100644
--- a/API/Entities/Series.cs
+++ b/API/Entities/Series.cs
@@ -36,7 +36,11 @@ namespace API.Entities
public string Summary { get; set; } // TODO: Migrate into SeriesMetdata (with Metadata update)
public DateTime Created { get; set; }
public DateTime LastModified { get; set; }
- public byte[] CoverImage { get; set; }
+ /// <summary>
+ /// Absolute path to the (managed) image file
+ /// </summary>
+ /// <remarks>The file is managed internally to Kavita's APPDIR</remarks>
+ public string CoverImage { get; set; }
/// <summary>
/// Denotes if the CoverImage has been overridden by the user. If so, it will not be updated during normal scan operations.
/// </summary>
diff --git a/API/Entities/Volume.cs b/API/Entities/Volume.cs
index dab9f2e1b..3be7a4d6a 100644
--- a/API/Entities/Volume.cs
+++ b/API/Entities/Volume.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using API.Entities.Interfaces;
+using Microsoft.EntityFrameworkCore;
namespace API.Entities
{
@@ -12,7 +13,11 @@ namespace API.Entities
public IList<Chapter> Chapters { get; set; }
public DateTime Created { get; set; }
public DateTime LastModified { get; set; }
- public byte[] CoverImage { get; set; }
+ /// <summary>
+ /// Absolute path to the (managed) image file
+ /// </summary>
+ /// <remarks>The file is managed internally to Kavita's APPDIR</remarks>
+ public string CoverImage { get; set; }
public int Pages { get; set; }
@@ -21,4 +26,4 @@ namespace API.Entities
public Series Series { get; set; }
public int SeriesId { get; set; }
}
-}
\ No newline at end of file
+}
diff --git a/API/Extensions/FileInfoExtensions.cs b/API/Extensions/FileInfoExtensions.cs
index a52141611..f7e1291e7 100644
--- a/API/Extensions/FileInfoExtensions.cs
+++ b/API/Extensions/FileInfoExtensions.cs
@@ -14,7 +14,6 @@ namespace API.Extensions
public static bool HasFileBeenModifiedSince(this FileInfo fileInfo, DateTime comparison)
{
return DateTime.Compare(fileInfo.LastWriteTime, comparison) > 0;
- //return fileInfo?.LastWriteTime > comparison;
}
}
}
diff --git a/API/Extensions/HttpExtensions.cs b/API/Extensions/HttpExtensions.cs
index db7bcd370..80b52f18f 100644
--- a/API/Extensions/HttpExtensions.cs
+++ b/API/Extensions/HttpExtensions.cs
@@ -1,4 +1,5 @@
using System.Linq;
+using System.Text;
using System.Text.Json;
using API.Helpers;
using Microsoft.AspNetCore.Http;
@@ -7,7 +8,7 @@ namespace API.Extensions
{
public static class HttpExtensions
{
- public static void AddPaginationHeader(this HttpResponse response, int currentPage,
+ public static void AddPaginationHeader(this HttpResponse response, int currentPage,
int itemsPerPage, int totalItems, int totalPages)
{
var paginationHeader = new PaginationHeader(currentPage, itemsPerPage, totalItems, totalPages);
@@ -15,7 +16,7 @@ namespace API.Extensions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
-
+
response.Headers.Add("Pagination", JsonSerializer.Serialize(paginationHeader, options));
response.Headers.Add("Access-Control-Expose-Headers", "Pagination");
}
@@ -31,6 +32,18 @@ namespace API.Extensions
using var sha1 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
response.Headers.Add("ETag", string.Concat(sha1.ComputeHash(content).Select(x => x.ToString("X2"))));
}
-
+
+ /// <summary>
+ /// Calculates SHA256 hash for a cover image filename and sets as ETag. Ensures Cache-Control: private header is added.
+ /// </summary>
+ /// <param name="response"></param>
+ /// <param name="filename"></param>
+ public static void AddCacheHeader(this HttpResponse response, string filename)
+ {
+ if (filename == null || filename.Length <= 0) return;
+ using var sha1 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
+ response.Headers.Add("ETag", string.Concat(sha1.ComputeHash(Encoding.UTF8.GetBytes(filename)).Select(x => x.ToString("X2"))));
+ }
+
}
-}
\ No newline at end of file
+}
diff --git a/API/Helpers/AutoMapperProfiles.cs b/API/Helpers/AutoMapperProfiles.cs
index 084a7d28c..03445ccb2 100644
--- a/API/Helpers/AutoMapperProfiles.cs
+++ b/API/Helpers/AutoMapperProfiles.cs
@@ -1,6 +1,8 @@
using System.Collections.Generic;
using System.Linq;
using API.DTOs;
+using API.DTOs.Reader;
+using API.DTOs.ReadingLists;
using API.Entities;
using API.Helpers.Converters;
using AutoMapper;
@@ -31,6 +33,9 @@ namespace API.Helpers
CreateMap<AppUserBookmark, BookmarkDto>();
+ CreateMap<ReadingList, ReadingListDto>();
+ CreateMap<ReadingListItem, ReadingListItemDto>();
+
CreateMap<Series, SearchResultDto>()
.ForMember(dest => dest.SeriesId,
opt => opt.MapFrom(src => src.Id))
diff --git a/API/Helpers/SQLHelper.cs b/API/Helpers/SQLHelper.cs
new file mode 100644
index 000000000..fcd44e7da
--- /dev/null
+++ b/API/Helpers/SQLHelper.cs
@@ -0,0 +1,30 @@
+using System;
+using System.Collections.Generic;
+using System.Data;
+using System.Data.Common;
+using Microsoft.EntityFrameworkCore;
+
+namespace API.Helpers
+{
+ public static class SqlHelper
+ {
+ public static List<T> RawSqlQuery<T>(DbContext context, string query, Func<DbDataReader, T> map)
+ {
+ using var command = context.Database.GetDbConnection().CreateCommand();
+ command.CommandText = query;
+ command.CommandType = CommandType.Text;
+
+ context.Database.OpenConnection();
+
+ using var result = command.ExecuteReader();
+ var entities = new List<T>();
+
+ while (result.Read())
+ {
+ entities.Add(map(result));
+ }
+
+ return entities;
+ }
+ }
+}
diff --git a/API/Interfaces/ITaskScheduler.cs b/API/Interfaces/ITaskScheduler.cs
index ead76e36a..08a450ac2 100644
--- a/API/Interfaces/ITaskScheduler.cs
+++ b/API/Interfaces/ITaskScheduler.cs
@@ -14,7 +14,7 @@ namespace API.Interfaces
void CleanupChapters(int[] chapterIds);
void RefreshMetadata(int libraryId, bool forceUpdate = true);
void CleanupTemp();
- void RefreshSeriesMetadata(int libraryId, int seriesId);
+ void RefreshSeriesMetadata(int libraryId, int seriesId, bool forceUpdate = false);
void ScanSeries(int libraryId, int seriesId, bool forceUpdate = false);
void CancelStatsTasks();
void RunStatCollection();
diff --git a/API/Interfaces/IUnitOfWork.cs b/API/Interfaces/IUnitOfWork.cs
index 3f7b12146..06b47bbe8 100644
--- a/API/Interfaces/IUnitOfWork.cs
+++ b/API/Interfaces/IUnitOfWork.cs
@@ -14,6 +14,7 @@ namespace API.Interfaces
ICollectionTagRepository CollectionTagRepository { get; }
IFileRepository FileRepository { get; }
IChapterRepository ChapterRepository { get; }
+ IReadingListRepository ReadingListRepository { get; }
bool Commit();
Task<bool> CommitAsync();
bool HasChanges();
diff --git a/API/Interfaces/IVolumeRepository.cs b/API/Interfaces/IVolumeRepository.cs
deleted file mode 100644
index 0cd703ee9..000000000
--- a/API/Interfaces/IVolumeRepository.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-using System.Collections.Generic;
-using System.Threading.Tasks;
-using API.DTOs;
-using API.Entities;
-
-namespace API.Interfaces
-{
- public interface IVolumeRepository
- {
- void Update(Volume volume);
- Task<Chapter> GetChapterAsync(int chapterId);
- Task<ChapterDto> GetChapterDtoAsync(int chapterId);
- Task<IList<MangaFile>> GetFilesForChapterAsync(int chapterId);
- Task<IList<MangaFile>> GetFilesForChaptersAsync(IReadOnlyList<int> chapterIds);
- Task<IList<Chapter>> GetChaptersAsync(int volumeId);
- Task<byte[]> GetChapterCoverImageAsync(int chapterId);
- Task<IList<MangaFile>> GetFilesForVolume(int volumeId);
- }
-}
diff --git a/API/Interfaces/IAppUserProgressRepository.cs b/API/Interfaces/Repositories/IAppUserProgressRepository.cs
similarity index 55%
rename from API/Interfaces/IAppUserProgressRepository.cs
rename to API/Interfaces/Repositories/IAppUserProgressRepository.cs
index 96ada0c50..d37198fb2 100644
--- a/API/Interfaces/IAppUserProgressRepository.cs
+++ b/API/Interfaces/Repositories/IAppUserProgressRepository.cs
@@ -1,11 +1,14 @@
using System.Threading.Tasks;
+using API.Entities;
using API.Entities.Enums;
-namespace API.Interfaces
+namespace API.Interfaces.Repositories
{
public interface IAppUserProgressRepository
{
+ void Update(AppUserProgress userProgress);
Task<int> CleanupAbandonedChapters();
Task<bool> UserHasProgress(LibraryType libraryType, int userId);
+ Task<AppUserProgress> GetUserProgressAsync(int chapterId, int userId);
}
-}
\ No newline at end of file
+}
diff --git a/API/Interfaces/Repositories/IChapterRepository.cs b/API/Interfaces/Repositories/IChapterRepository.cs
index 9f3f39a13..9ce145f4c 100644
--- a/API/Interfaces/Repositories/IChapterRepository.cs
+++ b/API/Interfaces/Repositories/IChapterRepository.cs
@@ -1,9 +1,24 @@
-using API.Entities;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using API.DTOs;
+using API.DTOs.Reader;
+using API.Entities;
namespace API.Interfaces.Repositories
{
public interface IChapterRepository
{
void Update(Chapter chapter);
+ Task<IEnumerable<Chapter>> GetChaptersByIdsAsync(IList<int> chapterIds);
+ Task<IChapterInfoDto> GetChapterInfoDtoAsync(int chapterId);
+ Task<int> GetChapterTotalPagesAsync(int chapterId);
+ Task<Chapter> GetChapterAsync(int chapterId);
+ Task<ChapterDto> GetChapterDtoAsync(int chapterId);
+ Task<IList<MangaFile>> GetFilesForChapterAsync(int chapterId);
+ Task<IList<Chapter>> GetChaptersAsync(int volumeId);
+ Task<IList<MangaFile>> GetFilesForChaptersAsync(IReadOnlyList<int> chapterIds);
+ Task<string> GetChapterCoverImageAsync(int chapterId);
+ Task<IList<string>> GetAllCoverImagesAsync();
+ Task<IEnumerable<string>> GetCoverImagesForLockedChaptersAsync();
}
}
diff --git a/API/Interfaces/ICollectionTagRepository.cs b/API/Interfaces/Repositories/ICollectionTagRepository.cs
similarity index 81%
rename from API/Interfaces/ICollectionTagRepository.cs
rename to API/Interfaces/Repositories/ICollectionTagRepository.cs
index 62f813c9d..03a552bd9 100644
--- a/API/Interfaces/ICollectionTagRepository.cs
+++ b/API/Interfaces/Repositories/ICollectionTagRepository.cs
@@ -3,19 +3,20 @@ using System.Threading.Tasks;
using API.DTOs;
using API.Entities;
-namespace API.Interfaces
+namespace API.Interfaces.Repositories
{
public interface ICollectionTagRepository
{
void Remove(CollectionTag tag);
Task<IEnumerable<CollectionTagDto>> GetAllTagDtosAsync();
Task<IEnumerable<CollectionTagDto>> SearchTagDtosAsync(string searchQuery);
- Task<byte[]> GetCoverImageAsync(int collectionTagId);
+ Task<string> GetCoverImageAsync(int collectionTagId);
Task<IEnumerable<CollectionTagDto>> GetAllPromotedTagDtosAsync();
Task<CollectionTag> GetTagAsync(int tagId);
Task<CollectionTag> GetFullTagAsync(int tagId);
void Update(CollectionTag tag);
Task<int> RemoveTagsWithoutSeries();
Task<IEnumerable<CollectionTag>> GetAllTagsAsync();
+ Task<IList<string>> GetAllCoverImagesAsync();
}
}
diff --git a/API/Interfaces/IFileRepository.cs b/API/Interfaces/Repositories/IFileRepository.cs
similarity index 81%
rename from API/Interfaces/IFileRepository.cs
rename to API/Interfaces/Repositories/IFileRepository.cs
index cde587855..a852032d7 100644
--- a/API/Interfaces/IFileRepository.cs
+++ b/API/Interfaces/Repositories/IFileRepository.cs
@@ -1,10 +1,10 @@
using System.Collections.Generic;
using System.Threading.Tasks;
-namespace API.Interfaces
+namespace API.Interfaces.Repositories
{
public interface IFileRepository
{
Task<IEnumerable<string>> GetFileExtensions();
}
-}
\ No newline at end of file
+}
diff --git a/API/Interfaces/ILibraryRepository.cs b/API/Interfaces/Repositories/ILibraryRepository.cs
similarity index 96%
rename from API/Interfaces/ILibraryRepository.cs
rename to API/Interfaces/Repositories/ILibraryRepository.cs
index 4977d38d5..4d9b03fe4 100644
--- a/API/Interfaces/ILibraryRepository.cs
+++ b/API/Interfaces/Repositories/ILibraryRepository.cs
@@ -4,7 +4,7 @@ using API.DTOs;
using API.Entities;
using API.Entities.Enums;
-namespace API.Interfaces
+namespace API.Interfaces.Repositories
{
public interface ILibraryRepository
{
diff --git a/API/Interfaces/Repositories/IReadingListRepository.cs b/API/Interfaces/Repositories/IReadingListRepository.cs
new file mode 100644
index 000000000..8b5ab085d
--- /dev/null
+++ b/API/Interfaces/Repositories/IReadingListRepository.cs
@@ -0,0 +1,22 @@
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using API.DTOs.ReadingLists;
+using API.Entities;
+using API.Helpers;
+
+namespace API.Interfaces.Repositories
+{
+ public interface IReadingListRepository
+ {
+ Task<PagedList<ReadingListDto>> GetReadingListDtosForUserAsync(int userId, bool includePromoted, UserParams userParams);
+ Task<ReadingList> GetReadingListByIdAsync(int readingListId);
+ Task<IEnumerable<ReadingListItemDto>> GetReadingListItemDtosByIdAsync(int readingListId, int userId);
+ Task<ReadingListDto> GetReadingListDtoByIdAsync(int readingListId, int userId);
+ Task<IEnumerable<ReadingListItemDto>> AddReadingProgressModifiers(int userId, IList<ReadingListItemDto> items);
+ Task<ReadingListDto> GetReadingListDtoByTitleAsync(string title);
+ Task<IEnumerable<ReadingListItem>> GetReadingListItemsByIdAsync(int readingListId);
+ void Remove(ReadingListItem item);
+ void BulkRemove(IEnumerable<ReadingListItem> items);
+ void Update(ReadingList list);
+ }
+}
diff --git a/API/Interfaces/ISeriesRepository.cs b/API/Interfaces/Repositories/ISeriesRepository.cs
similarity index 85%
rename from API/Interfaces/ISeriesRepository.cs
rename to API/Interfaces/Repositories/ISeriesRepository.cs
index a5518fc60..05fe937eb 100644
--- a/API/Interfaces/ISeriesRepository.cs
+++ b/API/Interfaces/Repositories/ISeriesRepository.cs
@@ -1,11 +1,13 @@
-using System.Collections.Generic;
+using System;
+using System.Collections;
+using System.Collections.Generic;
using System.Threading.Tasks;
using API.DTOs;
using API.DTOs.Filtering;
using API.Entities;
using API.Helpers;
-namespace API.Interfaces
+namespace API.Interfaces.Repositories
{
public interface ISeriesRepository
{
@@ -43,11 +45,12 @@ namespace API.Interfaces
/// <param name="volumeId"></param>
/// <returns></returns>
Task<VolumeDto> GetVolumeDtoAsync(int volumeId);
- Task<IEnumerable<Volume>> GetVolumesForSeriesAsync(int[] seriesIds);
+ Task<IEnumerable<Volume>> GetVolumesForSeriesAsync(IList<int> seriesIds, bool includeChapters = false);
Task<bool> DeleteSeriesAsync(int seriesId);
Task<Volume> GetVolumeByIdAsync(int volumeId);
Task<Series> GetSeriesByIdAsync(int seriesId);
Task<int[]> GetChapterIdsForSeriesAsync(int[] seriesIds);
+ Task<IDictionary<int, IList<int>>> GetChapterIdWithSeriesIdForSeriesAsync(int[] seriesIds);
/// <summary>
/// Used to add Progress/Rating information to series list.
/// </summary>
@@ -56,13 +59,15 @@ namespace API.Interfaces
/// <returns></returns>
Task AddSeriesModifiers(int userId, List<SeriesDto> series);
- Task<byte[]> GetVolumeCoverImageAsync(int volumeId);
- Task<byte[]> GetSeriesCoverImageAsync(int seriesId);
+
+ Task<string> GetSeriesCoverImageAsync(int seriesId);
Task<IEnumerable<SeriesDto>> GetInProgress(int userId, int libraryId, UserParams userParams, FilterDto filter);
Task<PagedList<SeriesDto>> GetRecentlyAdded(int libraryId, int userId, UserParams userParams, FilterDto filter);
Task<SeriesMetadataDto> GetSeriesMetadata(int seriesId);
Task<PagedList<SeriesDto>> GetSeriesDtoForCollectionAsync(int collectionId, int userId, UserParams userParams);
Task<IList<MangaFile>> GetFilesForSeries(int seriesId);
Task<IEnumerable<SeriesDto>> GetSeriesDtoForIdsAsync(IEnumerable<int> seriesIds, int userId);
+ Task<IList<string>> GetAllCoverImagesAsync();
+ Task<IEnumerable<string>> GetLockedCoverImagesAsync();
}
}
diff --git a/API/Interfaces/ISettingsRepository.cs b/API/Interfaces/Repositories/ISettingsRepository.cs
similarity index 90%
rename from API/Interfaces/ISettingsRepository.cs
rename to API/Interfaces/Repositories/ISettingsRepository.cs
index 5b0994d41..f1687743d 100644
--- a/API/Interfaces/ISettingsRepository.cs
+++ b/API/Interfaces/Repositories/ISettingsRepository.cs
@@ -4,7 +4,7 @@ using API.DTOs;
using API.Entities;
using API.Entities.Enums;
-namespace API.Interfaces
+namespace API.Interfaces.Repositories
{
public interface ISettingsRepository
{
@@ -12,6 +12,6 @@ namespace API.Interfaces
Task<ServerSettingDto> GetSettingsDtoAsync();
Task<ServerSetting> GetSettingAsync(ServerSettingKey key);
Task<IEnumerable<ServerSetting>> GetSettingsAsync();
-
+
}
-}
\ No newline at end of file
+}
diff --git a/API/Interfaces/IUserRepository.cs b/API/Interfaces/Repositories/IUserRepository.cs
similarity index 58%
rename from API/Interfaces/IUserRepository.cs
rename to API/Interfaces/Repositories/IUserRepository.cs
index c58eafdfc..22bd9dc92 100644
--- a/API/Interfaces/IUserRepository.cs
+++ b/API/Interfaces/Repositories/IUserRepository.cs
@@ -1,26 +1,31 @@
using System.Collections.Generic;
using System.Threading.Tasks;
+using API.Data.Repositories;
using API.DTOs;
+using API.DTOs.Reader;
using API.Entities;
-namespace API.Interfaces
+namespace API.Interfaces.Repositories
{
public interface IUserRepository
{
void Update(AppUser user);
void Update(AppUserPreferences preferences);
+ void Update(AppUserBookmark bookmark);
public void Delete(AppUser user);
- Task<AppUser> GetUserByUsernameAsync(string username);
- Task<AppUser> GetUserByIdAsync(int id);
Task<IEnumerable<MemberDto>> GetMembersAsync();
Task<IEnumerable<AppUser>> GetAdminUsersAsync();
Task<AppUserRating> GetUserRating(int seriesId, int userId);
- void AddRatingTracking(AppUserRating userRating);
Task<AppUserPreferences> GetPreferencesAsync(string username);
Task<IEnumerable<BookmarkDto>> GetBookmarkDtosForSeries(int userId, int seriesId);
Task<IEnumerable<BookmarkDto>> GetBookmarkDtosForVolume(int userId, int volumeId);
Task<IEnumerable<BookmarkDto>> GetBookmarkDtosForChapter(int userId, int chapterId);
Task<IEnumerable<BookmarkDto>> GetAllBookmarkDtos(int userId);
- Task<AppUser> GetUserByApiKeyAsync(string apiKey);
+ Task<AppUserBookmark> GetBookmarkForPage(int page, int chapterId, int userId);
+ Task<int> GetUserIdByApiKeyAsync(string apiKey);
+ Task<AppUser> GetUserByUsernameAsync(string username, AppUserIncludes includeFlags = AppUserIncludes.None);
+ Task<AppUser> GetUserByIdAsync(int userId, AppUserIncludes includeFlags = AppUserIncludes.None);
+ Task<int> GetUserIdByUsernameAsync(string username);
+ Task<AppUser> GetUserWithReadingListsByUsernameAsync(string username);
}
}
diff --git a/API/Interfaces/Repositories/IVolumeRepository.cs b/API/Interfaces/Repositories/IVolumeRepository.cs
new file mode 100644
index 000000000..62ec0ef9a
--- /dev/null
+++ b/API/Interfaces/Repositories/IVolumeRepository.cs
@@ -0,0 +1,15 @@
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using API.DTOs;
+using API.Entities;
+
+namespace API.Interfaces.Repositories
+{
+ public interface IVolumeRepository
+ {
+ void Update(Volume volume);
+ Task<IList<MangaFile>> GetFilesForVolume(int volumeId);
+ Task<string> GetVolumeCoverImageAsync(int volumeId);
+ Task<IList<int>> GetChapterIdsByVolumeIds(IReadOnlyList<int> volumeIds);
+ }
+}
diff --git a/API/Interfaces/Services/IArchiveService.cs b/API/Interfaces/Services/IArchiveService.cs
index 07c1e287d..ae9bddc98 100644
--- a/API/Interfaces/Services/IArchiveService.cs
+++ b/API/Interfaces/Services/IArchiveService.cs
@@ -10,7 +10,7 @@ namespace API.Interfaces.Services
{
void ExtractArchive(string archivePath, string extractPath);
int GetNumberOfPagesFromArchive(string archivePath);
- byte[] GetCoverImage(string archivePath, bool createThumbnail = false);
+ string GetCoverImage(string archivePath, string fileName);
bool IsValidArchive(string archivePath);
string GetSummaryInfo(string archivePath);
ArchiveLibrary CanOpen(string archivePath);
diff --git a/API/Interfaces/Services/IBackupService.cs b/API/Interfaces/Services/IBackupService.cs
index eaa140e46..315b852f0 100644
--- a/API/Interfaces/Services/IBackupService.cs
+++ b/API/Interfaces/Services/IBackupService.cs
@@ -1,11 +1,12 @@
using System.Collections.Generic;
+using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace API.Interfaces.Services
{
public interface IBackupService
{
- void BackupDatabase();
+ Task BackupDatabase();
/// <summary>
/// Returns a list of full paths of the logs files detailed in <see cref="IConfiguration"/>.
/// </summary>
diff --git a/API/Interfaces/Services/IBookService.cs b/API/Interfaces/Services/IBookService.cs
index b3afc13a8..cde2cad8e 100644
--- a/API/Interfaces/Services/IBookService.cs
+++ b/API/Interfaces/Services/IBookService.cs
@@ -8,7 +8,7 @@ namespace API.Interfaces.Services
public interface IBookService
{
int GetNumberOfPages(string filePath);
- byte[] GetCoverImage(string fileFilePath, bool createThumbnail = true);
+ string GetCoverImage(string fileFilePath, string fileName);
Task<Dictionary<string, int>> CreateKeyToPageMappingAsync(EpubBookRef book);
/// <summary>
diff --git a/API/Interfaces/Services/ICleanupService.cs b/API/Interfaces/Services/ICleanupService.cs
index da61943fe..afabb9900 100644
--- a/API/Interfaces/Services/ICleanupService.cs
+++ b/API/Interfaces/Services/ICleanupService.cs
@@ -1,7 +1,10 @@
-namespace API.Interfaces.Services
+using System.Threading.Tasks;
+
+namespace API.Interfaces.Services
{
public interface ICleanupService
{
- void Cleanup();
+ Task Cleanup();
+ void CleanupCacheDirectory();
}
-}
\ No newline at end of file
+}
diff --git a/API/Interfaces/Services/IImageService.cs b/API/Interfaces/Services/IImageService.cs
index 86f6fa489..0aba07f39 100644
--- a/API/Interfaces/Services/IImageService.cs
+++ b/API/Interfaces/Services/IImageService.cs
@@ -1,22 +1,23 @@
using API.Entities;
+using API.Services;
namespace API.Interfaces.Services
{
public interface IImageService
{
- byte[] GetCoverImage(string path, bool createThumbnail = false);
+ string GetCoverImage(string path, string fileName);
string GetCoverFile(MangaFile file);
/// <summary>
/// Creates a Thumbnail version of an image
/// </summary>
/// <param name="path">Path to the image file</param>
- /// <returns></returns>
- public byte[] CreateThumbnail(string path);
+ /// <returns>File name with extension of the file. This will always write to <see cref="DirectoryService.CoverImageDirectory"/></returns>
+ public string CreateThumbnail(string path, string fileName);
/// <summary>
/// Creates a Thumbnail version of a base64 image
/// </summary>
/// <param name="encodedImage">base64 encoded image</param>
- /// <returns></returns>
- public byte[] CreateThumbnailFromBase64(string encodedImage);
+ /// <returns>File name with extension of the file. This will always write to <see cref="DirectoryService.CoverImageDirectory"/></returns>
+ public string CreateThumbnailFromBase64(string encodedImage, string fileName);
}
}
diff --git a/API/Interfaces/Services/IMetadataService.cs b/API/Interfaces/Services/IMetadataService.cs
index 70b10b861..6d4d725cf 100644
--- a/API/Interfaces/Services/IMetadataService.cs
+++ b/API/Interfaces/Services/IMetadataService.cs
@@ -1,4 +1,5 @@
-using API.Entities;
+using System.Threading.Tasks;
+using API.Entities;
namespace API.Interfaces.Services
{
@@ -9,16 +10,16 @@ namespace API.Interfaces.Services
/// </summary>
/// <param name="libraryId"></param>
/// <param name="forceUpdate"></param>
- void RefreshMetadata(int libraryId, bool forceUpdate = false);
+ Task RefreshMetadata(int libraryId, bool forceUpdate = false);
- public void UpdateMetadata(Chapter chapter, bool forceUpdate);
- public void UpdateMetadata(Volume volume, bool forceUpdate);
- public void UpdateMetadata(Series series, bool forceUpdate);
+ public bool UpdateMetadata(Chapter chapter, bool forceUpdate);
+ public bool UpdateMetadata(Volume volume, bool forceUpdate);
+ public bool UpdateMetadata(Series series, bool forceUpdate);
/// <summary>
/// Performs a forced refresh of metatdata just for a series and it's nested entities
/// </summary>
/// <param name="libraryId"></param>
/// <param name="seriesId"></param>
- void RefreshMetadataForSeries(int libraryId, int seriesId);
+ Task RefreshMetadataForSeries(int libraryId, int seriesId, bool forceUpdate = false);
}
-}
\ No newline at end of file
+}
diff --git a/API/Interfaces/Services/IReaderService.cs b/API/Interfaces/Services/IReaderService.cs
index 5bb9baeb1..a72b90699 100644
--- a/API/Interfaces/Services/IReaderService.cs
+++ b/API/Interfaces/Services/IReaderService.cs
@@ -1,4 +1,5 @@
-using System.Threading.Tasks;
+using System.Collections.Generic;
+using System.Threading.Tasks;
using API.DTOs;
using API.Entities;
@@ -6,6 +7,11 @@ namespace API.Interfaces.Services
{
public interface IReaderService
{
- Task<bool> SaveReadingProgress(ProgressDto progressDto, AppUser user);
+ void MarkChaptersAsRead(AppUser user, int seriesId, IEnumerable<Chapter> chapters);
+ void MarkChaptersAsUnread(AppUser user, int seriesId, IEnumerable<Chapter> chapters);
+ Task<bool> SaveReadingProgress(ProgressDto progressDto, int userId);
+ Task<int> CapPageToChapter(int chapterId, int page);
+ Task<int> GetNextChapterIdAsync(int seriesId, int volumeId, int currentChapterId, int userId);
+ Task<int> GetPrevChapterIdAsync(int seriesId, int volumeId, int currentChapterId, int userId);
}
}
diff --git a/API/Interfaces/Services/IScannerService.cs b/API/Interfaces/Services/IScannerService.cs
index d235adfb5..b67290bfc 100644
--- a/API/Interfaces/Services/IScannerService.cs
+++ b/API/Interfaces/Services/IScannerService.cs
@@ -12,8 +12,8 @@ namespace API.Interfaces.Services
/// </summary>
/// <param name="libraryId">Library to scan against</param>
/// <param name="forceUpdate">Force overwriting for cover images</param>
- void ScanLibrary(int libraryId, bool forceUpdate);
- void ScanLibraries();
+ Task ScanLibrary(int libraryId, bool forceUpdate);
+ Task ScanLibraries();
Task ScanSeries(int libraryId, int seriesId, bool forceUpdate, CancellationToken token);
}
}
diff --git a/API/Interfaces/Services/ReaderService.cs b/API/Interfaces/Services/ReaderService.cs
index f71a10a7a..eaa3b96d7 100644
--- a/API/Interfaces/Services/ReaderService.cs
+++ b/API/Interfaces/Services/ReaderService.cs
@@ -1,51 +1,146 @@

using System;
using System.Collections.Generic;
+using System.Data;
using System.Linq;
using System.Threading.Tasks;
+using API.Comparators;
+using API.Data.Repositories;
using API.DTOs;
using API.Entities;
+using Microsoft.Extensions.Logging;
namespace API.Interfaces.Services
{
public class ReaderService : IReaderService
{
private readonly IUnitOfWork _unitOfWork;
+ private readonly ILogger<ReaderService> _logger;
+ private readonly ChapterSortComparer _chapterSortComparer = new ChapterSortComparer();
+ private readonly ChapterSortComparerZeroFirst _chapterSortComparerForInChapterSorting = new ChapterSortComparerZeroFirst();
- public ReaderService(IUnitOfWork unitOfWork)
+ public ReaderService(IUnitOfWork unitOfWork, ILogger<ReaderService> logger)
{
_unitOfWork = unitOfWork;
+ _logger = logger;
}
/// <summary>
- /// Saves progress to DB
+ /// Marks all Chapters as Read by creating or updating UserProgress rows. Does not commit.
/// </summary>
- /// <param name="progressDto"></param>
/// <param name="user"></param>
- /// <returns></returns>
- public async Task<bool> SaveReadingProgress(ProgressDto progressDto, AppUser user)
+ /// <param name="seriesId"></param>
+ /// <param name="chapters"></param>
+ public void MarkChaptersAsRead(AppUser user, int seriesId, IEnumerable<Chapter> chapters)
{
- // Don't let user save past total pages.
- var chapter = await _unitOfWork.VolumeRepository.GetChapterAsync(progressDto.ChapterId);
- if (progressDto.PageNum > chapter.Pages)
+ foreach (var chapter in chapters)
{
- progressDto.PageNum = chapter.Pages;
+ var userProgress = GetUserProgressForChapter(user, chapter);
+
+ if (userProgress == null)
+ {
+ user.Progresses.Add(new AppUserProgress
+ {
+ PagesRead = chapter.Pages,
+ VolumeId = chapter.VolumeId,
+ SeriesId = seriesId,
+ ChapterId = chapter.Id
+ });
+ }
+ else
+ {
+ userProgress.PagesRead = chapter.Pages;
+ userProgress.SeriesId = seriesId;
+ userProgress.VolumeId = chapter.VolumeId;
+ }
}
+ }
- if (progressDto.PageNum < 0)
+ /// <summary>
+ /// Marks all Chapters as Unread by creating or updating UserProgress rows. Does not commit.
+ /// </summary>
+ /// <param name="user"></param>
+ /// <param name="seriesId"></param>
+ /// <param name="chapters"></param>
+ public void MarkChaptersAsUnread(AppUser user, int seriesId, IEnumerable<Chapter> chapters)
+ {
+ foreach (var chapter in chapters)
{
- progressDto.PageNum = 0;
+ var userProgress = GetUserProgressForChapter(user, chapter);
+
+ if (userProgress == null)
+ {
+ user.Progresses.Add(new AppUserProgress
+ {
+ PagesRead = 0,
+ VolumeId = chapter.VolumeId,
+ SeriesId = seriesId,
+ ChapterId = chapter.Id
+ });
+ }
+ else
+ {
+ userProgress.PagesRead = 0;
+ userProgress.SeriesId = seriesId;
+ userProgress.VolumeId = chapter.VolumeId;
+ }
}
+ }
+
+ /// <summary>
+ /// Gets the User Progress for a given Chapter. This will handle any duplicates that might have occured in past versions and will delete them. Does not commit.
+ /// </summary>
+ /// <param name="user"></param>
+ /// <param name="chapter"></param>
+ /// <returns></returns>
+ public static AppUserProgress GetUserProgressForChapter(AppUser user, Chapter chapter)
+ {
+ AppUserProgress userProgress = null;
+ try
+ {
+ userProgress =
+ user.Progresses.SingleOrDefault(x => x.ChapterId == chapter.Id && x.AppUserId == user.Id);
+ }
+ catch (Exception)
+ {
+ // There is a very rare chance that user progress will duplicate current row. If that happens delete one with less pages
+ var progresses = user.Progresses.Where(x => x.ChapterId == chapter.Id && x.AppUserId == user.Id).ToList();
+ if (progresses.Count > 1)
+ {
+ user.Progresses = new List<AppUserProgress>()
+ {
+ user.Progresses.First()
+ };
+ userProgress = user.Progresses.First();
+ }
+ }
+
+ return userProgress;
+ }
+
+ /// <summary>
+ /// Saves progress to DB
+ /// </summary>
+ /// <param name="progressDto"></param>
+ /// <param name="userId"></param>
+ /// <returns></returns>
+ public async Task<bool> SaveReadingProgress(ProgressDto progressDto, int userId)
+ {
+ // Don't let user save past total pages.
+ progressDto.PageNum = await CapPageToChapter(progressDto.ChapterId, progressDto.PageNum);
try
{
- user.Progresses ??= new List<AppUserProgress>();
var userProgress =
- user.Progresses.FirstOrDefault(x => x.ChapterId == progressDto.ChapterId && x.AppUserId == user.Id);
+ await _unitOfWork.AppUserProgressRepository.GetUserProgressAsync(progressDto.ChapterId, userId);
if (userProgress == null)
{
- user.Progresses.Add(new AppUserProgress
+ // Create a user object
+ var userWithProgress =
+ await _unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.Progress);
+ userWithProgress.Progresses ??= new List<AppUserProgress>();
+ userWithProgress.Progresses.Add(new AppUserProgress
{
PagesRead = progressDto.PageNum,
VolumeId = progressDto.VolumeId,
@@ -54,6 +149,7 @@ namespace API.Interfaces.Services
BookScrollId = progressDto.BookScrollId,
LastModified = DateTime.Now
});
+ _unitOfWork.UserRepository.Update(userWithProgress);
}
else
{
@@ -62,21 +158,154 @@ namespace API.Interfaces.Services
userProgress.VolumeId = progressDto.VolumeId;
userProgress.BookScrollId = progressDto.BookScrollId;
userProgress.LastModified = DateTime.Now;
+ _unitOfWork.AppUserProgressRepository.Update(userProgress);
}
- _unitOfWork.UserRepository.Update(user);
-
if (await _unitOfWork.CommitAsync())
{
return true;
}
}
- catch (Exception)
+ catch (Exception exception)
{
+ _logger.LogError(exception, "Could not save progress");
await _unitOfWork.RollbackAsync();
}
return false;
}
+
+ /// <summary>
+ /// Ensures that the page is within 0 and total pages for a chapter. Makes one DB call.
+ /// </summary>
+ /// <param name="chapterId"></param>
+ /// <param name="page"></param>
+ /// <returns></returns>
+ public async Task<int> CapPageToChapter(int chapterId, int page)
+ {
+ var totalPages = await _unitOfWork.ChapterRepository.GetChapterTotalPagesAsync(chapterId);
+ if (page > totalPages)
+ {
+ page = totalPages;
+ }
+
+ if (page < 0)
+ {
+ page = 0;
+ }
+
+ return page;
+ }
+
+ /// <summary>
+ /// Tries to find the next logical Chapter
+ /// </summary>
+ /// <example>
+ /// V1 → V2 → V3 chapter 0 → V3 chapter 10 → SP 01 → SP 02
+ /// </example>
+ /// <param name="seriesId"></param>
+ /// <param name="volumeId"></param>
+ /// <param name="currentChapterId"></param>
+ /// <param name="userId"></param>
+ /// <returns>-1 if nothing can be found</returns>
+ public async Task<int> GetNextChapterIdAsync(int seriesId, int volumeId, int currentChapterId, int userId)
+ {
+ var volumes = (await _unitOfWork.SeriesRepository.GetVolumesDtoAsync(seriesId, userId)).ToList();
+ var currentVolume = volumes.Single(v => v.Id == volumeId);
+ var currentChapter = currentVolume.Chapters.Single(c => c.Id == currentChapterId);
+
+ if (currentVolume.Number == 0)
+ {
+ // Handle specials by sorting on their Filename aka Range
+ var chapterId = GetNextChapterId(currentVolume.Chapters.OrderBy(x => x.Range, new NaturalSortComparer()), currentChapter.Number);
+ if (chapterId > 0) return chapterId;
+ }
+
+ foreach (var volume in volumes)
+ {
+ if (volume.Number == currentVolume.Number && volume.Chapters.Count > 1)
+ {
+ // Handle Chapters within current Volume
+ // In this case, i need 0 first because 0 represents a full volume file.
+ var chapterId = GetNextChapterId(currentVolume.Chapters.OrderBy(x => double.Parse(x.Number), _chapterSortComparerForInChapterSorting), currentChapter.Number);
+ if (chapterId > 0) return chapterId;
+ }
+
+ if (volume.Number != currentVolume.Number + 1) continue;
+
+ // Handle Chapters within next Volume
+ // ! When selecting the chapter for the next volume, we need to make sure a c0 comes before a c1+
+ var chapters = volume.Chapters.OrderBy(x => double.Parse(x.Number), _chapterSortComparer).ToList();
+ if (currentChapter.Number.Equals("0") && chapters.Last().Number.Equals("0"))
+ {
+ return chapters.Last().Id;
+ }
+
+ var firstChapter = chapters.FirstOrDefault();
+ if (firstChapter == null) return -1;
+ return firstChapter.Id;
+
+ }
+
+ return -1;
+ }
+ /// <summary>
+ /// Tries to find the prev logical Chapter
+ /// </summary>
+ /// <example>
+ /// V1 ← V2 ← V3 chapter 0 ← V3 chapter 10 ← SP 01 ← SP 02
+ /// </example>
+ /// <param name="seriesId"></param>
+ /// <param name="volumeId"></param>
+ /// <param name="currentChapterId"></param>
+ /// <param name="userId"></param>
+ /// <returns>-1 if nothing can be found</returns>
+ public async Task<int> GetPrevChapterIdAsync(int seriesId, int volumeId, int currentChapterId, int userId)
+ {
+ var volumes = (await _unitOfWork.SeriesRepository.GetVolumesDtoAsync(seriesId, userId)).Reverse().ToList();
+ var currentVolume = volumes.Single(v => v.Id == volumeId);
+ var currentChapter = currentVolume.Chapters.Single(c => c.Id == currentChapterId);
+
+ if (currentVolume.Number == 0)
+ {
+ var chapterId = GetNextChapterId(currentVolume.Chapters.OrderBy(x => x.Range, new NaturalSortComparer()).Reverse(), currentChapter.Number);
+ if (chapterId > 0) return chapterId;
+ }
+
+ foreach (var volume in volumes)
+ {
+ if (volume.Number == currentVolume.Number)
+ {
+ var chapterId = GetNextChapterId(currentVolume.Chapters.OrderBy(x => double.Parse(x.Number), _chapterSortComparerForInChapterSorting).Reverse(), currentChapter.Number);
+ if (chapterId > 0) return chapterId;
+ }
+ if (volume.Number == currentVolume.Number - 1)
+ {
+ var lastChapter = volume.Chapters
+ .OrderBy(x => double.Parse(x.Number), _chapterSortComparerForInChapterSorting).LastOrDefault();
+ if (lastChapter == null) return -1;
+ return lastChapter.Id;
+ }
+ }
+ return -1;
+ }
+
+ private static int GetNextChapterId(IEnumerable<ChapterDto> chapters, string currentChapterNumber)
+ {
+ var next = false;
+ var chaptersList = chapters.ToList();
+ foreach (var chapter in chaptersList)
+ {
+ if (next)
+ {
+ return chapter.Id;
+ }
+ if (currentChapterNumber.Equals(chapter.Number)) next = true;
+ }
+
+ return -1;
+ }
+
+
}
}
diff --git a/API/Parser/Parser.cs b/API/Parser/Parser.cs
index b7b4ee8eb..0650faf4a 100644
--- a/API/Parser/Parser.cs
+++ b/API/Parser/Parser.cs
@@ -13,7 +13,7 @@ namespace API.Parser
public const string DefaultVolume = "0";
private static readonly TimeSpan RegexTimeout = TimeSpan.FromMilliseconds(500);
- public const string ImageFileExtensions = @"^(\.png|\.jpeg|\.jpg)";
+ public const string ImageFileExtensions = @"^(\.png|\.jpeg|\.jpg|\.webp)";
public const string ArchiveFileExtensions = @"\.cbz|\.zip|\.rar|\.cbr|\.tar.gz|\.7zip|\.7z|\.cb7|\.cbt";
public const string BookFileExtensions = @"\.epub|\.pdf";
public const string MacOsMetadataFileStartsWith = @"._";
@@ -102,11 +102,17 @@ namespace API.Parser
@"^(?<Series>.*)( |_)Vol\.?(\d+|tbd)",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
+ // Mad Chimera World - Volume 005 - Chapter 026.cbz (couldn't figure out how to get Volume negative lookaround working on below regex),
+ // The Duke of Death and His Black Maid - Vol. 04 Ch. 054.5 - V4 Omake
+ new Regex(
+ @"(?<Series>.+?)(\s|_|-)+(?:Vol(ume|\.)?(\s|_|-)+\d+)(\s|_|-)+(?:(Ch|Chapter|Ch)\.?)(\s|_|-)+(?<Chapter>\d+)",
+ RegexOptions.IgnoreCase | RegexOptions.Compiled,
+ RegexTimeout),
// Ichiban_Ushiro_no_Daimaou_v04_ch34_[VISCANS].zip, VanDread-v01-c01.zip
new Regex(
- @"(?<Series>.*)(\b|_)v(?<Volume>\d+-?\d*)(\s|_|-)",
- RegexOptions.IgnoreCase | RegexOptions.Compiled,
- RegexTimeout),
+ @"(?<Series>.*)(\b|_)v(?<Volume>\d+-?\d*)(\s|_|-)",
+ RegexOptions.IgnoreCase | RegexOptions.Compiled,
+ RegexTimeout),
// Gokukoku no Brynhildr - c001-008 (v01) [TrinityBAKumA], Black Bullet - v4 c17 [batoto]
new Regex(
@"(?<Series>.*)( - )(?:v|vo|c)\d",
@@ -117,11 +123,6 @@ namespace API.Parser
@"(?<Series>.*)(?:, Chapter )(?<Chapter>\d+)",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
- // Mad Chimera World - Volume 005 - Chapter 026.cbz (couldn't figure out how to get Volume negative lookaround working on below regex)
- new Regex(
- @"(?<Series>.*)(\s|_|-)(?:Volume(\s|_|-)+\d+)(\s|_|-)+(?:Chapter)(\s|_|-)(?<Chapter>\d+)",
- RegexOptions.IgnoreCase | RegexOptions.Compiled,
- RegexTimeout),
// Please Go Home, Akutsu-San! - Chapter 038.5 - Volume Announcement.cbz
new Regex(
@"(?<Series>.*)(\s|_|-)(?!Vol)(\s|_|-)(?:Chapter)(\s|_|-)(?<Chapter>\d+)",
@@ -129,9 +130,14 @@ namespace API.Parser
RegexTimeout),
// [dmntsf.net] One Piece - Digital Colored Comics Vol. 20 Ch. 177 - 30 Million vs 81 Million.cbz
new Regex(
- @"(?<Series>.*) (\b|_|-)(vol)\.?",
+ @"(?<Series>.*) (\b|_|-)(vol)\.?(\s|-|_)?\d+",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
+ // [xPearse] Kyochuu Rettou Volume 1 [English] [Manga] [Volume Scans]
+ new Regex(
+ @"(?<Series>.*) (\b|_|-)(vol)(ume)",
+ RegexOptions.IgnoreCase | RegexOptions.Compiled,
+ RegexTimeout),
//Knights of Sidonia c000 (S2 LE BD Omake - BLAME!) [Habanero Scans]
new Regex(
@"(?<Series>.*)(\bc\d+\b)",
@@ -144,7 +150,7 @@ namespace API.Parser
RegexTimeout),
// Momo The Blood Taker - Chapter 027 Violent Emotion.cbz, Grand Blue Dreaming - SP02 Extra (2019) (Digital) (danke-Empire).cbz
new Regex(
- @"(?<Series>.*)(\b|_|-|\s)(?:(chapter(\b|_|-|\s))|sp)\d",
+ @"^(?<Series>(?!Vol).+?)(?:(ch(apter|\.)(\b|_|-|\s))|sp)\d",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
// Historys Strongest Disciple Kenichi_v11_c90-98.zip, Killing Bites Vol. 0001 Ch. 0001 - Galactica Scanlations (gb)
@@ -240,9 +246,9 @@ namespace API.Parser
@"(?<Series>.*)(\s|_|-)#",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
- // Baketeriya ch01-05.zip, Akiiro Bousou Biyori - 01.jpg, Beelzebub_172_RHS.zip, Cynthia the Mission 29.rar
+ // Baketeriya ch01-05.zip, Akiiro Bousou Biyori - 01.jpg, Beelzebub_172_RHS.zip, Cynthia the Mission 29.rar, A Compendium of Ghosts - 031 - The Third Story_ Part 12 (Digital) (Cobalt001)
new Regex(
- @"^(?!Vol\.?)(?<Series>.*)( |_|-)(?<!-)(ch)?\d+-?\d*",
+ @"^(?!Vol\.?)(?<Series>.+?)( |_|-)(?<!-)(ch)?\d+-?\d*",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
// [BAA]_Darker_than_Black_c1 (This is very greedy, make sure it's close to last)
@@ -289,9 +295,14 @@ namespace API.Parser
@"^(?<Series>.*)(?: |_)i(ssue) #\d+",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
+ // Batman Wayne Family Adventures - Ep. 001 - Moving In
+ new Regex(
+ @"^(?<Series>.+?)(\s|_|-)?(?:Ep\.?)(\s|_|-)+\d+",
+ RegexOptions.IgnoreCase | RegexOptions.Compiled,
+ RegexTimeout),
// Batman & Catwoman - Trail of the Gun 01, Batman & Grendel (1996) 01 - Devil's Bones, Teen Titans v1 001 (1966-02) (digital) (OkC.O.M.P.U.T.O.-Novus)
new Regex(
- @"^(?<Series>.*)(?: \d+)",
+ @"^(?<Series>.+?)(?: \d+)",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
// Batman & Robin the Teen Wonder #0
@@ -318,78 +329,91 @@ namespace API.Parser
private static readonly Regex[] ComicVolumeRegex = new[]
{
- // 04 - Asterix the Gladiator (1964) (Digital-Empire) (WebP by Doc MaKS)
- new Regex(
- @"^(?<Volume>\d+) (- |_)?(?<Series>.*(\d{4})?)( |_)(\(|\d+)",
- RegexOptions.IgnoreCase | RegexOptions.Compiled,
- RegexTimeout),
- // 01 Spider-Man & Wolverine 01.cbr
- new Regex(
- @"^(?<Volume>\d+) (?:- )?(?<Series>.*) (\d+)?",
- RegexOptions.IgnoreCase | RegexOptions.Compiled,
- RegexTimeout),
- // Batman & Wildcat (1 of 3)
- new Regex(
- @"(?<Series>.*(\d{4})?)( |_)(?:\((?<Chapter>\d+) of \d+)",
- RegexOptions.IgnoreCase | RegexOptions.Compiled,
- RegexTimeout),
+ // // 04 - Asterix the Gladiator (1964) (Digital-Empire) (WebP by Doc MaKS)
+ // new Regex(
+ // @"^(?<Volume>\d+) (- |_)?(?<Series>.*(\d{4})?)( |_)(\(|\d+)",
+ // RegexOptions.IgnoreCase | RegexOptions.Compiled,
+ // RegexTimeout),
+ // // 01 Spider-Man & Wolverine 01.cbr
+ // new Regex(
+ // @"^(?<Volume>\d+) (?:- )?(?<Series>.*) (\d+)?",
+ // RegexOptions.IgnoreCase | RegexOptions.Compiled,
+ // RegexTimeout),
+ // // Batman & Wildcat (1 of 3)
+ // new Regex(
+ // @"(?<Series>.*(\d{4})?)( |_)(?:\((?<Chapter>\d+) of \d+)",
+ // RegexOptions.IgnoreCase | RegexOptions.Compiled,
+ // RegexTimeout),
// Teen Titans v1 001 (1966-02) (digital) (OkC.O.M.P.U.T.O.-Novus)
new Regex(
@"^(?<Series>.*)(?: |_)v(?<Volume>\d+)",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
// Scott Pilgrim 02 - Scott Pilgrim vs. The World (2005)
- new Regex(
- @"^(?<Series>.*)(?<!c(hapter)|i(ssue))(?<!of)(?: |_)(?<!of )(?<Volume>\d+)",
- RegexOptions.IgnoreCase | RegexOptions.Compiled,
- RegexTimeout),
+ // BUG: Negative lookbehind has to be fixed width
+ // NOTE: The case this is built for does not make much sense.
+ // new Regex(
+ // @"^(?<Series>.+?)(?<!c(hapter)|i(ssue))(?<!of)(?: |_)(?<!of )(?<Volume>\d+)",
+ // RegexOptions.IgnoreCase | RegexOptions.Compiled,
+ // RegexTimeout),
+
// Batman & Catwoman - Trail of the Gun 01, Batman & Grendel (1996) 01 - Devil's Bones, Teen Titans v1 001 (1966-02) (digital) (OkC.O.M.P.U.T.O.-Novus)
- new Regex(
- @"^(?<Series>.*)(?<!c(hapter)|i(ssue))(?<!of)(?: (?<Volume>\d+))",
- RegexOptions.IgnoreCase | RegexOptions.Compiled,
- RegexTimeout),
- // Batman & Robin the Teen Wonder #0
- new Regex(
- @"^(?<Series>.*)(?: |_)#(?<Volume>\d+)",
- RegexOptions.IgnoreCase | RegexOptions.Compiled,
- RegexTimeout),
+ // new Regex(
+ // @"^(?<Series>.+?)(?<!c(hapter)|i(ssue))(?<!of)(?: (?<Volume>\d+))",
+ // RegexOptions.IgnoreCase | RegexOptions.Compiled,
+ // RegexTimeout),
+ // // Batman & Robin the Teen Wonder #0
+ // new Regex(
+ // @"^(?<Series>.*)(?: |_)#(?<Volume>\d+)",
+ // RegexOptions.IgnoreCase | RegexOptions.Compiled,
+ // RegexTimeout),
};
private static readonly Regex[] ComicChapterRegex = new[]
{
- // Batman & Wildcat (1 of 3)
+ // Batman & Wildcat (1 of 3)
new Regex(
@"(?<Series>.*(\d{4})?)( |_)(?:\((?<Chapter>\d+) of \d+)",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
+ // Batman Beyond 04 (of 6) (1999)
+ new Regex(
+ @"(?<Series>.+?)(?<Chapter>\d+)(\s|_|-)?\(of",
+ RegexOptions.IgnoreCase | RegexOptions.Compiled,
+ RegexTimeout),
// Teen Titans v1 001 (1966-02) (digital) (OkC.O.M.P.U.T.O.-Novus)
new Regex(
- @"^(?<Series>.*)(?: |_)v(?<Volume>\d+)(?: |_)(c? ?)(?<Chapter>(\d+(\.\d)?)-?(\d+(\.\d)?)?)(c? ?)",
+ @"^(?<Series>.+?)(?: |_)v(?<Volume>\d+)(?: |_)(c? ?)(?<Chapter>(\d+(\.\d)?)-?(\d+(\.\d)?)?)(c? ?)",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
+ // Invincible 070.5 - Invincible Returns 1 (2010) (digital) (Minutemen-InnerDemons).cbr
+ new Regex(
+ @"^(?<Series>.+?)(?: |_)(c? ?)(?<Chapter>(\d+(\.\d)?)-?(\d+(\.\d)?)?)(c? ?)-",
+ RegexOptions.IgnoreCase | RegexOptions.Compiled,
+ RegexTimeout),
// Batman & Catwoman - Trail of the Gun 01, Batman & Grendel (1996) 01 - Devil's Bones, Teen Titans v1 001 (1966-02) (digital) (OkC.O.M.P.U.T.O.-Novus)
new Regex(
- @"^(?<Series>.*)(?: (?<Volume>\d+))",
+ @"^(?<Series>.+?)(?: (?<Chapter>\d+))",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
// Batman & Robin the Teen Wonder #0
new Regex(
- @"^(?<Series>.*)(?: |_)#(?<Volume>\d+)",
+ @"^(?<Series>.+?)(?:\s|_)#(?<Chapter>\d+)",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
- // Invincible 070.5 - Invincible Returns 1 (2010) (digital) (Minutemen-InnerDemons).cbr
+ // Saga 001 (2012) (Digital) (Empire-Zone)
new Regex(
- @"^(?<Series>.*)(?: |_)(c? ?)(?<Chapter>(\d+(\.\d)?)-?(\d+(\.\d)?)?)(c? ?)-",
+ @"(?<Series>.+?)(?: |_)(c? ?)(?<Chapter>(\d+(\.\d)?)-?(\d+(\.\d)?)?)\s\(\d{4}",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
// Amazing Man Comics chapter 25
new Regex(
- @"^(?!Vol)(?<Series>.*)( |_)c(hapter)( |_)(?<Chapter>\d*)",
+ @"^(?!Vol)(?<Series>.+?)( |_)c(hapter)( |_)(?<Chapter>\d*)",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
// Amazing Man Comics issue #25
new Regex(
- @"^(?!Vol)(?<Series>.*)( |_)i(ssue)( |_) #(?<Chapter>\d*)",
+ @"^(?!Vol)(?<Series>.+?)( |_)i(ssue)( |_) #(?<Chapter>\d*)",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
};
@@ -422,14 +446,14 @@ namespace API.Parser
@"^(?<Series>.*)(?: |_)#(?<Chapter>\d+)",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
- // Green Worldz - Chapter 027
+ // Green Worldz - Chapter 027, Kimi no Koto ga Daidaidaidaidaisuki na 100-nin no Kanojo Chapter 11-10
new Regex(
- @"^(?!Vol)(?<Series>.*)\s?(?<!vol\. )\sChapter\s(?<Chapter>\d+(?:\.?[\d-])?)",
+ @"^(?!Vol)(?<Series>.*)\s?(?<!vol\. )\sChapter\s(?<Chapter>\d+(?:\.?[\d-]+)?)",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
// Hinowa ga CRUSH! 018 (2019) (Digital) (LuCaZ).cbz, Hinowa ga CRUSH! 018.5 (2019) (Digital) (LuCaZ).cbz
new Regex(
- @"^(?!Vol)(?<Series>.*)\s(?<!vol\. )(?<Chapter>\d+(?:.\d+|-\d+)?)(?:\s\(\d{4}\))?(\b|_|-)",
+ @"^(?!Vol)(?<Series>.+?)\s(?<!vol\. )(?<Chapter>\d+(?:.\d+|-\d+)?)(?:\s\(\d{4}\))?(\b|_|-)",
RegexOptions.IgnoreCase | RegexOptions.Compiled,
RegexTimeout),
// Tower Of God S01 014 (CBT) (digital).cbz
@@ -822,8 +846,14 @@ namespace API.Parser
var tokens = value.Split("-");
var from = RemoveLeadingZeroes(tokens[0]);
- var to = RemoveLeadingZeroes(hasChapterPart ? AddChapterPart(tokens[1]) : tokens[1]);
- return $"{@from}-{to}";
+ if (tokens.Length == 2)
+ {
+ var to = RemoveLeadingZeroes(hasChapterPart ? AddChapterPart(tokens[1]) : tokens[1]);
+ return $"{@from}-{to}";
+ }
+
+ return from;
+
}
}
@@ -919,6 +949,9 @@ namespace API.Parser
/// <summary>
/// Translates _ -> spaces, trims front and back of string, removes release groups
+ /// <example>
+ /// Hippos_the_Great [Digital], -> Hippos the Great
+ /// </example>
/// </summary>
/// <param name="title"></param>
/// <returns></returns>
@@ -931,7 +964,7 @@ namespace API.Parser
title = RemoveSpecialTags(title);
title = title.Replace("_", " ").Trim();
- if (title.EndsWith("-"))
+ if (title.EndsWith("-") || title.EndsWith(","))
{
title = title.Substring(0, title.Length - 1);
}
diff --git a/API/Program.cs b/API/Program.cs
index 6d91f6d98..eddc4cb4e 100644
--- a/API/Program.cs
+++ b/API/Program.cs
@@ -1,10 +1,17 @@
using System;
+using System.Collections.Generic;
+using System.Data;
using System.IO;
+using System.Linq;
using System.Security.Cryptography;
using System.Threading;
+using System.Threading.Channels;
using System.Threading.Tasks;
using API.Data;
using API.Entities;
+using API.Helpers;
+using API.Interfaces;
+using API.Services;
using Kavita.Common;
using Kavita.Common.EnvironmentInfo;
using Microsoft.AspNetCore.Hosting;
@@ -14,6 +21,8 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
+using Microsoft.IO;
+using NetVips;
using Sentry;
namespace API
@@ -49,8 +58,29 @@ namespace API
{
var context = services.GetRequiredService<DataContext>();
var roleManager = services.GetRequiredService<RoleManager<AppRole>>();
+
+ var requiresCoverImageMigration = !Directory.Exists(DirectoryService.CoverImageDirectory);
+ try
+ {
+ // If this is a new install, tables wont exist yet
+ if (requiresCoverImageMigration)
+ {
+ MigrateCoverImages.ExtractToImages(context);
+ }
+ }
+ catch (Exception )
+ {
+ requiresCoverImageMigration = false;
+ }
+
// Apply all migrations on startup
await context.Database.MigrateAsync();
+
+ if (requiresCoverImageMigration)
+ {
+ await MigrateCoverImages.UpdateDatabaseWithImages(context);
+ }
+
await Seed.SeedRoles(roleManager);
await Seed.SeedSettings(context);
await Seed.SeedUserApiKeys(context);
diff --git a/API/Services/ArchiveService.cs b/API/Services/ArchiveService.cs
index d8b381b60..bfa36595c 100644
--- a/API/Services/ArchiveService.cs
+++ b/API/Services/ArchiveService.cs
@@ -28,7 +28,6 @@ namespace API.Services
{
private readonly ILogger<ArchiveService> _logger;
private readonly IDirectoryService _directoryService;
- private static readonly RecyclableMemoryStreamManager StreamManager = new();
private readonly NaturalSortComparer _comparer;
private const string ComicInfoFilename = "comicinfo";
@@ -147,12 +146,13 @@ namespace API.Services
///
/// This skips over any __MACOSX folder/file iteration.
/// </summary>
+ /// <remarks>This always creates a thumbnail</remarks>
/// <param name="archivePath"></param>
- /// <param name="createThumbnail">Create a smaller variant of file extracted from archive. Archive images are usually 1MB each.</param>
+ /// <param name="fileName">File name to use based on context of entity.</param>
/// <returns></returns>
- public byte[] GetCoverImage(string archivePath, bool createThumbnail = false)
+ public string GetCoverImage(string archivePath, string fileName)
{
- if (archivePath == null || !IsValidArchive(archivePath)) return Array.Empty<byte>();
+ if (archivePath == null || !IsValidArchive(archivePath)) return String.Empty;
try
{
var libraryHandler = CanOpen(archivePath);
@@ -168,7 +168,7 @@ namespace API.Services
var entry = archive.Entries.Single(e => e.FullName == entryName);
using var stream = entry.Open();
- return createThumbnail ? CreateThumbnail(entry.FullName, stream) : ConvertEntryToByteArray(entry);
+ return CreateThumbnail(archivePath + " - " + entry.FullName, stream, fileName);
}
case ArchiveLibrary.SharpCompress:
{
@@ -179,18 +179,16 @@ namespace API.Services
var entryName = FindFolderEntry(entryNames) ?? FirstFileEntry(entryNames);
var entry = archive.Entries.Single(e => e.Key == entryName);
- using var ms = StreamManager.GetStream();
- entry.WriteTo(ms);
- ms.Position = 0;
+ using var stream = entry.OpenEntryStream();
- return createThumbnail ? CreateThumbnail(entry.Key, ms, Path.GetExtension(entry.Key)) : ms.ToArray();
+ return CreateThumbnail(archivePath + " - " + entry.Key, stream, fileName);
}
case ArchiveLibrary.NotSupported:
_logger.LogWarning("[GetCoverImage] This archive cannot be read: {ArchivePath}. Defaulting to no cover image", archivePath);
- return Array.Empty<byte>();
+ return string.Empty;
default:
_logger.LogWarning("[GetCoverImage] There was an exception when reading archive stream: {ArchivePath}. Defaulting to no cover image", archivePath);
- return Array.Empty<byte>();
+ return string.Empty;
}
}
catch (Exception ex)
@@ -198,15 +196,7 @@ namespace API.Services
_logger.LogWarning(ex, "[GetCoverImage] There was an exception when reading archive stream: {ArchivePath}. Defaulting to no cover image", archivePath);
}
- return Array.Empty<byte>();
- }
-
- private static byte[] ConvertEntryToByteArray(ZipArchiveEntry entry)
- {
- using var stream = entry.Open();
- using var ms = StreamManager.GetStream();
- stream.CopyTo(ms);
- return ms.ToArray();
+ return string.Empty;
}
/// <summary>
@@ -223,6 +213,7 @@ namespace API.Services
archive.Entries.Any(e => e.FullName.Contains(Path.AltDirectorySeparatorChar) && !Parser.Parser.HasBlacklistedFolderInPath(e.FullName));
}
+ // TODO: Refactor CreateZipForDownload to return the temp file so we can stream it from temp
public async Task<Tuple<byte[], string>> CreateZipForDownload(IEnumerable<string> files, string tempFolder)
{
var dateString = DateTime.Now.ToShortDateString().Replace("/", "_");
@@ -254,23 +245,18 @@ namespace API.Services
return Tuple.Create(fileBytes, zipPath);
}
- private byte[] CreateThumbnail(string entryName, Stream stream, string formatExtension = ".jpg")
+ private string CreateThumbnail(string entryName, Stream stream, string fileName)
{
- if (!formatExtension.StartsWith("."))
- {
- formatExtension = $".{formatExtension}";
- }
try
{
- using var thumbnail = Image.ThumbnailStream(stream, MetadataService.ThumbnailWidth);
- return thumbnail.WriteToBuffer(formatExtension);
+ return ImageService.WriteCoverThumbnail(stream, fileName);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "[GetCoverImage] There was an error and prevented thumbnail generation on {EntryName}. Defaulting to no cover image", entryName);
}
- return Array.Empty<byte>();
+ return string.Empty;
}
/// <summary>
@@ -303,9 +289,7 @@ namespace API.Services
&& !Parser.Parser.HasBlacklistedFolderInPath(entry.Key)
&& Parser.Parser.IsXml(entry.Key))
{
- using var ms = StreamManager.GetStream();
- entry.WriteTo(ms);
- ms.Position = 0;
+ using var ms = entry.OpenEntryStream();
var serializer = new XmlSerializer(typeof(ComicInfo));
var info = (ComicInfo) serializer.Deserialize(ms);
@@ -332,7 +316,7 @@ namespace API.Services
{
case ArchiveLibrary.Default:
{
- _logger.LogDebug("Using default compression handling");
+ _logger.LogTrace("Using default compression handling");
using var archive = ZipFile.OpenRead(archivePath);
var entry = archive.Entries.SingleOrDefault(x => !Parser.Parser.HasBlacklistedFolderInPath(x.FullName)
&& Path.GetFileNameWithoutExtension(x.Name)?.ToLower() == ComicInfoFilename
@@ -348,7 +332,7 @@ namespace API.Services
}
case ArchiveLibrary.SharpCompress:
{
- _logger.LogDebug("Using SharpCompress compression handling");
+ _logger.LogTrace("Using SharpCompress compression handling");
using var archive = ArchiveFactory.Open(archivePath);
info = FindComicInfoXml(archive.Entries.Where(entry => !entry.IsDirectory
&& !Parser.Parser.HasBlacklistedFolderInPath(Path.GetDirectoryName(entry.Key) ?? string.Empty)
diff --git a/API/Services/BookService.cs b/API/Services/BookService.cs
index 6c02b68db..6231de20a 100644
--- a/API/Services/BookService.cs
+++ b/API/Services/BookService.cs
@@ -4,6 +4,7 @@ using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
+using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
@@ -378,18 +379,25 @@ namespace API.Services
for (var pageNumber = 0; pageNumber < pages; pageNumber++)
{
GetPdfPage(docReader, pageNumber, stream);
- File.WriteAllBytes(Path.Combine(targetDirectory, "Page-" + pageNumber + ".png"), stream.ToArray());
+ using var fileStream = File.Create(Path.Combine(targetDirectory, "Page-" + pageNumber + ".png"));
+ stream.Seek(0, SeekOrigin.Begin);
+ stream.CopyTo(fileStream);
}
}
-
- public byte[] GetCoverImage(string fileFilePath, bool createThumbnail = true)
+ /// <summary>
+ /// Extracts the cover image to covers directory and returns file path back
+ /// </summary>
+ /// <param name="fileFilePath"></param>
+ /// <param name="fileName">Name of the new file.</param>
+ /// <returns></returns>
+ public string GetCoverImage(string fileFilePath, string fileName)
{
- if (!IsValidFile(fileFilePath)) return Array.Empty<byte>();
+ if (!IsValidFile(fileFilePath)) return String.Empty;
if (Parser.Parser.IsPdf(fileFilePath))
{
- return GetPdfCoverImage(fileFilePath, createThumbnail);
+ return GetPdfCoverImage(fileFilePath, fileName);
}
using var epubBook = EpubReader.OpenBook(fileFilePath);
@@ -402,47 +410,41 @@ namespace API.Services
?? epubBook.Content.Images.Values.FirstOrDefault(file => Parser.Parser.IsCoverImage(file.FileName))
?? epubBook.Content.Images.Values.FirstOrDefault();
- if (coverImageContent == null) return Array.Empty<byte>();
-
- if (!createThumbnail) return coverImageContent.ReadContent();
+ if (coverImageContent == null) return string.Empty;
using var stream = StreamManager.GetStream("BookService.GetCoverImage", coverImageContent.ReadContent());
- using var thumbnail = NetVips.Image.ThumbnailStream(stream, MetadataService.ThumbnailWidth);
- return thumbnail.WriteToBuffer(".jpg");
-
+ return ImageService.WriteCoverThumbnail(stream, fileName);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "[BookService] There was a critical error and prevented thumbnail generation on {BookFile}. Defaulting to no cover image", fileFilePath);
}
- return Array.Empty<byte>();
+ return string.Empty;
}
- private byte[] GetPdfCoverImage(string fileFilePath, bool createThumbnail)
- {
- try
- {
- using var docReader = DocLib.Instance.GetDocReader(fileFilePath, new PageDimensions(1080, 1920));
- if (docReader.GetPageCount() == 0) return Array.Empty<byte>();
- using var stream = StreamManager.GetStream("BookService.GetPdfPage");
- GetPdfPage(docReader, 0, stream);
+ private string GetPdfCoverImage(string fileFilePath, string fileName)
+ {
+ try
+ {
+ using var docReader = DocLib.Instance.GetDocReader(fileFilePath, new PageDimensions(1080, 1920));
+ if (docReader.GetPageCount() == 0) return string.Empty;
- if (!createThumbnail) return stream.ToArray();
+ using var stream = StreamManager.GetStream("BookService.GetPdfPage");
+ GetPdfPage(docReader, 0, stream);
- using var thumbnail = NetVips.Image.ThumbnailStream(stream, MetadataService.ThumbnailWidth);
- return thumbnail.WriteToBuffer(".png");
+ return ImageService.WriteCoverThumbnail(stream, fileName);
- }
- catch (Exception ex)
- {
- _logger.LogWarning(ex,
- "[BookService] There was a critical error and prevented thumbnail generation on {BookFile}. Defaulting to no cover image",
- fileFilePath);
- }
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex,
+ "[BookService] There was a critical error and prevented thumbnail generation on {BookFile}. Defaulting to no cover image",
+ fileFilePath);
+ }
- return Array.Empty<byte>();
+ return string.Empty;
}
private static void GetPdfPage(IDocReader docReader, int pageNumber, Stream stream)
diff --git a/API/Services/CacheService.cs b/API/Services/CacheService.cs
index 968abaa72..8decdeccd 100644
--- a/API/Services/CacheService.cs
+++ b/API/Services/CacheService.cs
@@ -67,7 +67,7 @@ namespace API.Services
public async Task<Chapter> Ensure(int chapterId)
{
EnsureCacheDirectory();
- var chapter = await _unitOfWork.VolumeRepository.GetChapterAsync(chapterId);
+ var chapter = await _unitOfWork.ChapterRepository.GetChapterAsync(chapterId);
var extractPath = GetCachePath(chapterId);
if (!Directory.Exists(extractPath))
@@ -192,7 +192,7 @@ namespace API.Services
{
// Calculate what chapter the page belongs to
var pagesSoFar = 0;
- var chapterFiles = chapter.Files ?? await _unitOfWork.VolumeRepository.GetFilesForChapterAsync(chapter.Id);
+ var chapterFiles = chapter.Files ?? await _unitOfWork.ChapterRepository.GetFilesForChapterAsync(chapter.Id);
foreach (var mangaFile in chapterFiles)
{
if (page <= (mangaFile.Pages + pagesSoFar))
diff --git a/API/Services/DirectoryService.cs b/API/Services/DirectoryService.cs
index 6d545ea21..360492303 100644
--- a/API/Services/DirectoryService.cs
+++ b/API/Services/DirectoryService.cs
@@ -19,6 +19,7 @@ namespace API.Services
public static readonly string TempDirectory = Path.Join(Directory.GetCurrentDirectory(), "temp");
public static readonly string LogDirectory = Path.Join(Directory.GetCurrentDirectory(), "logs");
public static readonly string CacheDirectory = Path.Join(Directory.GetCurrentDirectory(), "cache");
+ public static readonly string CoverImageDirectory = Path.Join(Directory.GetCurrentDirectory(), "covers");
public DirectoryService(ILogger<DirectoryService> logger)
{
@@ -305,6 +306,44 @@ namespace API.Services
}
+ /// <summary>
+ /// Finds the highest directories from a set of MangaFiles
+ /// </summary>
+ /// <param name="libraryFolders">List of top level folders which files belong to</param>
+ /// <param name="filePaths">List of file paths that belong to libraryFolders</param>
+ /// <returns></returns>
+ public static Dictionary<string, string> FindHighestDirectoriesFromFiles(IEnumerable<string> libraryFolders, IList<string> filePaths)
+ {
+ var stopLookingForDirectories = false;
+ var dirs = new Dictionary<string, string>();
+ foreach (var folder in libraryFolders)
+ {
+ if (stopLookingForDirectories) break;
+ foreach (var file in filePaths)
+ {
+ if (!file.Contains(folder)) continue;
+
+ var parts = GetFoldersTillRoot(folder, file).ToList();
+ if (parts.Count == 0)
+ {
+ // Break from all loops, we done, just scan folder.Path (library root)
+ dirs.Add(folder, string.Empty);
+ stopLookingForDirectories = true;
+ break;
+ }
+
+ var fullPath = Path.Join(folder, parts.Last());
+ if (!dirs.ContainsKey(fullPath))
+ {
+ dirs.Add(fullPath, string.Empty);
+ }
+ }
+ }
+
+ return dirs;
+ }
+
+
/// <summary>
/// Recursively scans files and applies an action on them. This uses as many cores the underlying PC has to speed
/// up processing.
diff --git a/API/Services/DownloadService.cs b/API/Services/DownloadService.cs
index 6013d5c84..7d0f56b3d 100644
--- a/API/Services/DownloadService.cs
+++ b/API/Services/DownloadService.cs
@@ -4,7 +4,6 @@ using System.Linq;
using System.Threading.Tasks;
using API.Entities;
using API.Interfaces.Services;
-using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
namespace API.Services
diff --git a/API/Services/ImageService.cs b/API/Services/ImageService.cs
index cc4d92742..0f0f3aa16 100644
--- a/API/Services/ImageService.cs
+++ b/API/Services/ImageService.cs
@@ -14,13 +14,20 @@ namespace API.Services
{
private readonly ILogger<ImageService> _logger;
private readonly IDirectoryService _directoryService;
- private readonly NaturalSortComparer _naturalSortComparer;
+ public const string ChapterCoverImageRegex = @"v\d+_c\d+";
+ public const string SeriesCoverImageRegex = @"seres\d+";
+ public const string CollectionTagCoverImageRegex = @"tag\d+";
+
+
+ /// <summary>
+ /// Width of the Thumbnail generation
+ /// </summary>
+ private const int ThumbnailWidth = 320;
public ImageService(ILogger<ImageService> logger, IDirectoryService directoryService)
{
_logger = logger;
_directoryService = directoryService;
- _naturalSortComparer = new NaturalSortComparer();
}
/// <summary>
@@ -38,68 +45,108 @@ namespace API.Services
}
var firstImage = _directoryService.GetFilesWithExtension(directory, Parser.Parser.ImageFileExtensions)
- .OrderBy(f => f, _naturalSortComparer).FirstOrDefault();
+ .OrderBy(f => f, new NaturalSortComparer()).FirstOrDefault();
return firstImage;
}
- public byte[] GetCoverImage(string path, bool createThumbnail = false)
+ public string GetCoverImage(string path, string fileName)
{
- if (string.IsNullOrEmpty(path)) return Array.Empty<byte>();
+ if (string.IsNullOrEmpty(path)) return string.Empty;
try
{
- if (createThumbnail)
- {
- return CreateThumbnail(path);
- }
-
- using var img = Image.NewFromFile(path);
- using var stream = new MemoryStream();
- img.JpegsaveStream(stream);
- stream.Position = 0;
- return stream.ToArray();
+ return CreateThumbnail(path, fileName);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "[GetCoverImage] There was an error and prevented thumbnail generation on {ImageFile}. Defaulting to no cover image", path);
}
- return Array.Empty<byte>();
+ return string.Empty;
}
-
/// <inheritdoc />
- public byte[] CreateThumbnail(string path)
+ public string CreateThumbnail(string path, string fileName)
{
try
{
- using var thumbnail = Image.Thumbnail(path, MetadataService.ThumbnailWidth);
- return thumbnail.WriteToBuffer(".jpg");
+ using var thumbnail = Image.Thumbnail(path, ThumbnailWidth);
+ var filename = fileName + ".png";
+ thumbnail.WriteToFile(Path.Join(DirectoryService.CoverImageDirectory, fileName + ".png"));
+ return filename;
}
catch (Exception e)
{
_logger.LogError(e, "Error creating thumbnail from url");
}
- return Array.Empty<byte>();
+ return string.Empty;
+ }
+
+ /// <summary>
+ /// Creates a thumbnail out of a memory stream and saves to <see cref="DirectoryService.CoverImageDirectory"/> with the passed
+ /// fileName and .png extension.
+ /// </summary>
+ /// <param name="stream">Stream to write to disk. Ensure this is rewinded.</param>
+ /// <param name="fileName">filename to save as without extension</param>
+ /// <returns>File name with extension of the file. This will always write to <see cref="DirectoryService.CoverImageDirectory"/></returns>
+ public static string WriteCoverThumbnail(Stream stream, string fileName)
+ {
+ using var thumbnail = NetVips.Image.ThumbnailStream(stream, ThumbnailWidth);
+ var filename = fileName + ".png";
+ thumbnail.WriteToFile(Path.Join(DirectoryService.CoverImageDirectory, fileName + ".png"));
+ return filename;
}
/// <inheritdoc />
- public byte[] CreateThumbnailFromBase64(string encodedImage)
+ public string CreateThumbnailFromBase64(string encodedImage, string fileName)
{
try
{
- using var thumbnail = Image.ThumbnailBuffer(Convert.FromBase64String(encodedImage), MetadataService.ThumbnailWidth);
- return thumbnail.WriteToBuffer(".jpg");
+ using var thumbnail = Image.ThumbnailBuffer(Convert.FromBase64String(encodedImage), ThumbnailWidth);
+ var filename = fileName + ".png";
+ thumbnail.WriteToFile(Path.Join(DirectoryService.CoverImageDirectory, fileName + ".png"));
+ return filename;
}
catch (Exception e)
{
_logger.LogError(e, "Error creating thumbnail from url");
}
- return Array.Empty<byte>();
+ return string.Empty;
+ }
+
+ /// <summary>
+ /// Returns the name format for a chapter cover image
+ /// </summary>
+ /// <param name="chapterId"></param>
+ /// <param name="volumeId"></param>
+ /// <returns></returns>
+ public static string GetChapterFormat(int chapterId, int volumeId)
+ {
+ return $"v{volumeId}_c{chapterId}";
+ }
+
+ /// <summary>
+ /// Returns the name format for a series cover image
+ /// </summary>
+ /// <param name="seriesId"></param>
+ /// <returns></returns>
+ public static string GetSeriesFormat(int seriesId)
+ {
+ return $"series{seriesId}";
+ }
+
+ /// <summary>
+ /// Returns the name format for a collection tag cover image
+ /// </summary>
+ /// <param name="tagId"></param>
+ /// <returns></returns>
+ public static string GetCollectionTagFormat(int tagId)
+ {
+ return $"tag{tagId}";
}
}
}
diff --git a/API/Services/MetadataService.cs b/API/Services/MetadataService.cs
index aa175c021..d443f9f23 100644
--- a/API/Services/MetadataService.cs
+++ b/API/Services/MetadataService.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
+using System.IO;
using System.Linq;
using System.Threading.Tasks;
using API.Comparators;
@@ -9,6 +10,8 @@ using API.Entities.Enums;
using API.Extensions;
using API.Interfaces;
using API.Interfaces.Services;
+using API.SignalR;
+using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
namespace API.Services
@@ -20,58 +23,70 @@ namespace API.Services
private readonly IArchiveService _archiveService;
private readonly IBookService _bookService;
private readonly IImageService _imageService;
+ private readonly IHubContext<MessageHub> _messageHub;
private readonly ChapterSortComparerZeroFirst _chapterSortComparerForInChapterSorting = new ChapterSortComparerZeroFirst();
- /// <summary>
- /// Width of the Thumbnail generation
- /// </summary>
- public static readonly int ThumbnailWidth = 320; // 153w x 230h
public MetadataService(IUnitOfWork unitOfWork, ILogger<MetadataService> logger,
- IArchiveService archiveService, IBookService bookService, IImageService imageService)
+ IArchiveService archiveService, IBookService bookService, IImageService imageService, IHubContext<MessageHub> messageHub)
{
_unitOfWork = unitOfWork;
_logger = logger;
_archiveService = archiveService;
_bookService = bookService;
_imageService = imageService;
+ _messageHub = messageHub;
}
/// <summary>
- /// Determines whether an entity should regenerate cover image
+ /// Determines whether an entity should regenerate cover image.
/// </summary>
+ /// <remarks>If a cover image is locked but the underlying file has been deleted, this will allow regenerating. </remarks>
/// <param name="coverImage"></param>
/// <param name="firstFile"></param>
/// <param name="forceUpdate"></param>
/// <param name="isCoverLocked"></param>
+ /// <param name="coverImageDirectory">Directory where cover images are. Defaults to <see cref="DirectoryService.CoverImageDirectory"/></param>
/// <returns></returns>
- public static bool ShouldUpdateCoverImage(byte[] coverImage, MangaFile firstFile, bool forceUpdate = false,
- bool isCoverLocked = false)
+ public static bool ShouldUpdateCoverImage(string coverImage, MangaFile firstFile, bool forceUpdate = false,
+ bool isCoverLocked = false, string coverImageDirectory = null)
{
- if (isCoverLocked) return false;
+ if (string.IsNullOrEmpty(coverImageDirectory))
+ {
+ coverImageDirectory = DirectoryService.CoverImageDirectory;
+ }
+
+ var fileExists = File.Exists(Path.Join(coverImageDirectory, coverImage));
+ if (isCoverLocked && fileExists) return false;
if (forceUpdate) return true;
- return (firstFile != null && firstFile.HasFileBeenModified()) || !HasCoverImage(coverImage);
+ return (firstFile != null && firstFile.HasFileBeenModified()) || !HasCoverImage(coverImage, fileExists);
+ }
+
+
+ private static bool HasCoverImage(string coverImage)
+ {
+ return HasCoverImage(coverImage, File.Exists(coverImage));
}
- private static bool HasCoverImage(byte[] coverImage)
+ private static bool HasCoverImage(string coverImage, bool fileExists)
{
- return coverImage != null && coverImage.Any();
+ return !string.IsNullOrEmpty(coverImage) && fileExists;
}
- private byte[] GetCoverImage(MangaFile file, bool createThumbnail = true)
+ private string GetCoverImage(MangaFile file, int volumeId, int chapterId)
{
file.LastModified = DateTime.Now;
switch (file.Format)
{
case MangaFormat.Pdf:
case MangaFormat.Epub:
- return _bookService.GetCoverImage(file.FilePath, createThumbnail);
+ return _bookService.GetCoverImage(file.FilePath, ImageService.GetChapterFormat(chapterId, volumeId));
case MangaFormat.Image:
var coverImage = _imageService.GetCoverFile(file);
- return _imageService.GetCoverImage(coverImage, createThumbnail);
+ return _imageService.GetCoverImage(coverImage, ImageService.GetChapterFormat(chapterId, volumeId));
case MangaFormat.Archive:
- return _archiveService.GetCoverImage(file.FilePath, createThumbnail);
+ return _archiveService.GetCoverImage(file.FilePath, ImageService.GetChapterFormat(chapterId, volumeId));
default:
- return Array.Empty<byte>();
+ return string.Empty;
}
}
@@ -81,14 +96,17 @@ namespace API.Services
/// </summary>
/// <param name="chapter"></param>
/// <param name="forceUpdate">Force updating cover image even if underlying file has not been modified or chapter already has a cover image</param>
- public void UpdateMetadata(Chapter chapter, bool forceUpdate)
+ public bool UpdateMetadata(Chapter chapter, bool forceUpdate)
{
var firstFile = chapter.Files.OrderBy(x => x.Chapter).FirstOrDefault();
if (ShouldUpdateCoverImage(chapter.CoverImage, firstFile, forceUpdate, chapter.CoverImageLocked))
{
- chapter.CoverImage = GetCoverImage(firstFile);
+ chapter.CoverImage = GetCoverImage(firstFile, chapter.VolumeId, chapter.Id);
+ return true;
}
+
+ return false;
}
/// <summary>
@@ -96,17 +114,18 @@ namespace API.Services
/// </summary>
/// <param name="volume"></param>
/// <param name="forceUpdate">Force updating cover image even if underlying file has not been modified or chapter already has a cover image</param>
- public void UpdateMetadata(Volume volume, bool forceUpdate)
+ public bool UpdateMetadata(Volume volume, bool forceUpdate)
{
+ // We need to check if Volume coverImage matches first chapters if forceUpdate is false
if (volume == null || !ShouldUpdateCoverImage(volume.CoverImage, null, forceUpdate
- , false)) return;
+ , false)) return false;
volume.Chapters ??= new List<Chapter>();
var firstChapter = volume.Chapters.OrderBy(x => double.Parse(x.Number), _chapterSortComparerForInChapterSorting).FirstOrDefault();
-
- if (firstChapter == null) return;
+ if (firstChapter == null) return false;
volume.CoverImage = firstChapter.CoverImage;
+ return true;
}
/// <summary>
@@ -114,14 +133,15 @@ namespace API.Services
/// </summary>
/// <param name="series"></param>
/// <param name="forceUpdate">Force updating cover image even if underlying file has not been modified or chapter already has a cover image</param>
- public void UpdateMetadata(Series series, bool forceUpdate)
+ public bool UpdateMetadata(Series series, bool forceUpdate)
{
- if (series == null) return;
+ var madeUpdate = false;
+ if (series == null) return false;
if (ShouldUpdateCoverImage(series.CoverImage, null, forceUpdate, series.CoverImageLocked))
{
series.Volumes ??= new List<Volume>();
var firstCover = series.Volumes.GetCoverImage(series.Format);
- byte[] coverImage = null;
+ string coverImage = null;
if (firstCover == null && series.Volumes.Any())
{
// If firstCover is null and one volume, the whole series is Chapters under Vol 0.
@@ -129,39 +149,46 @@ namespace API.Services
{
coverImage = series.Volumes[0].Chapters.OrderBy(c => double.Parse(c.Number), _chapterSortComparerForInChapterSorting)
.FirstOrDefault(c => !c.IsSpecial)?.CoverImage;
+ madeUpdate = true;
}
if (!HasCoverImage(coverImage))
{
coverImage = series.Volumes[0].Chapters.OrderBy(c => double.Parse(c.Number), _chapterSortComparerForInChapterSorting)
.FirstOrDefault()?.CoverImage;
+ madeUpdate = true;
}
}
series.CoverImage = firstCover?.CoverImage ?? coverImage;
}
- UpdateSeriesSummary(series, forceUpdate);
+ return UpdateSeriesSummary(series, forceUpdate) || madeUpdate ;
}
- private void UpdateSeriesSummary(Series series, bool forceUpdate)
+ private bool UpdateSeriesSummary(Series series, bool forceUpdate)
{
- if (!string.IsNullOrEmpty(series.Summary) && !forceUpdate) return;
+ if (!string.IsNullOrEmpty(series.Summary) && !forceUpdate) return false;
var isBook = series.Library.Type == LibraryType.Book;
var firstVolume = series.Volumes.FirstWithChapters(isBook);
var firstChapter = firstVolume?.Chapters.GetFirstChapterWithFiles();
var firstFile = firstChapter?.Files.FirstOrDefault();
- if (firstFile == null || (!forceUpdate && !firstFile.HasFileBeenModified())) return;
- if (Parser.Parser.IsPdf(firstFile.FilePath)) return;
+ if (firstFile == null || (!forceUpdate && !firstFile.HasFileBeenModified())) return false;
+ if (Parser.Parser.IsPdf(firstFile.FilePath)) return false;
- var summary = Parser.Parser.IsEpub(firstFile.FilePath) ? _bookService.GetSummaryInfo(firstFile.FilePath) : _archiveService.GetSummaryInfo(firstFile.FilePath);
- if (string.IsNullOrEmpty(series.Summary))
+ if (series.Format is MangaFormat.Archive or MangaFormat.Epub)
{
- series.Summary = summary;
+ var summary = Parser.Parser.IsEpub(firstFile.FilePath) ? _bookService.GetSummaryInfo(firstFile.FilePath) : _archiveService.GetSummaryInfo(firstFile.FilePath);
+ if (!string.IsNullOrEmpty(series.Summary))
+ {
+ series.Summary = summary;
+ firstFile.LastModified = DateTime.Now;
+ return true;
+ }
}
-
- firstFile.LastModified = DateTime.Now;
+ firstFile.LastModified = DateTime.Now; // NOTE: Should I put this here as well since it might not have actually been parsed?
+ return false;
}
@@ -171,31 +198,33 @@ namespace API.Services
/// <remarks>This can be heavy on memory first run</remarks>
/// <param name="libraryId"></param>
/// <param name="forceUpdate">Force updating cover image even if underlying file has not been modified or chapter already has a cover image</param>
- public void RefreshMetadata(int libraryId, bool forceUpdate = false)
+ public async Task RefreshMetadata(int libraryId, bool forceUpdate = false)
{
var sw = Stopwatch.StartNew();
- var library = Task.Run(() => _unitOfWork.LibraryRepository.GetFullLibraryForIdAsync(libraryId)).GetAwaiter().GetResult();
+ var library = await _unitOfWork.LibraryRepository.GetFullLibraryForIdAsync(libraryId);
// PERF: See if we can break this up into multiple threads that process 20 series at a time then save so we can reduce amount of memory used
_logger.LogInformation("Beginning metadata refresh of {LibraryName}", library.Name);
foreach (var series in library.Series)
{
+ var volumeUpdated = false;
foreach (var volume in series.Volumes)
{
+ var chapterUpdated = false;
foreach (var chapter in volume.Chapters)
{
- UpdateMetadata(chapter, forceUpdate);
+ chapterUpdated = UpdateMetadata(chapter, forceUpdate);
}
- UpdateMetadata(volume, forceUpdate);
+ volumeUpdated = UpdateMetadata(volume, chapterUpdated || forceUpdate);
}
- UpdateMetadata(series, forceUpdate);
+ UpdateMetadata(series, volumeUpdated || forceUpdate);
_unitOfWork.SeriesRepository.Update(series);
}
- if (_unitOfWork.HasChanges() && Task.Run(() => _unitOfWork.CommitAsync()).Result)
+ if (_unitOfWork.HasChanges() && await _unitOfWork.CommitAsync())
{
_logger.LogInformation("Updated metadata for {LibraryName} in {ElapsedMilliseconds} milliseconds", library.Name, sw.ElapsedMilliseconds);
}
@@ -207,10 +236,10 @@ namespace API.Services
/// </summary>
/// <param name="libraryId"></param>
/// <param name="seriesId"></param>
- public void RefreshMetadataForSeries(int libraryId, int seriesId)
+ public async Task RefreshMetadataForSeries(int libraryId, int seriesId, bool forceUpdate = false)
{
var sw = Stopwatch.StartNew();
- var library = Task.Run(() => _unitOfWork.LibraryRepository.GetFullLibraryForIdAsync(libraryId)).GetAwaiter().GetResult();
+ var library = await _unitOfWork.LibraryRepository.GetFullLibraryForIdAsync(libraryId);
var series = library.Series.SingleOrDefault(s => s.Id == seriesId);
if (series == null)
@@ -219,23 +248,26 @@ namespace API.Services
return;
}
_logger.LogInformation("Beginning metadata refresh of {SeriesName}", series.Name);
+ var volumeUpdated = false;
foreach (var volume in series.Volumes)
{
+ var chapterUpdated = false;
foreach (var chapter in volume.Chapters)
{
- UpdateMetadata(chapter, true);
+ chapterUpdated = UpdateMetadata(chapter, forceUpdate);
}
- UpdateMetadata(volume, true);
+ volumeUpdated = UpdateMetadata(volume, chapterUpdated || forceUpdate);
}
- UpdateMetadata(series, true);
+ UpdateMetadata(series, volumeUpdated || forceUpdate);
_unitOfWork.SeriesRepository.Update(series);
- if (_unitOfWork.HasChanges() && Task.Run(() => _unitOfWork.CommitAsync()).Result)
+ if (_unitOfWork.HasChanges() && await _unitOfWork.CommitAsync())
{
_logger.LogInformation("Updated metadata for {SeriesName} in {ElapsedMilliseconds} milliseconds", series.Name, sw.ElapsedMilliseconds);
+ await _messageHub.Clients.All.SendAsync(SignalREvents.ScanSeries, MessageFactory.RefreshMetadataEvent(libraryId, seriesId));
}
}
}
diff --git a/API/Services/TaskScheduler.cs b/API/Services/TaskScheduler.cs
index f12926c68..2d1b25a7d 100644
--- a/API/Services/TaskScheduler.cs
+++ b/API/Services/TaskScheduler.cs
@@ -121,7 +121,7 @@ namespace API.Services
_logger.LogInformation("Enqueuing library scan for: {LibraryId}", libraryId);
BackgroundJob.Enqueue(() => _scannerService.ScanLibrary(libraryId, forceUpdate));
// When we do a scan, force cache to re-unpack in case page numbers change
- BackgroundJob.Enqueue(() => _cleanupService.Cleanup());
+ BackgroundJob.Enqueue(() => _cleanupService.CleanupCacheDirectory());
}
public void CleanupChapters(int[] chapterIds)
@@ -141,10 +141,10 @@ namespace API.Services
BackgroundJob.Enqueue(() => DirectoryService.ClearDirectory(tempDirectory));
}
- public void RefreshSeriesMetadata(int libraryId, int seriesId)
+ public void RefreshSeriesMetadata(int libraryId, int seriesId, bool forceUpdate = false)
{
_logger.LogInformation("Enqueuing series metadata refresh for: {SeriesId}", seriesId);
- BackgroundJob.Enqueue(() => _metadataService.RefreshMetadataForSeries(libraryId, seriesId));
+ BackgroundJob.Enqueue(() => _metadataService.RefreshMetadataForSeries(libraryId, seriesId, forceUpdate));
}
public void ScanSeries(int libraryId, int seriesId, bool forceUpdate = false)
@@ -161,6 +161,7 @@ namespace API.Services
/// <summary>
/// Not an external call. Only public so that we can call this for a Task
/// </summary>
+ // ReSharper disable once MemberCanBePrivate.Global
public async Task CheckForUpdate()
{
var update = await _versionUpdaterService.CheckForUpdate();
diff --git a/API/Services/Tasks/BackupService.cs b/API/Services/Tasks/BackupService.cs
index e04e5373f..35388985a 100644
--- a/API/Services/Tasks/BackupService.cs
+++ b/API/Services/Tasks/BackupService.cs
@@ -59,8 +59,11 @@ namespace API.Services.Tasks
return files;
}
+ /// <summary>
+ /// Will backup anything that needs to be backed up. This includes logs, setting files, bare minimum cover images (just locked and first cover).
+ /// </summary>
[AutomaticRetry(Attempts = 3, LogEvents = false, OnAttemptsExceeded = AttemptsExceededAction.Fail)]
- public void BackupDatabase()
+ public async Task BackupDatabase()
{
_logger.LogInformation("Beginning backup of Database at {BackupTime}", DateTime.Now);
var backupDirectory = Task.Run(() => _unitOfWork.SettingsRepository.GetSettingAsync(ServerSettingKey.BackupDirectory)).Result.Value;
@@ -87,6 +90,9 @@ namespace API.Services.Tasks
_directoryService.CopyFilesToDirectory(
_backupFiles.Select(file => Path.Join(Directory.GetCurrentDirectory(), file)).ToList(), tempDirectory);
+
+ await CopyCoverImagesToBackupDirectory(tempDirectory);
+
try
{
ZipFile.CreateFromDirectory(tempDirectory, zipPath);
@@ -100,6 +106,31 @@ namespace API.Services.Tasks
_logger.LogInformation("Database backup completed");
}
+ private async Task CopyCoverImagesToBackupDirectory(string tempDirectory)
+ {
+ var outputTempDir = Path.Join(tempDirectory, "covers");
+ DirectoryService.ExistOrCreate(outputTempDir);
+
+ try
+ {
+ var seriesImages = await _unitOfWork.SeriesRepository.GetLockedCoverImagesAsync();
+ _directoryService.CopyFilesToDirectory(
+ seriesImages.Select(s => Path.Join(DirectoryService.CoverImageDirectory, s)), outputTempDir);
+
+ var collectionTags = await _unitOfWork.CollectionTagRepository.GetAllCoverImagesAsync();
+ _directoryService.CopyFilesToDirectory(
+ collectionTags.Select(s => Path.Join(DirectoryService.CoverImageDirectory, s)), outputTempDir);
+
+ var chapterImages = await _unitOfWork.ChapterRepository.GetCoverImagesForLockedChaptersAsync();
+ _directoryService.CopyFilesToDirectory(
+ chapterImages.Select(s => Path.Join(DirectoryService.CoverImageDirectory, s)), outputTempDir);
+ }
+ catch (IOException e)
+ {
+ // Swallow exception. This can be a duplicate cover being copied as chapter and volumes can share same file.
+ }
+ }
+
/// <summary>
/// Removes Database backups older than 30 days. If all backups are older than 30 days, the latest is kept.
/// </summary>
diff --git a/API/Services/Tasks/CleanupService.cs b/API/Services/Tasks/CleanupService.cs
index ae04d46bd..c1edf2e6b 100644
--- a/API/Services/Tasks/CleanupService.cs
+++ b/API/Services/Tasks/CleanupService.cs
@@ -1,7 +1,11 @@
using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using API.Interfaces;
using API.Interfaces.Services;
using Hangfire;
using Microsoft.Extensions.Logging;
+using NetVips;
namespace API.Services.Tasks
{
@@ -13,27 +17,79 @@ namespace API.Services.Tasks
private readonly ICacheService _cacheService;
private readonly ILogger<CleanupService> _logger;
private readonly IBackupService _backupService;
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IDirectoryService _directoryService;
- public CleanupService(ICacheService cacheService, ILogger<CleanupService> logger, IBackupService backupService)
+ public CleanupService(ICacheService cacheService, ILogger<CleanupService> logger,
+ IBackupService backupService, IUnitOfWork unitOfWork, IDirectoryService directoryService)
{
_cacheService = cacheService;
_logger = logger;
_backupService = backupService;
+ _unitOfWork = unitOfWork;
+ _directoryService = directoryService;
+ }
+
+ public void CleanupCacheDirectory()
+ {
+ _logger.LogInformation("Cleaning cache directory");
+ _cacheService.Cleanup();
}
/// <summary>
- /// Cleans up Temp, cache, and old database backups
+ /// Cleans up Temp, cache, deleted cover images, and old database backups
/// </summary>
[AutomaticRetry(Attempts = 3, LogEvents = false, OnAttemptsExceeded = AttemptsExceededAction.Fail)]
- public void Cleanup()
+ public async Task Cleanup()
{
+ _logger.LogInformation("Starting Cleanup");
_logger.LogInformation("Cleaning temp directory");
var tempDirectory = Path.Join(Directory.GetCurrentDirectory(), "temp");
DirectoryService.ClearDirectory(tempDirectory);
- _logger.LogInformation("Cleaning cache directory");
- _cacheService.Cleanup();
+ CleanupCacheDirectory();
_logger.LogInformation("Cleaning old database backups");
_backupService.CleanupBackups();
+ _logger.LogInformation("Cleaning deleted cover images");
+ await DeleteSeriesCoverImages();
+ await DeleteChapterCoverImages();
+ await DeleteTagCoverImages();
+ _logger.LogInformation("Cleanup finished");
+ }
+
+ private async Task DeleteSeriesCoverImages()
+ {
+ var images = await _unitOfWork.SeriesRepository.GetAllCoverImagesAsync();
+ var files = _directoryService.GetFiles(DirectoryService.CoverImageDirectory, ImageService.SeriesCoverImageRegex);
+ foreach (var file in files)
+ {
+ if (images.Contains(Path.GetFileName(file))) continue;
+ File.Delete(file);
+
+ }
+ }
+
+ private async Task DeleteChapterCoverImages()
+ {
+ var images = await _unitOfWork.ChapterRepository.GetAllCoverImagesAsync();
+ var files = _directoryService.GetFiles(DirectoryService.CoverImageDirectory, ImageService.ChapterCoverImageRegex);
+ foreach (var file in files)
+ {
+ if (images.Contains(Path.GetFileName(file))) continue;
+ File.Delete(file);
+
+ }
+ }
+
+ private async Task DeleteTagCoverImages()
+ {
+ var images = await _unitOfWork.CollectionTagRepository.GetAllCoverImagesAsync();
+ var files = _directoryService.GetFiles(DirectoryService.CoverImageDirectory, ImageService.CollectionTagCoverImageRegex);
+ foreach (var file in files)
+ {
+ if (images.Contains(Path.GetFileName(file))) continue;
+ File.Delete(file);
+
+ }
}
}
}
diff --git a/API/Services/Tasks/Scanner/ParseScannedFiles.cs b/API/Services/Tasks/Scanner/ParseScannedFiles.cs
index 9be88dfde..afcfc1c13 100644
--- a/API/Services/Tasks/Scanner/ParseScannedFiles.cs
+++ b/API/Services/Tasks/Scanner/ParseScannedFiles.cs
@@ -39,18 +39,18 @@ namespace API.Services.Tasks.Scanner
_scannedSeries = new ConcurrentDictionary<ParsedSeries, List<ParserInfo>>();
}
+ /// <summary>
+ /// Gets the list of parserInfos given a Series. If the series does not exist within, return empty list.
+ /// </summary>
+ /// <param name="parsedSeries"></param>
+ /// <param name="series"></param>
+ /// <returns></returns>
public static IList<ParserInfo> GetInfosByName(Dictionary<ParsedSeries, List<ParserInfo>> parsedSeries, Series series)
{
var existingKey = parsedSeries.Keys.FirstOrDefault(ps =>
- ps.Format == series.Format && ps.NormalizedName == Parser.Parser.Normalize(series.OriginalName));
- existingKey ??= new ParsedSeries()
- {
- Format = series.Format,
- Name = series.OriginalName,
- NormalizedName = Parser.Parser.Normalize(series.OriginalName)
- };
+ ps.Format == series.Format && ps.NormalizedName.Equals(Parser.Parser.Normalize(series.OriginalName)));
- return parsedSeries[existingKey];
+ return existingKey != null ? parsedSeries[existingKey] : new List<ParserInfo>();
}
/// <summary>
diff --git a/API/Services/Tasks/ScannerService.cs b/API/Services/Tasks/ScannerService.cs
index 9fd90844c..15bb715c7 100644
--- a/API/Services/Tasks/ScannerService.cs
+++ b/API/Services/Tasks/ScannerService.cs
@@ -14,7 +14,9 @@ using API.Interfaces;
using API.Interfaces.Services;
using API.Parser;
using API.Services.Tasks.Scanner;
+using API.SignalR;
using Hangfire;
+using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
namespace API.Services.Tasks
@@ -27,10 +29,11 @@ namespace API.Services.Tasks
private readonly IMetadataService _metadataService;
private readonly IBookService _bookService;
private readonly ICacheService _cacheService;
+ private readonly IHubContext<MessageHub> _messageHub;
private readonly NaturalSortComparer _naturalSort = new ();
public ScannerService(IUnitOfWork unitOfWork, ILogger<ScannerService> logger, IArchiveService archiveService,
- IMetadataService metadataService, IBookService bookService, ICacheService cacheService)
+ IMetadataService metadataService, IBookService bookService, ICacheService cacheService, IHubContext<MessageHub> messageHub)
{
_unitOfWork = unitOfWork;
_logger = logger;
@@ -38,6 +41,7 @@ namespace API.Services.Tasks
_metadataService = metadataService;
_bookService = bookService;
_cacheService = cacheService;
+ _messageHub = messageHub;
}
[DisableConcurrentExecution(timeoutInSeconds: 360)]
@@ -47,7 +51,7 @@ namespace API.Services.Tasks
var files = await _unitOfWork.SeriesRepository.GetFilesForSeries(seriesId);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId);
var library = await _unitOfWork.LibraryRepository.GetFullLibraryForIdAsync(libraryId, seriesId);
- var dirs = FindHighestDirectoriesFromFiles(library, files);
+ var dirs = DirectoryService.FindHighestDirectoriesFromFiles(library.Folders.Select(f => f.Path), files.Select(f => f.FilePath).ToList());
var chapterIds = await _unitOfWork.SeriesRepository.GetChapterIdsForSeriesAsync(new []{ seriesId });
_logger.LogInformation("Beginning file scan on {SeriesName}", series.Name);
@@ -63,6 +67,37 @@ namespace API.Services.Tasks
parsedSeries.Remove(key);
}
+ if (parsedSeries.Count == 0)
+ {
+ // We need to do an additional check for an edge case: If the scan ran and the files do not match the existing Series name, then it is very likely,
+ // the files have crap naming and if we don't correct, the series will get deleted due to the parser not being able to fallback onto folder parsing as the root
+ // is the series folder.
+ var existingFolder = dirs.Keys.FirstOrDefault(key => key.Contains(series.OriginalName));
+ if (dirs.Keys.Count == 1 && !string.IsNullOrEmpty(existingFolder))
+ {
+ dirs = new Dictionary<string, string>();
+ var path = Path.GetPathRoot(existingFolder);
+ if (!string.IsNullOrEmpty(path))
+ {
+ dirs[path] = string.Empty;
+ }
+ }
+ _logger.LogDebug("{SeriesName} has bad naming convention, forcing rescan at a higher directory.", series.OriginalName);
+ scanner = new ParseScannedFiles(_bookService, _logger);
+ parsedSeries = scanner.ScanLibrariesForSeries(library.Type, dirs.Keys, out var totalFiles2, out var scanElapsedTime2);
+ totalFiles += totalFiles2;
+ scanElapsedTime += scanElapsedTime2;
+
+ // If a root level folder scan occurs, then multiple series gets passed in and thus we get a unique constraint issue
+ // Hence we clear out anything but what we selected for
+ firstSeries = library.Series.FirstOrDefault();
+ keys = parsedSeries.Keys;
+ foreach (var key in keys.Where(key => !firstSeries.NameInParserInfo(parsedSeries[key].FirstOrDefault()) || firstSeries?.Format != key.Format))
+ {
+ parsedSeries.Remove(key);
+ }
+ }
+
var sw = new Stopwatch();
UpdateLibrary(library, parsedSeries);
@@ -73,9 +108,11 @@ namespace API.Services.Tasks
"Processed {TotalFiles} files and {ParsedSeriesCount} series in {ElapsedScanTime} milliseconds for {SeriesName}",
totalFiles, parsedSeries.Keys.Count, sw.ElapsedMilliseconds + scanElapsedTime, series.Name);
- CleanupDbEntities();
- BackgroundJob.Enqueue(() => _metadataService.RefreshMetadataForSeries(libraryId, seriesId));
+ await CleanupDbEntities();
+ BackgroundJob.Enqueue(() => _metadataService.RefreshMetadataForSeries(libraryId, seriesId, forceUpdate));
BackgroundJob.Enqueue(() => _cacheService.CleanupChapters(chapterIds));
+ // Tell UI that this series is done
+ await _messageHub.Clients.All.SendAsync(SignalREvents.ScanSeries, MessageFactory.ScanSeriesEvent(seriesId), cancellationToken: token);
}
else
{
@@ -83,56 +120,21 @@ namespace API.Services.Tasks
"There was a critical error that resulted in a failed scan. Please check logs and rescan");
await _unitOfWork.RollbackAsync();
}
- }
- /// <summary>
- /// Finds the highest directories from a set of MangaFiles
- /// </summary>
- /// <param name="library"></param>
- /// <param name="files"></param>
- /// <returns></returns>
- private static Dictionary<string, string> FindHighestDirectoriesFromFiles(Library library, IList<MangaFile> files)
- {
- var stopLookingForDirectories = false;
- var dirs = new Dictionary<string, string>();
- foreach (var folder in library.Folders)
- {
- if (stopLookingForDirectories) break;
- foreach (var file in files)
- {
- if (!file.FilePath.Contains(folder.Path)) continue;
-
- var parts = DirectoryService.GetFoldersTillRoot(folder.Path, file.FilePath).ToList();
- if (parts.Count == 0)
- {
- // Break from all loops, we done, just scan folder.Path (library root)
- dirs.Add(folder.Path, string.Empty);
- stopLookingForDirectories = true;
- break;
- }
-
- var fullPath = Path.Join(folder.Path, parts.Last());
- if (!dirs.ContainsKey(fullPath))
- {
- dirs.Add(fullPath, string.Empty);
- }
- }
- }
-
- return dirs;
}
[DisableConcurrentExecution(timeoutInSeconds: 360)]
[AutomaticRetry(Attempts = 0, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
- public void ScanLibraries()
+ public async Task ScanLibraries()
{
- var libraries = Task.Run(() => _unitOfWork.LibraryRepository.GetLibrariesAsync()).Result.ToList();
+ _logger.LogInformation("Starting Scan of All Libraries");
+ var libraries = await _unitOfWork.LibraryRepository.GetLibrariesAsync();
foreach (var lib in libraries)
{
- ScanLibrary(lib.Id, false);
+ await ScanLibrary(lib.Id, false);
}
-
+ _logger.LogInformation("Scan of All Libraries Finished");
}
@@ -145,13 +147,12 @@ namespace API.Services.Tasks
/// <param name="forceUpdate"></param>
[DisableConcurrentExecution(360)]
[AutomaticRetry(Attempts = 0, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
- public void ScanLibrary(int libraryId, bool forceUpdate)
+ public async Task ScanLibrary(int libraryId, bool forceUpdate)
{
Library library;
try
{
- library = Task.Run(() => _unitOfWork.LibraryRepository.GetFullLibraryForIdAsync(libraryId)).GetAwaiter()
- .GetResult();
+ library = await _unitOfWork.LibraryRepository.GetFullLibraryForIdAsync(libraryId);
}
catch (Exception ex)
{
@@ -173,7 +174,7 @@ namespace API.Services.Tasks
UpdateLibrary(library, series);
_unitOfWork.LibraryRepository.Update(library);
- if (Task.Run(() => _unitOfWork.CommitAsync()).Result)
+ if (await _unitOfWork.CommitAsync())
{
_logger.LogInformation(
"Processed {TotalFiles} files and {ParsedSeriesCount} series in {ElapsedScanTime} milliseconds for {LibraryName}",
@@ -185,27 +186,29 @@ namespace API.Services.Tasks
"There was a critical error that resulted in a failed scan. Please check logs and rescan");
}
- CleanupUserProgress();
+ await CleanupAbandonedChapters();
BackgroundJob.Enqueue(() => _metadataService.RefreshMetadata(libraryId, forceUpdate));
+ await _messageHub.Clients.All.SendAsync(SignalREvents.ScanLibrary, MessageFactory.ScanLibraryEvent(libraryId, "complete"));
}
/// <summary>
/// Remove any user progress rows that no longer exist since scan library ran and deleted series/volumes/chapters
/// </summary>
- private void CleanupUserProgress()
+ private async Task CleanupAbandonedChapters()
{
- var cleanedUp = Task.Run(() => _unitOfWork.AppUserProgressRepository.CleanupAbandonedChapters()).Result;
+ var cleanedUp = await _unitOfWork.AppUserProgressRepository.CleanupAbandonedChapters();
_logger.LogInformation("Removed {Count} abandoned progress rows", cleanedUp);
}
+
/// <summary>
/// Cleans up any abandoned rows due to removals from Scan loop
/// </summary>
- private void CleanupDbEntities()
+ private async Task CleanupDbEntities()
{
- CleanupUserProgress();
- var cleanedUp = Task.Run( () => _unitOfWork.CollectionTagRepository.RemoveTagsWithoutSeries()).Result;
+ await CleanupAbandonedChapters();
+ var cleanedUp = await _unitOfWork.CollectionTagRepository.RemoveTagsWithoutSeries();
_logger.LogInformation("Removed {Count} abandoned collection tags", cleanedUp);
}
@@ -275,6 +278,9 @@ namespace API.Services.Tasks
_logger.LogError(ex, "There was an exception updating volumes for {SeriesName}", series.Name);
}
});
+
+ // Last step, remove any series that have no pages
+ library.Series = library.Series.Where(s => s.Pages > 0).ToList();
}
public IEnumerable<Series> FindSeriesNotOnDisk(ICollection<Series> existingSeries, Dictionary<ParsedSeries, List<ParserInfo>> parsedSeries)
diff --git a/API/Services/Tasks/VersionUpdaterService.cs b/API/Services/Tasks/VersionUpdaterService.cs
index 5b3607ffc..fbd3d4f10 100644
--- a/API/Services/Tasks/VersionUpdaterService.cs
+++ b/API/Services/Tasks/VersionUpdaterService.cs
@@ -23,6 +23,7 @@ namespace API.Services.Tasks
/// Name of the Tag
/// <example>v0.4.3</example>
/// </summary>
+ // ReSharper disable once InconsistentNaming
public string Tag_Name { get; init; }
/// <summary>
/// Name of the Release
@@ -35,6 +36,7 @@ namespace API.Services.Tasks
/// <summary>
/// Url of the release on Github
/// </summary>
+ // ReSharper disable once InconsistentNaming
public string Html_Url { get; init; }
}
@@ -53,8 +55,10 @@ namespace API.Services.Tasks
private readonly IHubContext<MessageHub> _messageHub;
private readonly IPresenceTracker _tracker;
private readonly Markdown _markdown = new MarkdownDeep.Markdown();
+#pragma warning disable S1075
private static readonly string GithubLatestReleasesUrl = "https://api.github.com/repos/Kareadita/Kavita/releases/latest";
private static readonly string GithubAllReleasesUrl = "https://api.github.com/repos/Kareadita/Kavita/releases";
+#pragma warning restore S1075
public VersionUpdaterService(ILogger<VersionUpdaterService> logger, IHubContext<MessageHub> messageHub, IPresenceTracker tracker)
{
@@ -90,12 +94,17 @@ namespace API.Services.Tasks
private UpdateNotificationDto CreateDto(GithubReleaseMetadata update)
{
if (update == null || string.IsNullOrEmpty(update.Tag_Name)) return null;
- var version = update.Tag_Name.Replace("v", string.Empty);
- var updateVersion = new Version(version);
+ var updateVersion = new Version(update.Tag_Name.Replace("v", string.Empty));
+ var currentVersion = BuildInfo.Version.ToString();
+
+ if (updateVersion.Revision == -1)
+ {
+ currentVersion = currentVersion.Substring(0, currentVersion.LastIndexOf(".", StringComparison.Ordinal));
+ }
return new UpdateNotificationDto()
{
- CurrentVersion = version,
+ CurrentVersion = currentVersion,
UpdateVersion = updateVersion.ToString(),
UpdateBody = _markdown.Transform(update.Body.Trim()),
UpdateTitle = update.Name,
@@ -131,11 +140,7 @@ namespace API.Services.Tasks
connections.AddRange(await _tracker.GetConnectionsForUser(admin));
}
- await _messageHub.Clients.Users(admins).SendAsync("UpdateAvailable", new SignalRMessage
- {
- Name = "UpdateAvailable",
- Body = update
- });
+ await _messageHub.Clients.Users(admins).SendAsync(SignalREvents.UpdateVersion, MessageFactory.UpdateVersionEvent(update));
}
diff --git a/API/SignalR/MessageFactory.cs b/API/SignalR/MessageFactory.cs
new file mode 100644
index 000000000..ad6eed5c9
--- /dev/null
+++ b/API/SignalR/MessageFactory.cs
@@ -0,0 +1,56 @@
+using System.Threading;
+using API.DTOs.Update;
+
+namespace API.SignalR
+{
+ public static class MessageFactory
+ {
+ public static SignalRMessage ScanSeriesEvent(int seriesId)
+ {
+ return new SignalRMessage()
+ {
+ Name = SignalREvents.ScanSeries,
+ Body = new
+ {
+ SeriesId = seriesId
+ }
+ };
+ }
+
+ public static SignalRMessage ScanLibraryEvent(int libraryId, string stage)
+ {
+ return new SignalRMessage()
+ {
+ Name = SignalREvents.ScanLibrary,
+ Body = new
+ {
+ LibraryId = libraryId,
+ Stage = stage
+ }
+ };
+ }
+
+ public static SignalRMessage RefreshMetadataEvent(int libraryId, int seriesId)
+ {
+ return new SignalRMessage()
+ {
+ Name = SignalREvents.RefreshMetadata,
+ Body = new
+ {
+ SeriesId = seriesId,
+ LibraryId = libraryId
+ }
+ };
+ }
+
+ public static SignalRMessage UpdateVersionEvent(UpdateNotificationDto update)
+ {
+ return new SignalRMessage
+ {
+ Name = SignalREvents.UpdateVersion,
+ Body = update
+ };
+ }
+
+ }
+}
diff --git a/API/SignalR/SignalREvents.cs b/API/SignalR/SignalREvents.cs
new file mode 100644
index 000000000..fcd077146
--- /dev/null
+++ b/API/SignalR/SignalREvents.cs
@@ -0,0 +1,11 @@
+namespace API.SignalR
+{
+ public static class SignalREvents
+ {
+ public const string UpdateVersion = "UpdateVersion";
+ public const string ScanSeries = "ScanSeries";
+ public const string RefreshMetadata = "RefreshMetadata";
+ public const string ScanLibrary = "ScanLibrary";
+
+ }
+}
diff --git a/API/Startup.cs b/API/Startup.cs
index cfdae2d9d..ee26e2d2b 100644
--- a/API/Startup.cs
+++ b/API/Startup.cs
@@ -2,6 +2,8 @@ using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
+using System.Net;
+using System.Net.Sockets;
using API.Extensions;
using API.Middleware;
using API.Services;
@@ -9,6 +11,7 @@ using API.Services.HostedServices;
using API.SignalR;
using Hangfire;
using Hangfire.MemoryStorage;
+using Kavita.Common;
using Kavita.Common.EnvironmentInfo;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
@@ -109,7 +112,7 @@ namespace API
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials() // For SignalR token query param
- .WithOrigins("http://localhost:4200")
+ .WithOrigins("http://localhost:4200", $"http://{GetLocalIpAddress()}:4200")
.WithExposedHeaders("Content-Disposition", "Pagination"));
}
@@ -132,7 +135,7 @@ namespace API
new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
{
Public = false,
- MaxAge = TimeSpan.FromSeconds(10)
+ MaxAge = TimeSpan.FromSeconds(10),
};
context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] =
new[] { "Accept-Encoding" };
@@ -164,6 +167,14 @@ namespace API
Console.WriteLine("You may now close the application window.");
}
+ private static string GetLocalIpAddress()
+ {
+ using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0);
+ socket.Connect("8.8.8.8", 65530);
+ if (socket.LocalEndPoint is IPEndPoint endPoint) return endPoint.Address.ToString();
+ throw new KavitaException("No network adapters with an IPv4 address in the system!");
+ }
+
}
}
diff --git a/Kavita.Common/Kavita.Common.csproj b/Kavita.Common/Kavita.Common.csproj
index f5e97d5f7..83192fafd 100644
--- a/Kavita.Common/Kavita.Common.csproj
+++ b/Kavita.Common/Kavita.Common.csproj
@@ -4,7 +4,7 @@
<TargetFramework>net5.0</TargetFramework>
<Company>kavitareader.com</Company>
<Product>Kavita</Product>
- <AssemblyVersion>0.4.5.1</AssemblyVersion>
+ <AssemblyVersion>0.4.6.1</AssemblyVersion>
<NeutralLanguage>en</NeutralLanguage>
</PropertyGroup>
diff --git a/UI/Web/package-lock.json b/UI/Web/package-lock.json
index 9f8f3aafa..2ae36e55d 100644
--- a/UI/Web/package-lock.json
+++ b/UI/Web/package-lock.json
@@ -245,6 +245,28 @@
"tslib": "^2.0.0"
}
},
+ "@angular/cdk": {
+ "version": "12.2.3",
+ "resolved": "https://registry.npmjs.org/@angular/cdk/-/cdk-12.2.3.tgz",
+ "integrity": "sha512-ahY3k5X3eoQlsCX/fYiwbe1z7nfmwY15EiLpcJ8YrnUoB+ZshPm8qFIZi6gwY4tsMmUN8OfsIGcUO701bdxFpg==",
+ "requires": {
+ "parse5": "^5.0.0",
+ "tslib": "^2.2.0"
+ },
+ "dependencies": {
+ "parse5": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-5.1.1.tgz",
+ "integrity": "sha512-ugq4DFI0Ptb+WWjAdOK16+u/nHfiIrcE+sh8kZMaM0WllQKLI9rOUq6c2b7cwPkXdzfQESqvoqK6ug7U/Yyzug==",
+ "optional": true
+ },
+ "tslib": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz",
+ "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw=="
+ }
+ }
+ },
"@angular/cli": {
"version": "11.2.11",
"resolved": "https://registry.npmjs.org/@angular/cli/-/cli-11.2.11.tgz",
@@ -2580,6 +2602,11 @@
}
}
},
+ "@polka/url": {
+ "version": "1.0.0-next.20",
+ "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.20.tgz",
+ "integrity": "sha512-88p7+M0QGxKpmnkfXjS4V26AnoC/eiqZutE8GLdaI5X12NY75bXSdTY9NkmYb2Xyk1O+MmkuO6Frmsj84V6I8Q=="
+ },
"@schematics/angular": {
"version": "11.2.11",
"resolved": "https://registry.npmjs.org/@schematics/angular/-/angular-11.2.11.tgz",
@@ -5762,6 +5789,11 @@
"is-obj": "^2.0.0"
}
},
+ "duplexer": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.2.tgz",
+ "integrity": "sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg=="
+ },
"duplexify": {
"version": "3.7.1",
"resolved": "https://registry.npmjs.org/duplexify/-/duplexify-3.7.1.tgz",
@@ -6957,6 +6989,14 @@
"dev": true,
"optional": true
},
+ "gzip-size": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/gzip-size/-/gzip-size-6.0.0.tgz",
+ "integrity": "sha512-ax7ZYomf6jqPTQ4+XCpUGyXKHk5WweS+e05MBO4/y3WJ5RkmPXNKvX+bx1behVILVwr6JSQvZAku021CHPXG3Q==",
+ "requires": {
+ "duplexer": "^0.1.2"
+ }
+ },
"handle-thing": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/handle-thing/-/handle-thing-2.0.1.tgz",
@@ -11166,6 +11206,11 @@
"is-wsl": "^2.1.1"
}
},
+ "opener": {
+ "version": "1.5.2",
+ "resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz",
+ "integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A=="
+ },
"opn": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/opn/-/opn-5.5.0.tgz",
@@ -14017,6 +14062,23 @@
}
}
},
+ "sirv": {
+ "version": "1.0.17",
+ "resolved": "https://registry.npmjs.org/sirv/-/sirv-1.0.17.tgz",
+ "integrity": "sha512-qx9go5yraB7ekT7bCMqUHJ5jEaOC/GXBxUWv+jeWnb7WzHUFdcQPGWk7YmAwFBaQBrogpuSqd/azbC2lZRqqmw==",
+ "requires": {
+ "@polka/url": "^1.0.0-next.20",
+ "mime": "^2.3.1",
+ "totalist": "^1.0.0"
+ },
+ "dependencies": {
+ "mime": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/mime/-/mime-2.5.2.tgz",
+ "integrity": "sha512-tqkh47FzKeCPD2PUiPB6pkbMzsCasjxAfC62/Wap5qrUWcb+sFasXUC5I3gYM5iBM8v/Qpn4UK0x+j0iHyFPDg=="
+ }
+ }
+ },
"sisteransi": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz",
@@ -15066,6 +15128,11 @@
"integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==",
"dev": true
},
+ "totalist": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/totalist/-/totalist-1.1.0.tgz",
+ "integrity": "sha512-gduQwd1rOdDMGxFG1gEvhV88Oirdo2p+KjoYFU7k2g+i7n6AFFbDQ5kMPUsW0pNbfQsB/cwXvT1i4Bue0s9g5g=="
+ },
"tough-cookie": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz",
@@ -16220,6 +16287,87 @@
}
}
},
+ "webpack-bundle-analyzer": {
+ "version": "4.4.2",
+ "resolved": "https://registry.npmjs.org/webpack-bundle-analyzer/-/webpack-bundle-analyzer-4.4.2.tgz",
+ "integrity": "sha512-PIagMYhlEzFfhMYOzs5gFT55DkUdkyrJi/SxJp8EF3YMWhS+T9vvs2EoTetpk5qb6VsCq02eXTlRDOydRhDFAQ==",
+ "requires": {
+ "acorn": "^8.0.4",
+ "acorn-walk": "^8.0.0",
+ "chalk": "^4.1.0",
+ "commander": "^6.2.0",
+ "gzip-size": "^6.0.0",
+ "lodash": "^4.17.20",
+ "opener": "^1.5.2",
+ "sirv": "^1.0.7",
+ "ws": "^7.3.1"
+ },
+ "dependencies": {
+ "acorn": {
+ "version": "8.5.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.5.0.tgz",
+ "integrity": "sha512-yXbYeFy+jUuYd3/CDcg2NkIYE991XYX/bje7LmjJigUciaeO1JR4XxXgCIV1/Zc/dRuFEyw1L0pbA+qynJkW5Q=="
+ },
+ "acorn-walk": {
+ "version": "8.2.0",
+ "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz",
+ "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA=="
+ },
+ "ansi-styles": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+ "requires": {
+ "color-convert": "^2.0.1"
+ }
+ },
+ "chalk": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
+ "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
+ "requires": {
+ "ansi-styles": "^4.1.0",
+ "supports-color": "^7.1.0"
+ }
+ },
+ "color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "requires": {
+ "color-name": "~1.1.4"
+ }
+ },
+ "color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="
+ },
+ "commander": {
+ "version": "6.2.1",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-6.2.1.tgz",
+ "integrity": "sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA=="
+ },
+ "has-flag": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="
+ },
+ "supports-color": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+ "requires": {
+ "has-flag": "^4.0.0"
+ }
+ },
+ "ws": {
+ "version": "7.5.5",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.5.tgz",
+ "integrity": "sha512-BAkMFcAzl8as1G/hArkxOxq3G7pjUqQ3gzYbLL0/5zNkph70e+lCoxBGnm6AW1+/aiNeV4fnKqZ8m4GZewmH2w=="
+ }
+ }
+ },
"webpack-dev-middleware": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-3.7.2.tgz",
diff --git a/UI/Web/package.json b/UI/Web/package.json
index 42caf67ec..515c35df8 100644
--- a/UI/Web/package.json
+++ b/UI/Web/package.json
@@ -6,7 +6,7 @@
"start": "ng serve",
"build": "ng build",
"prod": "ng build --prod",
- "explore": "ng build --stats-json && webpack-bundle-analyzer ../kavita/API/wwwroot/stats.json",
+ "explore": "ng build --stats-json && webpack-bundle-analyzer dist/stats.json",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
@@ -17,6 +17,7 @@
"dependencies": {
"@angular-slider/ngx-slider": "^2.0.3",
"@angular/animations": "~11.0.0",
+ "@angular/cdk": "^12.2.3",
"@angular/common": "~11.0.0",
"@angular/compiler": "~11.0.0",
"@angular/core": "~11.0.0",
@@ -45,6 +46,7 @@
"rxjs": "~6.6.0",
"swiper": "^6.5.8",
"tslib": "^2.0.0",
+ "webpack-bundle-analyzer": "^4.4.2",
"zone.js": "~0.10.2"
},
"devDependencies": {
diff --git a/UI/Web/src/app/_guards/admin.guard.ts b/UI/Web/src/app/_guards/admin.guard.ts
index e9483530e..b88c8d51c 100644
--- a/UI/Web/src/app/_guards/admin.guard.ts
+++ b/UI/Web/src/app/_guards/admin.guard.ts
@@ -19,7 +19,7 @@ export class AdminGuard implements CanActivate {
if (this.accountService.hasAdminRole(user)) {
return true;
}
-
+
this.toastr.error('You are not authorized to view this page.');
return false;
})
diff --git a/UI/Web/src/app/_guards/auth.guard.ts b/UI/Web/src/app/_guards/auth.guard.ts
index f477290fc..924f03bf2 100644
--- a/UI/Web/src/app/_guards/auth.guard.ts
+++ b/UI/Web/src/app/_guards/auth.guard.ts
@@ -19,7 +19,9 @@ export class AuthGuard implements CanActivate {
if (user) {
return true;
}
- this.toastr.error('You are not authorized to view this page.');
+ if (this.toastr.toasts.filter(toast => toast.message === 'Unauthorized' || toast.message === 'You are not authorized to view this page.').length === 0) {
+ this.toastr.error('You are not authorized to view this page.');
+ }
localStorage.setItem(this.urlKey, window.location.pathname);
this.router.navigateByUrl('/libraries');
return false;
diff --git a/UI/Web/src/app/_models/events/scan-library-event.ts b/UI/Web/src/app/_models/events/scan-library-event.ts
new file mode 100644
index 000000000..b0c663502
--- /dev/null
+++ b/UI/Web/src/app/_models/events/scan-library-event.ts
@@ -0,0 +1,4 @@
+export interface ScanLibraryEvent {
+ libraryId: number;
+ stage: 'complete';
+}
\ No newline at end of file
diff --git a/UI/Web/src/app/_models/events/scan-series-event.ts b/UI/Web/src/app/_models/events/scan-series-event.ts
new file mode 100644
index 000000000..45f7a07bc
--- /dev/null
+++ b/UI/Web/src/app/_models/events/scan-series-event.ts
@@ -0,0 +1,3 @@
+export interface ScanSeriesEvent {
+ seriesId: number;
+}
\ No newline at end of file
diff --git a/UI/Web/src/app/_models/reading-list.ts b/UI/Web/src/app/_models/reading-list.ts
new file mode 100644
index 000000000..ad1a325b8
--- /dev/null
+++ b/UI/Web/src/app/_models/reading-list.ts
@@ -0,0 +1,23 @@
+import { MangaFormat } from "./manga-format";
+
+export interface ReadingListItem {
+ pagesRead: number;
+ pagesTotal: number;
+ seriesName: string;
+ seriesFormat: MangaFormat;
+ seriesId: number;
+ chapterId: number;
+ order: number;
+ chapterNumber: string;
+ volumeNumber: string;
+ libraryId: number;
+ id: number;
+}
+
+export interface ReadingList {
+ id: number;
+ title: string;
+ summary: string;
+ promoted: boolean;
+ items: Array<ReadingListItem>;
+}
\ No newline at end of file
diff --git a/UI/Web/src/app/_models/series.ts b/UI/Web/src/app/_models/series.ts
index 5d163cddf..be233122b 100644
--- a/UI/Web/src/app/_models/series.ts
+++ b/UI/Web/src/app/_models/series.ts
@@ -8,7 +8,6 @@ export interface Series {
localizedName: string;
sortName: string;
summary: string;
- coverImage: string; // This is not passed from backend any longer. TODO: Remove this field
coverImageLocked: boolean;
volumes: Volume[];
pages: number; // Total pages in series
diff --git a/UI/Web/src/app/_services/action-factory.service.ts b/UI/Web/src/app/_services/action-factory.service.ts
index 178e72400..450b577bc 100644
--- a/UI/Web/src/app/_services/action-factory.service.ts
+++ b/UI/Web/src/app/_services/action-factory.service.ts
@@ -3,6 +3,7 @@ import { Chapter } from '../_models/chapter';
import { CollectionTag } from '../_models/collection-tag';
import { Library } from '../_models/library';
import { MangaFormat } from '../_models/manga-format';
+import { ReadingList } from '../_models/reading-list';
import { Series } from '../_models/series';
import { Volume } from '../_models/volume';
import { AccountService } from './account.service';
@@ -16,7 +17,9 @@ export enum Action {
Info = 5,
RefreshMetadata = 6,
Download = 7,
- Bookmarks = 8
+ Bookmarks = 8,
+ IncognitoRead = 9,
+ AddToReadingList = 10
}
export interface ActionItem<T> {
@@ -41,6 +44,8 @@ export class ActionFactoryService {
collectionTagActions: Array<ActionItem<CollectionTag>> = [];
+ readingListActions: Array<ActionItem<ReadingList>> = [];
+
isAdmin = false;
hasDownloadRole = false;
@@ -108,7 +113,7 @@ export class ActionFactoryService {
this.chapterActions.push({
action: Action.Edit,
- title: 'Edit',
+ title: 'Info',
callback: this.dummyCallback,
requiresAdmin: false
});
@@ -133,28 +138,39 @@ export class ActionFactoryService {
}
getLibraryActions(callback: (action: Action, library: Library) => void) {
- this.libraryActions.forEach(action => action.callback = callback);
- return this.libraryActions;
+ const actions = this.libraryActions.map(a => {return {...a}});
+ actions.forEach(action => action.callback = callback);
+ return actions;
}
getSeriesActions(callback: (action: Action, series: Series) => void) {
- this.seriesActions.forEach(action => action.callback = callback);
- return this.seriesActions;
+ const actions = this.seriesActions.map(a => {return {...a}});
+ actions.forEach(action => action.callback = callback);
+ return actions;
}
getVolumeActions(callback: (action: Action, volume: Volume) => void) {
- this.volumeActions.forEach(action => action.callback = callback);
- return this.volumeActions;
+ const actions = this.volumeActions.map(a => {return {...a}});
+ actions.forEach(action => action.callback = callback);
+ return actions;
}
getChapterActions(callback: (action: Action, chapter: Chapter) => void) {
- this.chapterActions.forEach(action => action.callback = callback);
- return this.chapterActions;
+ const actions = this.chapterActions.map(a => {return {...a}});
+ actions.forEach(action => action.callback = callback);
+ return actions;
}
getCollectionTagActions(callback: (action: Action, collectionTag: CollectionTag) => void) {
- this.collectionTagActions.forEach(action => action.callback = callback);
- return this.collectionTagActions;
+ const actions = this.collectionTagActions.map(a => {return {...a}});
+ actions.forEach(action => action.callback = callback);
+ return actions;
+ }
+
+ getReadingListActions(callback: (action: Action, readingList: ReadingList) => void) {
+ const actions = this.readingListActions.map(a => {return {...a}});
+ actions.forEach(action => action.callback = callback);
+ return actions;
}
filterBookmarksForFormat(action: ActionItem<Series>, series: Series) {
@@ -187,7 +203,13 @@ export class ActionFactoryService {
title: 'Bookmarks',
callback: this.dummyCallback,
requiresAdmin: false
- }
+ },
+ {
+ action: Action.AddToReadingList,
+ title: 'Add to Reading List',
+ callback: this.dummyCallback,
+ requiresAdmin: false
+ },
];
this.volumeActions = [
@@ -203,6 +225,18 @@ export class ActionFactoryService {
callback: this.dummyCallback,
requiresAdmin: false
},
+ {
+ action: Action.AddToReadingList,
+ title: 'Add to Reading List',
+ callback: this.dummyCallback,
+ requiresAdmin: false
+ },
+ {
+ action: Action.IncognitoRead,
+ title: 'Read in Incognito',
+ callback: this.dummyCallback,
+ requiresAdmin: false
+ },
{
action: Action.Edit,
title: 'Info',
@@ -223,7 +257,34 @@ export class ActionFactoryService {
title: 'Mark as Unread',
callback: this.dummyCallback,
requiresAdmin: false
- }
+ },
+ {
+ action: Action.IncognitoRead,
+ title: 'Read in Incognito',
+ callback: this.dummyCallback,
+ requiresAdmin: false
+ },
+ {
+ action: Action.AddToReadingList,
+ title: 'Add to Reading List',
+ callback: this.dummyCallback,
+ requiresAdmin: false
+ },
+ ];
+
+ this.readingListActions = [
+ {
+ action: Action.Edit,
+ title: 'Edit',
+ callback: this.dummyCallback,
+ requiresAdmin: false
+ },
+ {
+ action: Action.Delete,
+ title: 'Delete',
+ callback: this.dummyCallback,
+ requiresAdmin: false
+ },
];
}
}
diff --git a/UI/Web/src/app/_services/action.service.ts b/UI/Web/src/app/_services/action.service.ts
index 3e400a80b..0cdfb3cfe 100644
--- a/UI/Web/src/app/_services/action.service.ts
+++ b/UI/Web/src/app/_services/action.service.ts
@@ -1,11 +1,14 @@
import { Injectable, OnDestroy } from '@angular/core';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
-import { forkJoin, Subject } from 'rxjs';
-import { take, takeUntil } from 'rxjs/operators';
+import { Subject } from 'rxjs';
+import { take } from 'rxjs/operators';
import { BookmarksModalComponent } from '../cards/_modals/bookmarks-modal/bookmarks-modal.component';
+import { AddToListModalComponent, ADD_FLOW } from '../reading-list/_modals/add-to-list-modal/add-to-list-modal.component';
+import { EditReadingListModalComponent } from '../reading-list/_modals/edit-reading-list-modal/edit-reading-list-modal.component';
import { Chapter } from '../_models/chapter';
import { Library } from '../_models/library';
+import { ReadingList } from '../_models/reading-list';
import { Series } from '../_models/series';
import { Volume } from '../_models/volume';
import { LibraryService } from './library.service';
@@ -16,6 +19,8 @@ export type LibraryActionCallback = (library: Partial<Library>) => void;
export type SeriesActionCallback = (series: Series) => void;
export type VolumeActionCallback = (volume: Volume) => void;
export type ChapterActionCallback = (chapter: Chapter) => void;
+export type ReadingListActionCallback = (readingList: ReadingList) => void;
+export type VoidActionCallback = () => void;
/**
* Responsible for executing actions
@@ -27,6 +32,7 @@ export class ActionService implements OnDestroy {
private readonly onDestroy = new Subject<void>();
private bookmarkModalRef: NgbModalRef | null = null;
+ private readingListModalRef: NgbModalRef | null = null;
constructor(private libraryService: LibraryService, private seriesService: SeriesService,
private readerService: ReaderService, private toastr: ToastrService, private modalService: NgbModal) { }
@@ -156,7 +162,7 @@ export class ActionService implements OnDestroy {
* @param callback Optional callback to perform actions after API completes
*/
markVolumeAsUnread(seriesId: number, volume: Volume, callback?: VolumeActionCallback) {
- this.readerService.markVolumeRead(seriesId, volume.id).subscribe(() => {
+ this.readerService.markVolumeUnread(seriesId, volume.id).subscribe(() => {
volume.pagesRead = 0;
volume.chapters?.forEach(c => c.pagesRead = 0);
this.toastr.success('Marked as Unread');
@@ -198,6 +204,85 @@ export class ActionService implements OnDestroy {
});
}
+ /**
+ * Mark all chapters and the volumes as Read. All volumes and chapters must belong to a series
+ * @param seriesId Series Id
+ * @param volumes Volumes, should have id, chapters and pagesRead populated
+ * @param chapters? Chapters, should have id
+ * @param callback Optional callback to perform actions after API completes
+ */
+ markMultipleAsRead(seriesId: number, volumes: Array<Volume>, chapters?: Array<Chapter>, callback?: VoidActionCallback) {
+ this.readerService.markMultipleRead(seriesId, volumes.map(v => v.id), chapters?.map(c => c.id)).pipe(take(1)).subscribe(() => {
+ volumes.forEach(volume => {
+ volume.pagesRead = volume.pages;
+ volume.chapters?.forEach(c => c.pagesRead = c.pages);
+ });
+ chapters?.forEach(c => c.pagesRead = c.pages);
+ this.toastr.success('Marked as Read');
+
+ if (callback) {
+ callback();
+ }
+ });
+ }
+
+ /**
+ * Mark all chapters and the volumes as Unread. All volumes must belong to a series
+ * @param seriesId Series Id
+ * @param volumes Volumes, should have id, chapters and pagesRead populated
+ * @param callback Optional callback to perform actions after API completes
+ */
+ markMultipleAsUnread(seriesId: number, volumes: Array<Volume>, chapters?: Array<Chapter>, callback?: VoidActionCallback) {
+ this.readerService.markMultipleUnread(seriesId, volumes.map(v => v.id), chapters?.map(c => c.id)).pipe(take(1)).subscribe(() => {
+ volumes.forEach(volume => {
+ volume.pagesRead = volume.pages;
+ volume.chapters?.forEach(c => c.pagesRead = c.pages);
+ });
+ chapters?.forEach(c => c.pagesRead = c.pages);
+ this.toastr.success('Marked as Read');
+
+ if (callback) {
+ callback();
+ }
+ });
+ }
+
+ /**
+ * Mark all series as Read.
+ * @param series Series, should have id, pagesRead populated
+ * @param callback Optional callback to perform actions after API completes
+ */
+ markMultipleSeriesAsRead(series: Array<Series>, callback?: VoidActionCallback) {
+ this.readerService.markMultipleSeriesRead(series.map(v => v.id)).pipe(take(1)).subscribe(() => {
+ series.forEach(s => {
+ s.pagesRead = s.pages;
+ });
+ this.toastr.success('Marked as Read');
+
+ if (callback) {
+ callback();
+ }
+ });
+ }
+
+ /**
+ * Mark all series as Unread.
+ * @param series Series, should have id, pagesRead populated
+ * @param callback Optional callback to perform actions after API completes
+ */
+ markMultipleSeriesAsUnread(series: Array<Series>, callback?: VoidActionCallback) {
+ this.readerService.markMultipleSeriesUnread(series.map(v => v.id)).pipe(take(1)).subscribe(() => {
+ series.forEach(s => {
+ s.pagesRead = s.pages;
+ });
+ this.toastr.success('Marked as Unread');
+
+ if (callback) {
+ callback();
+ }
+ });
+ }
+
openBookmarkModal(series: Series, callback?: SeriesActionCallback) {
if (this.bookmarkModalRef != null) { return; }
@@ -217,4 +302,131 @@ export class ActionService implements OnDestroy {
});
}
+ addMultipleToReadingList(seriesId: number, volumes: Array<Volume>, chapters?: Array<Chapter>, callback?: VoidActionCallback) {
+ if (this.readingListModalRef != null) { return; }
+ this.readingListModalRef = this.modalService.open(AddToListModalComponent, { scrollable: true, size: 'md' });
+ this.readingListModalRef.componentInstance.seriesId = seriesId;
+ this.readingListModalRef.componentInstance.volumeIds = volumes.map(v => v.id);
+ this.readingListModalRef.componentInstance.chapterIds = chapters?.map(c => c.id);
+ this.readingListModalRef.componentInstance.title = 'Multiple Selections';
+ this.readingListModalRef.componentInstance.type = ADD_FLOW.Multiple;
+
+
+ this.readingListModalRef.closed.pipe(take(1)).subscribe(() => {
+ this.readingListModalRef = null;
+ if (callback) {
+ callback();
+ }
+ });
+ this.readingListModalRef.dismissed.pipe(take(1)).subscribe(() => {
+ this.readingListModalRef = null;
+ if (callback) {
+ callback();
+ }
+ });
+ }
+
+ addMultipleSeriesToReadingList(series: Array<Series>, callback?: VoidActionCallback) {
+ if (this.readingListModalRef != null) { return; }
+ this.readingListModalRef = this.modalService.open(AddToListModalComponent, { scrollable: true, size: 'md' });
+ this.readingListModalRef.componentInstance.seriesIds = series.map(v => v.id);
+ this.readingListModalRef.componentInstance.title = 'Multiple Selections';
+ this.readingListModalRef.componentInstance.type = ADD_FLOW.Multiple_Series;
+
+
+ this.readingListModalRef.closed.pipe(take(1)).subscribe(() => {
+ this.readingListModalRef = null;
+ if (callback) {
+ callback();
+ }
+ });
+ this.readingListModalRef.dismissed.pipe(take(1)).subscribe(() => {
+ this.readingListModalRef = null;
+ if (callback) {
+ callback();
+ }
+ });
+ }
+
+ addSeriesToReadingList(series: Series, callback?: SeriesActionCallback) {
+ if (this.readingListModalRef != null) { return; }
+ this.readingListModalRef = this.modalService.open(AddToListModalComponent, { scrollable: true, size: 'md' });
+ this.readingListModalRef.componentInstance.seriesId = series.id;
+ this.readingListModalRef.componentInstance.title = series.name;
+ this.readingListModalRef.componentInstance.type = ADD_FLOW.Series;
+
+
+ this.readingListModalRef.closed.pipe(take(1)).subscribe(() => {
+ this.readingListModalRef = null;
+ if (callback) {
+ callback(series);
+ }
+ });
+ this.readingListModalRef.dismissed.pipe(take(1)).subscribe(() => {
+ this.readingListModalRef = null;
+ if (callback) {
+ callback(series);
+ }
+ });
+ }
+
+ addVolumeToReadingList(volume: Volume, seriesId: number, callback?: VolumeActionCallback) {
+ if (this.readingListModalRef != null) { return; }
+ this.readingListModalRef = this.modalService.open(AddToListModalComponent, { scrollable: true, size: 'md' });
+ this.readingListModalRef.componentInstance.seriesId = seriesId;
+ this.readingListModalRef.componentInstance.volumeId = volume.id;
+ this.readingListModalRef.componentInstance.type = ADD_FLOW.Volume;
+
+
+ this.readingListModalRef.closed.pipe(take(1)).subscribe(() => {
+ this.readingListModalRef = null;
+ if (callback) {
+ callback(volume);
+ }
+ });
+ this.readingListModalRef.dismissed.pipe(take(1)).subscribe(() => {
+ this.readingListModalRef = null;
+ if (callback) {
+ callback(volume);
+ }
+ });
+ }
+
+ addChapterToReadingList(chapter: Chapter, seriesId: number, callback?: ChapterActionCallback) {
+ if (this.readingListModalRef != null) { return; }
+ this.readingListModalRef = this.modalService.open(AddToListModalComponent, { scrollable: true, size: 'md' });
+ this.readingListModalRef.componentInstance.seriesId = seriesId;
+ this.readingListModalRef.componentInstance.chapterId = chapter.id;
+ this.readingListModalRef.componentInstance.type = ADD_FLOW.Chapter;
+
+
+ this.readingListModalRef.closed.pipe(take(1)).subscribe(() => {
+ this.readingListModalRef = null;
+ if (callback) {
+ callback(chapter);
+ }
+ });
+ this.readingListModalRef.dismissed.pipe(take(1)).subscribe(() => {
+ this.readingListModalRef = null;
+ if (callback) {
+ callback(chapter);
+ }
+ });
+ }
+
+ editReadingList(readingList: ReadingList, callback?: ReadingListActionCallback) {
+ const readingListModalRef = this.modalService.open(EditReadingListModalComponent, { scrollable: true, size: 'md' });
+ readingListModalRef.componentInstance.readingList = readingList;
+ readingListModalRef.closed.pipe(take(1)).subscribe((list) => {
+ if (callback && list !== undefined) {
+ callback(readingList);
+ }
+ });
+ readingListModalRef.dismissed.pipe(take(1)).subscribe((list) => {
+ if (callback && list !== undefined) {
+ callback(readingList);
+ }
+ });
+ }
+
}
diff --git a/UI/Web/src/app/_services/library.service.ts b/UI/Web/src/app/_services/library.service.ts
index e6991e592..2c0b06f1f 100644
--- a/UI/Web/src/app/_services/library.service.ts
+++ b/UI/Web/src/app/_services/library.service.ts
@@ -37,7 +37,7 @@ export class LibraryService {
listDirectories(rootPath: string) {
let query = '';
if (rootPath !== undefined && rootPath.length > 0) {
- query = '?path=' + rootPath;
+ query = '?path=' + encodeURIComponent(rootPath);
}
return this.httpClient.get<string[]>(this.baseUrl + 'library/list' + query);
diff --git a/UI/Web/src/app/_services/message-hub.service.ts b/UI/Web/src/app/_services/message-hub.service.ts
index 33c39f18b..f5d193f6a 100644
--- a/UI/Web/src/app/_services/message-hub.service.ts
+++ b/UI/Web/src/app/_services/message-hub.service.ts
@@ -1,13 +1,18 @@
-import { Injectable } from '@angular/core';
+import { EventEmitter, Injectable } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@microsoft/signalr';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { User } from '@sentry/angular';
import { BehaviorSubject, ReplaySubject } from 'rxjs';
import { environment } from 'src/environments/environment';
import { UpdateNotificationModalComponent } from '../shared/update-notification/update-notification-modal.component';
+import { ScanLibraryEvent } from '../_models/events/scan-library-event';
+import { ScanSeriesEvent } from '../_models/events/scan-series-event';
export enum EVENTS {
- UpdateAvailable = 'UpdateAvailable'
+ UpdateAvailable = 'UpdateAvailable',
+ ScanSeries = 'ScanSeries',
+ ScanLibrary = 'ScanLibrary',
+ RefreshMetadata = 'RefreshMetadata',
}
export interface Message<T> {
@@ -26,6 +31,9 @@ export class MessageHubService {
private messagesSource = new ReplaySubject<Message<any>>(1);
public messages$ = this.messagesSource.asObservable();
+ public scanSeries: EventEmitter<ScanSeriesEvent> = new EventEmitter<ScanSeriesEvent>();
+ public scanLibrary: EventEmitter<ScanLibraryEvent> = new EventEmitter<ScanLibraryEvent>();
+
constructor(private modalService: NgbModal) { }
createHubConnection(user: User) {
@@ -44,6 +52,25 @@ export class MessageHubService {
//console.log('[Hub] Body: ', body);
});
+ this.hubConnection.on(EVENTS.ScanSeries, resp => {
+ this.messagesSource.next({
+ event: EVENTS.ScanSeries,
+ payload: resp.body
+ });
+ this.scanSeries.emit(resp.body);
+ });
+
+ this.hubConnection.on(EVENTS.ScanLibrary, resp => {
+ this.messagesSource.next({
+ event: EVENTS.ScanLibrary,
+ payload: resp.body
+ });
+ this.scanLibrary.emit(resp.body);
+ // if ((resp.body as ScanLibraryEvent).stage === 'complete') {
+ // this.toastr.
+ // }
+ });
+
this.hubConnection.on(EVENTS.UpdateAvailable, resp => {
this.messagesSource.next({
event: EVENTS.UpdateAvailable,
diff --git a/UI/Web/src/app/_services/reader.service.ts b/UI/Web/src/app/_services/reader.service.ts
index 042eab4a0..8281ab9e9 100644
--- a/UI/Web/src/app/_services/reader.service.ts
+++ b/UI/Web/src/app/_services/reader.service.ts
@@ -56,8 +56,8 @@ export class ReaderService {
return this.baseUrl + 'reader/image?chapterId=' + chapterId + '&page=' + page;
}
- getChapterInfo(seriesId: number, chapterId: number) {
- return this.httpClient.get<ChapterInfo>(this.baseUrl + 'reader/chapter-info?chapterId=' + chapterId + '&seriesId=' + seriesId);
+ getChapterInfo(chapterId: number) {
+ return this.httpClient.get<ChapterInfo>(this.baseUrl + 'reader/chapter-info?chapterId=' + chapterId);
}
saveProgress(seriesId: number, volumeId: number, chapterId: number, page: number, bookScrollId: string | null = null) {
@@ -68,17 +68,44 @@ export class ReaderService {
return this.httpClient.post(this.baseUrl + 'reader/mark-volume-read', {seriesId, volumeId});
}
- getNextChapter(seriesId: number, volumeId: number, currentChapterId: number) {
+ markMultipleRead(seriesId: number, volumeIds: Array<number>, chapterIds?: Array<number>) {
+ return this.httpClient.post(this.baseUrl + 'reader/mark-multiple-read', {seriesId, volumeIds, chapterIds});
+ }
+
+ markMultipleUnread(seriesId: number, volumeIds: Array<number>, chapterIds?: Array<number>) {
+ return this.httpClient.post(this.baseUrl + 'reader/mark-multiple-unread', {seriesId, volumeIds, chapterIds});
+ }
+
+ markMultipleSeriesRead(seriesIds: Array<number>) {
+ return this.httpClient.post(this.baseUrl + 'reader/mark-multiple-series-read', {seriesIds});
+ }
+
+ markMultipleSeriesUnread(seriesIds: Array<number>) {
+ return this.httpClient.post(this.baseUrl + 'reader/mark-multiple-series-unread', {seriesIds});
+ }
+
+ markVolumeUnread(seriesId: number, volumeId: number) {
+ return this.httpClient.post(this.baseUrl + 'reader/mark-volume-unread', {seriesId, volumeId});
+ }
+
+
+ getNextChapter(seriesId: number, volumeId: number, currentChapterId: number, readingListId: number = -1) {
+ if (readingListId > 0) {
+ return this.httpClient.get<number>(this.baseUrl + 'readinglist/next-chapter?seriesId=' + seriesId + '&currentChapterId=' + currentChapterId + '&readingListId=' + readingListId);
+ }
return this.httpClient.get<number>(this.baseUrl + 'reader/next-chapter?seriesId=' + seriesId + '&volumeId=' + volumeId + '&currentChapterId=' + currentChapterId);
}
- getPrevChapter(seriesId: number, volumeId: number, currentChapterId: number) {
+ getPrevChapter(seriesId: number, volumeId: number, currentChapterId: number, readingListId: number = -1) {
+ if (readingListId > 0) {
+ return this.httpClient.get<number>(this.baseUrl + 'readinglist/prev-chapter?seriesId=' + seriesId + '&currentChapterId=' + currentChapterId + '&readingListId=' + readingListId);
+ }
return this.httpClient.get<number>(this.baseUrl + 'reader/prev-chapter?seriesId=' + seriesId + '&volumeId=' + volumeId + '&currentChapterId=' + currentChapterId);
}
getCurrentChapter(volumes: Array<Volume>): Chapter {
let currentlyReadingChapter: Chapter | undefined = undefined;
- const chapters = volumes.filter(v => v.number !== 0).map(v => v.chapters || []).flat().sort(this.utilityService.sortChapters); // changed from === 0 to != 0
+ const chapters = volumes.filter(v => v.number !== 0).map(v => v.chapters || []).flat().sort(this.utilityService.sortChapters);
for (const c of chapters) {
if (c.pagesRead < c.pages) {
@@ -132,4 +159,38 @@ export class ReaderService {
if (imageSrc === undefined || imageSrc === '') { return -1; }
return parseInt(imageSrc.split('&page=')[1], 10);
}
+
+ getNextChapterUrl(url: string, nextChapterId: number, incognitoMode: boolean = false, readingListMode: boolean = false, readingListId: number = -1) {
+ const lastSlashIndex = url.lastIndexOf('/');
+ let newRoute = url.substring(0, lastSlashIndex + 1) + nextChapterId + '';
+ newRoute += this.getQueryParams(incognitoMode, readingListMode, readingListId);
+ return newRoute;
+ }
+
+
+ getQueryParamsObject(incognitoMode: boolean = false, readingListMode: boolean = false, readingListId: number = -1) {
+ let params: {[key: string]: any} = {};
+ if (incognitoMode) {
+ params['incognitoMode'] = true;
+ }
+ if (readingListMode) {
+ params['readingListId'] = readingListId;
+ }
+ return params;
+ }
+
+ getQueryParams(incognitoMode: boolean = false, readingListMode: boolean = false, readingListId: number = -1) {
+ let params = '';
+ if (incognitoMode) {
+ params += '?incognitoMode=true';
+ }
+ if (readingListMode) {
+ if (params.indexOf('?') > 0) {
+ params += '&readingListId=' + readingListId;
+ } else {
+ params += '?readingListId=' + readingListId;
+ }
+ }
+ return params;
+ }
}
diff --git a/UI/Web/src/app/_services/reading-list.service.ts b/UI/Web/src/app/_services/reading-list.service.ts
new file mode 100644
index 000000000..e520154d6
--- /dev/null
+++ b/UI/Web/src/app/_services/reading-list.service.ts
@@ -0,0 +1,110 @@
+import { HttpClient, HttpParams } from '@angular/common/http';
+import { Injectable } from '@angular/core';
+import { map } from 'rxjs/operators';
+import { environment } from 'src/environments/environment';
+import { PaginatedResult } from '../_models/pagination';
+import { ReadingList, ReadingListItem } from '../_models/reading-list';
+import { ActionItem } from './action-factory.service';
+
+@Injectable({
+ providedIn: 'root'
+})
+export class ReadingListService {
+
+ baseUrl = environment.apiUrl;
+
+ constructor(private httpClient: HttpClient) { }
+
+ getReadingList(readingListId: number) {
+ return this.httpClient.get<ReadingList>(this.baseUrl + 'readinglist?readingListId=' + readingListId);
+ }
+
+ getReadingLists(includePromoted: boolean = true, pageNum?: number, itemsPerPage?: number) {
+ let params = new HttpParams();
+ params = this._addPaginationIfExists(params, pageNum, itemsPerPage);
+
+ return this.httpClient.post<PaginatedResult<ReadingList[]>>(this.baseUrl + 'readinglist/lists?includePromoted=' + includePromoted, {}, {observe: 'response', params}).pipe(
+ map((response: any) => {
+ return this._cachePaginatedResults(response, new PaginatedResult<ReadingList[]>());
+ })
+ );
+ }
+
+ getListItems(readingListId: number) {
+ return this.httpClient.get<ReadingListItem[]>(this.baseUrl + 'readinglist/items?readingListId=' + readingListId);
+ }
+
+ createList(title: string) {
+ return this.httpClient.post<ReadingList>(this.baseUrl + 'readinglist/create', {title});
+ }
+
+ update(model: {readingListId: number, title?: string, summary?: string, promoted: boolean}) {
+ return this.httpClient.post(this.baseUrl + 'readinglist/update', model, { responseType: 'text' as 'json' });
+ }
+
+ updateByMultiple(readingListId: number, seriesId: number, volumeIds: Array<number>, chapterIds?: Array<number>) {
+ return this.httpClient.post(this.baseUrl + 'readinglist/update-by-multiple', {readingListId, seriesId, volumeIds, chapterIds});
+ }
+
+ updateByMultipleSeries(readingListId: number, seriesIds: Array<number>) {
+ return this.httpClient.post(this.baseUrl + 'readinglist/update-by-multiple-series', {readingListId, seriesIds});
+ }
+
+ updateBySeries(readingListId: number, seriesId: number) {
+ return this.httpClient.post(this.baseUrl + 'readinglist/update-by-series', {readingListId, seriesId}, { responseType: 'text' as 'json' });
+ }
+
+ updateByVolume(readingListId: number, seriesId: number, volumeId: number) {
+ return this.httpClient.post(this.baseUrl + 'readinglist/update-by-volume', {readingListId, seriesId, volumeId}, { responseType: 'text' as 'json' });
+ }
+
+ updateByChapter(readingListId: number, seriesId: number, chapterId: number) {
+ return this.httpClient.post(this.baseUrl + 'readinglist/update-by-chapter', {readingListId, seriesId, chapterId}, { responseType: 'text' as 'json' });
+ }
+
+ delete(readingListId: number) {
+ return this.httpClient.delete(this.baseUrl + 'readinglist?readingListId=' + readingListId, { responseType: 'text' as 'json' });
+ }
+
+ updatePosition(readingListId: number, readingListItemId: number, fromPosition: number, toPosition: number) {
+ return this.httpClient.post(this.baseUrl + 'readinglist/update-position', {readingListId, readingListItemId, fromPosition, toPosition}, { responseType: 'text' as 'json' });
+ }
+
+ deleteItem(readingListId: number, readingListItemId: number) {
+ return this.httpClient.post(this.baseUrl + 'readinglist/delete-item', {readingListId, readingListItemId}, { responseType: 'text' as 'json' });
+ }
+
+ removeRead(readingListId: number) {
+ return this.httpClient.post(this.baseUrl + 'readinglist/remove-read?readingListId=' + readingListId, { responseType: 'text' as 'json' });
+ }
+
+ actionListFilter(action: ActionItem<ReadingList>, readingList: ReadingList, isAdmin: boolean) {
+ if (readingList?.promoted && !isAdmin) return false;
+ return true;
+ }
+
+ _addPaginationIfExists(params: HttpParams, pageNum?: number, itemsPerPage?: number) {
+ // TODO: Move to utility service
+ if (pageNum !== null && pageNum !== undefined && itemsPerPage !== null && itemsPerPage !== undefined) {
+ params = params.append('pageNumber', pageNum + '');
+ params = params.append('pageSize', itemsPerPage + '');
+ }
+ return params;
+ }
+
+ _cachePaginatedResults(response: any, paginatedVariable: PaginatedResult<any[]>) {
+ // TODO: Move to utility service
+ if (response.body === null) {
+ paginatedVariable.result = [];
+ } else {
+ paginatedVariable.result = response.body;
+ }
+
+ const pageHeader = response.headers.get('Pagination');
+ if (pageHeader !== null) {
+ paginatedVariable.pagination = JSON.parse(pageHeader);
+ }
+
+ return paginatedVariable;
+ }
+}
diff --git a/UI/Web/src/app/admin/_modals/directory-picker/directory-picker.component.html b/UI/Web/src/app/admin/_modals/directory-picker/directory-picker.component.html
index 78440a06b..6f6d02630 100644
--- a/UI/Web/src/app/admin/_modals/directory-picker/directory-picker.component.html
+++ b/UI/Web/src/app/admin/_modals/directory-picker/directory-picker.component.html
@@ -9,7 +9,7 @@
<div class="form-group">
<label for="filter">Filter</label>
<div class="input-group">
- <input id="filter" autocomplete="false" class="form-control" [(ngModel)]="filterQuery" type="text" aria-describedby="reset-input">
+ <input id="filter" autocomplete="off" class="form-control" [(ngModel)]="filterQuery" type="text" aria-describedby="reset-input">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="reset-input" (click)="filterQuery = '';">Clear</button>
</div>
@@ -27,7 +27,7 @@
</li>
</ol>
<ng-template #noBreadcrumb>
- <div class="breadcrumb">Select a folder to view breadcrumb</div>
+ <div class="breadcrumb">Select a folder to view breadcrumb. Don't see your directory, try checking / first.</div>
</ng-template>
</nav>
<ul class="list-group">
@@ -50,5 +50,6 @@
</ul>
</div>
<div class="modal-footer">
+ <a class="btn btn-info" href="https://wiki.kavitareader.com/en/guides/adding-a-library" target="_blank">Help</a>
<button type="button" class="btn btn-secondary" (click)="close()">Cancel</button>
</div>
diff --git a/UI/Web/src/app/admin/_modals/library-access-modal/library-access-modal.component.html b/UI/Web/src/app/admin/_modals/library-access-modal/library-access-modal.component.html
index 458880b5e..de4001387 100644
--- a/UI/Web/src/app/admin/_modals/library-access-modal/library-access-modal.component.html
+++ b/UI/Web/src/app/admin/_modals/library-access-modal/library-access-modal.component.html
@@ -14,6 +14,9 @@
<label attr.for="library-{{i}}" class="form-check-label">{{library.data.name}}</label>
</div>
</li>
+ <li class="list-group-item" *ngIf="selectedLibraries.length === 0">
+ There are no libraries setup yet.
+ </li>
</div>
</div>
<div class="modal-footer">
diff --git a/UI/Web/src/app/admin/_modals/library-editor-modal/library-editor-modal.component.ts b/UI/Web/src/app/admin/_modals/library-editor-modal/library-editor-modal.component.ts
index f1257aa8d..441a1ca2a 100644
--- a/UI/Web/src/app/admin/_modals/library-editor-modal/library-editor-modal.component.ts
+++ b/UI/Web/src/app/admin/_modals/library-editor-modal/library-editor-modal.component.ts
@@ -1,6 +1,7 @@
import { Component, Input, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
+import { ToastrService } from 'ngx-toastr';
import { Library } from 'src/app/_models/library';
import { LibraryService } from 'src/app/_services/library.service';
import { SettingsService } from '../../settings.service';
@@ -26,7 +27,8 @@ export class LibraryEditorModalComponent implements OnInit {
libraryTypes: string[] = []
- constructor(private modalService: NgbModal, private libraryService: LibraryService, public modal: NgbActiveModal, private settingService: SettingsService) { }
+ constructor(private modalService: NgbModal, private libraryService: LibraryService, public modal: NgbActiveModal, private settingService: SettingsService,
+ private toastr: ToastrService) { }
ngOnInit(): void {
@@ -64,6 +66,7 @@ export class LibraryEditorModalComponent implements OnInit {
model.folders = model.folders.map((item: string) => item.startsWith('\\') ? item.substr(1, item.length) : item);
model.type = parseInt(model.type, 10);
this.libraryService.create(model).subscribe(() => {
+ this.toastr.success('Library created, a scan has been started');
this.close(true);
}, err => {
this.errorMessage = err;
diff --git a/UI/Web/src/app/admin/admin.module.ts b/UI/Web/src/app/admin/admin.module.ts
index 73b3717e3..5ffadf3a1 100644
--- a/UI/Web/src/app/admin/admin.module.ts
+++ b/UI/Web/src/app/admin/admin.module.ts
@@ -12,10 +12,10 @@ import { DirectoryPickerComponent } from './_modals/directory-picker/directory-p
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ResetPasswordModalComponent } from './_modals/reset-password-modal/reset-password-modal.component';
import { ManageSettingsComponent } from './manage-settings/manage-settings.component';
-import { FilterPipe } from './filter.pipe';
import { EditRbsModalComponent } from './_modals/edit-rbs-modal/edit-rbs-modal.component';
import { ManageSystemComponent } from './manage-system/manage-system.component';
import { ChangelogComponent } from './changelog/changelog.component';
+import { PipeModule } from '../pipe/pipe.module';
@@ -30,7 +30,6 @@ import { ChangelogComponent } from './changelog/changelog.component';
DirectoryPickerComponent,
ResetPasswordModalComponent,
ManageSettingsComponent,
- FilterPipe,
EditRbsModalComponent,
ManageSystemComponent,
ChangelogComponent,
@@ -44,6 +43,7 @@ import { ChangelogComponent } from './changelog/changelog.component';
NgbTooltipModule,
NgbDropdownModule,
SharedModule,
+ PipeModule
],
providers: []
})
diff --git a/UI/Web/src/app/admin/changelog/changelog.component.html b/UI/Web/src/app/admin/changelog/changelog.component.html
index 073b72b95..03ef9fe5d 100644
--- a/UI/Web/src/app/admin/changelog/changelog.component.html
+++ b/UI/Web/src/app/admin/changelog/changelog.component.html
@@ -1,7 +1,10 @@
<ng-container *ngFor="let update of updates; let indx = index;">
<div class="card w-100 mb-2" style="width: 18rem;">
<div class="card-body">
- <h5 class="card-title">{{update.updateTitle}}&nbsp;<span class="badge badge-secondary" *ngIf="update.updateVersion === update.currentVersion">Installed</span></h5>
+ <h5 class="card-title">{{update.updateTitle}}&nbsp;
+ <span class="badge badge-secondary" *ngIf="update.updateVersion === update.currentVersion">Installed</span>
+ <span class="badge badge-secondary" *ngIf="update.updateVersion > update.currentVersion">Available</span>
+ </h5>
<pre class="card-text update-body" [innerHtml]="update.updateBody | safeHtml"></pre>
<a *ngIf="!update.isDocker" href="{{update.updateUrl}}" class="btn btn-{{indx === 0 ? 'primary' : 'secondary'}} float-right" target="_blank">Download</a>
</div>
@@ -11,4 +14,4 @@
<div class="spinner-border text-secondary" *ngIf="isLoading" role="status">
<span class="invisible">Loading...</span>
-</div>
\ No newline at end of file
+</div>
diff --git a/UI/Web/src/app/admin/dashboard/dashboard.component.html b/UI/Web/src/app/admin/dashboard/dashboard.component.html
index 26886dd7f..9b34f71f8 100644
--- a/UI/Web/src/app/admin/dashboard/dashboard.component.html
+++ b/UI/Web/src/app/admin/dashboard/dashboard.component.html
@@ -1,7 +1,7 @@
<div class="container">
<h2>Admin Dashboard</h2>
- <ul ngbNav #nav="ngbNav" [(activeId)]="active" class="nav-tabs">
+ <ul ngbNav #nav="ngbNav" [(activeId)]="active" class="nav-tabs nav-pills">
<li *ngFor="let tab of tabs" [ngbNavItem]="tab">
<a ngbNavLink routerLink="." [fragment]="tab.fragment">{{ tab.title | titlecase }}</a>
<ng-template ngbNavContent>
diff --git a/UI/Web/src/app/admin/manage-users/manage-users.component.html b/UI/Web/src/app/admin/manage-users/manage-users.component.html
index b73841af4..5aff35f12 100644
--- a/UI/Web/src/app/admin/manage-users/manage-users.component.html
+++ b/UI/Web/src/app/admin/manage-users/manage-users.component.html
@@ -9,7 +9,7 @@
<li *ngFor="let member of members; let idx = index;" class="list-group-item">
<div>
<h4>
- <i class="presence fa fa-circle" title="Active" aria-hidden="true" *ngIf="false && (presence.onlineUsers$ | async)?.includes(member.username)"></i><span id="member-name--{{idx}}">{{member.username | titlecase}} </span><span *ngIf="member.isAdmin" class="badge badge-pill badge-secondary">Admin</span>
+ <i class="presence fa fa-circle" title="Active" aria-hidden="true" *ngIf="false && (presence.onlineUsers$ | async)?.includes(member.username)"></i><span id="member-name--{{idx}}">{{member.username | titlecase}} </span><span *ngIf="member.username === loggedInUsername">(You)</span>
<div class="float-right" *ngIf="canEditMember(member)">
<button class="btn btn-danger mr-2" (click)="deleteUser(member)" placement="top" ngbTooltip="Delete User" attr.aria-label="Delete User {{member.username | titlecase}}"><i class="fa fa-trash" aria-hidden="true"></i></button>
<button class="btn btn-secondary mr-2" (click)="updatePassword(member)" placement="top" ngbTooltip="Change Password" attr.aria-label="Change Password for {{member.username | titlecase}}"><i class="fa fa-key" aria-hidden="true"></i></button>
diff --git a/UI/Web/src/app/admin/manage-users/manage-users.component.ts b/UI/Web/src/app/admin/manage-users/manage-users.component.ts
index 48185ba56..fd3d50f62 100644
--- a/UI/Web/src/app/admin/manage-users/manage-users.component.ts
+++ b/UI/Web/src/app/admin/manage-users/manage-users.component.ts
@@ -53,7 +53,18 @@ export class ManageUsersComponent implements OnInit, OnDestroy {
loadMembers() {
this.loadingMembers = true;
this.memberService.getMembers().subscribe(members => {
- this.members = members.filter(member => member.username !== this.loggedInUsername);
+ this.members = members;
+ // Show logged in user at the top of the list
+ this.members.sort((a: Member, b: Member) => {
+ if (a.username === this.loggedInUsername) return 1;
+ if (b.username === this.loggedInUsername) return 1;
+
+ const nameA = a.username.toUpperCase();
+ const nameB = b.username.toUpperCase();
+ if (nameA < nameB) return -1;
+ if (nameA > nameB) return 1;
+ return 0;
+ })
this.loadingMembers = false;
});
}
diff --git a/UI/Web/src/app/app-routing.module.ts b/UI/Web/src/app/app-routing.module.ts
index 21155ec75..e65fd5ee3 100644
--- a/UI/Web/src/app/app-routing.module.ts
+++ b/UI/Web/src/app/app-routing.module.ts
@@ -10,6 +10,8 @@ import { UserLoginComponent } from './user-login/user-login.component';
import { AuthGuard } from './_guards/auth.guard';
import { LibraryAccessGuard } from './_guards/library-access.guard';
import { InProgressComponent } from './in-progress/in-progress.component';
+import { DashboardComponent as AdminDashboardComponent } from './admin/dashboard/dashboard.component';
+import { DashboardComponent } from './dashboard/dashboard.component';
// TODO: Once we modularize the components, use this and measure performance impact: https://angular.io/guide/lazy-loading-ngmodules#preloading-modules
@@ -27,6 +29,10 @@ const routes: Routes = [
path: 'preferences',
loadChildren: () => import('./user-settings/user-settings.module').then(m => m.UserSettingsModule)
},
+ {
+ path: 'lists',
+ loadChildren: () => import('./reading-list/reading-list.module').then(m => m.ReadingListModule)
+ },
{
path: '',
runGuardsAndResolvers: 'always',
@@ -49,7 +55,7 @@ const routes: Routes = [
runGuardsAndResolvers: 'always',
canActivate: [AuthGuard],
children: [
- {path: 'library', component: LibraryComponent},
+ {path: 'library', component: DashboardComponent},
{path: 'recently-added', component: RecentlyAddedComponent},
{path: 'in-progress', component: InProgressComponent},
]
diff --git a/UI/Web/src/app/app.module.ts b/UI/Web/src/app/app.module.ts
index a8d5915a5..9a029e665 100644
--- a/UI/Web/src/app/app.module.ts
+++ b/UI/Web/src/app/app.module.ts
@@ -7,7 +7,7 @@ import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HomeComponent } from './home/home.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
-import { NgbAccordionModule, NgbDropdownModule, NgbNavModule, NgbPaginationModule, NgbRatingModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
+import { NgbDropdownModule, NgbNavModule, NgbPaginationModule, NgbRatingModule } from '@ng-bootstrap/ng-bootstrap';
import { NavHeaderComponent } from './nav-header/nav-header.component';
import { JwtInterceptor } from './_interceptors/jwt.interceptor';
import { UserLoginComponent } from './user-login/user-login.component';
@@ -21,7 +21,6 @@ import { NotConnectedComponent } from './not-connected/not-connected.component';
import { AutocompleteLibModule } from 'angular-ng-autocomplete';
import { ReviewSeriesModalComponent } from './_modals/review-series-modal/review-series-modal.component';
import { CarouselModule } from './carousel/carousel.module';
-import { NgxSliderModule } from '@angular-slider/ngx-slider';
import * as Sentry from '@sentry/angular';
@@ -33,11 +32,12 @@ import { Dedupe as DedupeIntegration } from '@sentry/integrations';
import { PersonBadgeComponent } from './person-badge/person-badge.component';
import { TypeaheadModule } from './typeahead/typeahead.module';
import { RecentlyAddedComponent } from './recently-added/recently-added.component';
-import { InProgressComponent } from './in-progress/in-progress.component';
import { CardsModule } from './cards/cards.module';
import { CollectionsModule } from './collections/collections.module';
-import { CommonModule } from '@angular/common';
+import { InProgressComponent } from './in-progress/in-progress.component';
import { SAVER, getSaver } from './shared/_providers/saver.provider';
+import { ReadingListModule } from './reading-list/reading-list.module';
+import { DashboardComponent } from './dashboard/dashboard.component';
let sentryProviders: any[] = [];
@@ -98,6 +98,7 @@ if (environment.production) {
PersonBadgeComponent,
RecentlyAddedComponent,
InProgressComponent,
+ DashboardComponent,
],
imports: [
HttpClientModule,
@@ -109,19 +110,16 @@ if (environment.production) {
NgbDropdownModule, // Nav
AutocompleteLibModule, // Nav
- //NgbTooltipModule, // Shared & SettingsModule
NgbRatingModule, // Series Detail
NgbNavModule,
- //NgbAccordionModule, // User Preferences
- //NgxSliderModule, // User Preference
NgbPaginationModule,
-
SharedModule,
CarouselModule,
TypeaheadModule,
CardsModule,
CollectionsModule,
+ ReadingListModule,
ToastrModule.forRoot({
positionClass: 'toast-bottom-right',
diff --git a/UI/Web/src/app/book-reader/_models/book-info.ts b/UI/Web/src/app/book-reader/_models/book-info.ts
new file mode 100644
index 000000000..4816bd324
--- /dev/null
+++ b/UI/Web/src/app/book-reader/_models/book-info.ts
@@ -0,0 +1,9 @@
+import { MangaFormat } from "src/app/_models/manga-format";
+
+export interface BookInfo {
+ bookTitle: string;
+ seriesFormat: MangaFormat;
+ seriesId: number;
+ libraryId: number;
+ volumeId: number;
+}
\ No newline at end of file
diff --git a/UI/Web/src/app/book-reader/book-reader/book-reader.component.html b/UI/Web/src/app/book-reader/book-reader/book-reader.component.html
index fb727f93f..93f458d35 100644
--- a/UI/Web/src/app/book-reader/book-reader/book-reader.component.html
+++ b/UI/Web/src/app/book-reader/book-reader/book-reader.component.html
@@ -63,11 +63,13 @@
</div>
</div>
<div class="row no-gutters">
- <div class="col-1">{{pageNum}}</div>
- <div class="col-10" style="margin-top: 9px">
+ <button class="btn btn-small btn-icon col-1" [disabled]="prevChapterDisabled" (click)="loadPrevChapter()" title="Prev Chapter/Volume"><i class="fa fa-fast-backward" aria-hidden="true"></i></button>
+ <div class="col-1" style="margin-top: 6px">{{pageNum}}</div>
+ <div class="col-8" style="margin-top: 15px">
<ngb-progressbar style="cursor: pointer" title="Go to page" (click)="goToPage()" type="primary" height="5px" [value]="pageNum" [max]="maxPages - 1"></ngb-progressbar>
</div>
- <div class="col-1">{{maxPages - 1}}</div>
+ <div class="col-1 btn-icon" style="margin-top: 6px" (click)="goToPage(maxPages - 1)" title="Go to last page">{{maxPages - 1}}</div>
+ <button class="btn btn-small btn-icon col-1" [disabled]="nextChapterDisabled" (click)="loadNextChapter()" title="Next Chapter/Volume"><i class="fa fa-fast-forward" aria-hidden="true"></i></button>
</div>
<div class="table-of-contents">
<h3>Table of Contents</h3>
@@ -77,18 +79,18 @@
<div *ngIf="chapters.length === 1; else nestedChildren">
<ul>
<li *ngFor="let chapter of chapters[0].children">
- <a href="javascript:void(0);" (click)="loadChapter(chapter.page, chapter.part)">{{chapter.title}}</a>
+ <a href="javascript:void(0);" (click)="loadChapterPage(chapter.page, chapter.part)">{{chapter.title}}</a>
</li>
</ul>
</div>
<ng-template #nestedChildren>
<ul *ngFor="let chapterGroup of chapters" style="padding-inline-start: 0px">
- <li class="{{chapterGroup.page == pageNum ? 'active': ''}}" (click)="loadChapter(chapterGroup.page, '')">
+ <li class="{{chapterGroup.page == pageNum ? 'active': ''}}" (click)="loadChapterPage(chapterGroup.page, '')">
{{chapterGroup.title}}
</li>
<ul *ngFor="let chapter of chapterGroup.children">
<li class="{{cleanIdSelector(chapter.part) === currentPageAnchor ? 'active' : ''}}">
- <a href="javascript:void(0);" (click)="loadChapter(chapter.page, chapter.part)">{{chapter.title}}</a>
+ <a href="javascript:void(0);" (click)="loadChapterPage(chapter.page, chapter.part)">{{chapter.title}}</a>
</li>
</ul>
</ul>
@@ -110,9 +112,9 @@
<div #readingSection class="reading-section" [ngStyle]="{'padding-top': topOffset + 20 + 'px'}" [@isLoading]="isLoading ? true : false" (click)="handleReaderClick($event)">
<div #readingHtml [innerHtml]="page" *ngIf="page !== undefined"></div>
- <div class="left {{clickOverlayClass('left')}}" (click)="prevPage()" *ngIf="clickToPaginate">
+ <div class="left {{clickOverlayClass('left')}} no-observe" (click)="prevPage()" *ngIf="clickToPaginate">
</div>
- <div class="right {{clickOverlayClass('right')}}" (click)="nextPage()" *ngIf="clickToPaginate">
+ <div class="right {{clickOverlayClass('right')}} no-observe" (click)="nextPage()" *ngIf="clickToPaginate">
</div>
<div [ngStyle]="{'padding-top': topOffset + 20 + 'px'}" *ngIf="page !== undefined && scrollbarNeeded">
@@ -122,12 +124,22 @@
<ng-template #actionBar>
<div class="reading-bar row no-gutters justify-content-between">
- <button class="btn btn-outline-secondary btn-icon col-2 col-xs-1" (click)="prevPage()" [disabled]="readingDirection === 0 ? pageNum === 0 : pageNum + 1 >= maxPages - 1" title="{{readingDirection === 0 ? 'Previous' : 'Next'}} Page"><i class="fa fa-arrow-left" aria-hidden="true"></i><span class="phone-hidden">&nbsp;{{readingDirection === 0 ? 'Previous' : 'Next'}}</span></button>
+ <button class="btn btn-outline-secondary btn-icon col-2 col-xs-1" (click)="prevPage()"
+ [disabled]="IsPrevDisabled"
+ title="{{readingDirection === ReadingDirection.LeftToRight ? 'Previous' : 'Next'}} Page">
+ <i class="fa {{(readingDirection === ReadingDirection.LeftToRight ? pageNum === 0 : pageNum + 1 >= maxPages - 1) ? 'fa-angle-double-left' : 'fa-angle-left'}}" aria-hidden="true"></i>
+ <span class="phone-hidden">&nbsp;{{readingDirection === ReadingDirection.LeftToRight ? 'Previous' : 'Next'}}</span>
+ </button>
<button *ngIf="!this.adhocPageHistory.isEmpty()" class="btn btn-outline-secondary btn-icon col-2 col-xs-1" (click)="goBack()" title="Go Back"><i class="fa fa-reply" aria-hidden="true"></i><span class="phone-hidden">&nbsp;Go Back</span></button>
<button class="btn btn-secondary col-2 col-xs-1" (click)="toggleDrawer()"><i class="fa fa-bars" aria-hidden="true"></i><span class="phone-hidden">&nbsp;Settings</span></button>
- <div class="book-title col-2 phone-hidden">{{bookTitle}} </div>
+ <div class="book-title col-2 phone-hidden">{{bookTitle}} <span *ngIf="incognitoMode">(<i class="fa fa-glasses" aria-hidden="true"></i><span class="sr-only">Incognito Mode</span>)</span></div>
<button class="btn btn-secondary col-2 col-xs-1" (click)="closeReader()"><i class="fa fa-times-circle" aria-hidden="true"></i><span class="phone-hidden">&nbsp;Close</span></button>
- <button class="btn btn-outline-secondary btn-icon col-2 col-xs-1" [disabled]="readingDirection === 0 ? pageNum + 1 >= maxPages - 1 : pageNum === 0" (click)="nextPage()" title="{{readingDirection === 0 ? 'Next' : 'Previous'}} Page"><span class="phone-hidden">{{readingDirection === 0 ? 'Next' : 'Previous'}}&nbsp;</span><i class="fa fa-arrow-right" aria-hidden="true"></i></button>
+ <button class="btn btn-outline-secondary btn-icon col-2 col-xs-1"
+ [disabled]="IsNextDisabled"
+ (click)="nextPage()" title="{{readingDirection === ReadingDirection.LeftToRight ? 'Next' : 'Previous'}} Page">
+ <span class="phone-hidden">{{readingDirection === ReadingDirection.LeftToRight ? 'Next' : 'Previous'}}&nbsp;</span>
+ <i class="fa {{(readingDirection === ReadingDirection.LeftToRight ? pageNum + 1 >= maxPages - 1 : pageNum === 0) ? 'fa-angle-double-right' : 'fa-angle-right'}}" aria-hidden="true"></i>
+ </button>
</div>
</ng-template>
diff --git a/UI/Web/src/app/book-reader/book-reader/book-reader.component.ts b/UI/Web/src/app/book-reader/book-reader/book-reader.component.ts
index 0b6e35163..8f3984565 100644
--- a/UI/Web/src/app/book-reader/book-reader/book-reader.component.ts
+++ b/UI/Web/src/app/book-reader/book-reader/book-reader.component.ts
@@ -22,6 +22,7 @@ import { Preferences } from 'src/app/_models/preferences/preferences';
import { MemberService } from 'src/app/_services/member.service';
import { ReadingDirection } from 'src/app/_models/preferences/reading-direction';
import { ScrollService } from 'src/app/scroll.service';
+import { MangaFormat } from 'src/app/_models/manga-format';
interface PageStyle {
@@ -38,7 +39,8 @@ interface HistoryPoint {
}
const TOP_OFFSET = -50 * 1.5; // px the sticky header takes up
-const SCROLL_PART_TIMEOUT = 5000;
+const CHAPTER_ID_NOT_FETCHED = -2;
+const CHAPTER_ID_DOESNT_EXIST = -1;
@Component({
selector: 'app-book-reader',
@@ -64,12 +66,31 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
volumeId!: number;
chapterId!: number;
chapter!: Chapter;
+ /**
+ * Reading List id. Defaults to -1.
+ */
+ readingListId: number = CHAPTER_ID_DOESNT_EXIST;
+
+ /**
+ * If this is true, no progress will be saved.
+ */
+ incognitoMode: boolean = false;
+
+ /**
+ * If this is true, chapters will be fetched in the order of a reading list, rather than natural series order.
+ */
+ readingListMode: boolean = false;
chapters: Array<BookChapterItem> = [];
pageNum = 0;
maxPages = 1;
adhocPageHistory: Stack<HistoryPoint> = new Stack<HistoryPoint>();
+ /**
+ * A stack of the chapter ids we come across during continuous reading mode. When we traverse a boundary, we use this to avoid extra API calls.
+ * @see Stack
+ */
+ continuousChaptersStack: Stack<number> = new Stack();
user!: User;
@@ -90,6 +111,38 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChild('readingSection', {static: false}) readingSectionElemRef!: ElementRef<HTMLDivElement>;
@ViewChild('stickyTop', {static: false}) stickyTopElemRef!: ElementRef<HTMLDivElement>;
+ /**
+ * Next Chapter Id. This is not garunteed to be a valid ChapterId. Prefetched on page load (non-blocking).
+ */
+ nextChapterId: number = CHAPTER_ID_NOT_FETCHED;
+ /**
+ * Previous Chapter Id. This is not garunteed to be a valid ChapterId. Prefetched on page load (non-blocking).
+ */
+ prevChapterId: number = CHAPTER_ID_NOT_FETCHED;
+ /**
+ * Is there a next chapter. If not, this will disable UI controls.
+ */
+ nextChapterDisabled: boolean = false;
+ /**
+ * Is there a previous chapter. If not, this will disable UI controls.
+ */
+ prevChapterDisabled: boolean = false;
+ /**
+ * Has the next chapter been prefetched. Prefetched means the backend will cache the files.
+ */
+ nextChapterPrefetched: boolean = false;
+ /**
+ * Has the previous chapter been prefetched. Prefetched means the backend will cache the files.
+ */
+ prevChapterPrefetched: boolean = false;
+ /**
+ * If the prev page allows a page change to occur.
+ */
+ prevPageDisabled = false;
+ /**
+ * If the next page allows a page change to occur.
+ */
+ nextPageDisabled = false;
/**
* Internal property used to capture all the different css properties to render on all elements
@@ -118,6 +171,7 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
* Last seen progress part path
*/
lastSeenScrollPartPath: string = '';
+
/**
* Hack: Override background color for reader and restore it onDestroy
*/
@@ -147,6 +201,24 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
}
`;
+ get ReadingDirection(): typeof ReadingDirection {
+ return ReadingDirection;
+ }
+
+ get IsPrevDisabled() {
+ if (this.readingDirection === ReadingDirection.LeftToRight) {
+ return this.prevPageDisabled && this.pageNum === 0;
+ }
+ return this.nextPageDisabled && this.pageNum + 1 >= this.maxPages - 1;
+ }
+
+ get IsNextDisabled() {
+ if (this.readingDirection === ReadingDirection.LeftToRight) {
+ this.nextPageDisabled && this.pageNum + 1 >= this.maxPages - 1;
+ }
+ return this.prevPageDisabled && this.pageNum === 0;
+ }
+
constructor(private route: ActivatedRoute, private router: Router, private accountService: AccountService,
private seriesService: SeriesService, private readerService: ReaderService, private location: Location,
private renderer: Renderer2, private navService: NavService, private toastr: ToastrService,
@@ -214,14 +286,17 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
const alreadyReached = Object.values(this.pageAnchors).filter((i: number) => i <= verticalOffset);
if (alreadyReached.length > 0) {
this.currentPageAnchor = Object.keys(this.pageAnchors)[alreadyReached.length - 1];
- this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, this.pageNum, this.lastSeenScrollPartPath).pipe(take(1)).subscribe(() => {/* No operation */});
+
+ if (!this.incognitoMode) {
+ this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, this.pageNum, this.lastSeenScrollPartPath).pipe(take(1)).subscribe(() => {/* No operation */});
+ }
return;
} else {
this.currentPageAnchor = '';
}
}
- if (this.lastSeenScrollPartPath !== '') {
+ if (this.lastSeenScrollPartPath !== '' && !this.incognitoMode) {
this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, this.pageNum, this.lastSeenScrollPartPath).pipe(take(1)).subscribe(() => {/* No operation */});
}
});
@@ -268,6 +343,14 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
this.libraryId = parseInt(libraryId, 10);
this.seriesId = parseInt(seriesId, 10);
this.chapterId = parseInt(chapterId, 10);
+ this.incognitoMode = this.route.snapshot.queryParamMap.get('incognitoMode') === 'true';
+
+ const readingListId = this.route.snapshot.queryParamMap.get('readingListId');
+ if (readingListId != null) {
+ this.readingListMode = true;
+ this.readingListId = parseInt(readingListId, 10);
+ }
+
this.memberService.hasReadingProgress(this.libraryId).pipe(take(1)).subscribe(hasProgress => {
if (!hasProgress) {
@@ -276,32 +359,71 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
}
});
- forkJoin({
- chapter: this.seriesService.getChapter(this.chapterId),
- progress: this.readerService.getProgress(this.chapterId),
- chapters: this.bookService.getBookChapters(this.chapterId),
- info: this.bookService.getBookInfo(this.chapterId)
- }).pipe(take(1)).subscribe(results => {
- this.chapter = results.chapter;
- this.volumeId = results.chapter.volumeId;
- this.maxPages = results.chapter.pages;
- this.chapters = results.chapters;
- this.pageNum = results.progress.pageNum;
- this.bookTitle = results.info;
-
-
- if (this.pageNum >= this.maxPages) {
- this.pageNum = this.maxPages - 1;
- this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, this.pageNum).pipe(take(1)).subscribe(() => {/* No operation */});
+ this.init();
+ }
+
+ init() {
+ this.nextChapterId = CHAPTER_ID_NOT_FETCHED;
+ this.prevChapterId = CHAPTER_ID_NOT_FETCHED;
+ this.nextChapterDisabled = false;
+ this.prevChapterDisabled = false;
+ this.nextChapterPrefetched = false;
+
+ this.bookService.getBookInfo(this.chapterId).subscribe(info => {
+ this.bookTitle = info.bookTitle;
+
+ if (this.readingListMode && info.seriesFormat !== MangaFormat.EPUB) {
+ // Redirect to the manga reader.
+ const params = this.readerService.getQueryParamsObject(this.incognitoMode, this.readingListMode, this.readingListId);
+ this.router.navigate(['library', info.libraryId, 'series', info.seriesId, 'manga', this.chapterId], {queryParams: params});
+ return;
}
- // Check if user progress has part, if so load it so we scroll to it
- this.loadPage(results.progress.bookScrollId || undefined);
- }, () => {
- setTimeout(() => {
- this.closeReader();
- }, 200);
+ forkJoin({
+ chapter: this.seriesService.getChapter(this.chapterId),
+ progress: this.readerService.getProgress(this.chapterId),
+ chapters: this.bookService.getBookChapters(this.chapterId),
+ }).pipe(take(1)).subscribe(results => {
+ this.chapter = results.chapter;
+ this.volumeId = results.chapter.volumeId;
+ this.maxPages = results.chapter.pages;
+ this.chapters = results.chapters;
+ this.pageNum = results.progress.pageNum;
+
+
+ this.continuousChaptersStack.push(this.chapterId);
+
+
+ if (this.pageNum >= this.maxPages) {
+ this.pageNum = this.maxPages - 1;
+ if (!this.incognitoMode) {
+ this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, this.pageNum).pipe(take(1)).subscribe(() => {/* No operation */});
+ }
+ }
+
+ this.readerService.getNextChapter(this.seriesId, this.volumeId, this.chapterId, this.readingListId).pipe(take(1)).subscribe(chapterId => {
+ this.nextChapterId = chapterId;
+ if (chapterId === CHAPTER_ID_DOESNT_EXIST || chapterId === this.chapterId) {
+ this.nextChapterDisabled = true;
+ }
+ });
+ this.readerService.getPrevChapter(this.seriesId, this.volumeId, this.chapterId, this.readingListId).pipe(take(1)).subscribe(chapterId => {
+ this.prevChapterId = chapterId;
+ if (chapterId === CHAPTER_ID_DOESNT_EXIST || chapterId === this.chapterId) {
+ this.prevChapterDisabled = true;
+ }
+ });
+
+ // Check if user progress has part, if so load it so we scroll to it
+ this.loadPage(results.progress.bookScrollId || undefined);
+ }, () => {
+ setTimeout(() => {
+ this.closeReader();
+ }, 200);
+ });
});
+
+
}
@HostListener('window:keydown', ['$event'])
@@ -322,7 +444,9 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
}
handleIntersection(entries: IntersectionObserverEntry[]) {
- const intersectingEntries = Array.from(entries).filter(entry => entry.isIntersecting).map(entry => entry.target);
+ let intersectingEntries = Array.from(entries)
+ .filter(entry => entry.isIntersecting)
+ .map(entry => entry.target)
intersectingEntries.sort((a: Element, b: Element) => {
const aTop = a.getBoundingClientRect().top;
const bTop = b.getBoundingClientRect().top;
@@ -336,6 +460,7 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
return 0;
});
+
if (intersectingEntries.length > 0) {
let path = this.getXPathTo(intersectingEntries[0]);
if (path === '') { return; }
@@ -346,13 +471,74 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
}
}
- loadChapter(pageNum: number, part: string) {
+ loadNextChapter() {
+ if (this.nextPageDisabled) { return; }
+ this.isLoading = true;
+ if (this.nextChapterId === CHAPTER_ID_NOT_FETCHED || this.nextChapterId === this.chapterId) {
+ this.readerService.getNextChapter(this.seriesId, this.volumeId, this.chapterId, this.readingListId).pipe(take(1)).subscribe(chapterId => {
+ this.nextChapterId = chapterId;
+ this.loadChapter(chapterId, 'Next');
+ });
+ } else {
+ this.loadChapter(this.nextChapterId, 'Next');
+ }
+ }
+
+ loadPrevChapter() {
+ if (this.prevPageDisabled) { return; }
+ this.isLoading = true;
+ this.continuousChaptersStack.pop();
+ const prevChapter = this.continuousChaptersStack.peek();
+ if (prevChapter != this.chapterId) {
+ if (prevChapter !== undefined) {
+ this.chapterId = prevChapter;
+ this.init();
+ return;
+ }
+ }
+
+ if (this.prevChapterId === CHAPTER_ID_NOT_FETCHED || this.prevChapterId === this.chapterId) {
+ this.readerService.getPrevChapter(this.seriesId, this.volumeId, this.chapterId, this.readingListId).pipe(take(1)).subscribe(chapterId => {
+ this.prevChapterId = chapterId;
+ this.loadChapter(chapterId, 'Prev');
+ });
+ } else {
+ this.loadChapter(this.prevChapterId, 'Prev');
+ }
+ }
+
+ loadChapter(chapterId: number, direction: 'Next' | 'Prev') {
+ if (chapterId >= 0) {
+ this.chapterId = chapterId;
+ this.continuousChaptersStack.push(chapterId);
+ // Load chapter Id onto route but don't reload
+ const newRoute = this.readerService.getNextChapterUrl(this.router.url, this.chapterId, this.incognitoMode, this.readingListMode, this.readingListId);
+ window.history.replaceState({}, '', newRoute);
+ this.init();
+ this.toastr.info(direction + ' chapter loaded', '', {timeOut: 3000});
+ } else {
+ // This will only happen if no actual chapter can be found
+ this.toastr.warning('Could not find ' + direction + ' chapter');
+ this.isLoading = false;
+ if (direction === 'Prev') {
+ this.prevPageDisabled = true;
+ } else {
+ this.nextPageDisabled = true;
+ }
+ }
+ }
+
+ loadChapterPage(pageNum: number, part: string) {
this.setPageNum(pageNum);
this.loadPage('id("' + part + '")');
}
closeReader() {
- this.location.back();
+ if (this.readingListMode) {
+ this.router.navigateByUrl('lists/' + this.readingListId);
+ } else {
+ this.location.back();
+ }
}
resetSettings() {
@@ -466,7 +652,9 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
setupPageAnchors() {
this.readingSectionElemRef.nativeElement.querySelectorAll('div,o,p,ul,li,a,img,h1,h2,h3,h4,h5,h6,span').forEach(elem => {
- this.intersectionObserver.observe(elem);
+ if (!elem.classList.contains('no-observe')) {
+ this.intersectionObserver.observe(elem);
+ }
});
this.pageAnchors = {};
@@ -483,7 +671,9 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
loadPage(part?: string | undefined, scrollTop?: number | undefined) {
this.isLoading = true;
- this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, this.pageNum).pipe(take(1)).subscribe(() => {/* No operation */});
+ if (!this.incognitoMode) {
+ this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, this.pageNum).pipe(take(1)).subscribe(() => {/* No operation */});
+ }
this.bookService.getBookPage(this.chapterId, this.pageNum).pipe(take(1)).subscribe(content => {
this.page = this.domSanitizer.bypassSecurityTrustHtml(content);
@@ -563,7 +753,14 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
this.setPageNum(this.pageNum + 1);
}
+ if (oldPageNum === 0) {
+ // Move to next volume/chapter automatically
+ this.loadPrevChapter();
+ return;
+ }
+
if (oldPageNum === this.pageNum) { return; }
+
this.loadPage();
}
@@ -579,7 +776,12 @@ export class BookReaderComponent implements OnInit, AfterViewInit, OnDestroy {
} else {
this.setPageNum(this.pageNum - 1);
}
-
+
+ if (this.pageNum >= this.maxPages - 1) {
+ // Move to next volume/chapter automatically
+ this.loadNextChapter();
+ }
+
if (oldPageNum === this.pageNum) { return; }
this.loadPage();
diff --git a/UI/Web/src/app/book-reader/book.service.ts b/UI/Web/src/app/book-reader/book.service.ts
index d3d650600..bef4ce73d 100644
--- a/UI/Web/src/app/book-reader/book.service.ts
+++ b/UI/Web/src/app/book-reader/book.service.ts
@@ -2,6 +2,7 @@ import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { BookChapterItem } from './_models/book-chapter-item';
+import { BookInfo } from './_models/book-info';
export interface BookPage {
bookTitle: string;
@@ -32,7 +33,7 @@ export class BookService {
}
getBookInfo(chapterId: number) {
- return this.http.get<string>(this.baseUrl + 'book/' + chapterId + '/book-info', {responseType: 'text' as 'json'});
+ return this.http.get<BookInfo>(this.baseUrl + 'book/' + chapterId + '/book-info');
}
getBookPageUrl(chapterId: number, page: number) {
diff --git a/UI/Web/src/app/cards/_modals/card-details-modal/card-details-modal.component.html b/UI/Web/src/app/cards/_modals/card-details-modal/card-details-modal.component.html
index 4542f7938..d18987f6b 100644
--- a/UI/Web/src/app/cards/_modals/card-details-modal/card-details-modal.component.html
+++ b/UI/Web/src/app/cards/_modals/card-details-modal/card-details-modal.component.html
@@ -37,8 +37,8 @@
<h5 class="mt-0 mb-1">
<span *ngIf="chapter.number !== '0'; else specialHeader">
<span class="">
- <app-card-actionables (actionHandler)="performAction($event, chapter)" [actions]="chapterActions" [labelBy]="'Chapter' + formatChapterNumber(chapter)"></app-card-actionables>
- </span>&nbsp;Chapter {{formatChapterNumber(chapter)}}
+ <app-card-actionables (actionHandler)="performAction($event, chapter)" [actions]="chapterActions" [labelBy]="'Chapter' + formatChapterNumber(chapter)"></app-card-actionables>&nbsp;
+ </span>Chapter {{formatChapterNumber(chapter)}}
<span class="badge badge-primary badge-pill">
<span *ngIf="chapter.pagesRead > 0 && chapter.pagesRead < chapter.pages">{{chapter.pagesRead}} / {{chapter.pages}}</span>
<span *ngIf="chapter.pagesRead === 0">UNREAD</span>
diff --git a/UI/Web/src/app/cards/_modals/edit-collection-tags/edit-collection-tags.component.html b/UI/Web/src/app/cards/_modals/edit-collection-tags/edit-collection-tags.component.html
index 168c9cf5d..2f7caacaf 100644
--- a/UI/Web/src/app/cards/_modals/edit-collection-tags/edit-collection-tags.component.html
+++ b/UI/Web/src/app/cards/_modals/edit-collection-tags/edit-collection-tags.component.html
@@ -11,7 +11,7 @@
Promotion means that the tag can be seen server-wide, not just for admin users. All series that have this tag will still have user-access restrictions placed on them.
</p>
- <ul ngbNav #nav="ngbNav" [(activeId)]="active" class="nav-tabs">
+ <ul ngbNav #nav="ngbNav" [(activeId)]="active" class="nav-tabs nav-pills">
<li [ngbNavItem]="tabs[0]">
<a ngbNavLink>{{tabs[0]}}</a>
<ng-template ngbNavContent>
diff --git a/UI/Web/src/app/cards/_modals/edit-series-modal/edit-series-modal.component.html b/UI/Web/src/app/cards/_modals/edit-series-modal/edit-series-modal.component.html
index b968228b3..c354ac22d 100644
--- a/UI/Web/src/app/cards/_modals/edit-series-modal/edit-series-modal.component.html
+++ b/UI/Web/src/app/cards/_modals/edit-series-modal/edit-series-modal.component.html
@@ -6,13 +6,13 @@
<span aria-hidden="true">&times;</span>
</button>
</div>
- <div class="modal-body scrollable-modal">
- <form [formGroup]="editSeriesForm">
- <ul ngbNav #nav="ngbNav" [(activeId)]="active" class="nav-tabs">
+ <div class="modal-body scrollable-modal {{utilityService.getActiveBreakpoint() === Breakpoint.Mobile ? '' : 'd-flex'}}">
+
+ <ul ngbNav #nav="ngbNav" [(activeId)]="active" class="nav-pills" orientation="{{utilityService.getActiveBreakpoint() === Breakpoint.Mobile ? 'horizontal' : 'vertical'}}" style="min-width: 135px;">
<li [ngbNavItem]="tabs[0]">
<a ngbNavLink>{{tabs[0]}}</a>
<ng-template ngbNavContent>
-
+ <form [formGroup]="editSeriesForm">
<div class="row no-gutters">
<div class="form-group" style="width: 100%">
<label for="name">Name</label>
@@ -77,6 +77,7 @@
<textarea id="summary" class="form-control" formControlName="summary" rows="4"></textarea>
</div>
</div>
+ </form>
</ng-template>
</li>
@@ -117,7 +118,6 @@
</div>
<div class="row no-gutters">
<div class="col">
- <!-- Is Special: {{volume.isSpecial}} -->
<button type="button" class="btn btn-outline-primary" (click)="collapse.toggle()" [attr.aria-expanded]="!volumeCollapsed[volume.name]">
View Files
</button>
@@ -152,9 +152,8 @@
</ng-template>
</li>
</ul>
- </form>
- <div [ngbNavOutlet]="nav" class="mt-3"></div>
+ <div [ngbNavOutlet]="nav" class="tab-content {{utilityService.getActiveBreakpoint() === Breakpoint.Mobile ? 'mt-3' : 'ml-4 flex-fill'}}"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" (click)="close()">Close</button>
diff --git a/UI/Web/src/app/cards/_modals/edit-series-modal/edit-series-modal.component.ts b/UI/Web/src/app/cards/_modals/edit-series-modal/edit-series-modal.component.ts
index 4f2103e67..dd3be4ead 100644
--- a/UI/Web/src/app/cards/_modals/edit-series-modal/edit-series-modal.component.ts
+++ b/UI/Web/src/app/cards/_modals/edit-series-modal/edit-series-modal.component.ts
@@ -3,7 +3,7 @@ import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { forkJoin, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
-import { UtilityService } from 'src/app/shared/_services/utility.service';
+import { Breakpoint, UtilityService } from 'src/app/shared/_services/utility.service';
import { TypeaheadSettings } from 'src/app/typeahead/typeahead-settings';
import { Chapter } from 'src/app/_models/chapter';
import { CollectionTag } from 'src/app/_models/collection-tag';
@@ -43,6 +43,10 @@ export class EditSeriesModalComponent implements OnInit, OnDestroy {
*/
selectedCover: string = '';
+ get Breakpoint(): typeof Breakpoint {
+ return Breakpoint;
+ }
+
constructor(public modal: NgbActiveModal,
private seriesService: SeriesService,
public utilityService: UtilityService,
@@ -83,6 +87,7 @@ export class EditSeriesModalComponent implements OnInit, OnDestroy {
if (metadata) {
this.metadata = metadata;
this.settings.savedData = metadata.tags;
+ this.tags = metadata.tags;
}
});
@@ -147,6 +152,7 @@ export class EditSeriesModalComponent implements OnInit, OnDestroy {
this.seriesService.updateMetadata(this.metadata, this.tags)
];
+
if (selectedIndex > 0) {
apis.push(this.uploadService.updateSeriesCoverImage(model.id, this.selectedCover));
}
diff --git a/UI/Web/src/app/cards/bulk-operations/bulk-operations.component.html b/UI/Web/src/app/cards/bulk-operations/bulk-operations.component.html
new file mode 100644
index 000000000..2d328bfb3
--- /dev/null
+++ b/UI/Web/src/app/cards/bulk-operations/bulk-operations.component.html
@@ -0,0 +1,8 @@
+<div *ngIf="bulkSelectionService.hasSelections()" class="bulk-select mb-3 fixed-top" [ngStyle]="{'margin-top': topOffset + 'px'}">
+ <div class="d-flex justify-content-around align-items-center">
+ <span class="highlight"><i class="fa fa-check" aria-hidden="true"></i>&nbsp;{{bulkSelectionService.totalSelections()}} selected</span>
+ <app-card-actionables [actions]="actions" labelBy="bulk-actions-header" iconClass="fa-ellipsis-h" (actionHandler)="performAction($event)"></app-card-actionables>
+ <span id="bulk-actions-header" class="sr-only">Bulk Actions</span>
+ <button class="btn btn-icon" (click)="bulkSelectionService.deselectAll()"><i class="fa fa-times" aria-hidden="true"></i>&nbsp;Deselect All</button>
+ </div>
+</div>
\ No newline at end of file
diff --git a/UI/Web/src/app/cards/bulk-operations/bulk-operations.component.scss b/UI/Web/src/app/cards/bulk-operations/bulk-operations.component.scss
new file mode 100644
index 000000000..b385680ee
--- /dev/null
+++ b/UI/Web/src/app/cards/bulk-operations/bulk-operations.component.scss
@@ -0,0 +1,16 @@
+@import "../../../theme/colors";
+@import "../../../assets/themes/dark.scss";
+
+.bulk-select {
+ background-color: $dark-form-background-no-opacity;
+ border-bottom: 2px solid $primary-color;
+ color: white;
+}
+
+.btn-icon {
+ color: white;
+}
+
+.highlight {
+ color: $primary-color !important;
+}
\ No newline at end of file
diff --git a/UI/Web/src/app/cards/bulk-operations/bulk-operations.component.ts b/UI/Web/src/app/cards/bulk-operations/bulk-operations.component.ts
new file mode 100644
index 000000000..6f5590339
--- /dev/null
+++ b/UI/Web/src/app/cards/bulk-operations/bulk-operations.component.ts
@@ -0,0 +1,39 @@
+import { Component, Input, OnInit } from '@angular/core';
+import { Action, ActionItem } from 'src/app/_services/action-factory.service';
+import { BulkSelectionService } from '../bulk-selection.service';
+
+@Component({
+ selector: 'app-bulk-operations',
+ templateUrl: './bulk-operations.component.html',
+ styleUrls: ['./bulk-operations.component.scss']
+})
+export class BulkOperationsComponent implements OnInit {
+
+ @Input() actionCallback!: (action: Action, data: any) => void;
+ topOffset: number = 0;
+
+ get actions() {
+ return this.bulkSelectionService.getActions(this.actionCallback.bind(this));
+ }
+
+ constructor(public bulkSelectionService: BulkSelectionService) { }
+
+ ngOnInit(): void {
+ const navBar = document.querySelector('.navbar');
+ if (navBar) {
+ this.topOffset = Math.ceil(navBar.getBoundingClientRect().height);
+ }
+ }
+
+ handleActionCallback(action: Action, data: any) {
+ this.actionCallback(action, data);
+ }
+
+ performAction(action: ActionItem<any>) {
+ if (typeof action.callback === 'function') {
+ action.callback(action.action, null);
+ }
+ }
+
+
+}
diff --git a/UI/Web/src/app/cards/bulk-selection.service.ts b/UI/Web/src/app/cards/bulk-selection.service.ts
new file mode 100644
index 000000000..47072c014
--- /dev/null
+++ b/UI/Web/src/app/cards/bulk-selection.service.ts
@@ -0,0 +1,147 @@
+import { Injectable } from '@angular/core';
+import { NavigationStart, Router } from '@angular/router';
+import { filter } from 'rxjs/operators';
+import { Action, ActionFactoryService } from '../_services/action-factory.service';
+
+type DataSource = 'volume' | 'chapter' | 'special' | 'series';
+
+/**
+ * Responsible for handling selections on cards. Can handle multiple card sources next to each other in different loops.
+ * This will clear selections between pages.
+ *
+ * Remakrs: Page which renders cards is responsible for listening for shift keydown/keyup and updating our state variable.
+ */
+@Injectable({
+ providedIn: 'root'
+})
+export class BulkSelectionService {
+
+ private debug: boolean = false;
+ private prevIndex: number = 0;
+ private prevDataSource!: DataSource;
+ private selectedCards: { [key: string]: {[key: number]: boolean} } = {};
+ private dataSourceMax: { [key: string]: number} = {};
+ public isShiftDown: boolean = false;
+
+ constructor(private router: Router, private actionFactory: ActionFactoryService) {
+ router.events
+ .pipe(filter(event => event instanceof NavigationStart))
+ .subscribe((event) => {
+ this.deselectAll();
+ this.dataSourceMax = {};
+ this.prevIndex = 0;
+ });
+ }
+
+ handleCardSelection(dataSource: DataSource, index: number, maxIndex: number, wasSelected: boolean) {
+ if (this.isShiftDown) {
+
+ if (dataSource === this.prevDataSource) {
+ this.debugLog('Selecting ' + dataSource + ' cards from ' + this.prevIndex + ' to ' + index);
+ this.selectCards(dataSource, this.prevIndex, index, !wasSelected);
+ } else {
+ const isForwardSelection = index < this.prevIndex;
+
+ if (isForwardSelection) {
+ this.debugLog('Selecting ' + this.prevDataSource + ' cards from ' + this.prevIndex + ' to ' + this.dataSourceMax[this.prevDataSource]);
+ this.selectCards(this.prevDataSource, this.prevIndex, this.dataSourceMax[this.prevDataSource], !wasSelected);
+ this.debugLog('Selecting ' + dataSource + ' cards from ' + 0 + ' to ' + index);
+ this.selectCards(dataSource, 0, index, !wasSelected);
+ } else {
+ this.debugLog('Selecting ' + this.prevDataSource + ' cards from ' + 0 + ' to ' + this.prevIndex);
+ this.selectCards(this.prevDataSource, this.prevIndex, 0, !wasSelected);
+ this.debugLog('Selecting ' + dataSource + ' cards from ' + index + ' to ' + maxIndex);
+ this.selectCards(dataSource, index, maxIndex, !wasSelected);
+ }
+ }
+ } else {
+ this.debugLog('Selecting ' + dataSource + ' cards at ' + index);
+ this.selectCards(dataSource, index, index, !wasSelected);
+ }
+ this.prevIndex = index;
+ this.prevDataSource = dataSource;
+ this.dataSourceMax[dataSource] = maxIndex;
+ }
+
+ isCardSelected(dataSource: DataSource, index: number) {
+ if (this.selectedCards.hasOwnProperty(dataSource) && this.selectedCards[dataSource].hasOwnProperty(index)) {
+ return this.selectedCards[dataSource][index];
+ }
+ return false;
+ }
+
+ selectCards(dataSource: DataSource, from: number, to: number, value: boolean) {
+ if (!this.selectedCards.hasOwnProperty(dataSource)) {
+ this.selectedCards[dataSource] = {};
+ }
+
+ if (from === to) {
+ this.selectedCards[dataSource][to] = value;
+ return;
+ }
+
+ if (from > to) {
+ for (let i = to; i <= from; i++) {
+ this.selectedCards[dataSource][i] = value;
+ }
+ }
+
+ for (let i = from; i <= to; i++) {
+ this.selectedCards[dataSource][i] = value;
+ }
+ }
+
+ deselectAll() {
+ this.selectedCards = {};
+ }
+
+ hasSelections() {
+ const keys = Object.keys(this.selectedCards);
+ return keys.filter(key => {
+ return Object.values(this.selectedCards[key]).filter(item => item).length > 0;
+ }).length > 0;
+ }
+
+ totalSelections() {
+ let sum = 0;
+ const keys = Object.keys(this.selectedCards);
+ keys.forEach(key => {
+ sum += Object.values(this.selectedCards[key]).filter(item => item).length;
+ });
+ return sum;
+ }
+
+ getSelectedCardsForSource(dataSource: DataSource) {
+ if (!this.selectedCards.hasOwnProperty(dataSource)) return [];
+
+ let ret = [];
+ for(let k in this.selectedCards[dataSource]) {
+ if (this.selectedCards[dataSource][k]) {
+ ret.push(k);
+ }
+ }
+
+ return ret;
+ }
+
+ getActions(callback: (action: Action, data: any) => void) {
+ // checks if series is present. If so, returns only series actions
+ // else returns volume/chapter items
+ const allowedActions = [Action.AddToReadingList, Action.MarkAsRead, Action.MarkAsUnread];
+ if (Object.keys(this.selectedCards).filter(item => item === 'series').length > 0) {
+ return this.actionFactory.getSeriesActions(callback).filter(item => allowedActions.includes(item.action));
+ }
+
+ return this.actionFactory.getVolumeActions(callback).filter(item => allowedActions.includes(item.action));
+ }
+
+ private debugLog(message: string, extraData?: any) {
+ if (!this.debug) return;
+
+ if (extraData !== undefined) {
+ console.log(message, extraData);
+ } else {
+ console.log(message);
+ }
+ }
+}
diff --git a/UI/Web/src/app/cards/card-detail-layout/card-detail-layout.component.html b/UI/Web/src/app/cards/card-detail-layout/card-detail-layout.component.html
index d005bab63..7f85064e3 100644
--- a/UI/Web/src/app/cards/card-detail-layout/card-detail-layout.component.html
+++ b/UI/Web/src/app/cards/card-detail-layout/card-detail-layout.component.html
@@ -3,8 +3,8 @@
<div class="col mr-auto">
<h2 style="display: inline-block">
<span *ngIf="actions.length > 0" class="">
- <app-card-actionables (actionHandler)="performAction($event)" [actions]="actions" [labelBy]="header"></app-card-actionables>
- </span>&nbsp;{{header}}&nbsp;
+ <app-card-actionables (actionHandler)="performAction($event)" [actions]="actions" [labelBy]="header"></app-card-actionables>&nbsp;
+ </span>{{header}}&nbsp;
<!-- NOTE: On mobile the pill can eat up a lot of space, we can hide it and move to the filter section if user is interested -->
<span class="badge badge-primary badge-pill" attr.aria-label="{{pagination.totalItems}} total items" *ngIf="pagination != undefined">{{pagination.totalItems}}</span>
</h2>
diff --git a/UI/Web/src/app/cards/card-item/card-actionables/card-actionables.component.ts b/UI/Web/src/app/cards/card-item/card-actionables/card-actionables.component.ts
index b7441e62c..fc3138cbf 100644
--- a/UI/Web/src/app/cards/card-item/card-actionables/card-actionables.component.ts
+++ b/UI/Web/src/app/cards/card-item/card-actionables/card-actionables.component.ts
@@ -39,7 +39,4 @@ export class CardActionablesComponent implements OnInit {
}
}
- // TODO: Insert hr to separate admin actions
-
-
}
diff --git a/UI/Web/src/app/cards/card-item/card-item.component.html b/UI/Web/src/app/cards/card-item/card-item.component.html
index 478764aaf..c4fac279a 100644
--- a/UI/Web/src/app/cards/card-item/card-item.component.html
+++ b/UI/Web/src/app/cards/card-item/card-item.component.html
@@ -1,5 +1,5 @@
<div class="card">
- <div class="overlay" (click)="handleClick()">
+ <div class="overlay" (click)="handleClick($event)">
<img *ngIf="total > 0 || supressArchiveWarning" class="img-top lazyload" [src]="imageService.placeholderImage" [attr.data-src]="imageUrl"
(error)="imageService.updateErroredImage($event)" aria-hidden="true" height="230px" width="158px">
<img *ngIf="total === 0 && !supressArchiveWarning" class="img-top lazyload" [src]="imageService.errorImage" [attr.data-src]="imageUrl"
@@ -15,22 +15,24 @@
</span>
</div>
<div class="error-banner" *ngIf="total === 0 && !supressArchiveWarning">
- Cannot Read Archive
+ Cannot Read
</div>
-
-
<div class="not-read-badge" *ngIf="read === 0 && total > 0"></div>
+ <div class="bulk-mode {{bulkSelectionService.hasSelections() ? 'always-show' : ''}}" (click)="handleSelection($event)" *ngIf="allowSelection">
+ <input type="checkbox" attr.aria-labelledby="{{title}}_{{entity.id}}" [ngModel]="selected" [ngModelOptions]="{standalone: true}">
+ </div>
</div>
+
<div class="card-body" *ngIf="title.length > 0 || actions.length > 0">
<div>
- <span class="card-title" placement="top" ngbTooltip="{{title}}" (click)="handleClick()" tabindex="0">
+ <span class="card-title" placement="top" id="{{title}}_{{entity.id}}" ngbTooltip="{{title}}" (click)="handleClick()" tabindex="0">
<span *ngIf="isPromoted()">
<i class="fa fa-angle-double-up" aria-hidden="true"></i>
+ <span class="sr-only">(promoted)</span>
</span>
<i class="fa {{utilityService.mangaFormatIcon(format)}}" aria-hidden="true" *ngIf="format != MangaFormat.UNKNOWN" title="{{utilityService.mangaFormat(format)}}"></i><span class="sr-only">{{utilityService.mangaFormat(format)}}</span>
&nbsp;{{title}}
- <span class="sr-only">(promoted)</span>
</span>
<span class="card-actions float-right">
<app-card-actionables (actionHandler)="performAction($event)" [actions]="actions" [labelBy]="title"></app-card-actionables>
diff --git a/UI/Web/src/app/cards/card-item/card-item.component.scss b/UI/Web/src/app/cards/card-item/card-item.component.scss
index e1b5ceecc..0aa5c8ef6 100644
--- a/UI/Web/src/app/cards/card-item/card-item.component.scss
+++ b/UI/Web/src/app/cards/card-item/card-item.component.scss
@@ -38,6 +38,8 @@ $image-width: 160px;
margin-bottom: 0px;
}
+
+
.img-top {
height: $image-height;
}
@@ -71,12 +73,38 @@ $image-width: 160px;
border-color: transparent $primary-color transparent transparent;
}
+
+.bulk-mode {
+ position: absolute;
+ top: 5px;
+ left: 5px;
+ visibility: hidden;
+
+ &.always-show {
+ visibility: visible !important;
+ width: $image-width;
+ height: $image-height;
+ }
+
+ input[type="checkbox"] {
+ width: 20px;
+ height: 20px;
+ }
+}
+
+
.overlay {
height: $image-height;
+
+
&:hover {
visibility: visible;
+ .bulk-mode {
+ visibility: visible;
+ }
+
.overlay-item {
visibility: visible;
}
diff --git a/UI/Web/src/app/cards/card-item/card-item.component.ts b/UI/Web/src/app/cards/card-item/card-item.component.ts
index 826c068d8..740cf6043 100644
--- a/UI/Web/src/app/cards/card-item/card-item.component.ts
+++ b/UI/Web/src/app/cards/card-item/card-item.component.ts
@@ -1,4 +1,4 @@
-import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core';
+import { Component, EventEmitter, HostListener, Input, OnDestroy, OnInit, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { Observable, Subject } from 'rxjs';
import { finalize, take, takeUntil, takeWhile } from 'rxjs/operators';
@@ -13,6 +13,7 @@ import { Volume } from 'src/app/_models/volume';
import { Action, ActionItem } from 'src/app/_services/action-factory.service';
import { ImageService } from 'src/app/_services/image.service';
import { LibraryService } from 'src/app/_services/library.service';
+import { BulkSelectionService } from '../bulk-selection.service';
@Component({
selector: 'app-card-item',
@@ -21,23 +22,71 @@ import { LibraryService } from 'src/app/_services/library.service';
})
export class CardItemComponent implements OnInit, OnDestroy {
+ /**
+ * Card item url. Will internally handle error and missing covers
+ */
@Input() imageUrl = '';
+ /**
+ * Name of the card
+ */
@Input() title = '';
+ /**
+ * Any actions to perform on the card
+ */
@Input() actions: ActionItem<any>[] = [];
- @Input() read = 0; // Pages read
- @Input() total = 0; // Total Pages
+ /**
+ * Pages Read
+ */
+ @Input() read = 0;
+ /**
+ * Total Pages
+ */
+ @Input() total = 0;
+ /**
+ * Supress library link
+ */
@Input() supressLibraryLink = false;
- @Input() entity!: Series | Volume | Chapter | CollectionTag; // This is the entity we are representing. It will be returned if an action is executed.
+ /**
+ * This is the entity we are representing. It will be returned if an action is executed.
+ */
+ @Input() entity!: Series | Volume | Chapter | CollectionTag;
+ /**
+ * If the entity is selected or not.
+ */
+ @Input() selected: boolean = false;
+ /**
+ * If the entity should show selection code
+ */
+ @Input() allowSelection: boolean = false;
+ /**
+ * Event emitted when item is clicked
+ */
@Output() clicked = new EventEmitter<string>();
-
- libraryName: string | undefined = undefined; // Library name item belongs to
+ /**
+ * When the card is selected.
+ */
+ @Output() selection = new EventEmitter<boolean>();
+ /**
+ * Library name item belongs to
+ */
+ libraryName: string | undefined = undefined;
libraryId: number | undefined = undefined;
- supressArchiveWarning: boolean = false; // This will supress the cannot read archive warning when total pages is 0
+ /**
+ * This will supress the cannot read archive warning when total pages is 0
+ */
+ supressArchiveWarning: boolean = false;
+ /**
+ * Format of the entity (only applies to Series)
+ */
format: MangaFormat = MangaFormat.UNKNOWN;
+
download$: Observable<Download> | null = null;
downloadInProgress: boolean = false;
+ isShiftDown: boolean = false;
+
+
get MangaFormat(): typeof MangaFormat {
return MangaFormat;
}
@@ -46,7 +95,7 @@ export class CardItemComponent implements OnInit, OnDestroy {
constructor(public imageService: ImageService, private libraryService: LibraryService,
public utilityService: UtilityService, private downloadService: DownloadService,
- private toastr: ToastrService) {}
+ private toastr: ToastrService, public bulkSelectionService: BulkSelectionService) {}
ngOnInit(): void {
if (this.entity.hasOwnProperty('promoted') && this.entity.hasOwnProperty('title')) {
@@ -69,7 +118,25 @@ export class CardItemComponent implements OnInit, OnDestroy {
this.onDestroy.complete();
}
- handleClick() {
+
+ prevTouchTime: number = 0;
+ @HostListener('touchstart', ['$event'])
+ onTouchStart(event: TouchEvent) {
+ this.prevTouchTime = event.timeStamp;
+ }
+
+ @HostListener('touchend', ['$event'])
+ onTouchEnd(event: TouchEvent) {
+ if (event.timeStamp - this.prevTouchTime >= 200) {
+ this.handleSelection();
+ event.stopPropagation();
+ event.preventDefault();
+ }
+ this.prevTouchTime = 0;
+ }
+
+
+ handleClick(event?: any) {
this.clicked.emit(this.title);
}
@@ -148,4 +215,12 @@ export class CardItemComponent implements OnInit, OnDestroy {
const tag = this.entity as CollectionTag;
return tag.hasOwnProperty('promoted') && tag.promoted;
}
+
+
+ handleSelection(event?: any) {
+ if (event) {
+ event.stopPropagation();
+ }
+ this.selection.emit(this.selected);
+ }
}
diff --git a/UI/Web/src/app/cards/cards.module.ts b/UI/Web/src/app/cards/cards.module.ts
index c9d427307..7c7db5c54 100644
--- a/UI/Web/src/app/cards/cards.module.ts
+++ b/UI/Web/src/app/cards/cards.module.ts
@@ -19,6 +19,7 @@ import { TypeaheadModule } from '../typeahead/typeahead.module';
import { BrowserModule } from '@angular/platform-browser';
import { CardDetailLayoutComponent } from './card-detail-layout/card-detail-layout.component';
import { CardDetailsModalComponent } from './_modals/card-details-modal/card-details-modal.component';
+import { BulkOperationsComponent } from './bulk-operations/bulk-operations.component';
@@ -34,7 +35,8 @@ import { CardDetailsModalComponent } from './_modals/card-details-modal/card-det
BookmarksModalComponent,
CardActionablesComponent,
CardDetailLayoutComponent,
- CardDetailsModalComponent
+ CardDetailsModalComponent,
+ BulkOperationsComponent
],
imports: [
CommonModule,
@@ -70,7 +72,8 @@ import { CardDetailsModalComponent } from './_modals/card-details-modal/card-det
BookmarksModalComponent,
CardActionablesComponent,
CardDetailLayoutComponent,
- CardDetailsModalComponent
+ CardDetailsModalComponent,
+ BulkOperationsComponent
]
})
export class CardsModule { }
diff --git a/UI/Web/src/app/cards/series-card/series-card.component.html b/UI/Web/src/app/cards/series-card/series-card.component.html
index 18190842f..8653e3f9d 100644
--- a/UI/Web/src/app/cards/series-card/series-card.component.html
+++ b/UI/Web/src/app/cards/series-card/series-card.component.html
@@ -1,3 +1,6 @@
<ng-container *ngIf="data !== undefined">
- <app-card-item [title]="data.name" [actions]="actions" [supressLibraryLink]="suppressLibraryLink" [imageUrl]="imageUrl" [entity]="data" [total]="data.pages" [read]="data.pagesRead" (clicked)="handleClick()"></app-card-item>
+ <app-card-item [title]="data.name" [actions]="actions" [supressLibraryLink]="suppressLibraryLink" [imageUrl]="imageUrl"
+ [entity]="data" [total]="data.pages" [read]="data.pagesRead" (clicked)="handleClick()"
+ [allowSelection]="allowSelection" (selection)="selection.emit(selected)" [selected]="selected"
+ ></app-card-item>
</ng-container>
\ No newline at end of file
diff --git a/UI/Web/src/app/cards/series-card/series-card.component.ts b/UI/Web/src/app/cards/series-card/series-card.component.ts
index 42c1ccfde..57c2af992 100644
--- a/UI/Web/src/app/cards/series-card/series-card.component.ts
+++ b/UI/Web/src/app/cards/series-card/series-card.component.ts
@@ -21,9 +21,22 @@ export class SeriesCardComponent implements OnInit, OnChanges {
@Input() data!: Series;
@Input() libraryId = 0;
@Input() suppressLibraryLink = false;
+ /**
+ * If the entity is selected or not.
+ */
+ @Input() selected: boolean = false;
+ /**
+ * If the entity should show selection code
+ */
+ @Input() allowSelection: boolean = false;
+
@Output() clicked = new EventEmitter<Series>();
@Output() reload = new EventEmitter<boolean>();
@Output() dataChanged = new EventEmitter<Series>();
+ /**
+ * When the card is selected.
+ */
+ @Output() selection = new EventEmitter<boolean>();
isAdmin = false;
actions: ActionItem<Series>[] = [];
@@ -78,6 +91,9 @@ export class SeriesCardComponent implements OnInit, OnChanges {
case(Action.Bookmarks):
this.actionService.openBookmarkModal(series, (series) => {/* No Operation */ });
break;
+ case(Action.AddToReadingList):
+ this.actionService.addSeriesToReadingList(series, (series) => {/* No Operation */ });
+ break;
default:
break;
}
@@ -91,7 +107,6 @@ export class SeriesCardComponent implements OnInit, OnChanges {
if (closeResult.success) {
if (closeResult.coverImageUpdate) {
this.imageUrl = this.imageService.randomize(this.imageService.getSeriesCoverImage(closeResult.series.id));
- console.log('image url: ', this.imageUrl);
}
this.seriesService.getSeries(data.id).subscribe(series => {
this.data = series;
diff --git a/UI/Web/src/app/collections/all-collections/all-collections.component.html b/UI/Web/src/app/collections/all-collections/all-collections.component.html
index 38b7195f3..8cde25096 100644
--- a/UI/Web/src/app/collections/all-collections/all-collections.component.html
+++ b/UI/Web/src/app/collections/all-collections/all-collections.component.html
@@ -1,23 +1,8 @@
-<ng-container *ngIf="collectionTagId === 0; else collectionTagDetail;">
- <app-card-detail-layout header="Collections"
+<app-card-detail-layout header="Collections"
[isLoading]="isLoading"
[items]="collections"
- (pageChange)="onPageChange($event)"
>
<ng-template #cardItem let-item let-position="idx">
<app-card-item [title]="item.title" [entity]="item" [actions]="collectionTagActions" [imageUrl]="item.coverImage" (clicked)="loadCollection(item)"></app-card-item>
</ng-template>
- </app-card-detail-layout>
-</ng-container>
-<ng-template #collectionTagDetail>
- <app-card-detail-layout header="{{collectionTagName}} Collection"
- [isLoading]="isLoading"
- [items]="series"
- [pagination]="seriesPagination"
- (pageChange)="onPageChange($event)"
- >
- <ng-template #cardItem let-item let-position="idx">
- <app-series-card [data]="item" [libraryId]="item.libraryId" (reload)="loadPage()"></app-series-card>
- </ng-template>
- </app-card-detail-layout>
-</ng-template>
\ No newline at end of file
+</app-card-detail-layout>
\ No newline at end of file
diff --git a/UI/Web/src/app/collections/all-collections/all-collections.component.ts b/UI/Web/src/app/collections/all-collections/all-collections.component.ts
index d696b04bc..223894632 100644
--- a/UI/Web/src/app/collections/all-collections/all-collections.component.ts
+++ b/UI/Web/src/app/collections/all-collections/all-collections.component.ts
@@ -1,21 +1,14 @@
import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
-import { ActivatedRoute, Router } from '@angular/router';
+import { Router } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
-import { ToastrService } from 'ngx-toastr';
import { EditCollectionTagsComponent } from 'src/app/cards/_modals/edit-collection-tags/edit-collection-tags.component';
import { CollectionTag } from 'src/app/_models/collection-tag';
-import { Pagination } from 'src/app/_models/pagination';
-import { Series } from 'src/app/_models/series';
import { ActionItem, ActionFactoryService, Action } from 'src/app/_services/action-factory.service';
import { CollectionTagService } from 'src/app/_services/collection-tag.service';
import { ImageService } from 'src/app/_services/image.service';
-import { SeriesService } from 'src/app/_services/series.service';
-/**
- * This component is used as a standard layout for any card detail. ie) series, in-progress, collections, etc.
- */
@Component({
selector: 'app-all-collections',
templateUrl: './all-collections.component.html',
@@ -25,32 +18,13 @@ export class AllCollectionsComponent implements OnInit {
isLoading: boolean = true;
collections: CollectionTag[] = [];
- collectionTagId: number = 0; // 0 is not a valid id, if 0, we will load all tags
- collectionTagName: string = '';
- series: Array<Series> = [];
- seriesPagination!: Pagination;
collectionTagActions: ActionItem<CollectionTag>[] = [];
- constructor(private collectionService: CollectionTagService, private router: Router, private route: ActivatedRoute,
- private seriesService: SeriesService, private toastr: ToastrService, private actionFactoryService: ActionFactoryService,
- private modalService: NgbModal, private titleService: Title, private imageService: ImageService) {
+ constructor(private collectionService: CollectionTagService, private router: Router,
+ private actionFactoryService: ActionFactoryService, private modalService: NgbModal,
+ private titleService: Title, private imageService: ImageService) {
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
-
- const routeId = this.route.snapshot.paramMap.get('id');
- if (routeId != null) {
- this.collectionTagId = parseInt(routeId, 10);
- this.collectionService.allTags().subscribe(tags => {
- this.collections = tags;
- const matchingTags = this.collections.filter(t => t.id === this.collectionTagId);
- if (matchingTags.length === 0) {
- this.toastr.error('You don\'t have access to any libraries this tag belongs to or this tag is invalid');
- this.router.navigate(['collections']);
- return;
- }
- this.collectionTagName = tags.filter(item => item.id === this.collectionTagId)[0].title;
- this.titleService.setTitle('Kavita - ' + this.collectionTagName + ' Collection');
- });
- }
+ this.titleService.setTitle('Kavita - Collections');
}
ngOnInit() {
@@ -60,38 +34,15 @@ export class AllCollectionsComponent implements OnInit {
loadCollection(item: CollectionTag) {
- this.collectionTagId = item.id;
- this.collectionTagName = item.title;
- this.router.navigate(['collections', this.collectionTagId]);
+ this.router.navigate(['collections', item.id]);
this.loadPage();
}
- onPageChange(pagination: Pagination) {
- this.router.navigate(['collections', this.collectionTagId], {replaceUrl: true, queryParamsHandling: 'merge', queryParams: {page: this.seriesPagination.currentPage} });
- }
-
loadPage() {
- const page = this.route.snapshot.queryParamMap.get('page');
- if (page != null) {
- if (this.seriesPagination === undefined || this.seriesPagination === null) {
- this.seriesPagination = {currentPage: 0, itemsPerPage: 30, totalItems: 0, totalPages: 1};
- }
- this.seriesPagination.currentPage = parseInt(page, 10);
- }
- // Reload page after a series is updated or first load
- if (this.collectionTagId === 0) {
- this.collectionService.allTags().subscribe(tags => {
- this.collections = tags;
- this.isLoading = false;
- });
- } else {
- this.seriesService.getSeriesForTag(this.collectionTagId, this.seriesPagination?.currentPage, this.seriesPagination?.itemsPerPage).subscribe(tags => {
- this.series = tags.result;
- this.seriesPagination = tags.pagination;
- this.isLoading = false;
- window.scrollTo(0, 0);
- });
- }
+ this.collectionService.allTags().subscribe(tags => {
+ this.collections = tags;
+ this.isLoading = false;
+ });
}
handleCollectionActionCallback(action: Action, collectionTag: CollectionTag) {
diff --git a/UI/Web/src/app/collections/collection-detail/collection-detail.component.html b/UI/Web/src/app/collections/collection-detail/collection-detail.component.html
index ff77357ef..431680257 100644
--- a/UI/Web/src/app/collections/collection-detail/collection-detail.component.html
+++ b/UI/Web/src/app/collections/collection-detail/collection-detail.component.html
@@ -11,14 +11,6 @@
</h2>
</div>
<div class="row no-gutters mt-2 mb-2">
- <!-- <div>
- <button class="btn btn-primary" (click)="read()" [disabled]="isLoading">
- <span>
- <i class="fa fa-book-open"></i>
- </span>
- <span class="read-btn--text">&nbsp;Read</span>
- </button>
- </div> -->
<div class="ml-2" *ngIf="isAdmin">
<button class="btn btn-secondary" (click)="openEditCollectionTagModal(collectionTag)" title="Edit Series information">
<span>
@@ -33,6 +25,7 @@
</div>
</div>
<hr>
+ <app-bulk-operations [actionCallback]="bulkActionCallback"></app-bulk-operations>
<app-card-detail-layout
header="Series"
@@ -44,7 +37,9 @@
(applyFilter)="updateFilter($event)"
>
<ng-template #cardItem let-item let-position="idx">
- <app-series-card [data]="item" [libraryId]="item.libraryId" (reload)="loadPage()"></app-series-card>
+ <app-series-card [data]="item" [libraryId]="item.libraryId" (reload)="loadPage()"
+ (selection)="bulkSelectionService.handleCardSelection('series', position, series.length, $event)" [selected]="bulkSelectionService.isCardSelected('series', position)" [allowSelection]="true"
+ ></app-series-card>
</ng-template>
</app-card-detail-layout>
diff --git a/UI/Web/src/app/collections/collection-detail/collection-detail.component.ts b/UI/Web/src/app/collections/collection-detail/collection-detail.component.ts
index e7013f34e..5f3fa3145 100644
--- a/UI/Web/src/app/collections/collection-detail/collection-detail.component.ts
+++ b/UI/Web/src/app/collections/collection-detail/collection-detail.component.ts
@@ -1,19 +1,20 @@
-import { Component, OnInit } from '@angular/core';
+import { Component, HostListener, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router, ActivatedRoute } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { take } from 'rxjs/operators';
+import { BulkSelectionService } from 'src/app/cards/bulk-selection.service';
import { UpdateFilterEvent } from 'src/app/cards/card-detail-layout/card-detail-layout.component';
import { EditCollectionTagsComponent } from 'src/app/cards/_modals/edit-collection-tags/edit-collection-tags.component';
-import { UtilityService } from 'src/app/shared/_services/utility.service';
+import { KEY_CODES } from 'src/app/shared/_services/utility.service';
import { CollectionTag } from 'src/app/_models/collection-tag';
-import { MangaFormat } from 'src/app/_models/manga-format';
import { Pagination } from 'src/app/_models/pagination';
import { Series } from 'src/app/_models/series';
import { FilterItem, mangaFormatFilters, SeriesFilter } from 'src/app/_models/series-filter';
import { AccountService } from 'src/app/_services/account.service';
import { Action, ActionFactoryService, ActionItem } from 'src/app/_services/action-factory.service';
+import { ActionService } from 'src/app/_services/action.service';
import { CollectionTagService } from 'src/app/_services/collection-tag.service';
import { ImageService } from 'src/app/_services/image.service';
import { SeriesService } from 'src/app/_services/series.service';
@@ -39,9 +40,35 @@ export class CollectionDetailComponent implements OnInit {
mangaFormat: null
};
+ bulkActionCallback = (action: Action, data: any) => {
+ const selectedSeriesIndexies = this.bulkSelectionService.getSelectedCardsForSource('series');
+ const selectedSeries = this.series.filter((series, index: number) => selectedSeriesIndexies.includes(index + ''));
+
+ switch (action) {
+ case Action.AddToReadingList:
+ this.actionService.addMultipleSeriesToReadingList(selectedSeries, () => {
+ this.bulkSelectionService.deselectAll();
+ });
+ break;
+ case Action.MarkAsRead:
+ this.actionService.markMultipleSeriesAsRead(selectedSeries, () => {
+ this.loadPage();
+ this.bulkSelectionService.deselectAll();
+ });
+ break;
+ case Action.MarkAsUnread:
+ this.actionService.markMultipleSeriesAsUnread(selectedSeries, () => {
+ this.loadPage();
+ this.bulkSelectionService.deselectAll();
+ });
+ break;
+ }
+ }
+
constructor(public imageService: ImageService, private collectionService: CollectionTagService, private router: Router, private route: ActivatedRoute,
private seriesService: SeriesService, private toastr: ToastrService, private actionFactoryService: ActionFactoryService,
- private modalService: NgbModal, private titleService: Title, private accountService: AccountService, private utilityService: UtilityService) {
+ private modalService: NgbModal, private titleService: Title, private accountService: AccountService,
+ public bulkSelectionService: BulkSelectionService, private actionService: ActionService) {
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.accountService.currentUser$.pipe(take(1)).subscribe(user => {
@@ -63,6 +90,20 @@ export class CollectionDetailComponent implements OnInit {
this.collectionTagActions = this.actionFactoryService.getCollectionTagActions(this.handleCollectionActionCallback.bind(this));
}
+ @HostListener('document:keydown.shift', ['$event'])
+ handleKeypress(event: KeyboardEvent) {
+ if (event.key === KEY_CODES.SHIFT) {
+ this.bulkSelectionService.isShiftDown = true;
+ }
+ }
+
+ @HostListener('document:keyup.shift', ['$event'])
+ handleKeyUp(event: KeyboardEvent) {
+ if (event.key === KEY_CODES.SHIFT) {
+ this.bulkSelectionService.isShiftDown = false;
+ }
+ }
+
updateTag(tagId: number) {
this.collectionService.allTags().subscribe(tags => {
this.collections = tags;
diff --git a/UI/Web/src/app/collections/collections.module.ts b/UI/Web/src/app/collections/collections.module.ts
index eb0f8690e..0863647c8 100644
--- a/UI/Web/src/app/collections/collections.module.ts
+++ b/UI/Web/src/app/collections/collections.module.ts
@@ -18,6 +18,9 @@ import { AllCollectionsComponent } from './all-collections/all-collections.compo
SharedModule,
CardsModule,
CollectionsRoutingModule,
+ ],
+ exports: [
+ AllCollectionsComponent
]
})
export class CollectionsModule { }
diff --git a/UI/Web/src/app/dashboard/dashboard.component.html b/UI/Web/src/app/dashboard/dashboard.component.html
new file mode 100644
index 000000000..73bda1d74
--- /dev/null
+++ b/UI/Web/src/app/dashboard/dashboard.component.html
@@ -0,0 +1,21 @@
+<div class="container-fluid">
+ <nav role="navigation">
+ <ul ngbNav #nav="ngbNav" [(activeId)]="active" class="nav nav-pills justify-content-center mt-3" role="tab">
+ <li *ngFor="let tab of tabs" [ngbNavItem]="tab" class="nav-item">
+ <a ngbNavLink routerLink="." [fragment]="tab.fragment">{{ tab.title | titlecase }}</a>
+ <ng-template ngbNavContent>
+ <ng-container *ngIf="tab.fragment === ''">
+ <app-library></app-library>
+ </ng-container>
+ <ng-container *ngIf="tab.fragment === 'lists'">
+ <app-reading-lists></app-reading-lists>
+ </ng-container>
+ <ng-container *ngIf="tab.fragment === 'collections'">
+ <app-all-collections></app-all-collections>
+ </ng-container>
+ </ng-template>
+ </li>
+ </ul>
+ </nav>
+ <div [ngbNavOutlet]="nav" class="mt-3"></div>
+</div>
\ No newline at end of file
diff --git a/UI/Web/src/app/dashboard/dashboard.component.scss b/UI/Web/src/app/dashboard/dashboard.component.scss
new file mode 100644
index 000000000..e69de29bb
diff --git a/UI/Web/src/app/dashboard/dashboard.component.ts b/UI/Web/src/app/dashboard/dashboard.component.ts
new file mode 100644
index 000000000..518ee208e
--- /dev/null
+++ b/UI/Web/src/app/dashboard/dashboard.component.ts
@@ -0,0 +1,37 @@
+import { Component, OnInit } from '@angular/core';
+import { Title } from '@angular/platform-browser';
+import { ActivatedRoute } from '@angular/router';
+import { ToastrService } from 'ngx-toastr';
+import { ServerService } from '../_services/server.service';
+
+@Component({
+ selector: 'app-dashboard',
+ templateUrl: './dashboard.component.html',
+ styleUrls: ['./dashboard.component.scss']
+})
+export class DashboardComponent implements OnInit {
+
+ tabs: Array<{title: string, fragment: string}> = [
+ {title: 'Libraries', fragment: ''},
+ {title: 'Lists', fragment: 'lists'},
+ {title: 'Collections', fragment: 'collections'},
+ ];
+ active = this.tabs[0];
+
+ constructor(public route: ActivatedRoute, private serverService: ServerService,
+ private toastr: ToastrService, private titleService: Title) {
+ this.route.fragment.subscribe(frag => {
+ const tab = this.tabs.filter(item => item.fragment === frag);
+ if (tab.length > 0) {
+ this.active = tab[0];
+ } else {
+ this.active = this.tabs[0]; // Default to first tab
+ }
+ });
+ this.titleService.setTitle('Kavita - Dashboard');
+ }
+
+ ngOnInit(): void {
+ }
+
+}
diff --git a/UI/Web/src/app/library-detail/library-detail.component.html b/UI/Web/src/app/library-detail/library-detail.component.html
index 652e0c849..6d7885385 100644
--- a/UI/Web/src/app/library-detail/library-detail.component.html
+++ b/UI/Web/src/app/library-detail/library-detail.component.html
@@ -1,3 +1,4 @@
+<app-bulk-operations [actionCallback]="bulkActionCallback"></app-bulk-operations>
<app-card-detail-layout header="{{libraryName}}"
[isLoading]="loadingSeries"
[items]="series"
@@ -8,6 +9,6 @@
(pageChange)="onPageChange($event)"
>
<ng-template #cardItem let-item let-position="idx">
- <app-series-card [data]="item" [libraryId]="libraryId" [suppressLibraryLink]="true" (reload)="loadPage()"></app-series-card>
+ <app-series-card [data]="item" [libraryId]="libraryId" [suppressLibraryLink]="true" (reload)="loadPage()" (selection)="bulkSelectionService.handleCardSelection('series', position, series.length, $event)" [selected]="bulkSelectionService.isCardSelected('series', position)" [allowSelection]="true"></app-series-card>
</ng-template>
</app-card-detail-layout>
diff --git a/UI/Web/src/app/library-detail/library-detail.component.ts b/UI/Web/src/app/library-detail/library-detail.component.ts
index 01ad75c1f..fdd58fb33 100644
--- a/UI/Web/src/app/library-detail/library-detail.component.ts
+++ b/UI/Web/src/app/library-detail/library-detail.component.ts
@@ -1,8 +1,10 @@
-import { Component, OnInit } from '@angular/core';
+import { Component, HostListener, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { take } from 'rxjs/operators';
+import { BulkSelectionService } from '../cards/bulk-selection.service';
import { UpdateFilterEvent } from '../cards/card-detail-layout/card-detail-layout.component';
+import { KEY_CODES } from '../shared/_services/utility.service';
import { Library } from '../_models/library';
import { Pagination } from '../_models/pagination';
import { Series } from '../_models/series';
@@ -30,9 +32,35 @@ export class LibraryDetailComponent implements OnInit {
mangaFormat: null
};
+ bulkActionCallback = (action: Action, data: any) => {
+ const selectedSeriesIndexies = this.bulkSelectionService.getSelectedCardsForSource('series');
+ const selectedSeries = this.series.filter((series, index: number) => selectedSeriesIndexies.includes(index + ''));
+
+ switch (action) {
+ case Action.AddToReadingList:
+ this.actionService.addMultipleSeriesToReadingList(selectedSeries, () => {
+ this.bulkSelectionService.deselectAll();
+ });
+ break;
+ case Action.MarkAsRead:
+ this.actionService.markMultipleSeriesAsRead(selectedSeries, () => {
+ this.loadPage();
+ this.bulkSelectionService.deselectAll();
+ });
+
+ break;
+ case Action.MarkAsUnread:
+ this.actionService.markMultipleSeriesAsUnread(selectedSeries, () => {
+ this.loadPage();
+ this.bulkSelectionService.deselectAll();
+ });
+ break;
+ }
+ }
+
constructor(private route: ActivatedRoute, private router: Router, private seriesService: SeriesService,
private libraryService: LibraryService, private titleService: Title, private actionFactoryService: ActionFactoryService,
- private actionService: ActionService) {
+ private actionService: ActionService, public bulkSelectionService: BulkSelectionService) {
const routeId = this.route.snapshot.paramMap.get('id');
if (routeId === null) {
this.router.navigateByUrl('/libraries');
@@ -53,6 +81,20 @@ export class LibraryDetailComponent implements OnInit {
}
+ @HostListener('document:keydown.shift', ['$event'])
+ handleKeypress(event: KeyboardEvent) {
+ if (event.key === KEY_CODES.SHIFT) {
+ this.bulkSelectionService.isShiftDown = true;
+ }
+ }
+
+ @HostListener('document:keyup.shift', ['$event'])
+ handleKeyUp(event: KeyboardEvent) {
+ if (event.key === KEY_CODES.SHIFT) {
+ this.bulkSelectionService.isShiftDown = false;
+ }
+ }
+
handleAction(action: Action, library: Library) {
let lib: Partial<Library> = library;
if (library === undefined) {
diff --git a/UI/Web/src/app/library/library.component.html b/UI/Web/src/app/library/library.component.html
index c80c3223f..d1522bb8a 100644
--- a/UI/Web/src/app/library/library.component.html
+++ b/UI/Web/src/app/library/library.component.html
@@ -1,33 +1,24 @@
+<div *ngIf="libraries.length === 0 && !isLoading && isAdmin" class="d-flex justify-content-center">
+ <p>There are no libraries setup yet. Configure some in <a href="/admin/dashboard#libraries">Server settings</a>.</p>
+</div>
+<div *ngIf="libraries.length === 0 && !isLoading && !isAdmin" class="d-flex justify-content-center">
+ <p>You haven't been granted access to any libraries.</p>
+</div>
-<div class="container-fluid">
- <div *ngIf="libraries.length === 0 && !isLoading && isAdmin" class="d-flex justify-content-center">
- <p>There are no libraries setup yet. Configure some in <a href="/admin/dashboard#libraries">Server settings</a>.</p>
- </div>
- <div *ngIf="libraries.length === 0 && !isLoading && !isAdmin" class="d-flex justify-content-center">
- <p>You haven't been granted access to any libraries.</p>
- </div>
- <app-carousel-reel [items]="libraries" title="Libraries">
- <ng-template #carouselItem let-item let-position="idx">
- <app-library-card [data]="item"></app-library-card>
- </ng-template>
- </app-carousel-reel>
+<app-carousel-reel [items]="inProgress" title="In Progress" (sectionClick)="handleSectionClick($event)">
+ <ng-template #carouselItem let-item let-position="idx">
+ <app-series-card [data]="item" [libraryId]="item.libraryId" (reload)="reloadInProgress($event)" (dataChanged)="reloadInProgress($event)"></app-series-card>
+ </ng-template>
+</app-carousel-reel>
- <app-carousel-reel [items]="inProgress" title="In Progress" (sectionClick)="handleSectionClick($event)">
- <ng-template #carouselItem let-item let-position="idx">
- <app-series-card [data]="item" [libraryId]="item.libraryId" (reload)="reloadInProgress($event)" (dataChanged)="reloadInProgress($event)"></app-series-card>
- </ng-template>
- </app-carousel-reel>
+<app-carousel-reel [items]="recentlyAdded" title="Recently Added" (sectionClick)="handleSectionClick($event)">
+ <ng-template #carouselItem let-item let-position="idx">
+ <app-series-card [data]="item" [libraryId]="item.libraryId" (reload)="reloadTags()" (dataChanged)="loadRecentlyAdded()"></app-series-card>
+ </ng-template>
+</app-carousel-reel>
- <app-carousel-reel [items]="recentlyAdded" title="Recently Added" (sectionClick)="handleSectionClick($event)">
- <ng-template #carouselItem let-item let-position="idx">
- <app-series-card [data]="item" [libraryId]="item.libraryId" (reload)="reloadTags()" (dataChanged)="loadRecentlyAdded()"></app-series-card>
- </ng-template>
- </app-carousel-reel>
-
- <app-carousel-reel [items]="collectionTags" title="Collections" (sectionClick)="handleSectionClick($event)">
- <ng-template #carouselItem let-item let-position="idx">
- <app-card-item [title]="item.title" [entity]="item" [actions]="collectionTagActions" [imageUrl]="item.coverImage" (clicked)="loadCollection(item)"></app-card-item>
- </ng-template>
- </app-carousel-reel>
-
-</div>
\ No newline at end of file
+<app-carousel-reel [items]="libraries" title="Libraries">
+ <ng-template #carouselItem let-item let-position="idx">
+ <app-library-card [data]="item"></app-library-card>
+ </ng-template>
+</app-carousel-reel>
diff --git a/UI/Web/src/app/library/library.component.ts b/UI/Web/src/app/library/library.component.ts
index f31e98445..bf862f730 100644
--- a/UI/Web/src/app/library/library.component.ts
+++ b/UI/Web/src/app/library/library.component.ts
@@ -5,7 +5,6 @@ import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { Subject } from 'rxjs';
import { take, takeUntil } from 'rxjs/operators';
import { EditCollectionTagsComponent } from '../cards/_modals/edit-collection-tags/edit-collection-tags.component';
-import { ScrollService } from '../scroll.service';
import { CollectionTag } from '../_models/collection-tag';
import { InProgressChapter } from '../_models/in-progress-chapter';
import { Library } from '../_models/library';
@@ -33,8 +32,8 @@ export class LibraryComponent implements OnInit, OnDestroy {
recentlyAdded: Series[] = [];
inProgress: Series[] = [];
continueReading: InProgressChapter[] = [];
- collectionTags: CollectionTag[] = [];
- collectionTagActions: ActionItem<CollectionTag>[] = [];
+ // collectionTags: CollectionTag[] = [];
+ // collectionTagActions: ActionItem<CollectionTag>[] = [];
private readonly onDestroy = new Subject<void>();
@@ -43,8 +42,7 @@ export class LibraryComponent implements OnInit, OnDestroy {
constructor(public accountService: AccountService, private libraryService: LibraryService,
private seriesService: SeriesService, private actionFactoryService: ActionFactoryService,
private collectionService: CollectionTagService, private router: Router,
- private modalService: NgbModal, private titleService: Title, public imageService: ImageService,
- private scrollService: ScrollService) { }
+ private modalService: NgbModal, private titleService: Title, public imageService: ImageService) { }
ngOnInit(): void {
this.titleService.setTitle('Kavita - Dashboard');
@@ -58,7 +56,7 @@ export class LibraryComponent implements OnInit, OnDestroy {
});
});
- this.collectionTagActions = this.actionFactoryService.getCollectionTagActions(this.handleCollectionActionCallback.bind(this));
+ //this.collectionTagActions = this.actionFactoryService.getCollectionTagActions(this.handleCollectionActionCallback.bind(this));
this.reloadSeries();
}
@@ -103,9 +101,9 @@ export class LibraryComponent implements OnInit, OnDestroy {
}
reloadTags() {
- this.collectionService.allTags().pipe(takeUntil(this.onDestroy)).subscribe(tags => {
- this.collectionTags = tags;
- });
+ // this.collectionService.allTags().pipe(takeUntil(this.onDestroy)).subscribe(tags => {
+ // this.collectionTags = tags;
+ // });
}
handleSectionClick(sectionTitle: string) {
@@ -119,24 +117,24 @@ export class LibraryComponent implements OnInit, OnDestroy {
}
loadCollection(item: CollectionTag) {
- this.router.navigate(['collections', item.id]);
+ //this.router.navigate(['collections', item.id]);
}
- handleCollectionActionCallback(action: Action, collectionTag: CollectionTag) {
- switch (action) {
- case(Action.Edit):
- const modalRef = this.modalService.open(EditCollectionTagsComponent, { size: 'lg', scrollable: true });
- modalRef.componentInstance.tag = collectionTag;
- modalRef.closed.subscribe((results: {success: boolean, coverImageUpdated: boolean}) => {
- this.reloadTags();
- if (results.coverImageUpdated) {
- collectionTag.coverImage = this.imageService.randomize(collectionTag.coverImage);
- }
- });
- break;
- default:
- break;
- }
- }
+ // handleCollectionActionCallback(action: Action, collectionTag: CollectionTag) {
+ // switch (action) {
+ // case(Action.Edit):
+ // const modalRef = this.modalService.open(EditCollectionTagsComponent, { size: 'lg', scrollable: true });
+ // modalRef.componentInstance.tag = collectionTag;
+ // modalRef.closed.subscribe((results: {success: boolean, coverImageUpdated: boolean}) => {
+ // this.reloadTags();
+ // if (results.coverImageUpdated) {
+ // collectionTag.coverImage = this.imageService.randomize(collectionTag.coverImage);
+ // }
+ // });
+ // break;
+ // default:
+ // break;
+ // }
+ // }
}
diff --git a/UI/Web/src/app/manga-reader/_models/chapter-info.ts b/UI/Web/src/app/manga-reader/_models/chapter-info.ts
index fff07b12b..f83c86902 100644
--- a/UI/Web/src/app/manga-reader/_models/chapter-info.ts
+++ b/UI/Web/src/app/manga-reader/_models/chapter-info.ts
@@ -1,8 +1,13 @@
+import { MangaFormat } from "src/app/_models/manga-format";
+
export interface ChapterInfo {
chapterNumber: string;
volumeNumber: string;
chapterTitle: string;
seriesName: string;
+ seriesFormat: MangaFormat;
+ seriesId: number;
+ libraryId: number;
fileName: string;
isSpecial: boolean;
volumeId: number;
diff --git a/UI/Web/src/app/manga-reader/_models/reader-enums.ts b/UI/Web/src/app/manga-reader/_models/reader-enums.ts
index 0117ed5d2..9738edf9f 100644
--- a/UI/Web/src/app/manga-reader/_models/reader-enums.ts
+++ b/UI/Web/src/app/manga-reader/_models/reader-enums.ts
@@ -2,21 +2,21 @@ export enum FITTING_OPTION {
HEIGHT = 'full-height',
WIDTH = 'full-width',
ORIGINAL = 'original'
- }
+}
export enum SPLIT_PAGE_PART {
NO_SPLIT = 'none',
LEFT_PART = 'left',
RIGHT_PART = 'right'
- }
+}
export enum PAGING_DIRECTION {
FORWARD = 1,
BACKWARDS = -1,
- }
+}
export enum COLOR_FILTER {
NONE = '',
SEPIA = 'filter-sepia',
DARK = 'filter-dark'
- }
+}
diff --git a/UI/Web/src/app/manga-reader/infinite-scroller/infinite-scroller.component.html b/UI/Web/src/app/manga-reader/infinite-scroller/infinite-scroller.component.html
index 92be7cb04..c0d5ff542 100644
--- a/UI/Web/src/app/manga-reader/infinite-scroller/infinite-scroller.component.html
+++ b/UI/Web/src/app/manga-reader/infinite-scroller/infinite-scroller.component.html
@@ -1,15 +1,43 @@
-<div class="fixed-top overlay" *ngIf="debug">
+<div class="fixed-top overlay" *ngIf="showDebugBar()">
<strong>Captures Scroll Events:</strong> {{!this.isScrolling && this.allImagesLoaded}}
<strong>Is Scrolling:</strong> {{isScrollingForwards() ? 'Forwards' : 'Backwards'}} {{this.isScrolling}}
<strong>All Images Loaded:</strong> {{this.allImagesLoaded}}
<strong>Prefetched</strong> {{minPageLoaded}}-{{maxPageLoaded}}
- <strong>Current Page:</strong>{{pageNum}}
- <strong>Width:</strong> {{webtoonImageWidth}}
+ <strong>Pages:</strong> {{pageNum}} / {{totalPages}}
+ <strong>At Top:</strong> {{atTop}}
+ <strong>At Bottom:</strong> {{atBottom}}
+ <strong>Total Height:</strong> {{getTotalHeight()}}
+ <strong>Total Scroll:</strong> {{getTotalScroll()}}
+ <strong>Scroll Top:</strong> {{getScrollTop()}}
</div>
-
+<div *ngIf="atTop" class="spacer top" role="alert" (click)="loadPrevChapter.emit()">
+ <div style="height: 200px"></div>
+ <div>
+ <button class="btn btn-icon mx-auto">
+ <i class="fa fa-angle-double-up animate" aria-hidden="true"></i>
+ </button>
+ <span class="mx-auto text">Previous Chapter</span>
+ <button class="btn btn-icon mx-auto">
+ <i class="fa fa-angle-double-up animate" aria-hidden="true"></i>
+ </button>
+ <span class="sr-only">Scroll up to move to next chapter</span>
+ </div>
+</div>
<ng-container *ngFor="let item of webtoonImages | async; let index = index;">
- <img src="{{item.src}}" style="display: block" class="mx-auto {{pageNum === item.page && debug ? 'active': ''}}" *ngIf="pageNum >= pageNum - bufferPages && pageNum <= pageNum + bufferPages" rel="nofollow" alt="image" (load)="onImageLoad($event)" id="page-{{item.page}}" [attr.page]="item.page" ondragstart="return false;" onselectstart="return false;">
+ <img src="{{item.src}}" style="display: block" class="mx-auto {{pageNum === item.page && showDebugOutline() ? 'active': ''}}" *ngIf="pageNum >= pageNum - bufferPages && pageNum <= pageNum + bufferPages" rel="nofollow" alt="image" (load)="onImageLoad($event)" id="page-{{item.page}}" [attr.page]="item.page" ondragstart="return false;" onselectstart="return false;">
</ng-container>
-
+<div *ngIf="atBottom" class="spacer bottom" role="alert" (click)="loadPrevChapter.emit()">
+ <div>
+ <button class="btn btn-icon mx-auto">
+ <i class="fa fa-angle-double-down animate" aria-hidden="true"></i>
+ </button>
+ <span class="mx-auto text">Next Chapter</span>
+ <button class="btn btn-icon mx-auto">
+ <i class="fa fa-angle-double-down animate" aria-hidden="true"></i>
+ </button>
+ <span class="sr-only">Scroll down to move to next chapter</span>
+ </div>
+ <div style="height: 200px"></div>
+</div>
diff --git a/UI/Web/src/app/manga-reader/infinite-scroller/infinite-scroller.component.scss b/UI/Web/src/app/manga-reader/infinite-scroller/infinite-scroller.component.scss
index c7308aa33..4277b6760 100644
--- a/UI/Web/src/app/manga-reader/infinite-scroller/infinite-scroller.component.scss
+++ b/UI/Web/src/app/manga-reader/infinite-scroller/infinite-scroller.component.scss
@@ -4,4 +4,28 @@
}
.active {
border: 2px solid red;
+}
+
+.spacer {
+ width: 100%;
+ height: 300px;
+ cursor: pointer;
+
+ .animate {
+ animation: move-up-down 1s linear infinite;
+ }
+
+ .text {
+ z-index: 101;
+
+ }
+}
+
+@keyframes move-up-down {
+ 0%, 100% {
+ transform: translateY(0);
+ }
+ 50% {
+ transform: translateY(-10px);
+ }
}
\ No newline at end of file
diff --git a/UI/Web/src/app/manga-reader/infinite-scroller/infinite-scroller.component.ts b/UI/Web/src/app/manga-reader/infinite-scroller/infinite-scroller.component.ts
index 5e6973ecd..d40eec83d 100644
--- a/UI/Web/src/app/manga-reader/infinite-scroller/infinite-scroller.component.ts
+++ b/UI/Web/src/app/manga-reader/infinite-scroller/infinite-scroller.component.ts
@@ -1,10 +1,40 @@
import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, Renderer2, SimpleChanges } from '@angular/core';
+import { ToastrService } from 'ngx-toastr';
import { BehaviorSubject, fromEvent, ReplaySubject, Subject } from 'rxjs';
import { debounceTime, takeUntil } from 'rxjs/operators';
import { ReaderService } from '../../_services/reader.service';
import { PAGING_DIRECTION } from '../_models/reader-enums';
import { WebtoonImage } from '../_models/webtoon-image';
+/**
+ * How much additional space should pass, past the original bottom of the document height before we trigger the next chapter load
+ */
+const SPACER_SCROLL_INTO_PX = 200;
+
+/**
+ * Bitwise enums for configuring how much debug information we want
+ */
+const enum DEBUG_MODES {
+ /**
+ * No Debug information
+ */
+ None = 0,
+ /**
+ * Turn on debug logging
+ */
+ Logs = 2,
+ /**
+ * Turn on the action bar in UI
+ */
+ ActionBar = 4,
+ /**
+ * Turn on Page outline
+ */
+ Outline = 8
+
+
+}
+
@Component({
selector: 'app-infinite-scroller',
templateUrl: './infinite-scroller.component.html',
@@ -29,6 +59,8 @@ export class InfiniteScrollerComponent implements OnInit, OnChanges, OnDestroy {
*/
@Input() urlProvider!: (page: number) => string;
@Output() pageNumberChange: EventEmitter<number> = new EventEmitter<number>();
+ @Output() loadNextChapter: EventEmitter<void> = new EventEmitter<void>();
+ @Output() loadPrevChapter: EventEmitter<void> = new EventEmitter<void>();
@Input() goToPage: ReplaySubject<number> = new ReplaySubject<number>();
@@ -71,9 +103,21 @@ export class InfiniteScrollerComponent implements OnInit, OnChanges, OnDestroy {
*/
imagesLoaded: {[key: number]: number} = {};
/**
- * Debug mode. Will show extra information
+ * If the user has scrolled all the way to the bottom. This is used solely for continuous reading
+ */
+ atBottom: boolean = false;
+ /**
+ * If the user has scrolled all the way to the top. This is used solely for continuous reading
+ */
+ atTop: boolean = false;
+ /**
+ * Keeps track of the previous scrolling height for restoring scroll position after we inject spacer block
+ */
+ previousScrollHeightMinusTop: number = 0;
+ /**
+ * Debug mode. Will show extra information. Use bitwise (|) operators between different modes to enable different output
*/
- debug: boolean = false;
+ debugMode: DEBUG_MODES = DEBUG_MODES.None;
get minPageLoaded() {
return Math.min(...Object.values(this.imagesLoaded));
@@ -85,9 +129,10 @@ export class InfiniteScrollerComponent implements OnInit, OnChanges, OnDestroy {
+
private readonly onDestroy = new Subject<void>();
- constructor(private readerService: ReaderService, private renderer: Renderer2) { }
+ constructor(private readerService: ReaderService, private renderer: Renderer2, private toastr: ToastrService) {}
ngOnChanges(changes: SimpleChanges): void {
if (changes.hasOwnProperty('totalPages') && changes['totalPages'].previousValue != changes['totalPages'].currentValue) {
@@ -104,7 +149,7 @@ export class InfiniteScrollerComponent implements OnInit, OnChanges, OnDestroy {
ngOnInit(): void {
fromEvent(window, 'scroll')
- .pipe(debounceTime(20), takeUntil(this.onDestroy))
+ .pipe(debounceTime(20), takeUntil(this.onDestroy))
.subscribe((event) => this.handleScrollEvent(event));
if (this.goToPage) {
@@ -145,6 +190,61 @@ export class InfiniteScrollerComponent implements OnInit, OnChanges, OnDestroy {
this.scrollingDirection = PAGING_DIRECTION.BACKWARDS;
}
this.prevScrollPosition = verticalOffset;
+
+ // Check if we hit the last page
+ this.checkIfShouldTriggerContinuousReader();
+
+ }
+
+ getTotalHeight() {
+ let totalHeight = 0;
+ document.querySelectorAll('img[id^="page-"]').forEach(img => totalHeight += img.getBoundingClientRect().height);
+ return totalHeight;
+ }
+ getTotalScroll() {
+ return document.documentElement.offsetHeight + document.documentElement.scrollTop;
+ }
+ getScrollTop() {
+ return document.documentElement.scrollTop
+ }
+
+ checkIfShouldTriggerContinuousReader() {
+ if (this.isScrolling) return;
+
+ if (this.scrollingDirection === PAGING_DIRECTION.FORWARD) {
+ const totalHeight = this.getTotalHeight();
+ const totalScroll = this.getTotalScroll();
+
+ // If we were at top but have started scrolling down past page 0, remove top spacer
+ if (this.atTop && this.pageNum > 0) {
+ this.atTop = false;
+ }
+ // debug mode will add an extra pixel from the image border + (this.debug ? 1 : 0)
+ if (totalScroll === totalHeight && !this.atBottom) {
+ this.atBottom = true;
+ this.setPageNum(this.totalPages);
+ // Scroll user back to original location
+ this.previousScrollHeightMinusTop = document.documentElement.scrollTop;
+ requestAnimationFrame(() => document.documentElement.scrollTop = this.previousScrollHeightMinusTop + (SPACER_SCROLL_INTO_PX / 2));
+ } else if (totalScroll >= totalHeight + SPACER_SCROLL_INTO_PX && this.atBottom) {
+ // This if statement will fire once we scroll into the spacer at all
+ this.loadNextChapter.emit();
+ }
+ } else {
+ // < 5 because debug mode and FF (mobile) can report non 0, despite being at 0
+ if (this.getScrollTop() < 5 && this.pageNum === 0 && !this.atTop) {
+ this.atBottom = false;
+
+ this.atTop = true;
+ // Scroll user back to original location
+ this.previousScrollHeightMinusTop = document.documentElement.scrollHeight - document.documentElement.scrollTop;
+ requestAnimationFrame(() => window.scrollTo(0, SPACER_SCROLL_INTO_PX));
+ } else if (this.getScrollTop() < 5 && this.pageNum === 0 && this.atTop) {
+ // If already at top, then we moving on
+ this.loadPrevChapter.emit();
+ }
+ }
+
}
/**
@@ -170,6 +270,8 @@ export class InfiniteScrollerComponent implements OnInit, OnChanges, OnDestroy {
initWebtoonReader() {
this.imagesLoaded = {};
this.webtoonImages.next([]);
+ this.atBottom = false;
+ this.checkIfShouldTriggerContinuousReader();
const [startingIndex, endingIndex] = this.calculatePrefetchIndecies();
@@ -236,6 +338,11 @@ export class InfiniteScrollerComponent implements OnInit, OnChanges, OnDestroy {
* @param scrollToPage Optional (default false) parameter to trigger scrolling to the newly set page
*/
setPageNum(pageNum: number, scrollToPage: boolean = false) {
+ if (pageNum > this.totalPages) {
+ pageNum = this.totalPages;
+ } else if (pageNum < 0) {
+ pageNum = 0;
+ }
this.pageNum = pageNum;
this.pageNumberChange.emit(this.pageNum);
@@ -341,7 +448,7 @@ export class InfiniteScrollerComponent implements OnInit, OnChanges, OnDestroy {
if (startingIndex === 0 && endingIndex === 0) { return; }
this.debugLog('\t[PREFETCH] prefetching pages: ' + startingIndex + ' to ' + endingIndex);
- for(let i = startingIndex; i < endingIndex; i++) {
+ for(let i = startingIndex; i <= endingIndex; i++) {
this.loadWebtoonImage(i);
}
@@ -354,7 +461,7 @@ export class InfiniteScrollerComponent implements OnInit, OnChanges, OnDestroy {
}
debugLog(message: string, extraData?: any) {
- if (!this.debug) { return; }
+ if (!(this.debugMode & DEBUG_MODES.Logs)) return;
if (extraData !== undefined) {
console.log(message, extraData);
@@ -362,4 +469,12 @@ export class InfiniteScrollerComponent implements OnInit, OnChanges, OnDestroy {
console.log(message);
}
}
+
+ showDebugBar() {
+ return this.debugMode & DEBUG_MODES.ActionBar;
+ }
+
+ showDebugOutline() {
+ return this.debugMode & DEBUG_MODES.Outline;
+ }
}
diff --git a/UI/Web/src/app/manga-reader/manga-reader.component.html b/UI/Web/src/app/manga-reader/manga-reader.component.html
index 1dd55b6f3..0a96cadd0 100644
--- a/UI/Web/src/app/manga-reader/manga-reader.component.html
+++ b/UI/Web/src/app/manga-reader/manga-reader.component.html
@@ -7,7 +7,7 @@
</button>
<div>
- <div style="font-weight: bold;">{{title}}</div>
+ <div style="font-weight: bold;">{{title}} <span *ngIf="incognitoMode">(<i class="fa fa-glasses" aria-hidden="true"></i><span class="sr-only">Incognito Mode</span>)</span></div>
<div class="subtitle">
{{subtitle}}
</div>
@@ -28,29 +28,28 @@
ondragstart="return false;" onselectstart="return false;">
</canvas>
<div class="webtoon-images" *ngIf="readerMode === READER_MODE.WEBTOON && !isLoading">
- <app-infinite-scroller [pageNum]="pageNum" [bufferPages]="5" [goToPage]="goToPageEvent" (pageNumberChange)="handleWebtoonPageChange($event)" [totalPages]="maxPages" [urlProvider]="getPageUrl"></app-infinite-scroller>
+ <app-infinite-scroller [pageNum]="pageNum" [bufferPages]="5" [goToPage]="goToPageEvent" (pageNumberChange)="handleWebtoonPageChange($event)" [totalPages]="maxPages - 1" [urlProvider]="getPageUrl" (loadNextChapter)="loadNextChapter()" (loadPrevChapter)="loadPrevChapter()"></app-infinite-scroller>
</div>
- <ng-container *ngIf="readerMode === READER_MODE.MANGA_LR || readerMode === READER_MODE.MANGA_UD"> <!--; else webtoonClickArea; See if people want this mode WEBTOON_WITH_CLICKS-->
+ <ng-container *ngIf="readerMode === READER_MODE.MANGA_LR || readerMode === READER_MODE.MANGA_UD">
<div class="{{readerMode === READER_MODE.MANGA_LR ? 'right' : 'top'}} {{clickOverlayClass('right')}}" (click)="handlePageChange($event, 'right')"></div>
<div class="{{readerMode === READER_MODE.MANGA_LR ? 'left' : 'bottom'}} {{clickOverlayClass('left')}}" (click)="handlePageChange($event, 'left')"></div>
</ng-container>
- <ng-template #webtoonClickArea>
- <div class="top {{clickOverlayClass('right')}}" (click)="handlePageChange($event, 'right')"></div>
- <div class="right {{clickOverlayClass('right')}}" (click)="handlePageChange($event, 'right')"></div>
- <div class="left {{clickOverlayClass('left')}}" (click)="handlePageChange($event, 'left')"></div>
- <div class="bottom {{clickOverlayClass('left')}}" (click)="handlePageChange($event, 'left')"></div>
- </ng-template>
</div>
<div class="fixed-bottom overlay" *ngIf="menuOpen" [@slideFromBottom]="menuOpen">
- <div class="form-group" *ngIf="pageOptions != undefined && pageOptions.ceil != undefined && pageOptions.ceil > 0">
+ <div class="form-group" *ngIf="pageOptions != undefined && pageOptions.ceil != undefined">
<span class="sr-only" id="slider-info"></span>
<div class="row no-gutters">
<button class="btn btn-small btn-icon col-1" [disabled]="prevChapterDisabled" (click)="loadPrevChapter();resetMenuCloseTimer();" title="Prev Chapter/Volume"><i class="fa fa-fast-backward" aria-hidden="true"></i></button>
<button class="btn btn-small btn-icon col-1" [disabled]="prevPageDisabled || pageNum === 0" (click)="goToPage(0);resetMenuCloseTimer();" title="First Page"><i class="fa fa-step-backward" aria-hidden="true"></i></button>
- <div class="col custom-slider">
+ <div class="col custom-slider" *ngIf="pageOptions.ceil > 0; else noSlider">
<ngx-slider [options]="pageOptions" [value]="pageNum" aria-describedby="slider-info" [manualRefresh]="refreshSlider" (userChangeEnd)="sliderPageUpdate($event);startMenuCloseTimer()" (userChangeStart)="cancelMenuCloseTimer();"></ngx-slider>
</div>
+ <ng-template #noSlider>
+ <div class="col custom-slider">
+ <ngx-slider [options]="pageOptions" [value]="pageNum" aria-describedby="slider-info" (userChangeEnd)="startMenuCloseTimer()" (userChangeStart)="cancelMenuCloseTimer();"></ngx-slider>
+ </div>
+ </ng-template>
<button class="btn btn-small btn-icon col-2" [disabled]="nextPageDisabled || pageNum >= maxPages - 1" (click)="goToPage(this.maxPages);resetMenuCloseTimer();" title="Last Page"><i class="fa fa-step-forward" aria-hidden="true"></i></button>
<button class="btn btn-small btn-icon col-1" [disabled]="nextChapterDisabled" (click)="loadNextChapter();resetMenuCloseTimer();" title="Next Chapter/Volume"><i class="fa fa-fast-forward" aria-hidden="true"></i></button>
</div>
@@ -59,7 +58,7 @@
</div>
<div class="row pt-4 ml-2 mr-2">
<div class="col">
- <button class="btn btn-icon" (click)="setReadingDirection();resetMenuCloseTimer();" [disabled]="readerMode === READER_MODE.WEBTOON" aria-describedby="reading-direction" title="Reading Direction: {{readingDirection === ReadingDirection.LeftToRight ? 'Left to Right' : 'Right to Left'}}">
+ <button class="btn btn-icon" (click)="setReadingDirection();resetMenuCloseTimer();" [disabled]="readerMode === READER_MODE.WEBTOON || readerMode === READER_MODE.MANGA_UD" aria-describedby="reading-direction" title="Reading Direction: {{readingDirection === ReadingDirection.LeftToRight ? 'Left to Right' : 'Right to Left'}}">
<i class="fa fa-angle-double-{{readingDirection === ReadingDirection.LeftToRight ? 'right' : 'left'}}" aria-hidden="true"></i>
<span id="reading-direction" class="sr-only">{{readingDirection === ReadingDirection.LeftToRight ? 'Left to Right' : 'Right to Left'}}</span>
</button>
diff --git a/UI/Web/src/app/manga-reader/manga-reader.component.scss b/UI/Web/src/app/manga-reader/manga-reader.component.scss
index c076922bc..5f3d2c334 100644
--- a/UI/Web/src/app/manga-reader/manga-reader.component.scss
+++ b/UI/Web/src/app/manga-reader/manga-reader.component.scss
@@ -92,20 +92,6 @@ canvas {
}
-.center-menu {
- position: fixed;
- top: 10px;
- left: $side-width;
- width: $center-width;
- border-bottom: $dash-width dashed $secondary-color;
- text-align: center;
- z-index: 2;
- padding-bottom: 10px;
- padding-left: 10px;
- padding-right: 10px;
-}
-
-
.right {
position: fixed;
right: 0px;
diff --git a/UI/Web/src/app/manga-reader/manga-reader.component.ts b/UI/Web/src/app/manga-reader/manga-reader.component.ts
index 8e6d8c9b3..9f34eb75b 100644
--- a/UI/Web/src/app/manga-reader/manga-reader.component.ts
+++ b/UI/Web/src/app/manga-reader/manga-reader.component.ts
@@ -22,6 +22,7 @@ import { ChapterInfo } from './_models/chapter-info';
import { COLOR_FILTER, FITTING_OPTION, PAGING_DIRECTION, SPLIT_PAGE_PART } from './_models/reader-enums';
import { Preferences, scalingOptions } from '../_models/preferences/preferences';
import { READER_MODE } from '../_models/preferences/reader-mode';
+import { MangaFormat } from '../_models/manga-format';
const PREFETCH_PAGES = 5;
@@ -65,7 +66,20 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
seriesId!: number;
volumeId!: number;
chapterId!: number;
+ /**
+ * Reading List id. Defaults to -1.
+ */
+ readingListId: number = CHAPTER_ID_DOESNT_EXIST;
+
+ /**
+ * If this is true, no progress will be saved.
+ */
+ incognitoMode: boolean = false;
+ /**
+ * If this is true, chapters will be fetched in the order of a reading list, rather than natural series order.
+ */
+ readingListMode: boolean = false;
/**
* The current page. UI will show this number + 1.
*/
@@ -259,6 +273,14 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
this.libraryId = parseInt(libraryId, 10);
this.seriesId = parseInt(seriesId, 10);
this.chapterId = parseInt(chapterId, 10);
+ this.incognitoMode = this.route.snapshot.queryParamMap.get('incognitoMode') === 'true';
+
+ const readingListId = this.route.snapshot.queryParamMap.get('readingListId');
+ if (readingListId != null) {
+ this.readingListMode = true;
+ this.readingListId = parseInt(readingListId, 10);
+ }
+
this.continuousChaptersStack.push(this.chapterId);
@@ -325,11 +347,26 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
@HostListener('window:keyup', ['$event'])
handleKeyPress(event: KeyboardEvent) {
- if (event.key === KEY_CODES.RIGHT_ARROW || event.key === KEY_CODES.DOWN_ARROW) {
- this.readingDirection === ReadingDirection.LeftToRight ? this.nextPage() : this.prevPage();
- } else if (event.key === KEY_CODES.LEFT_ARROW || event.key === KEY_CODES.UP_ARROW) {
- this.readingDirection === ReadingDirection.LeftToRight ? this.prevPage() : this.nextPage();
- } else if (event.key === KEY_CODES.ESC_KEY) {
+
+ switch (this.readerMode) {
+ case READER_MODE.MANGA_LR:
+ if (event.key === KEY_CODES.RIGHT_ARROW) {
+ this.readingDirection === ReadingDirection.LeftToRight ? this.nextPage() : this.prevPage();
+ } else if (event.key === KEY_CODES.LEFT_ARROW) {
+ this.readingDirection === ReadingDirection.LeftToRight ? this.prevPage() : this.nextPage();
+ }
+ break;
+ case READER_MODE.MANGA_UD:
+ case READER_MODE.WEBTOON:
+ if (event.key === KEY_CODES.DOWN_ARROW) {
+ this.nextPage()
+ } else if (event.key === KEY_CODES.UP_ARROW) {
+ this.prevPage()
+ }
+ break;
+ }
+
+ if (event.key === KEY_CODES.ESC_KEY) {
if (this.menuOpen) {
this.toggleMenu();
event.stopPropagation();
@@ -343,6 +380,8 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
const goToPageNum = this.promptForPage();
if (goToPageNum === null) { return; }
this.goToPage(parseInt(goToPageNum.trim(), 10));
+ } else if (event.key === KEY_CODES.B) {
+ this.bookmarkPage();
}
}
@@ -352,21 +391,30 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
this.nextChapterDisabled = false;
this.prevChapterDisabled = false;
this.nextChapterPrefetched = false;
- this.pageNum = 1;
+ this.pageNum = 0;
forkJoin({
progress: this.readerService.getProgress(this.chapterId),
- chapterInfo: this.readerService.getChapterInfo(this.seriesId, this.chapterId),
+ chapterInfo: this.readerService.getChapterInfo(this.chapterId),
bookmarks: this.readerService.getBookmarks(this.chapterId)
}).pipe(take(1)).subscribe(results => {
+
+ if (this.readingListMode && results.chapterInfo.seriesFormat === MangaFormat.EPUB) {
+ // Redirect to the book reader.
+ const params = this.readerService.getQueryParamsObject(this.incognitoMode, this.readingListMode, this.readingListId);
+ this.router.navigate(['library', results.chapterInfo.libraryId, 'series', results.chapterInfo.seriesId, 'book', this.chapterId], {queryParams: params});
+ return;
+ }
+
this.volumeId = results.chapterInfo.volumeId;
this.maxPages = results.chapterInfo.pages;
-
let page = results.progress.pageNum;
- if (page >= this.maxPages) {
+ if (page > this.maxPages) {
page = this.maxPages - 1;
}
this.setPageNum(page);
+
+
// Due to change detection rules in Angular, we need to re-create the options object to apply the change
const newOptions: Options = Object.assign({}, this.pageOptions);
@@ -381,20 +429,20 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
this.bookmarks[bookmark.page] = 1;
});
- this.readerService.getNextChapter(this.seriesId, this.volumeId, this.chapterId).pipe(take(1)).subscribe(chapterId => {
+ this.readerService.getNextChapter(this.seriesId, this.volumeId, this.chapterId, this.readingListId).pipe(take(1)).subscribe(chapterId => {
this.nextChapterId = chapterId;
if (chapterId === CHAPTER_ID_DOESNT_EXIST || chapterId === this.chapterId) {
this.nextChapterDisabled = true;
}
});
- this.readerService.getPrevChapter(this.seriesId, this.volumeId, this.chapterId).pipe(take(1)).subscribe(chapterId => {
+ this.readerService.getPrevChapter(this.seriesId, this.volumeId, this.chapterId, this.readingListId).pipe(take(1)).subscribe(chapterId => {
this.prevChapterId = chapterId;
if (chapterId === CHAPTER_ID_DOESNT_EXIST || chapterId === this.chapterId) {
this.prevChapterDisabled = true;
}
});
- // ! Should I move the prefetching code if we start in webtoon reader mode?
+
const images = [];
for (let i = 0; i < PREFETCH_PAGES + 2; i++) {
images.push(new Image());
@@ -420,7 +468,11 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
}
closeReader() {
- this.location.back();
+ if (this.readingListMode) {
+ this.router.navigateByUrl('lists/' + this.readingListId);
+ } else {
+ this.location.back();
+ }
}
updateTitle(chapterInfo: ChapterInfo) {
@@ -668,12 +720,12 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
if (this.nextPageDisabled) { return; }
this.isLoading = true;
if (this.nextChapterId === CHAPTER_ID_NOT_FETCHED || this.nextChapterId === this.chapterId) {
- this.readerService.getNextChapter(this.seriesId, this.volumeId, this.chapterId).pipe(take(1)).subscribe(chapterId => {
+ this.readerService.getNextChapter(this.seriesId, this.volumeId, this.chapterId, this.readingListId).pipe(take(1)).subscribe(chapterId => {
this.nextChapterId = chapterId;
- this.loadChapter(chapterId, 'next');
+ this.loadChapter(chapterId, 'Next');
});
} else {
- this.loadChapter(this.nextChapterId, 'next');
+ this.loadChapter(this.nextChapterId, 'Next');
}
}
@@ -691,29 +743,29 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
}
if (this.prevChapterId === CHAPTER_ID_NOT_FETCHED || this.prevChapterId === this.chapterId) {
- this.readerService.getPrevChapter(this.seriesId, this.volumeId, this.chapterId).pipe(take(1)).subscribe(chapterId => {
+ this.readerService.getPrevChapter(this.seriesId, this.volumeId, this.chapterId, this.readingListId).pipe(take(1)).subscribe(chapterId => {
this.prevChapterId = chapterId;
- this.loadChapter(chapterId, 'prev');
+ this.loadChapter(chapterId, 'Prev');
});
} else {
- this.loadChapter(this.prevChapterId, 'prev');
+ this.loadChapter(this.prevChapterId, 'Prev');
}
}
- loadChapter(chapterId: number, direction: 'next' | 'prev') {
+ loadChapter(chapterId: number, direction: 'Next' | 'Prev') {
if (chapterId >= 0) {
this.chapterId = chapterId;
this.continuousChaptersStack.push(chapterId);
// Load chapter Id onto route but don't reload
- const lastSlashIndex = this.router.url.lastIndexOf('/');
- const newRoute = this.router.url.substring(0, lastSlashIndex + 1) + this.chapterId + '';
+ const newRoute = this.readerService.getNextChapterUrl(this.router.url, this.chapterId, this.incognitoMode, this.readingListMode, this.readingListId);
window.history.replaceState({}, '', newRoute);
this.init();
+ this.toastr.info(direction + ' chapter loaded', '', {timeOut: 3000});
} else {
// This will only happen if no actual chapter can be found
- this.toastr.warning('Could not find ' + direction + ' chapter');
+ this.toastr.warning('Could not find ' + direction.toLowerCase() + ' chapter');
this.isLoading = false;
- if (direction === 'prev') {
+ if (direction === 'Prev') {
this.prevPageDisabled = true;
} else {
this.nextPageDisabled = true;
@@ -722,12 +774,44 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
}
}
+ /**
+ * There are some hard limits on the size of canvas' that we must cap at. https://github.com/jhildenbiddle/canvas-size#test-results
+ * For Safari, it's 16,777,216, so we cap at 4096x4096 when this happens. The drawImage in render will perform bi-cubic scaling for us.
+ * @returns If we should continue to the render loop
+ */
+ setCanvasSize() {
+ if (this.ctx && this.canvas) {
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+ // @ts-ignore
+ const isSafari = [
+ 'iPad Simulator',
+ 'iPhone Simulator',
+ 'iPod Simulator',
+ 'iPad',
+ 'iPhone',
+ 'iPod'
+ ].includes(navigator.platform)
+ // iPad on iOS 13 detection
+ || (navigator.userAgent.includes("Mac") && "ontouchend" in document);
+ const canvasLimit = isSafari ? 16_777_216 : 124_992_400;
+ const needsScaling = this.canvasImage.width * this.canvasImage.height > canvasLimit;
+ if (needsScaling) {
+ this.canvas.nativeElement.width = isSafari ? 4_096 : 16_384;
+ this.canvas.nativeElement.height = isSafari ? 4_096 : 16_384;
+ } else {
+ this.canvas.nativeElement.width = this.canvasImage.width;
+ this.canvas.nativeElement.height = this.canvasImage.height;
+ }
+ }
+ return true;
+ }
+
renderPage() {
if (this.ctx && this.canvas) {
this.canvasImage.onload = null;
- //this.ctx.imageSmoothingEnabled = true;
- this.canvas.nativeElement.width = this.canvasImage.width;
- this.canvas.nativeElement.height = this.canvasImage.height;
+
+ if (!this.setCanvasSize()) return;
+
const needsSplitting = this.canvasImage.width > this.canvasImage.height;
this.updateSplitPage();
@@ -777,8 +861,9 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
pageNum = this.pageNum + 1;
}
-
- this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, pageNum).pipe(take(1)).subscribe(() => {/* No operation */});
+ if (!this.incognitoMode) {
+ this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, pageNum).pipe(take(1)).subscribe(() => {/* No operation */});
+ }
this.isLoading = true;
this.canvasImage = this.cachedImages.current();
@@ -838,13 +923,13 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
if (this.pageNum >= this.maxPages - 10) {
// Tell server to cache the next chapter
if (this.nextChapterId > 0 && !this.nextChapterPrefetched) {
- this.readerService.getChapterInfo(this.seriesId, this.nextChapterId).pipe(take(1)).subscribe(res => {
+ this.readerService.getChapterInfo(this.nextChapterId).pipe(take(1)).subscribe(res => {
this.nextChapterPrefetched = true;
});
}
} else if (this.pageNum <= 10) {
if (this.prevChapterId > 0 && !this.prevChapterPrefetched) {
- this.readerService.getChapterInfo(this.seriesId, this.prevChapterId).pipe(take(1)).subscribe(res => {
+ this.readerService.getChapterInfo(this.prevChapterId).pipe(take(1)).subscribe(res => {
this.prevChapterPrefetched = true;
});
}
@@ -901,11 +986,10 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
switch(this.readerMode) {
case READER_MODE.MANGA_LR:
this.readerMode = READER_MODE.MANGA_UD;
+ this.pagingDirection = PAGING_DIRECTION.FORWARD;
break;
case READER_MODE.MANGA_UD:
this.readerMode = READER_MODE.WEBTOON;
- // Temp disable ability to use webtoon
- //this.readerMode = READER_MODE.MANGA_LR;
break;
case READER_MODE.WEBTOON:
this.readerMode = READER_MODE.MANGA_LR;
@@ -929,10 +1013,12 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
handleWebtoonPageChange(updatedPageNum: number) {
this.setPageNum(updatedPageNum);
+ if (this.incognitoMode) return;
this.readerService.saveProgress(this.seriesId, this.volumeId, this.chapterId, this.pageNum).pipe(take(1)).subscribe(() => {/* No operation */});
}
saveSettings() {
+ // NOTE: This is not called anywhere
if (this.user === undefined) return;
const data: Preferences = {
@@ -974,9 +1060,9 @@ export class MangaReaderComponent implements OnInit, AfterViewInit, OnDestroy {
* Bookmarks the current page for the chapter
*/
bookmarkPage() {
+ // TODO: Show some sort of UI visual to show that a page was bookmarked
const pageNum = this.pageNum;
if (this.pageBookmarked) {
- // Remove bookmark
this.readerService.unbookmark(this.seriesId, this.volumeId, this.chapterId, pageNum).pipe(take(1)).subscribe(() => {
delete this.bookmarks[pageNum];
});
diff --git a/UI/Web/src/app/manga-reader/manga-reader.router.module.ts b/UI/Web/src/app/manga-reader/manga-reader.router.module.ts
index 388f727b2..680c7cde7 100644
--- a/UI/Web/src/app/manga-reader/manga-reader.router.module.ts
+++ b/UI/Web/src/app/manga-reader/manga-reader.router.module.ts
@@ -6,7 +6,12 @@ const routes: Routes = [
{
path: ':chapterId',
component: MangaReaderComponent
- }
+ },
+ {
+ // This will allow the MangaReader to have a list to use for next/prev chapters rather than natural sort order
+ path: ':chapterId/list/:listId',
+ component: MangaReaderComponent
+}
];
diff --git a/UI/Web/src/app/nav-header/nav-header.component.html b/UI/Web/src/app/nav-header/nav-header.component.html
index 28da75c1e..c371393d3 100644
--- a/UI/Web/src/app/nav-header/nav-header.component.html
+++ b/UI/Web/src/app/nav-header/nav-header.component.html
@@ -2,7 +2,7 @@
<div class="container-fluid">
<a class="sr-only sr-only-focusable focus-visible" href="javascript:void(0);" (click)="moveFocus()">Skip to main content</a>
<a class="navbar-brand" routerLink="/library" routerLinkActive="active"><img class="logo" src="../../assets/images/logo.png" alt="kavita icon" aria-hidden="true"/><span class="phone-hidden"> Kavita</span></a>
- <ul class="navbar-nav mr-auto">
+ <ul class="navbar-nav col mr-auto">
<div class="nav-item" *ngIf="(accountService.currentUser$ | async) as user">
<div>
diff --git a/UI/Web/src/app/nav-header/nav-header.component.ts b/UI/Web/src/app/nav-header/nav-header.component.ts
index 1216af274..d9005bc10 100644
--- a/UI/Web/src/app/nav-header/nav-header.component.ts
+++ b/UI/Web/src/app/nav-header/nav-header.component.ts
@@ -72,7 +72,7 @@ export class NavHeaderComponent implements OnInit, OnDestroy {
onChangeSearch(val: string) {
this.isLoading = true;
- this.searchTerm = val;
+ this.searchTerm = val.trim();
this.libraryService.search(val).pipe(takeUntil(this.onDestroy)).subscribe(results => {
this.searchResults = results;
this.isLoading = false;
diff --git a/UI/Web/src/app/admin/filter.pipe.ts b/UI/Web/src/app/pipe/filter.pipe.ts
similarity index 100%
rename from UI/Web/src/app/admin/filter.pipe.ts
rename to UI/Web/src/app/pipe/filter.pipe.ts
diff --git a/UI/Web/src/app/pipe/pipe.module.ts b/UI/Web/src/app/pipe/pipe.module.ts
new file mode 100644
index 000000000..4361180d5
--- /dev/null
+++ b/UI/Web/src/app/pipe/pipe.module.ts
@@ -0,0 +1,18 @@
+import { NgModule } from '@angular/core';
+import { CommonModule } from '@angular/common';
+import { FilterPipe } from './filter.pipe';
+
+
+
+@NgModule({
+ declarations: [
+ FilterPipe
+ ],
+ imports: [
+ CommonModule,
+ ],
+ exports: [
+ FilterPipe
+ ]
+})
+export class PipeModule { }
diff --git a/UI/Web/src/app/reading-list/_modals/add-to-list-modal/add-to-list-modal.component.html b/UI/Web/src/app/reading-list/_modals/add-to-list-modal/add-to-list-modal.component.html
new file mode 100644
index 000000000..fbcf8083d
--- /dev/null
+++ b/UI/Web/src/app/reading-list/_modals/add-to-list-modal/add-to-list-modal.component.html
@@ -0,0 +1,46 @@
+
+<div class="modal-header">
+ <h4 class="modal-title" id="modal-basic-title">Add to Reading List</h4>
+ <button type="button" class="close" aria-label="Close" (click)="close()">
+ <span aria-hidden="true">&times;</span>
+ </button>
+</div>
+<form style="width: 100%" [formGroup]="listForm">
+<div class="modal-body">
+ <div class="form-group" *ngIf="lists.length >= 5">
+ <label for="filter">Filter</label>
+ <div class="input-group">
+ <input id="filter" autocomplete="off" class="form-control" formControlName="filterQuery" type="text" aria-describedby="reset-input">
+ <div class="input-group-append">
+ <button class="btn btn-outline-secondary" type="button" id="reset-input" (click)="listForm.get('filterQuery')?.setValue('');">Clear</button>
+ </div>
+ </div>
+ </div>
+ <ul class="list-group">
+ <li class="list-group-item clickable" tabindex="0" role="button" *ngFor="let readingList of lists | filter: filterList; let i = index" (click)="addToList(readingList)">
+ {{readingList.title}} <i class="fa fa-angle-double-up" *ngIf="readingList.promoted" title="Promoted"></i>
+ </li>
+ <li class="list-group-item" *ngIf="lists.length === 0 && !loading">No lists created yet</li>
+ <li class="list-group-item" *ngIf="loading">
+ <div class="spinner-border text-secondary" role="status">
+ <span class="sr-only">Loading...</span>
+ </div>
+ </li>
+ </ul>
+</div>
+<div class="modal-footer" style="justify-content: normal">
+ <div style="width: 100%;">
+ <div class="form-row">
+ <div class="col-9 col-lg-10">
+ <label class="sr-only" for="add-rlist">Reading List</label>
+ <input width="100%" #title ngbAutofocus type="text" class="form-control mb-2" id="add-rlist" formControlName="title">
+ </div>
+ <div class="col-2">
+ <button type="submit" class="btn btn-primary" (click)="create()">Create</button>
+ </div>
+ </div>
+ </div>
+</div>
+</form>
+
+
diff --git a/UI/Web/src/app/reading-list/_modals/add-to-list-modal/add-to-list-modal.component.scss b/UI/Web/src/app/reading-list/_modals/add-to-list-modal/add-to-list-modal.component.scss
new file mode 100644
index 000000000..91847160a
--- /dev/null
+++ b/UI/Web/src/app/reading-list/_modals/add-to-list-modal/add-to-list-modal.component.scss
@@ -0,0 +1,7 @@
+.clickable {
+ cursor: pointer;
+}
+
+.clickable:hover, .clickable:focus {
+ background-color: lightgreen;
+}
\ No newline at end of file
diff --git a/UI/Web/src/app/reading-list/_modals/add-to-list-modal/add-to-list-modal.component.ts b/UI/Web/src/app/reading-list/_modals/add-to-list-modal/add-to-list-modal.component.ts
new file mode 100644
index 000000000..a33d69332
--- /dev/null
+++ b/UI/Web/src/app/reading-list/_modals/add-to-list-modal/add-to-list-modal.component.ts
@@ -0,0 +1,137 @@
+import { noUndefined } from '@angular/compiler/src/util';
+import { AfterViewInit, Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
+import { FormControl, FormGroup, Validators } from '@angular/forms';
+import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
+import { ToastrService } from 'ngx-toastr';
+import { ReadingList } from 'src/app/_models/reading-list';
+import { ReadingListService } from 'src/app/_services/reading-list.service';
+
+export enum ADD_FLOW {
+ Series = 0,
+ Volume = 1,
+ Chapter = 2,
+ Multiple = 3,
+ Multiple_Series
+}
+
+@Component({
+ selector: 'app-add-to-list-modal',
+ templateUrl: './add-to-list-modal.component.html',
+ styleUrls: ['./add-to-list-modal.component.scss']
+})
+export class AddToListModalComponent implements OnInit, AfterViewInit {
+
+ @Input() title!: string;
+ /**
+ * Only used in Series flow
+ */
+ @Input() seriesId?: number;
+ /**
+ * Only used in Volume flow
+ */
+ @Input() volumeId?: number;
+ /**
+ * Only used in Chapter flow
+ */
+ @Input() chapterId?: number;
+ /**
+ * Only used in Multiple flow
+ */
+ @Input() volumeIds?: Array<number>;
+ /**
+ * Only used in Multiple flow
+ */
+ @Input() chapterIds?: Array<number>;
+ /**
+ * Only used in Multiple_Series flow
+ */
+ @Input() seriesIds?: Array<number>;
+
+ /**
+ * Determines which Input is required and which API is used to associate to the Reading List
+ */
+ @Input() type!: ADD_FLOW;
+
+ /**
+ * All existing reading lists sorted by recent use date
+ */
+ lists: Array<any> = [];
+ loading: boolean = false;
+ listForm: FormGroup = new FormGroup({});
+
+ @ViewChild('title') inputElem!: ElementRef<HTMLInputElement>;
+
+
+ constructor(private modal: NgbActiveModal, private readingListService: ReadingListService, private toastr: ToastrService) { }
+
+ ngOnInit(): void {
+
+ this.listForm.addControl('title', new FormControl(this.title, []));
+ this.listForm.addControl('filterQuery', new FormControl('', []));
+
+ this.loading = true;
+ this.readingListService.getReadingLists(false).subscribe(lists => {
+ this.lists = lists.result;
+ this.loading = false;
+ });
+
+
+ }
+
+ ngAfterViewInit() {
+ // Shift focus to input
+ if (this.inputElem) {
+ this.inputElem.nativeElement.select();
+ }
+ }
+
+ close() {
+ this.modal.close();
+ }
+
+ create() {
+ this.readingListService.createList(this.listForm.value.title).subscribe(list => {
+ this.addToList(list);
+ });
+ }
+
+ addToList(readingList: ReadingList) {
+
+ if (this.type === ADD_FLOW.Multiple_Series && this.seriesIds !== undefined) {
+ this.readingListService.updateByMultipleSeries(readingList.id, this.seriesIds).subscribe(() => {
+ this.toastr.success('Series added to reading list');
+ this.modal.close();
+ });
+ }
+
+ if (this.seriesId === undefined) return;
+
+ if (this.type === ADD_FLOW.Series && this.seriesId !== undefined) {
+ this.readingListService.updateBySeries(readingList.id, this.seriesId).subscribe(() => {
+ this.toastr.success('Series added to reading list');
+ this.modal.close();
+ });
+ } else if (this.type === ADD_FLOW.Volume && this.volumeId !== undefined) {
+ this.readingListService.updateByVolume(readingList.id, this.seriesId, this.volumeId).subscribe(() => {
+ this.toastr.success('Volumes added to reading list');
+ this.modal.close();
+ });
+ } else if (this.type === ADD_FLOW.Chapter && this.chapterId !== undefined) {
+ this.readingListService.updateByChapter(readingList.id, this.seriesId, this.chapterId).subscribe(() => {
+ this.toastr.success('Chapter added to reading list');
+ this.modal.close();
+ });
+ } else if (this.type === ADD_FLOW.Multiple && this.volumeIds !== undefined && this.chapterIds !== undefined) {
+ this.readingListService.updateByMultiple(readingList.id, this.seriesId, this.volumeIds, this.chapterIds).subscribe(() => {
+ this.toastr.success('Chapters and Volumes added to reading list');
+ this.modal.close();
+ });
+ }
+
+ }
+
+ filterList = (listItem: ReadingList) => {
+ return listItem.title.toLowerCase().indexOf((this.listForm.value.filterQuery || '').toLowerCase()) >= 0;
+ }
+
+}
diff --git a/UI/Web/src/app/reading-list/_modals/edit-reading-list-modal/edit-reading-list-modal.component.html b/UI/Web/src/app/reading-list/_modals/edit-reading-list-modal/edit-reading-list-modal.component.html
new file mode 100644
index 000000000..c07d65d6a
--- /dev/null
+++ b/UI/Web/src/app/reading-list/_modals/edit-reading-list-modal/edit-reading-list-modal.component.html
@@ -0,0 +1,31 @@
+
+<div class="modal-header">
+ <h4 class="modal-title" id="modal-basic-title">Edit {{readingList.title}} Reading List</h4>
+ <button type="button" class="close" aria-label="Close" (click)="close()">
+ <span aria-hidden="true">&times;</span>
+ </button>
+</div>
+<div class="modal-body">
+ <p>
+ This list is currently {{readingList?.promoted ? 'promoted' : 'not promoted'}} (<i class="fa fa-angle-double-up" aria-hidden="true"></i>).
+ Promotion means that the list can be seen server-wide, not just for admin users. All series that are within this list will still have user-access restrictions placed on them.
+ </p>
+ <form [formGroup]="reviewGroup">
+ <div class="form-group">
+ <label for="title">Name</label>
+ <input id="title" class="form-control" formControlName="title" type="text">
+ </div>
+
+ <div class="form-group">
+ <label for="summary">Summary</label>
+ <textarea id="summary" class="form-control" formControlName="summary" rows="3"></textarea>
+ </div>
+ </form>
+</div>
+<div class="modal-footer">
+ <button type="button" class="btn btn-secondary" (click)="close()">Close</button>
+ <button type="button" class="btn btn-info" (click)="togglePromotion()">{{readingList.promoted ? 'Demote' : 'Promote'}}</button>
+ <button type="submit" class="btn btn-primary" [disabled]="reviewGroup.get('title')?.value.trim().length === 0" (click)="save()">Save</button>
+</div>
+
+
diff --git a/UI/Web/src/app/reading-list/_modals/edit-reading-list-modal/edit-reading-list-modal.component.scss b/UI/Web/src/app/reading-list/_modals/edit-reading-list-modal/edit-reading-list-modal.component.scss
new file mode 100644
index 000000000..e69de29bb
diff --git a/UI/Web/src/app/reading-list/_modals/edit-reading-list-modal/edit-reading-list-modal.component.ts b/UI/Web/src/app/reading-list/_modals/edit-reading-list-modal/edit-reading-list-modal.component.ts
new file mode 100644
index 000000000..58bd80b9b
--- /dev/null
+++ b/UI/Web/src/app/reading-list/_modals/edit-reading-list-modal/edit-reading-list-modal.component.ts
@@ -0,0 +1,52 @@
+import { Component, Input, OnInit } from '@angular/core';
+import { FormGroup, FormControl, Validators } from '@angular/forms';
+import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
+import { ReadingList } from 'src/app/_models/reading-list';
+import { ReadingListService } from 'src/app/_services/reading-list.service';
+
+@Component({
+ selector: 'app-edit-reading-list-modal',
+ templateUrl: './edit-reading-list-modal.component.html',
+ styleUrls: ['./edit-reading-list-modal.component.scss']
+})
+export class EditReadingListModalComponent implements OnInit {
+
+ @Input() readingList!: ReadingList;
+ reviewGroup!: FormGroup;
+
+ constructor(private ngModal: NgbActiveModal, private readingListService: ReadingListService) { }
+
+ ngOnInit(): void {
+ this.reviewGroup = new FormGroup({
+ title: new FormControl(this.readingList.title, [Validators.required]),
+ summary: new FormControl(this.readingList.summary, [])
+ });
+ }
+
+ close() {
+ this.ngModal.dismiss(undefined);
+ }
+
+ save() {
+ if (this.reviewGroup.value.title.trim() === '') return;
+ const model = {...this.reviewGroup.value, readingListId: this.readingList.id, promoted: this.readingList.promoted};
+
+ this.readingListService.update(model).subscribe(() => {
+ this.readingList.title = model.title;
+ this.readingList.summary = model.summary;
+ this.ngModal.close(this.readingList);
+ });
+ }
+
+ togglePromotion() {
+ const originalPromotion = this.readingList.promoted;
+ this.readingList.promoted = !this.readingList.promoted;
+ const model = {readingListId: this.readingList.id, promoted: this.readingList.promoted};
+ this.readingListService.update(model).subscribe(res => {
+ /* No Operation */
+ }, err => {
+ this.readingList.promoted = originalPromotion;
+ });
+ }
+
+}
diff --git a/UI/Web/src/app/reading-list/dragable-ordered-list/dragable-ordered-list.component.html b/UI/Web/src/app/reading-list/dragable-ordered-list/dragable-ordered-list.component.html
new file mode 100644
index 000000000..3bee8ee51
--- /dev/null
+++ b/UI/Web/src/app/reading-list/dragable-ordered-list/dragable-ordered-list.component.html
@@ -0,0 +1,23 @@
+<div cdkDropList class="{{items.length > 0 ? 'example-list list-group-flush' : ''}}" (cdkDropListDropped)="drop($event)">
+ <div class="example-box" *ngFor="let item of items; index as i" cdkDrag [cdkDragData]="item" cdkDragBoundary=".example-list">
+ <div class="mr-3 align-middle">
+ <i class="fa fa-grip-vertical drag-handle" aria-hidden="true" cdkDragHandle></i>
+ </div>
+
+ <ng-container style="display: inline-block" [ngTemplateOutlet]="itemTemplate" [ngTemplateOutletContext]="{ $implicit: item, idx: i }"></ng-container>
+
+ <div class="align-middle" style="padding-top: 40px">
+ <label for="reorder-{{i}}" class="sr-only">Reorder</label>
+ <input *ngIf="accessibilityMode" id="reorder-{{i}}" type="number" min="0" [max]="items.length - 1" [value]="i" style="width: 40px" (focusout)="updateIndex(i, item)" (keydown.enter)="updateIndex(i, item)" aria-describedby="instructions">
+ </div>
+ <button class="btn btn-icon pull-right" (click)="removeItem(item, i)">
+ <i class="fa fa-times" aria-hidden="true"></i>
+ <span class="sr-only" attr.aria-labelledby="item.id--{{i}}">Remove item</span>
+ </button>
+
+ </div>
+</div>
+
+<p class="sr-only" id="instructions">
+
+</p>
\ No newline at end of file
diff --git a/UI/Web/src/app/reading-list/dragable-ordered-list/dragable-ordered-list.component.scss b/UI/Web/src/app/reading-list/dragable-ordered-list/dragable-ordered-list.component.scss
new file mode 100644
index 000000000..dccf8be4e
--- /dev/null
+++ b/UI/Web/src/app/reading-list/dragable-ordered-list/dragable-ordered-list.component.scss
@@ -0,0 +1,47 @@
+.example-list {
+ min-width: 500px;
+ max-width: 100%;
+ min-height: 60px;
+ display: block;
+ border-radius: 4px;
+ overflow: hidden;
+ }
+
+ .example-box {
+ padding: 20px 10px;
+ border-bottom: solid 1px #ccc;
+ display: flex;
+ flex-direction: row;
+ box-sizing: border-box;
+ font-size: 14px;
+
+ .drag-handle {
+ cursor: move;
+ font-size: 24px;
+ margin-top: 215%;
+ }
+ }
+
+ .cdk-drag-preview {
+ box-sizing: border-box;
+ border-radius: 4px;
+ box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
+ 0 8px 10px 1px rgba(0, 0, 0, 0.14),
+ 0 3px 14px 2px rgba(0, 0, 0, 0.12);
+ }
+
+ .cdk-drag-placeholder {
+ opacity: 0;
+ }
+
+ .cdk-drag-animating {
+ transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
+ }
+
+ .example-box:last-child {
+ border: none;
+ }
+
+ .example-list.cdk-drop-list-dragging .example-box:not(.cdk-drag-placeholder) {
+ transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
+ }
\ No newline at end of file
diff --git a/UI/Web/src/app/reading-list/dragable-ordered-list/dragable-ordered-list.component.ts b/UI/Web/src/app/reading-list/dragable-ordered-list/dragable-ordered-list.component.ts
new file mode 100644
index 000000000..fddf4ac43
--- /dev/null
+++ b/UI/Web/src/app/reading-list/dragable-ordered-list/dragable-ordered-list.component.ts
@@ -0,0 +1,63 @@
+import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
+import { Component, ContentChild, EventEmitter, Input, OnInit, Output, TemplateRef } from '@angular/core';
+
+export interface IndexUpdateEvent {
+ fromPosition: number;
+ toPosition: number;
+ item: any;
+}
+
+export interface ItemRemoveEvent {
+ position: number;
+ item: any;
+}
+
+@Component({
+ selector: 'app-dragable-ordered-list',
+ templateUrl: './dragable-ordered-list.component.html',
+ styleUrls: ['./dragable-ordered-list.component.scss']
+})
+export class DragableOrderedListComponent implements OnInit {
+
+ @Input() accessibilityMode: boolean = false;
+ @Input() items: Array<any> = [];
+ @Output() orderUpdated: EventEmitter<IndexUpdateEvent> = new EventEmitter<IndexUpdateEvent>();
+ @Output() itemRemove: EventEmitter<ItemRemoveEvent> = new EventEmitter<ItemRemoveEvent>();
+ @ContentChild('draggableItem') itemTemplate!: TemplateRef<any>;
+
+ constructor() { }
+
+ ngOnInit(): void {
+ }
+
+ drop(event: CdkDragDrop<string[]>) {
+ if (event.previousIndex === event.currentIndex) return;
+ moveItemInArray(this.items, event.previousIndex, event.currentIndex);
+ this.orderUpdated.emit({
+ fromPosition: event.previousIndex,
+ toPosition: event.currentIndex,
+ item: this.items[event.currentIndex]
+ });
+ }
+
+ updateIndex(previousIndex: number, item: any) {
+ // get the new value of the input
+ var inputElem = <HTMLInputElement>document.querySelector('#reorder-' + previousIndex);
+ const newIndex = parseInt(inputElem.value, 10);
+ if (previousIndex === newIndex) return;
+ moveItemInArray(this.items, previousIndex, newIndex);
+ this.orderUpdated.emit({
+ fromPosition: previousIndex,
+ toPosition: newIndex,
+ item: this.items[newIndex]
+ });
+ }
+
+ removeItem(item: any, position: number) {
+ this.itemRemove.emit({
+ position,
+ item
+ });
+ }
+
+}
diff --git a/UI/Web/src/app/reading-list/reading-list-detail/reading-list-detail.component.html b/UI/Web/src/app/reading-list/reading-list-detail/reading-list-detail.component.html
new file mode 100644
index 000000000..bfe2e5d09
--- /dev/null
+++ b/UI/Web/src/app/reading-list/reading-list-detail/reading-list-detail.component.html
@@ -0,0 +1,73 @@
+<div class="container-sm mt-2" *ngIf="readingList">
+ <div class="mb-3">
+ <!-- Title row-->
+ <div class="row no-gutters">
+
+ <h2 style="display: inline-block">
+ <span *ngIf="actions.length > 0">
+ <app-card-actionables (actionHandler)="performAction($event)" [actions]="actions" [labelBy]="readingList.title"></app-card-actionables>&nbsp;
+ </span>
+ {{readingList.title}}&nbsp;<span *ngIf="readingList?.promoted">(<i class="fa fa-angle-double-up" aria-hidden="true"></i>)</span>&nbsp;
+ <span class="badge badge-primary badge-pill" attr.aria-label="{{items.length}} total items">{{items.length}}</span>
+ </h2>
+ </div>
+ <!-- Action row-->
+ <div class="row no-gutters">
+ <div class="mr-2">
+ <button class="btn btn-primary" title="Read" (click)="read()">
+ <span>
+ <i class="fa fa-book-open" aria-hidden="true"></i>
+ <span class="read-btn--text">&nbsp;Read</span>
+ </span>
+ </button>
+ </div>
+ <div>
+ <button class="btn btn-secondary" (click)="removeRead()" [disabled]="readingList?.promoted && !this.isAdmin">
+ <span>
+ <i class="fa fa-check"></i>
+ </span>
+ <span class="read-btn--text">&nbsp;Remove Read</span>
+ </button>
+ </div>
+ <div class="ml-2 mt-2" *ngIf="!(readingList?.promoted && !this.isAdmin)">
+ <div class="form-check form-check-inline">
+ <input class="form-check-input" type="checkbox" id="accessibilit-mode" [value]="accessibilityMode" (change)="accessibilityMode = !accessibilityMode">
+ <label class="form-check-label" for="accessibilit-mode">Order Numbers</label>
+ </div>
+ </div>
+ </div>
+ <!-- Summary row-->
+ <div class="row no-gutters mt-2">
+ <app-read-more [text]="readingList.summary" [maxLength]="250"></app-read-more>
+ </div>
+ </div>
+
+ <div *ngIf="items.length === 0">
+ No chapters added
+ </div>
+
+ <app-dragable-ordered-list [items]="items" (orderUpdated)="orderUpdated($event)" (itemRemove)="itemRemoved($event)" [accessibilityMode]="accessibilityMode">
+ <ng-template #draggableItem let-item let-position="idx">
+ <div class="media" style="width: 100%;">
+ <img width="74px" style="width: 74px;" class="img-top lazyload mr-3" [src]="imageService.placeholderImage" [attr.data-src]="imageService.getChapterCoverImage(item.chapterId)"
+ (error)="imageService.updateErroredImage($event)">
+ <div class="media-body">
+ <h5 class="mt-0 mb-1" id="item.id--{{position}}">{{formatTitle(item)}}&nbsp;
+ <span class="badge badge-primary badge-pill">
+ <span *ngIf="item.pagesRead > 0 && item.pagesRead < item.pagesTotal">{{item.pagesRead}} / {{item.pagesTotal}}</span>
+ <span *ngIf="item.pagesRead === 0">UNREAD</span>
+ <span *ngIf="item.pagesRead === item.pagesTotal">READ</span>
+ </span>
+ </h5>
+ <i class="fa {{utilityService.mangaFormatIcon(item.seriesFormat)}}" aria-hidden="true" *ngIf="item.seriesFormat != MangaFormat.UNKNOWN" title="{{utilityService.mangaFormat(item.seriesFormat)}}"></i>
+ <span class="sr-only">{{utilityService.mangaFormat(item.seriesFormat)}}</span>&nbsp;
+
+ <a href="/library/{{item.libraryId}}/series/{{item.seriesId}}">{{item.seriesName}}</a>
+ <span *ngIf="item.promoted">
+ <i class="fa fa-angle-double-up" aria-hidden="true"></i>
+ </span>
+ </div>
+ </div>
+ </ng-template>
+ </app-dragable-ordered-list>
+</div>
\ No newline at end of file
diff --git a/UI/Web/src/app/reading-list/reading-list-detail/reading-list-detail.component.scss b/UI/Web/src/app/reading-list/reading-list-detail/reading-list-detail.component.scss
new file mode 100644
index 000000000..f191b076d
--- /dev/null
+++ b/UI/Web/src/app/reading-list/reading-list-detail/reading-list-detail.component.scss
@@ -0,0 +1,4 @@
+.container-sm {
+ padding-left: 0px;
+ padding-right: 0px;
+}
\ No newline at end of file
diff --git a/UI/Web/src/app/reading-list/reading-list-detail/reading-list-detail.component.ts b/UI/Web/src/app/reading-list/reading-list-detail/reading-list-detail.component.ts
new file mode 100644
index 000000000..5c1728157
--- /dev/null
+++ b/UI/Web/src/app/reading-list/reading-list-detail/reading-list-detail.component.ts
@@ -0,0 +1,159 @@
+import { Component, OnInit } from '@angular/core';
+import { ActivatedRoute, Router } from '@angular/router';
+import { ToastrService } from 'ngx-toastr';
+import { take } from 'rxjs/operators';
+import { ConfirmService } from 'src/app/shared/confirm.service';
+import { UtilityService } from 'src/app/shared/_services/utility.service';
+import { MangaFormat } from 'src/app/_models/manga-format';
+import { ReadingList, ReadingListItem } from 'src/app/_models/reading-list';
+import { AccountService } from 'src/app/_services/account.service';
+import { Action, ActionFactoryService, ActionItem } from 'src/app/_services/action-factory.service';
+import { ActionService } from 'src/app/_services/action.service';
+import { ImageService } from 'src/app/_services/image.service';
+import { ReadingListService } from 'src/app/_services/reading-list.service';
+import { IndexUpdateEvent, ItemRemoveEvent } from '../dragable-ordered-list/dragable-ordered-list.component';
+
+@Component({
+ selector: 'app-reading-list-detail',
+ templateUrl: './reading-list-detail.component.html',
+ styleUrls: ['./reading-list-detail.component.scss']
+})
+export class ReadingListDetailComponent implements OnInit {
+
+ items: Array<ReadingListItem> = [];
+ listId!: number;
+ readingList!: ReadingList;
+ actions: Array<ActionItem<any>> = [];
+ isAdmin: boolean = false;
+ isLoading: boolean = false;
+ accessibilityMode: boolean = false;
+
+ // Downloading
+ hasDownloadingRole: boolean = false;
+ downloadInProgress: boolean = false;
+
+
+ get MangaFormat(): typeof MangaFormat {
+ return MangaFormat;
+ }
+
+ constructor(private route: ActivatedRoute, private router: Router, private readingListService: ReadingListService,
+ private actionService: ActionService, private actionFactoryService: ActionFactoryService, public utilityService: UtilityService,
+ public imageService: ImageService, private accountService: AccountService, private toastr: ToastrService, private confirmService: ConfirmService) {}
+
+ ngOnInit(): void {
+ const listId = this.route.snapshot.paramMap.get('id');
+
+ if (listId === null) {
+ this.router.navigateByUrl('/libraries');
+ return;
+ }
+
+ this.listId = parseInt(listId, 10);
+
+ this.readingListService.getReadingList(this.listId).subscribe(readingList => {
+ if (readingList == null) {
+ // The list doesn't exist
+ this.toastr.error('This list doesn\'t exist.');
+ this.router.navigateByUrl('library');
+ return;
+ }
+ this.readingList = readingList;
+
+ this.accountService.currentUser$.pipe(take(1)).subscribe(user => {
+ if (user) {
+ this.isAdmin = this.accountService.hasAdminRole(user);
+ this.hasDownloadingRole = this.accountService.hasDownloadRole(user);
+
+ this.actions = this.actionFactoryService.getReadingListActions(this.handleReadingListActionCallback.bind(this)).filter(action => this.readingListService.actionListFilter(action, readingList, this.isAdmin));
+ }
+ });
+ });
+ this.getListItems();
+ }
+
+ getListItems() {
+ this.isLoading = true;
+ this.readingListService.getListItems(this.listId).subscribe(items => {
+ this.items = items;
+ this.isLoading = false;
+ });
+ }
+
+ performAction(action: ActionItem<any>) {
+ // TODO: Try to move performAction into the actionables component. (have default handler in the component, allow for overridding to pass additional context)
+ if (typeof action.callback === 'function') {
+ action.callback(action.action, this.readingList);
+ }
+ }
+
+ handleReadingListActionCallback(action: Action, readingList: ReadingList) {
+ switch(action) {
+ case Action.Delete:
+ this.deleteList(readingList);
+ break;
+ case Action.Edit:
+ this.actionService.editReadingList(readingList, (readingList: ReadingList) => {
+ // Reload information around list
+ this.readingList = readingList;
+ });
+ break;
+ }
+ }
+
+ async deleteList(readingList: ReadingList) {
+ if (!await this.confirmService.confirm('Are you sure you want to delete the reading list? This cannot be undone.')) return;
+
+ this.readingListService.delete(readingList.id).subscribe(() => {
+ this.toastr.success('Reading list deleted');
+ this.router.navigateByUrl('library#lists');
+ });
+ }
+
+ formatTitle(item: ReadingListItem) {
+ if (item.chapterNumber === '0') {
+ return 'Volume ' + item.volumeNumber;
+ }
+
+ if (item.seriesFormat === MangaFormat.EPUB) {
+ return 'Volume ' + this.utilityService.cleanSpecialTitle(item.chapterNumber);
+ }
+
+ return 'Chapter ' + item.chapterNumber;
+ }
+
+ orderUpdated(event: IndexUpdateEvent) {
+ this.readingListService.updatePosition(this.readingList.id, event.item.id, event.fromPosition, event.toPosition).subscribe(() => { /* No Operation */ });
+ }
+
+ itemRemoved(event: ItemRemoveEvent) {
+ this.readingListService.deleteItem(this.readingList.id, event.item.id).subscribe(() => {
+ this.items.splice(event.position, 1);
+ this.toastr.success('Item removed');
+ });
+ }
+
+ removeRead() {
+ this.isLoading = true;
+ this.readingListService.removeRead(this.readingList.id).subscribe(() => {
+ this.getListItems();
+ });
+ }
+
+ read() {
+ let currentlyReadingChapter = this.items[0];
+ for (let i = 0; i < this.items.length; i++) {
+ if (this.items[i].pagesRead >= this.items[i].pagesTotal) {
+ continue;
+ }
+ currentlyReadingChapter = this.items[i];
+ break;
+ }
+
+ if (currentlyReadingChapter.seriesFormat === MangaFormat.EPUB) {
+ this.router.navigate(['library', currentlyReadingChapter.libraryId, 'series', currentlyReadingChapter.seriesId, 'book', currentlyReadingChapter.chapterId], {queryParams: {readingListId: this.readingList.id}});
+ } else {
+ this.router.navigate(['library', currentlyReadingChapter.libraryId, 'series', currentlyReadingChapter.seriesId, 'manga', currentlyReadingChapter.chapterId], {queryParams: {readingListId: this.readingList.id}});
+ }
+ }
+}
diff --git a/UI/Web/src/app/reading-list/reading-list.module.ts b/UI/Web/src/app/reading-list/reading-list.module.ts
new file mode 100644
index 000000000..8b22b67c5
--- /dev/null
+++ b/UI/Web/src/app/reading-list/reading-list.module.ts
@@ -0,0 +1,40 @@
+import { NgModule } from '@angular/core';
+import { CommonModule } from '@angular/common';
+import { DragableOrderedListComponent } from './dragable-ordered-list/dragable-ordered-list.component';
+import { ReadingListDetailComponent } from './reading-list-detail/reading-list-detail.component';
+import { ReadingListRoutingModule } from './reading-list.router.module';
+import {DragDropModule} from '@angular/cdk/drag-drop';
+import { AddToListModalComponent } from './_modals/add-to-list-modal/add-to-list-modal.component';
+import { ReactiveFormsModule } from '@angular/forms';
+import { CardsModule } from '../cards/cards.module';
+import { ReadingListsComponent } from './reading-lists/reading-lists.component';
+import { EditReadingListModalComponent } from './_modals/edit-reading-list-modal/edit-reading-list-modal.component';
+import { PipeModule } from '../pipe/pipe.module';
+import { SharedModule } from '../shared/shared.module';
+
+
+
+@NgModule({
+ declarations: [
+ DragableOrderedListComponent,
+ ReadingListDetailComponent,
+ AddToListModalComponent,
+ ReadingListsComponent,
+ EditReadingListModalComponent
+ ],
+ imports: [
+ CommonModule,
+ ReadingListRoutingModule,
+ ReactiveFormsModule,
+ DragDropModule,
+ CardsModule,
+ PipeModule,
+ SharedModule
+ ],
+ exports: [
+ AddToListModalComponent,
+ ReadingListsComponent,
+ EditReadingListModalComponent
+ ]
+})
+export class ReadingListModule { }
diff --git a/UI/Web/src/app/reading-list/reading-list.router.module.ts b/UI/Web/src/app/reading-list/reading-list.router.module.ts
new file mode 100644
index 000000000..3e664265f
--- /dev/null
+++ b/UI/Web/src/app/reading-list/reading-list.router.module.ts
@@ -0,0 +1,23 @@
+import { NgModule } from "@angular/core";
+import { Routes, RouterModule } from "@angular/router";
+import { AuthGuard } from "../_guards/auth.guard";
+import { ReadingListDetailComponent } from "./reading-list-detail/reading-list-detail.component";
+
+const routes: Routes = [
+ {
+ path: '',
+ runGuardsAndResolvers: 'always',
+ canActivate: [AuthGuard],
+ children: [
+ {path: '', component: ReadingListDetailComponent, pathMatch: 'full'},
+ {path: ':id', component: ReadingListDetailComponent, pathMatch: 'full'},
+ ]
+ }
+];
+
+
+@NgModule({
+ imports: [RouterModule.forChild(routes)],
+ exports: [RouterModule]
+})
+export class ReadingListRoutingModule { }
diff --git a/UI/Web/src/app/reading-list/reading-lists/reading-lists.component.html b/UI/Web/src/app/reading-list/reading-lists/reading-lists.component.html
new file mode 100644
index 000000000..96837060c
--- /dev/null
+++ b/UI/Web/src/app/reading-list/reading-lists/reading-lists.component.html
@@ -0,0 +1,11 @@
+<app-card-detail-layout header="Reading Lists"
+ [isLoading]="loadingLists"
+ [items]="lists"
+ [actions]="actions"
+ [pagination]="pagination"
+ (pageChange)="onPageChange($event)"
+ >
+ <ng-template #cardItem let-item let-position="idx">
+ <app-card-item [title]="item.title" [entity]="item" [actions]="getActions(item)" [supressLibraryLink]="true" [imageUrl]="imageService.placeholderImage" (clicked)="handleClick(item)"></app-card-item>
+ </ng-template>
+</app-card-detail-layout>
diff --git a/UI/Web/src/app/reading-list/reading-lists/reading-lists.component.scss b/UI/Web/src/app/reading-list/reading-lists/reading-lists.component.scss
new file mode 100644
index 000000000..e69de29bb
diff --git a/UI/Web/src/app/reading-list/reading-lists/reading-lists.component.ts b/UI/Web/src/app/reading-list/reading-lists/reading-lists.component.ts
new file mode 100644
index 000000000..d7051df2e
--- /dev/null
+++ b/UI/Web/src/app/reading-list/reading-lists/reading-lists.component.ts
@@ -0,0 +1,96 @@
+import { Component, OnInit } from '@angular/core';
+import { Router } from '@angular/router';
+import { ToastrService } from 'ngx-toastr';
+import { take } from 'rxjs/operators';
+import { PaginatedResult, Pagination } from 'src/app/_models/pagination';
+import { ReadingList } from 'src/app/_models/reading-list';
+import { AccountService } from 'src/app/_services/account.service';
+import { Action, ActionFactoryService, ActionItem } from 'src/app/_services/action-factory.service';
+import { ActionService } from 'src/app/_services/action.service';
+import { ImageService } from 'src/app/_services/image.service';
+import { ReadingListService } from 'src/app/_services/reading-list.service';
+
+@Component({
+ selector: 'app-reading-lists',
+ templateUrl: './reading-lists.component.html',
+ styleUrls: ['./reading-lists.component.scss']
+})
+export class ReadingListsComponent implements OnInit {
+
+ lists: ReadingList[] = [];
+ loadingLists = false;
+ pagination!: Pagination;
+ actions: ActionItem<ReadingList>[] = [];
+ isAdmin: boolean = false;
+
+ constructor(private readingListService: ReadingListService, public imageService: ImageService, private actionFactoryService: ActionFactoryService,
+ private accountService: AccountService, private toastr: ToastrService, private router: Router, private actionService: ActionService) { }
+
+ ngOnInit(): void {
+ this.loadPage();
+
+ this.accountService.currentUser$.pipe(take(1)).subscribe(user => {
+ if (user) {
+ this.isAdmin = this.accountService.hasAdminRole(user);
+ }
+ });
+ }
+
+ getActions(readingList: ReadingList) {
+ return this.actionFactoryService.getReadingListActions(this.handleReadingListActionCallback.bind(this)).filter(action => this.readingListService.actionListFilter(action, readingList, this.isAdmin));
+ }
+
+ performAction(action: ActionItem<any>, readingList: ReadingList) {
+ // TODO: Try to move performAction into the actionables component. (have default handler in the component, allow for overridding to pass additional context)
+ if (typeof action.callback === 'function') {
+ action.callback(action.action, readingList);
+ }
+ }
+
+ handleReadingListActionCallback(action: Action, readingList: ReadingList) {
+ switch(action) {
+ case Action.Delete:
+ this.readingListService.delete(readingList.id).subscribe(() => {
+ this.toastr.success('Reading list deleted');
+ this.loadPage();
+ });
+ break;
+ case Action.Edit:
+ this.actionService.editReadingList(readingList, (updatedList: ReadingList) => {
+ // Reload information around list
+ readingList = updatedList;
+ });
+ break;
+ }
+ }
+
+ getPage() {
+ const urlParams = new URLSearchParams(window.location.search);
+ return urlParams.get('page');
+ }
+
+ loadPage() {
+ const page = this.getPage();
+ if (page != null) {
+ this.pagination.currentPage = parseInt(page, 10);
+ }
+ this.loadingLists = true;
+
+ this.readingListService.getReadingLists(true, this.pagination?.currentPage, this.pagination?.itemsPerPage).pipe(take(1)).subscribe((readingLists: PaginatedResult<ReadingList[]>) => {
+ this.lists = readingLists.result;
+ this.pagination = readingLists.pagination;
+ this.loadingLists = false;
+ window.scrollTo(0, 0);
+ });
+ }
+
+ onPageChange(pagination: Pagination) {
+ window.history.replaceState(window.location.href, '', window.location.href.split('?')[0] + '?page=' + this.pagination.currentPage);
+ this.loadPage();
+ }
+
+ handleClick(list: ReadingList) {
+ this.router.navigateByUrl('lists/' + list.id);
+ }
+
+}
diff --git a/UI/Web/src/app/series-detail/series-detail.component.html b/UI/Web/src/app/series-detail/series-detail.component.html
index 7976265d5..541ff5b88 100644
--- a/UI/Web/src/app/series-detail/series-detail.component.html
+++ b/UI/Web/src/app/series-detail/series-detail.component.html
@@ -95,19 +95,18 @@
</div>
</div>
</div>
- <hr>
-
<div>
- <ul ngbNav #nav="ngbNav" [(activeId)]="activeTabId" class="nav-tabs" [destroyOnHide]="false">
+ <app-bulk-operations [actionCallback]="bulkActionCallback"></app-bulk-operations>
+ <ul ngbNav #nav="ngbNav" [(activeId)]="activeTabId" class="nav-tabs nav-pills" [destroyOnHide]="false">
<li [ngbNavItem]="1" *ngIf="hasSpecials">
<a ngbNavLink>Specials</a>
<ng-template ngbNavContent>
- <div class="row">
- <div *ngFor="let chapter of specials">
- <app-card-item class="col-auto" *ngIf="chapter.isSpecial" [entity]="chapter" [title]="chapter.title || chapter.range" (click)="openChapter(chapter)"
+ <div class="row no-gutters">
+ <div *ngFor="let chapter of specials; let idx = index; trackBy: trackByChapterIdentity">
+ <app-card-item class="col-auto" *ngIf="chapter.isSpecial" [entity]="chapter" [title]="chapter.title || chapter.range" (click)="openChapter(chapter)"
[imageUrl]="imageService.getChapterCoverImage(chapter.id)"
- [read]="chapter.pagesRead" [total]="chapter.pages" [actions]="chapterActions"></app-card-item>
+ [read]="chapter.pagesRead" [total]="chapter.pages" [actions]="chapterActions" (selection)="bulkSelectionService.handleCardSelection('special', idx, chapters.length, $event)" [selected]="bulkSelectionService.isCardSelected('special', idx)" [allowSelection]="true"></app-card-item>
</div>
</div>
</ng-template>
@@ -115,17 +114,17 @@
<li [ngbNavItem]="2" *ngIf="hasNonSpecialVolumeChapters">
<a ngbNavLink>Volumes/Chapters</a>
<ng-template ngbNavContent>
- <div class="row">
- <div *ngFor="let volume of volumes">
- <app-card-item class="col-auto" *ngIf="volume.number != 0" [entity]="volume" [title]="'Volume ' + volume.name" (click)="openVolume(volume)"
- [imageUrl]="imageService.getVolumeCoverImage(volume.id) + '&offset=' + coverImageOffset"
- [read]="volume.pagesRead" [total]="volume.pages" [actions]="volumeActions"></app-card-item>
- </div>
- <div *ngFor="let chapter of chapters">
- <app-card-item class="col-auto" *ngIf="!chapter.isSpecial" [entity]="chapter" [title]="'Chapter ' + chapter.range" (click)="openChapter(chapter)"
- [imageUrl]="imageService.getChapterCoverImage(chapter.id) + '&offset=' + coverImageOffset"
- [read]="chapter.pagesRead" [total]="chapter.pages" [actions]="chapterActions"></app-card-item>
- </div>
+ <div class="row no-gutters">
+ <div *ngFor="let volume of volumes; let idx = index; trackBy: trackByVolumeIdentity">
+ <app-card-item class="col-auto" *ngIf="volume.number != 0" [entity]="volume" [title]="'Volume ' + volume.name" (click)="openVolume(volume)"
+ [imageUrl]="imageService.getVolumeCoverImage(volume.id) + '&offset=' + coverImageOffset"
+ [read]="volume.pagesRead" [total]="volume.pages" [actions]="volumeActions" (selection)="bulkSelectionService.handleCardSelection('volume', idx, volumes.length, $event)" [selected]="bulkSelectionService.isCardSelected('volume', idx)" [allowSelection]="true"></app-card-item>
+ </div>
+ <div *ngFor="let chapter of chapters; let idx = index; trackBy: trackByChapterIdentity">
+ <app-card-item class="col-auto" *ngIf="!chapter.isSpecial" [entity]="chapter" [title]="'Chapter ' + chapter.range" (click)="openChapter(chapter)"
+ [imageUrl]="imageService.getChapterCoverImage(chapter.id) + '&offset=' + coverImageOffset"
+ [read]="chapter.pagesRead" [total]="chapter.pages" [actions]="chapterActions" (selection)="bulkSelectionService.handleCardSelection('chapter', idx, chapters.length, $event)" [selected]="bulkSelectionService.isCardSelected('chapter', idx)" [allowSelection]="true"></app-card-item>
+ </div>
</div>
</ng-template>
</li>
diff --git a/UI/Web/src/app/series-detail/series-detail.component.scss b/UI/Web/src/app/series-detail/series-detail.component.scss
index 06c2a718c..3819e8b7a 100644
--- a/UI/Web/src/app/series-detail/series-detail.component.scss
+++ b/UI/Web/src/app/series-detail/series-detail.component.scss
@@ -13,7 +13,7 @@
.poster {
width: 100%;
- max-height: 481px;
+ max-width: 400px;
}
diff --git a/UI/Web/src/app/series-detail/series-detail.component.ts b/UI/Web/src/app/series-detail/series-detail.component.ts
index 56b562fec..208bbd363 100644
--- a/UI/Web/src/app/series-detail/series-detail.component.ts
+++ b/UI/Web/src/app/series-detail/series-detail.component.ts
@@ -1,18 +1,21 @@
-import { Component, OnInit } from '@angular/core';
+import { Component, HostListener, OnDestroy, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { NgbModal, NgbRatingConfig } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
-import { finalize, take, takeWhile } from 'rxjs/operators';
+import { Subject } from 'rxjs';
+import { finalize, take, takeUntil, takeWhile } from 'rxjs/operators';
+import { BulkSelectionService } from '../cards/bulk-selection.service';
import { CardDetailsModalComponent } from '../cards/_modals/card-details-modal/card-details-modal.component';
import { EditSeriesModalComponent } from '../cards/_modals/edit-series-modal/edit-series-modal.component';
import { ConfirmConfig } from '../shared/confirm-dialog/_models/confirm-config';
import { ConfirmService } from '../shared/confirm.service';
import { TagBadgeCursor } from '../shared/tag-badge/tag-badge.component';
import { DownloadService } from '../shared/_services/download.service';
-import { UtilityService } from '../shared/_services/utility.service';
+import { KEY_CODES, UtilityService } from '../shared/_services/utility.service';
import { ReviewSeriesModalComponent } from '../_modals/review-series-modal/review-series-modal.component';
import { Chapter } from '../_models/chapter';
+import { ScanSeriesEvent } from '../_models/events/scan-series-event';
import { LibraryType } from '../_models/library';
import { MangaFormat } from '../_models/manga-format';
import { Series } from '../_models/series';
@@ -23,6 +26,7 @@ import { ActionItem, ActionFactoryService, Action } from '../_services/action-fa
import { ActionService } from '../_services/action.service';
import { ImageService } from '../_services/image.service';
import { LibraryService } from '../_services/library.service';
+import { MessageHubService } from '../_services/message-hub.service';
import { ReaderService } from '../_services/reader.service';
import { SeriesService } from '../_services/series.service';
@@ -32,7 +36,7 @@ import { SeriesService } from '../_services/series.service';
templateUrl: './series-detail.component.html',
styleUrls: ['./series-detail.component.scss']
})
-export class SeriesDetailComponent implements OnInit {
+export class SeriesDetailComponent implements OnInit, OnDestroy {
series!: Series;
volumes: Volume[] = [];
@@ -50,6 +54,7 @@ export class SeriesDetailComponent implements OnInit {
seriesActions: ActionItem<Series>[] = [];
volumeActions: ActionItem<Volume>[] = [];
chapterActions: ActionItem<Chapter>[] = [];
+ bulkActions: ActionItem<any>[] = [];
hasSpecials = false;
specials: Array<Chapter> = [];
@@ -76,6 +81,57 @@ export class SeriesDetailComponent implements OnInit {
*/
actionInProgress: boolean = false;
+ /**
+ * Track by function for Volume to tell when to refresh card data
+ */
+ trackByVolumeIdentity = (index: number, item: Volume) => `${item.name}_${item.pagesRead}`;
+ /**
+ * Track by function for Chapter to tell when to refresh card data
+ */
+ trackByChapterIdentity = (index: number, item: Chapter) => `${item.title}_${item.number}_${item.pagesRead}`;
+
+ bulkActionCallback = (action: Action, data: any) => {
+ if (this.series === undefined) {
+ return;
+ }
+ const seriesId = this.series.id;
+ // we need to figure out what is actually selected now
+ const selectedVolumeIndexes = this.bulkSelectionService.getSelectedCardsForSource('volume');
+ const selectedChapterIndexes = this.bulkSelectionService.getSelectedCardsForSource('chapter');
+ const selectedSpecialIndexes = this.bulkSelectionService.getSelectedCardsForSource('special');
+
+ const selectedChapterIds = this.chapters.filter((_chapter, index: number) => selectedChapterIndexes.includes(index + ''));
+ const selectedVolumeIds = this.volumes.filter((_volume, index: number) => selectedVolumeIndexes.includes(index + ''));
+ const selectedSpecials = this.specials.filter((_chapter, index: number) => selectedSpecialIndexes.includes(index + ''));
+ const chapters = [...selectedChapterIds, ...selectedSpecials];
+
+ switch (action) {
+ case Action.AddToReadingList:
+ this.actionService.addMultipleToReadingList(seriesId, selectedVolumeIds, chapters, () => {
+ this.actionInProgress = false;
+ this.bulkSelectionService.deselectAll();
+ });
+ break;
+ case Action.MarkAsRead:
+ this.actionService.markMultipleAsRead(seriesId, selectedVolumeIds, chapters, () => {
+ this.setContinuePoint();
+ this.actionInProgress = false;
+ this.bulkSelectionService.deselectAll();
+ });
+
+ break;
+ case Action.MarkAsUnread:
+ this.actionService.markMultipleAsUnread(seriesId, selectedVolumeIds, chapters, () => {
+ this.setContinuePoint();
+ this.actionInProgress = false;
+ this.bulkSelectionService.deselectAll();
+ });
+ break;
+ }
+ }
+
+ private onDestroy: Subject<void> = new Subject();
+
get LibraryType(): typeof LibraryType {
return LibraryType;
@@ -97,7 +153,8 @@ export class SeriesDetailComponent implements OnInit {
private actionFactoryService: ActionFactoryService, private libraryService: LibraryService,
private confirmService: ConfirmService, private titleService: Title,
private downloadService: DownloadService, private actionService: ActionService,
- public imageSerivce: ImageService) {
+ public imageSerivce: ImageService, private messageHub: MessageHubService,
+ public bulkSelectionService: BulkSelectionService) {
ratingConfig.max = 5;
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.accountService.currentUser$.pipe(take(1)).subscribe(user => {
@@ -116,20 +173,39 @@ export class SeriesDetailComponent implements OnInit {
return;
}
+ this.messageHub.scanSeries.pipe(takeUntil(this.onDestroy)).subscribe((event: ScanSeriesEvent) => {
+ if (event.seriesId == this.series.id)
+ this.loadSeries(seriesId);
+ this.seriesImage = this.imageService.randomize(this.imageService.getSeriesCoverImage(this.series.id));
+ this.toastr.success('Scan series completed');
+ });
+
const seriesId = parseInt(routeId, 10);
this.libraryId = parseInt(libraryId, 10);
this.seriesImage = this.imageService.getSeriesCoverImage(seriesId);
- this.loadSeriesMetadata(seriesId);
this.libraryService.getLibraryType(this.libraryId).subscribe(type => {
this.libraryType = type;
this.loadSeries(seriesId);
});
}
- loadSeriesMetadata(seriesId: number) {
- this.seriesService.getMetadata(seriesId).subscribe(metadata => {
- this.seriesMetadata = metadata;
- });
+ ngOnDestroy() {
+ this.onDestroy.next();
+ this.onDestroy.complete();
+ }
+
+ @HostListener('document:keydown.shift', ['$event'])
+ handleKeypress(event: KeyboardEvent) {
+ if (event.key === KEY_CODES.SHIFT) {
+ this.bulkSelectionService.isShiftDown = true;
+ }
+ }
+
+ @HostListener('document:keyup.shift', ['$event'])
+ handleKeyUp(event: KeyboardEvent) {
+ if (event.key === KEY_CODES.SHIFT) {
+ this.bulkSelectionService.isShiftDown = false;
+ }
}
handleSeriesActionCallback(action: Action, series: Series) {
@@ -159,6 +235,9 @@ export class SeriesDetailComponent implements OnInit {
case(Action.Bookmarks):
this.actionService.openBookmarkModal(series, () => this.actionInProgress = false);
break;
+ case(Action.AddToReadingList):
+ this.actionService.addSeriesToReadingList(series, () => this.actionInProgress = false);
+ break;
default:
break;
}
@@ -175,6 +254,14 @@ export class SeriesDetailComponent implements OnInit {
case(Action.Edit):
this.openViewInfo(volume);
break;
+ case(Action.AddToReadingList):
+ this.actionService.addVolumeToReadingList(volume, this.series.id, () => {/* No Operation */ });
+ break;
+ case(Action.IncognitoRead):
+ if (volume.chapters != undefined && volume.chapters?.length >= 1) {
+ this.openChapter(volume.chapters[0], true);
+ }
+ break;
default:
break;
}
@@ -191,6 +278,12 @@ export class SeriesDetailComponent implements OnInit {
case(Action.Edit):
this.openViewInfo(chapter);
break;
+ case(Action.AddToReadingList):
+ this.actionService.addChapterToReadingList(chapter, this.series.id, () => {/* No Operation */ });
+ break;
+ case(Action.IncognitoRead):
+ this.openChapter(chapter, true);
+ break;
default:
break;
}
@@ -245,6 +338,7 @@ export class SeriesDetailComponent implements OnInit {
this.volumeActions = this.actionFactoryService.getVolumeActions(this.handleVolumeActionCallback.bind(this));
this.chapterActions = this.actionFactoryService.getChapterActions(this.handleChapterActionCallback.bind(this));
+
this.seriesService.getVolumes(this.series.id).subscribe(volumes => {
this.chapters = volumes.filter(v => v.number === 0).map(v => v.chapters || []).flat().sort(this.utilityService.sortChapters);
@@ -269,6 +363,11 @@ export class SeriesDetailComponent implements OnInit {
this.hasNonSpecialVolumeChapters = false;
}
+ // If an update occured and we were on specials, re-activate Volumes/Chapters
+ if (!this.hasSpecials && this.activeTabId != 2) {
+ this.activeTabId = 2;
+ }
+
this.isLoading = false;
});
}, err => {
@@ -348,16 +447,16 @@ export class SeriesDetailComponent implements OnInit {
});
}
- openChapter(chapter: Chapter) {
+ openChapter(chapter: Chapter, incognitoMode = false) {
if (chapter.pages === 0) {
this.toastr.error('There are no pages. Kavita was not able to read this archive.');
return;
}
if (chapter.files.length > 0 && chapter.files[0].format === MangaFormat.EPUB) {
- this.router.navigate(['library', this.libraryId, 'series', this.series?.id, 'book', chapter.id]);
+ this.router.navigate(['library', this.libraryId, 'series', this.series?.id, 'book', chapter.id], {queryParams: {incognitoMode}});
} else {
- this.router.navigate(['library', this.libraryId, 'series', this.series?.id, 'manga', chapter.id]);
+ this.router.navigate(['library', this.libraryId, 'series', this.series?.id, 'manga', chapter.id], {queryParams: {incognitoMode}});
}
}
@@ -405,7 +504,6 @@ export class SeriesDetailComponent implements OnInit {
window.scrollTo(0, 0);
if (closeResult.success) {
this.loadSeries(this.series.id);
- this.loadSeriesMetadata(this.series.id);
if (closeResult.coverImageUpdate) {
// Random triggers a load change without any problems with API
this.seriesImage = this.imageService.randomize(this.imageService.getSeriesCoverImage(this.series.id));
@@ -450,7 +548,6 @@ export class SeriesDetailComponent implements OnInit {
}
downloadSeries() {
-
this.downloadService.downloadSeriesSize(this.series.id).pipe(take(1)).subscribe(async (size) => {
const wantToDownload = await this.downloadService.confirmSize(size, 'series');
if (!wantToDownload) { return; }
diff --git a/UI/Web/src/app/shared/_services/download.service.ts b/UI/Web/src/app/shared/_services/download.service.ts
index 0919eb0e7..882d789c8 100644
--- a/UI/Web/src/app/shared/_services/download.service.ts
+++ b/UI/Web/src/app/shared/_services/download.service.ts
@@ -73,7 +73,7 @@ export class DownloadService {
}));
}
- async confirmSize(size: number, entityType: 'volume' | 'chapter' | 'series') {
+ async confirmSize(size: number, entityType: 'volume' | 'chapter' | 'series' | 'reading list') {
return (size < this.SIZE_WARNING || await this.confirmService.confirm('The ' + entityType + ' is ' + this.humanFileSize(size) + '. Are you sure you want to continue?'));
}
@@ -85,6 +85,8 @@ export class DownloadService {
}));
}
+
+
/**
* Format bytes as human-readable text.
*
diff --git a/UI/Web/src/app/shared/_services/utility.service.ts b/UI/Web/src/app/shared/_services/utility.service.ts
index 3c2ed50d5..b66f67cb9 100644
--- a/UI/Web/src/app/shared/_services/utility.service.ts
+++ b/UI/Web/src/app/shared/_services/utility.service.ts
@@ -13,10 +13,19 @@ export enum KEY_CODES {
SPACE = ' ',
ENTER = 'Enter',
G = 'g',
+ B = 'b',
BACKSPACE = 'Backspace',
- DELETE = 'Delete'
+ DELETE = 'Delete',
+ SHIFT = 'Shift'
}
+export enum Breakpoint {
+ Mobile = 768,
+ Tablet = 1280,
+ Desktop = 1440
+}
+
+
@Injectable({
providedIn: 'root'
})
@@ -110,4 +119,12 @@ export class UtilityService {
return <Series>d;
}
+ getActiveBreakpoint(): Breakpoint {
+ if (window.innerWidth <= Breakpoint.Mobile) return Breakpoint.Mobile;
+ else if (window.innerWidth > Breakpoint.Mobile && window.innerWidth <= Breakpoint.Tablet) return Breakpoint.Tablet;
+ else if (window.innerWidth > Breakpoint.Tablet) return Breakpoint.Desktop
+
+ return Breakpoint.Desktop;
+ }
+
}
diff --git a/UI/Web/src/app/shared/shared.module.ts b/UI/Web/src/app/shared/shared.module.ts
index 790333aa8..246d9363c 100644
--- a/UI/Web/src/app/shared/shared.module.ts
+++ b/UI/Web/src/app/shared/shared.module.ts
@@ -13,7 +13,6 @@ import { ShowIfScrollbarDirective } from './show-if-scrollbar.directive';
import { A11yClickDirective } from './a11y-click.directive';
import { SeriesFormatComponent } from './series-format/series-format.component';
import { UpdateNotificationModalComponent } from './update-notification/update-notification-modal.component';
-import { SAVER, getSaver } from './_providers/saver.provider';
import { CircularLoaderComponent } from './circular-loader/circular-loader.component';
import { NgCircleProgressModule } from 'ng-circle-progress';
@@ -51,6 +50,5 @@ import { NgCircleProgressModule } from 'ng-circle-progress';
TagBadgeComponent,
CircularLoaderComponent,
],
- //providers: [{provide: SAVER, useFactory: getSaver}]
})
export class SharedModule { }
diff --git a/UI/Web/src/app/user-settings/user-preferences/user-preferences.component.html b/UI/Web/src/app/user-settings/user-preferences/user-preferences.component.html
index ed5078041..1a1dee3b3 100644
--- a/UI/Web/src/app/user-settings/user-preferences/user-preferences.component.html
+++ b/UI/Web/src/app/user-settings/user-preferences/user-preferences.component.html
@@ -1,6 +1,6 @@
<div class="container">
<h2>User Dashboard</h2>
- <ul ngbNav #nav="ngbNav" [(activeId)]="active" class="nav-tabs">
+ <ul ngbNav #nav="ngbNav" [(activeId)]="active" class="nav-tabs nav-pills">
<li *ngFor="let tab of tabs" [ngbNavItem]="tab">
<a ngbNavLink routerLink="." [fragment]="tab.fragment">{{ tab.title | titlecase }}</a>
<ng-template ngbNavContent>
@@ -9,8 +9,14 @@
These are global settings that are bound to your account.
</p>
- <ngb-accordion [closeOthers]="true" activeIds="site-panel">
+ <ngb-accordion [closeOthers]="true" activeIds="site-panel" #acc="ngbAccordion">
<ngb-panel id="site-panel" title="Site">
+ <ng-template ngbPanelHeader>
+ <div class="d-flex align-items-center justify-content-between">
+ <button ngbPanelToggle class="btn container-fluid text-left pl-0 accordion-header">Site</button>
+ <span class="pull-right"><i class="fa fa-angle-{{acc.isExpanded('site-panel') ? 'down' : 'up'}}" aria-hidden="true"></i></span>
+ </div>
+ </ng-template>
<ng-template ngbPanelContent>
<form [formGroup]="settingsForm" *ngIf="user !== undefined">
<div class="form-group">
@@ -34,6 +40,12 @@
</ng-template>
</ngb-panel>
<ngb-panel id="reading-panel" title="Reading">
+ <ng-template ngbPanelHeader>
+ <div class="d-flex align-items-center justify-content-between">
+ <button ngbPanelToggle class="btn container-fluid text-left pl-0 accordion-header">Reading</button>
+ <span class="pull-right"><i class="fa fa-angle-{{acc.isExpanded('reading-panel') ? 'down' : 'up'}}" aria-hidden="true"></i></span>
+ </div>
+ </ng-template>
<ng-template ngbPanelContent>
<form [formGroup]="settingsForm" *ngIf="user !== undefined">
<h3 id="manga-header">Manga</h3>
@@ -130,20 +142,20 @@
</div>
<div class="form-group">
<label id="font-size">Font Size</label>
- <ngx-slider [options]="bookReaderFontSizeOptions" formControlName="bookReaderFontSize" aria-labelledby="font-size"></ngx-slider>
+ <div class="custom-slider"><ngx-slider [options]="bookReaderFontSizeOptions" formControlName="bookReaderFontSize" aria-labelledby="font-size"></ngx-slider></div>
</div>
<div class="form-group">
<label>Line Height</label>&nbsp;<i class="fa fa-info-circle" aria-hidden="true" placement="right" [ngbTooltip]="bookLineHeightOptionTooltip" role="button" tabindex="0"></i>
<ng-template #bookLineHeightOptionTooltip>How much spacing between the lines of the book</ng-template>
<span class="sr-only" id="settings-booklineheight-option-help">How much spacing between the lines of the book</span>
- <ngx-slider [options]="bookReaderLineSpacingOptions" formControlName="bookReaderLineSpacing" aria-describedby="settings-booklineheight-option-help"></ngx-slider>
+ <div class="custom-slider"><ngx-slider [options]="bookReaderLineSpacingOptions" formControlName="bookReaderLineSpacing" aria-describedby="settings-booklineheight-option-help"></ngx-slider></div>
</div>
<div class="form-group">
<label>Margin</label>&nbsp;<i class="fa fa-info-circle" aria-hidden="true" placement="right" [ngbTooltip]="bookReaderMarginOptionTooltip" role="button" tabindex="0"></i>
<ng-template #bookReaderMarginOptionTooltip>How much spacing on each side of the screen. This will override to 0 on mobile devices regardless of this setting.</ng-template>
<span class="sr-only" id="settings-bookmargin-option-help">How much spacing on each side of the screen. This will override to 0 on mobile devices regardless of this setting.</span>
- <ngx-slider [options]="bookReaderMarginOptions" formControlName="bookReaderMargin" aria-describedby="bookmargin"></ngx-slider>
+ <div class="custom-slider"><ngx-slider [options]="bookReaderMarginOptions" formControlName="bookReaderMargin" aria-describedby="bookmargin"></ngx-slider></div>
</div>
<div class="float-right mb-3">
@@ -156,6 +168,12 @@
<ngb-panel id="password-panel" title="Password">
+ <ng-template ngbPanelHeader>
+ <div class="d-flex align-items-center justify-content-between">
+ <button ngbPanelToggle class="btn container-fluid text-left pl-0 accordion-header">Password</button>
+ <span class="pull-right"><i class="fa fa-angle-{{acc.isExpanded('password-panel') ? 'down' : 'up'}}" aria-hidden="true"></i></span>
+ </div>
+ </ng-template>
<ng-template ngbPanelContent>
<p>Change your Password</p>
<div class="alert alert-danger" role="alert" *ngIf="resetPasswordErrors.length > 0">
@@ -191,6 +209,12 @@
</ng-template>
</ngb-panel>
<ngb-panel id="api-panel" title="OPDS">
+ <ng-template ngbPanelHeader>
+ <div class="d-flex align-items-center justify-content-between">
+ <button ngbPanelToggle class="btn container-fluid text-left pl-0 accordion-header">OPDS</button>
+ <span class="pull-right"><i class="fa fa-angle-{{acc.isExpanded('api-panel') ? 'down' : 'up'}}" aria-hidden="true"></i></span>
+ </div>
+ </ng-template>
<ng-template ngbPanelContent>
<p class="alert alert-danger" role="alert" *ngIf="!opdsEnabled">
OPDS is not enabled on this server!
diff --git a/UI/Web/src/app/user-settings/user-preferences/user-preferences.component.scss b/UI/Web/src/app/user-settings/user-preferences/user-preferences.component.scss
index 761d937db..1bce1dcb8 100644
--- a/UI/Web/src/app/user-settings/user-preferences/user-preferences.component.scss
+++ b/UI/Web/src/app/user-settings/user-preferences/user-preferences.component.scss
@@ -1,3 +1,55 @@
+@import '../../../theme/colors';
+
.invalid-feedback {
display: inline-block !important;
-}
\ No newline at end of file
+}
+
+// Slider handle override
+::ng-deep {
+ .custom-slider .ngx-slider .ngx-slider-bar {
+ background: #545a52;
+ height: 2px;
+ }
+ .custom-slider .ngx-slider .ngx-slider-selection {
+ background: $primary-color;
+ }
+
+ .custom-slider .ngx-slider .ngx-slider-pointer {
+ width: 8px;
+ height: 16px;
+ top: auto; /* to remove the default positioning */
+ bottom: 0;
+ background-color: $primary-color;
+ border-top-left-radius: 3px;
+ border-top-right-radius: 3px;
+ }
+
+ .custom-slider .ngx-slider .ngx-slider-pointer:after {
+ display: none;
+ }
+
+ .custom-slider .ngx-slider .ngx-slider-bubble {
+ bottom: 14px;
+ font-weight: bold;
+ }
+
+ .custom-slider .ngx-slider .ngx-slider-limit {
+ font-weight: bold;
+ color: white !important;
+
+ }
+
+
+ .custom-slider .ngx-slider .ngx-slider-tick {
+ width: 1px;
+ height: 10px;
+ margin-left: 4px;
+ border-radius: 0;
+ background: #ffe4d1;
+ top: -1px;
+ }
+
+ .custom-slider .ngx-slider .ngx-slider-tick.ngx-slider-selected {
+ background: $primary-color;
+ }
+ }
\ No newline at end of file
diff --git a/UI/Web/src/assets/themes/dark.scss b/UI/Web/src/assets/themes/dark.scss
index 62e5b1c94..0cc5a6716 100644
--- a/UI/Web/src/assets/themes/dark.scss
+++ b/UI/Web/src/assets/themes/dark.scss
@@ -5,6 +5,7 @@ $dark-primary-color: rgba(74, 198, 148, 0.9);
$dark-text-color: #efefef;
$dark-hover-color: #4ac694;
$dark-form-background: rgba(1, 4, 9, 0.5);
+$dark-form-background-no-opacity: rgb(1, 4, 9);
$dark-form-placeholder: #efefef;
$dark-link-color: rgb(88, 166, 255);
$dark-icon-color: white;
@@ -30,6 +31,11 @@ $dark-item-accent-bg: #292d32;
color: white;
}
+ .accordion-header {
+ font-weight: bold;
+ color: $dark-primary-color;
+ }
+
.accent {
background-color: $dark-form-background !important;
@@ -121,6 +127,7 @@ $dark-item-accent-bg: #292d32;
.dropdown-menu {
+ background-color: #171719;
.dropdown-item:hover, .dropdown-item:focus {
color: $dark-text-color;
background-color: $dark-hover-color;
diff --git a/UI/Web/src/styles.scss b/UI/Web/src/styles.scss
index 0e3faf2d4..386d8a2de 100644
--- a/UI/Web/src/styles.scss
+++ b/UI/Web/src/styles.scss
@@ -51,54 +51,6 @@ body {
cursor: pointer;
}
-// Slider handle override
-::ng-deep {
- .custom-slider .ngx-slider .ngx-slider-bar {
- background: #ffe4d1;
- height: 2px;
- }
- .custom-slider .ngx-slider .ngx-slider-selection {
- background: orange;
- }
-
- .custom-slider .ngx-slider .ngx-slider-pointer {
- width: 8px;
- height: 16px;
- top: auto; /* to remove the default positioning */
- bottom: 0;
- background-color: #333;
- border-top-left-radius: 3px;
- border-top-right-radius: 3px;
- }
-
- .custom-slider .ngx-slider .ngx-slider-pointer:after {
- display: none;
- }
-
- .custom-slider .ngx-slider .ngx-slider-bubble {
- bottom: 14px;
- }
-
- .custom-slider .ngx-slider .ngx-slider-limit {
- font-weight: bold;
- color: orange;
- }
-
- .custom-slider .ngx-slider .ngx-slider-tick {
- width: 1px;
- height: 10px;
- margin-left: 4px;
- border-radius: 0;
- background: #ffe4d1;
- top: -1px;
- }
-
- .custom-slider .ngx-slider .ngx-slider-tick.ngx-slider-selected {
- background: orange;
- }
-}
-
-
// Utiliities
@include media-breakpoint-down(xs, (xs: 0, sm: 576px, md: 768px, lg: 992px, xl: 1200px)) {
diff --git a/UI/Web/tsconfig.json b/UI/Web/tsconfig.json
index 28c4a614d..1f73487e2 100644
--- a/UI/Web/tsconfig.json
+++ b/UI/Web/tsconfig.json
@@ -4,6 +4,7 @@
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
+ "removeComments": true /* Do not emit comments to output. */,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitReturns": true,
diff --git a/entrypoint.sh b/entrypoint.sh
index 0db3d824a..283db922c 100755
--- a/entrypoint.sh
+++ b/entrypoint.sh
@@ -74,6 +74,20 @@ else
ln -s /kavita/data/stats /kavita/stats
fi
+if [ -d /kavita/data/covers ]
+then
+ if [ -d /kavita/covers ]
+ then
+ unlink /kavita/covers
+ ln -s /kavita/data/covers /kavita/covers
+ else
+ ln -s /kavita/data/covers /kavita/covers
+ fi
+else
+ mkdir /kavita/data/covers
+ ln -s /kavita/data/covers /kavita/covers
+fi
+
chmod +x ./Kavita
./Kavita