Compare commits
151 Commits
1.4.2
...
ad4027779f
Author | SHA1 | Date | |
---|---|---|---|
ad4027779f | |||
98ec0b837f | |||
1afa3df316 | |||
d83aa1ef5b | |||
b610ec734e | |||
abf587377c | |||
437349bd27 | |||
000539d6a6 | |||
b4bef25a22 | |||
579e400a5d | |||
8af2b12fc0 | |||
bad4330330 | |||
42596752d3 | |||
16238c590b | |||
9f38dc3b6a | |||
485637d99a | |||
de14ff0b75 | |||
f947c37bd6 | |||
77eec0f696 | |||
18323f9f51 | |||
2cd2b6842d | |||
09f815903f | |||
c108478039 | |||
74289e43b7 | |||
2779f9ba09 | |||
59a8e556f0 | |||
074b137b5c | |||
3cb2540794 | |||
02c9934896 | |||
b2e1c95bca | |||
8c9e3ea6b6 | |||
db441607ad | |||
91c56783dc | |||
2c288eeeea | |||
57a1ea91fc | |||
06138a3927 | |||
84b053e672 | |||
0fe0cbc4ad | |||
62e6ce8363 | |||
a4f3ec6580 | |||
8b4e996b7e | |||
964540d30f | |||
fa69f4488f | |||
42c2876188 | |||
715244ff1b | |||
2333cd9095 | |||
c8225db4fe | |||
6741ca096b | |||
a897a7b3a2 | |||
0f8932e712 | |||
78023ef0fd | |||
d171f34e4e | |||
aa0dc4fa35 | |||
25f48592c0 | |||
398ac304d2 | |||
58a62f8272 | |||
86752c9a7e | |||
f9a7828d02 | |||
c97ff69148 | |||
1735bbcf8a | |||
9ae8ca65df | |||
00599cd24e | |||
6d5618a1f7 | |||
a1202a875d | |||
98946b4aa3 | |||
41b6bb77b6 | |||
e70a14ca56 | |||
b099da1156 | |||
01d1f922c2 | |||
47a80d67a8 | |||
16e3549455 | |||
be8c6b50ba | |||
a38fcf50ca | |||
82f6c7b3fe | |||
5586d2c104 | |||
62dc9fee2a | |||
ac96fca6dc | |||
25a6ceff10 | |||
b3e1d39d0f | |||
2833b7f22a | |||
cbdd305b69 | |||
b88890817e | |||
f66ab7d40b | |||
4cb3694cd5 | |||
a05d4c8bd9 | |||
22f87a74b2 | |||
ba57282879 | |||
9ccba6fba6 | |||
4f01c1166f | |||
0a51e7ad3d | |||
e541b922dc | |||
604abd5f9a | |||
7b311eae75 | |||
d4eb72cd99 | |||
b515215f4b | |||
a16686dfbf | |||
4275703941 | |||
c3342984ea | |||
ed4bdb5b33 | |||
0f0902c932 | |||
6508055b43 | |||
abc66511d8 | |||
9ed36c47b5 | |||
fd1b2a8470 | |||
8058749ab5 | |||
8737617e5f | |||
7e4f43f1e2 | |||
12b1b2afd6 | |||
0f9ac60fcd | |||
8c87f2948c | |||
e0fb817256 | |||
cdd2d94ba1 | |||
d5b7645cd2 | |||
9af5c1603e | |||
1035939309 | |||
3b542c04f6 | |||
a809b7c285 | |||
e883277400 | |||
23dfdc0933 | |||
edc24fff5b | |||
6cdccdf66b | |||
a4c9168551 | |||
821a1b7c3a | |||
b2b4256972 | |||
d2f46e4637 | |||
303fc293ba | |||
36c145da26 | |||
c822c74f42 | |||
dda4054d34 | |||
5b2546fdbc | |||
c11e3993ea | |||
02a382a99a | |||
c6c8f5cdf6 | |||
84842aed3c | |||
d9ced11cd1 | |||
25c90782dc | |||
e789c429cd | |||
93de471836 | |||
8b58e7dd13 | |||
b571bfa43d | |||
088d1c4647 | |||
f280c01802 | |||
1be10b310d | |||
a0469f3145 | |||
fcd81f03b3 | |||
76604d84d8 | |||
af822febbe | |||
8e207c3119 | |||
b6f8c8aab5 | |||
36f7cbd3e9 | |||
3b2643d949 |
7
.github/dependabot.yml
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
version: 2
|
||||
updates:
|
||||
# Maintain dependencies for GitHub Actions
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
43
.github/workflows/docker-base.yml
vendored
Normal file
@ -0,0 +1,43 @@
|
||||
name: Docker Image CI
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# https://github.com/docker/setup-qemu-action#usage
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2.2.0
|
||||
|
||||
# https://github.com/marketplace/actions/docker-setup-buildx
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@v2.9.1
|
||||
|
||||
# https://github.com/docker/login-action#docker-hub
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
# https://github.com/docker/build-push-action#multi-platform-image
|
||||
- name: Build and push base
|
||||
uses: docker/build-push-action@v4.1.1
|
||||
with:
|
||||
context: ./
|
||||
file: ./Dockerfile-base
|
||||
#platforms: linux/amd64,linux/arm64,linux/riscv64,linux/ppc64le,linux/s390x,linux/386,linux/mips64le,linux/mips64,linux/arm/v7,linux/arm/v6
|
||||
platforms: linux/amd64
|
||||
pull: true
|
||||
push: true
|
||||
tags: |
|
||||
glax/tranga-base:latest
|
58
.github/workflows/docker-image-cuttingedge.yml
vendored
Normal file
@ -0,0 +1,58 @@
|
||||
name: Docker Image CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "cuttingedge" ]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# https://github.com/docker/setup-qemu-action#usage
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2.2.0
|
||||
|
||||
# https://github.com/marketplace/actions/docker-setup-buildx
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@v2.9.1
|
||||
|
||||
# https://github.com/docker/login-action#docker-hub
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
# https://github.com/docker/build-push-action#multi-platform-image
|
||||
- name: Build and push API
|
||||
uses: docker/build-push-action@v4.1.1
|
||||
with:
|
||||
context: ./
|
||||
file: ./API/Dockerfile
|
||||
#platforms: linux/amd64,linux/arm64,linux/riscv64,linux/ppc64le,linux/s390x,linux/386,linux/mips64le,linux/mips64,linux/arm/v7,linux/arm/v6
|
||||
platforms: linux/amd64
|
||||
pull: true
|
||||
push: true
|
||||
tags: |
|
||||
glax/tranga-api:cuttingedge
|
||||
|
||||
# https://github.com/docker/build-push-action#multi-platform-image
|
||||
- name: Build and push Website
|
||||
uses: docker/build-push-action@v4.1.1
|
||||
with:
|
||||
context: ./Website
|
||||
file: ./Website/Dockerfile
|
||||
#platforms: linux/amd64,linux/arm64,linux/riscv64,linux/ppc64le,linux/s390x,linux/386,linux/mips64le,linux/mips64,linux/arm/v7,linux/arm/v6
|
||||
platforms: linux/amd64
|
||||
pull: true
|
||||
push: true
|
||||
tags: |
|
||||
glax/tranga-website:cuttingedge
|
60
.github/workflows/docker-image-master.yml
vendored
Normal file
@ -0,0 +1,60 @@
|
||||
name: Docker Image CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# https://github.com/docker/setup-qemu-action#usage
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2.2.0
|
||||
|
||||
# https://github.com/marketplace/actions/docker-setup-buildx
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@v2.9.1
|
||||
|
||||
# https://github.com/docker/login-action#docker-hub
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
# https://github.com/docker/build-push-action#multi-platform-image
|
||||
- name: Build and push API
|
||||
uses: docker/build-push-action@v4.1.1
|
||||
with:
|
||||
context: ./
|
||||
file: ./API/Dockerfile
|
||||
#platforms: linux/amd64,linux/arm64,linux/riscv64,linux/ppc64le,linux/s390x,linux/386,linux/mips64le,linux/mips64,linux/arm/v7,linux/arm/v6
|
||||
platforms: linux/amd64
|
||||
pull: true
|
||||
push: true
|
||||
tags: |
|
||||
glax/tranga-api:latest
|
||||
|
||||
# https://github.com/docker/build-push-action#multi-platform-image
|
||||
- name: Build and push Website
|
||||
uses: docker/build-push-action@v4.1.1
|
||||
with:
|
||||
context: ./Website
|
||||
file: ./Website/Dockerfile
|
||||
#platforms: linux/amd64,linux/arm64,linux/riscv64,linux/ppc64le,linux/s390x,linux/386,linux/mips64le,linux/mips64,linux/arm/v7,linux/arm/v6
|
||||
platforms: linux/amd64
|
||||
pull: true
|
||||
push: true
|
||||
tags: |
|
||||
glax/tranga-website:latest
|
@ -1,10 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>Tranga_API</RootNamespace>
|
||||
<Nullable>enable</Nullable>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
</PropertyGroup>
|
||||
|
||||
@ -15,14 +15,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Logging\Logging.csproj" />
|
||||
<ProjectReference Include="..\Tranga\Tranga.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.5" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.6" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -3,12 +3,11 @@
|
||||
FROM mcr.microsoft.com/dotnet/sdk:7.0 as build-env
|
||||
WORKDIR /src
|
||||
COPY . /src/
|
||||
RUN dotnet restore Tranga-API/Tranga-API.csproj
|
||||
RUN dotnet restore /src/API/API.csproj
|
||||
RUN dotnet publish -c Release -o /publish
|
||||
|
||||
#FROM mcr.microsoft.com/dotnet/aspnet:7.0 as runtime
|
||||
FROM glax/tranga-base:latest as runtime
|
||||
WORKDIR /publish
|
||||
COPY --from=build-env /publish .
|
||||
EXPOSE 80
|
||||
ENTRYPOINT ["dotnet", "/publish/Tranga-API.dll"]
|
||||
EXPOSE 6531
|
||||
ENTRYPOINT ["dotnet", "/publish/API.dll"]
|
52
API/Program.cs
Normal file
@ -0,0 +1,52 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Logging;
|
||||
using Tranga;
|
||||
using Tranga.NotificationManagers;
|
||||
using Tranga.LibraryManagers;
|
||||
|
||||
namespace API;
|
||||
|
||||
public static class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
string applicationFolderPath = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Tranga-API");
|
||||
string downloadFolderPath = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "/Manga" : Path.Join(applicationFolderPath, "Manga");
|
||||
string logsFolderPath = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "/var/logs/Tranga" : Path.Join(applicationFolderPath, "logs");
|
||||
string logFilePath = Path.Join(logsFolderPath, $"log-{DateTime.Now:dd-M-yyyy-HH-mm-ss}.txt");
|
||||
string settingsFilePath = Path.Join(applicationFolderPath, "settings.json");
|
||||
|
||||
Directory.CreateDirectory(logsFolderPath);
|
||||
Logger logger = new(new[] { Logger.LoggerType.FileLogger, Logger.LoggerType.ConsoleLogger }, Console.Out, Console.Out.Encoding, logFilePath);
|
||||
|
||||
logger.WriteLine("Tranga",value: "\n"+
|
||||
"-------------------------------------------\n"+
|
||||
" Starting Tranga-API\n"+
|
||||
"-------------------------------------------");
|
||||
logger.WriteLine("Tranga", "Loading settings.");
|
||||
|
||||
TrangaSettings settings;
|
||||
if (File.Exists(settingsFilePath))
|
||||
settings = TrangaSettings.LoadSettings(settingsFilePath, logger);
|
||||
else
|
||||
settings = new TrangaSettings(downloadFolderPath, applicationFolderPath, new HashSet<LibraryManager>(), new HashSet<NotificationManager>(), logger);
|
||||
|
||||
Directory.CreateDirectory(settings.workingDirectory);
|
||||
Directory.CreateDirectory(settings.downloadLocation);
|
||||
Directory.CreateDirectory(settings.coverImageCache);
|
||||
|
||||
settings.logger?.WriteLine("Tranga",$"Application-Folder: {settings.workingDirectory}");
|
||||
settings.logger?.WriteLine("Tranga",$"Settings-File-Path: {settings.settingsFilePath}");
|
||||
settings.logger?.WriteLine("Tranga",$"Download-Folder-Path: {settings.downloadLocation}");
|
||||
settings.logger?.WriteLine("Tranga",$"Logfile-Path: {logFilePath}");
|
||||
settings.logger?.WriteLine("Tranga",$"Image-Cache-Path: {settings.coverImageCache}");
|
||||
|
||||
settings.logger?.WriteLine("Tranga", "Loading Taskmanager.");
|
||||
TaskManager taskManager = new (settings);
|
||||
|
||||
Server server = new (6531, taskManager);
|
||||
foreach(NotificationManager nm in taskManager.settings.notificationManagers)
|
||||
nm.SendNotification("Tranga-API", "Started Tranga-API");
|
||||
}
|
||||
}
|
||||
|
365
API/RequestHandler.cs
Normal file
@ -0,0 +1,365 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using Tranga;
|
||||
using Tranga.Connectors;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
namespace API;
|
||||
|
||||
public class RequestHandler
|
||||
{
|
||||
private TaskManager _taskManager;
|
||||
private Server _parent;
|
||||
|
||||
private List<ValueTuple<HttpMethod, string, string[]>> _validRequestPaths = new()
|
||||
{
|
||||
new(HttpMethod.Get, "/", Array.Empty<string>()),
|
||||
new(HttpMethod.Get, "/Connectors", Array.Empty<string>()),
|
||||
new(HttpMethod.Get, "/Publications/Known", new[] { "internalId?" }),
|
||||
new(HttpMethod.Get, "/Publications/FromConnector", new[] { "connectorName", "title" }),
|
||||
new(HttpMethod.Get, "/Publications/Chapters",
|
||||
new[] { "connectorName", "internalId", "onlyNew?", "onlyExisting?", "language?" }),
|
||||
new(HttpMethod.Get, "/Tasks/Types", Array.Empty<string>()),
|
||||
new(HttpMethod.Post, "/Tasks/CreateMonitorTask",
|
||||
new[] { "connectorName", "internalId", "reoccurrenceTime", "language?", "ignoreChaptersBelow?" }),
|
||||
new(HttpMethod.Post, "/Tasks/CreateDownloadChaptersTask",
|
||||
new[] { "connectorName", "internalId", "chapters", "language?" }),
|
||||
new(HttpMethod.Get, "/Tasks", new[] { "taskType", "connectorName?", "publicationId?" }),
|
||||
new(HttpMethod.Delete, "/Tasks", new[] { "taskType", "connectorName?", "searchString?" }),
|
||||
new(HttpMethod.Get, "/Tasks/Progress",
|
||||
new[] { "taskType", "connectorName", "publicationId", "chapterSortNumber?" }),
|
||||
new(HttpMethod.Post, "/Tasks/Start", new[] { "taskType", "connectorName?", "internalId?" }),
|
||||
new(HttpMethod.Get, "/Tasks/RunningTasks", Array.Empty<string>()),
|
||||
new(HttpMethod.Get, "/Queue/List", Array.Empty<string>()),
|
||||
new(HttpMethod.Post, "/Queue/Enqueue", new[] { "taskType", "connectorName?", "publicationId?" }),
|
||||
new(HttpMethod.Delete, "/Queue/Dequeue", new[] { "taskType", "connectorName?", "publicationId?" }),
|
||||
new(HttpMethod.Get, "/Settings", Array.Empty<string>()),
|
||||
new(HttpMethod.Post, "/Settings/Update", new[]
|
||||
{
|
||||
"downloadLocation?", "komgaUrl?", "komgaAuth?", "kavitaUrl?", "kavitaUsername?",
|
||||
"kavitaPassword?", "gotifyUrl?", "gotifyAppToken?", "lunaseaWebhook?"
|
||||
})
|
||||
};
|
||||
|
||||
public RequestHandler(TaskManager taskManager, Server parent)
|
||||
{
|
||||
this._taskManager = taskManager;
|
||||
this._parent = parent;
|
||||
}
|
||||
|
||||
internal void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
|
||||
{
|
||||
string requestPath = request.Url!.LocalPath;
|
||||
if (requestPath.Contains("favicon"))
|
||||
{
|
||||
_parent.SendResponse(HttpStatusCode.NoContent, response);
|
||||
return;
|
||||
}
|
||||
if (!this._validRequestPaths.Any(path => path.Item1.Method == request.HttpMethod && path.Item2 == requestPath))
|
||||
{
|
||||
_parent.SendResponse(HttpStatusCode.BadRequest, response);
|
||||
return;
|
||||
}
|
||||
Dictionary<string, string> variables = GetRequestVariables(request.Url!.Query);
|
||||
object? responseObject = null;
|
||||
switch (request.HttpMethod)
|
||||
{
|
||||
case "GET":
|
||||
responseObject = this.HandleGet(requestPath, variables);
|
||||
break;
|
||||
case "POST":
|
||||
this.HandlePost(requestPath, variables);
|
||||
break;
|
||||
case "DELETE":
|
||||
this.HandleDelete(requestPath, variables);
|
||||
break;
|
||||
}
|
||||
_parent.SendResponse(HttpStatusCode.OK, response, responseObject);
|
||||
}
|
||||
|
||||
private Dictionary<string, string> GetRequestVariables(string query)
|
||||
{
|
||||
Dictionary<string, string> ret = new();
|
||||
Regex queryRex = new (@"\?{1}&?([A-z0-9-=]+=[A-z0-9-=]+)+(&[A-z0-9-=]+=[A-z0-9-=]+)*");
|
||||
if (!queryRex.IsMatch(query))
|
||||
return ret;
|
||||
query = query.Substring(1);
|
||||
foreach (string kvpair in query.Split('&').Where(str => str.Length >= 3))
|
||||
{
|
||||
string var = kvpair.Split('=')[0];
|
||||
string val = Regex.Replace(kvpair.Substring(var.Length + 1), "%20", " ");
|
||||
val = Regex.Replace(val, "%[0-9]{2}", "");
|
||||
ret.Add(var, val);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
private void HandleDelete(string requestPath, Dictionary<string, string> variables)
|
||||
{
|
||||
switch (requestPath)
|
||||
{
|
||||
case "/Tasks":
|
||||
variables.TryGetValue("taskType", out string? taskType1);
|
||||
variables.TryGetValue("connectorName", out string? connectorName1);
|
||||
variables.TryGetValue("publicationId", out string? publicationId1);
|
||||
if(taskType1 is null)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
TrangaTask.Task task = Enum.Parse<TrangaTask.Task>(taskType1);
|
||||
foreach(TrangaTask tTask in _taskManager.GetTasksMatching(task, connectorName1, internalId: publicationId1))
|
||||
_taskManager.DeleteTask(tTask);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case "/Queue/Dequeue":
|
||||
variables.TryGetValue("taskType", out string? taskType2);
|
||||
variables.TryGetValue("connectorName", out string? connectorName2);
|
||||
variables.TryGetValue("publicationId", out string? publicationId2);
|
||||
if(taskType2 is null)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
TrangaTask.Task pTask = Enum.Parse<TrangaTask.Task>(taskType2);
|
||||
TrangaTask? task = _taskManager
|
||||
.GetTasksMatching(pTask, connectorName: connectorName2, internalId: publicationId2).FirstOrDefault();
|
||||
|
||||
if (task is null)
|
||||
return;
|
||||
_taskManager.RemoveTaskFromQueue(task);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void HandlePost(string requestPath, Dictionary<string, string> variables)
|
||||
{
|
||||
switch (requestPath)
|
||||
{
|
||||
|
||||
case "/Tasks/CreateMonitorTask":
|
||||
variables.TryGetValue("connectorName", out string? connectorName1);
|
||||
variables.TryGetValue("internalId", out string? internalId1);
|
||||
variables.TryGetValue("reoccurrenceTime", out string? reoccurrenceTime1);
|
||||
variables.TryGetValue("language", out string? language1);
|
||||
variables.TryGetValue("ignoreChaptersBelow", out string? minChapter);
|
||||
if (connectorName1 is null || internalId1 is null || reoccurrenceTime1 is null)
|
||||
return;
|
||||
Connector? connector1 =
|
||||
_taskManager.GetAvailableConnectors().FirstOrDefault(con => con.Key == connectorName1).Value;
|
||||
if (connector1 is null)
|
||||
return;
|
||||
Publication? publication1 = _taskManager.GetAllPublications().FirstOrDefault(pub => pub.internalId == internalId1);
|
||||
if (!publication1.HasValue)
|
||||
return;
|
||||
Publication pPublication1 = (Publication)publication1;
|
||||
if (minChapter is not null)
|
||||
pPublication1.ignoreChaptersBelow = float.Parse(minChapter,new NumberFormatInfo() { NumberDecimalSeparator = "." });
|
||||
_taskManager.AddTask(new MonitorPublicationTask(connectorName1, pPublication1, TimeSpan.Parse(reoccurrenceTime1), language1 ?? "en"));
|
||||
break;
|
||||
case "/Tasks/CreateDownloadChaptersTask":
|
||||
variables.TryGetValue("connectorName", out string? connectorName2);
|
||||
variables.TryGetValue("internalId", out string? internalId2);
|
||||
variables.TryGetValue("chapters", out string? chapters);
|
||||
variables.TryGetValue("language", out string? language2);
|
||||
if (connectorName2 is null || internalId2 is null || chapters is null)
|
||||
return;
|
||||
Connector? connector2 =
|
||||
_taskManager.GetAvailableConnectors().FirstOrDefault(con => con.Key == connectorName2).Value;
|
||||
if (connector2 is null)
|
||||
return;
|
||||
Publication? publication2 = _taskManager.GetAllPublications().FirstOrDefault(pub => pub.internalId == internalId2);
|
||||
if (publication2 is null)
|
||||
return;
|
||||
|
||||
IEnumerable<Chapter> toDownload = connector2.SelectChapters((Publication)publication2, chapters, language2 ?? "en");
|
||||
foreach(Chapter chapter in toDownload)
|
||||
_taskManager.AddTask(new DownloadChapterTask(connectorName2, (Publication)publication2, chapter, "en"));
|
||||
break;
|
||||
case "/Tasks/Start":
|
||||
variables.TryGetValue("taskType", out string? taskType1);
|
||||
variables.TryGetValue("connectorName", out string? connectorName3);
|
||||
variables.TryGetValue("internalId", out string? internalId3);
|
||||
if (taskType1 is null)
|
||||
return;
|
||||
try
|
||||
{
|
||||
TrangaTask.Task pTask = Enum.Parse<TrangaTask.Task>(taskType1);
|
||||
TrangaTask? task = _taskManager
|
||||
.GetTasksMatching(pTask, connectorName: connectorName3, internalId: internalId3).FirstOrDefault();
|
||||
|
||||
if (task is null)
|
||||
return;
|
||||
_taskManager.ExecuteTaskNow(task);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case "/Queue/Enqueue":
|
||||
variables.TryGetValue("taskType", out string? taskType2);
|
||||
variables.TryGetValue("connectorName", out string? connectorName4);
|
||||
variables.TryGetValue("publicationId", out string? publicationId);
|
||||
if (taskType2 is null)
|
||||
return;
|
||||
try
|
||||
{
|
||||
TrangaTask.Task pTask = Enum.Parse<TrangaTask.Task>(taskType2);
|
||||
TrangaTask? task = _taskManager
|
||||
.GetTasksMatching(pTask, connectorName: connectorName4, internalId: publicationId).FirstOrDefault();
|
||||
|
||||
if (task is null)
|
||||
return;
|
||||
_taskManager.AddTaskToQueue(task);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case "/Settings/Update":
|
||||
variables.TryGetValue("downloadLocation", out string? downloadLocation);
|
||||
variables.TryGetValue("komgaUrl", out string? komgaUrl);
|
||||
variables.TryGetValue("komgaAuth", out string? komgaAuth);
|
||||
variables.TryGetValue("kavitaUrl", out string? kavitaUrl);
|
||||
variables.TryGetValue("kavitaUsername", out string? kavitaUsername);
|
||||
variables.TryGetValue("kavitaPassword", out string? kavitaPassword);
|
||||
variables.TryGetValue("gotifyUrl", out string? gotifyUrl);
|
||||
variables.TryGetValue("gotifyAppToken", out string? gotifyAppToken);
|
||||
variables.TryGetValue("lunaseaWebhook", out string? lunaseaWebhook);
|
||||
|
||||
if (downloadLocation is not null && downloadLocation.Length > 0)
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.DownloadLocation, downloadLocation);
|
||||
if (komgaUrl is not null && komgaAuth is not null && komgaUrl.Length > 5 && komgaAuth.Length > 0)
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.Komga, komgaUrl, komgaAuth);
|
||||
if (kavitaUrl is not null && kavitaPassword is not null && kavitaUsername is not null && kavitaUrl.Length > 5 &&
|
||||
kavitaUsername.Length > 0 && kavitaPassword.Length > 0)
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.Kavita, kavitaUrl, kavitaUsername,
|
||||
kavitaPassword);
|
||||
if (gotifyUrl is not null && gotifyAppToken is not null && gotifyUrl.Length > 5 && gotifyAppToken.Length > 0)
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.Gotify, gotifyUrl, gotifyAppToken);
|
||||
if(lunaseaWebhook is not null && lunaseaWebhook.Length > 5)
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.LunaSea, lunaseaWebhook);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private object? HandleGet(string requestPath, Dictionary<string, string> variables)
|
||||
{
|
||||
switch (requestPath)
|
||||
{
|
||||
case "/Connectors":
|
||||
return this._taskManager.GetAvailableConnectors().Keys.ToArray();
|
||||
case "/Publications/Known":
|
||||
variables.TryGetValue("internalId", out string? internalId1);
|
||||
if(internalId1 is null)
|
||||
return _taskManager.GetAllPublications();
|
||||
return new [] { _taskManager.GetAllPublications().FirstOrDefault(pub => pub.internalId == internalId1) };
|
||||
case "/Publications/FromConnector":
|
||||
variables.TryGetValue("connectorName", out string? connectorName1);
|
||||
variables.TryGetValue("title", out string? title);
|
||||
if (connectorName1 is null || title is null)
|
||||
return null;
|
||||
Connector? connector1 = _taskManager.GetAvailableConnectors().FirstOrDefault(con => con.Key == connectorName1).Value;
|
||||
if (connector1 is null)
|
||||
return null;
|
||||
if(title.Length < 4)
|
||||
return null;
|
||||
return connector1.GetPublications(ref _taskManager.collection, title);
|
||||
case "/Publications/Chapters":
|
||||
string[] yes = { "true", "yes", "1", "y" };
|
||||
variables.TryGetValue("connectorName", out string? connectorName2);
|
||||
variables.TryGetValue("internalId", out string? internalId2);
|
||||
variables.TryGetValue("onlyNew", out string? onlyNew);
|
||||
variables.TryGetValue("onlyExisting", out string? onlyExisting);
|
||||
variables.TryGetValue("language", out string? language);
|
||||
if (connectorName2 is null || internalId2 is null)
|
||||
return null;
|
||||
bool newOnly = onlyNew is not null && yes.Contains(onlyNew);
|
||||
bool existingOnly = onlyExisting is not null && yes.Contains(onlyExisting);
|
||||
|
||||
Connector? connector2 = _taskManager.GetAvailableConnectors().FirstOrDefault(con => con.Key == connectorName2).Value;
|
||||
if (connector2 is null)
|
||||
return null;
|
||||
Publication? publication = _taskManager.GetAllPublications().FirstOrDefault(pub => pub.internalId == internalId2);
|
||||
if (publication is null)
|
||||
return null;
|
||||
|
||||
if(newOnly)
|
||||
return connector2.GetNewChaptersList((Publication)publication, language??"en", ref _taskManager.collection).ToArray();
|
||||
else if (existingOnly)
|
||||
return _taskManager.GetExistingChaptersList(connector2, (Publication)publication, language ?? "en").ToArray();
|
||||
else
|
||||
return connector2.GetChapters((Publication)publication, language??"en");
|
||||
case "/Tasks/Types":
|
||||
return Enum.GetNames(typeof(TrangaTask.Task));
|
||||
case "/Tasks":
|
||||
variables.TryGetValue("taskType", out string? taskType1);
|
||||
variables.TryGetValue("connectorName", out string? connectorName3);
|
||||
variables.TryGetValue("searchString", out string? searchString);
|
||||
if (taskType1 is null)
|
||||
return null;
|
||||
try
|
||||
{
|
||||
TrangaTask.Task task = Enum.Parse<TrangaTask.Task>(taskType1);
|
||||
return _taskManager.GetTasksMatching(task, connectorName:connectorName3, searchString:searchString);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
case "/Tasks/Progress":
|
||||
variables.TryGetValue("taskType", out string? taskType2);
|
||||
variables.TryGetValue("connectorName", out string? connectorName4);
|
||||
variables.TryGetValue("publicationId", out string? publicationId);
|
||||
variables.TryGetValue("chapterNumber", out string? chapterNumber);
|
||||
if (taskType2 is null || connectorName4 is null || publicationId is null)
|
||||
return null;
|
||||
Connector? connector =
|
||||
_taskManager.GetAvailableConnectors().FirstOrDefault(con => con.Key == connectorName4).Value;
|
||||
if (connector is null)
|
||||
return null;
|
||||
try
|
||||
{
|
||||
TrangaTask? task = null;
|
||||
TrangaTask.Task pTask = Enum.Parse<TrangaTask.Task>(taskType2);
|
||||
if (pTask is TrangaTask.Task.MonitorPublication)
|
||||
{
|
||||
task = _taskManager.GetTasksMatching(pTask, connectorName: connectorName4, internalId: publicationId).FirstOrDefault();
|
||||
}else if (pTask is TrangaTask.Task.DownloadChapter && chapterNumber is not null)
|
||||
{
|
||||
task = _taskManager.GetTasksMatching(pTask, connectorName: connectorName4, internalId: publicationId,
|
||||
chapterNumber: chapterNumber).FirstOrDefault();
|
||||
}
|
||||
if (task is null)
|
||||
return null;
|
||||
|
||||
return task.progress;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
case "/Tasks/RunningTasks":
|
||||
return _taskManager.GetAllTasks().Where(task => task.state is TrangaTask.ExecutionState.Running);
|
||||
case "/Queue/List":
|
||||
return _taskManager.GetAllTasks().Where(task => task.state is TrangaTask.ExecutionState.Enqueued).OrderBy(task => task.nextExecution);
|
||||
case "/Settings":
|
||||
return _taskManager.settings;
|
||||
case "/":
|
||||
default:
|
||||
return this._validRequestPaths;
|
||||
}
|
||||
}
|
||||
}
|
90
API/Server.cs
Normal file
@ -0,0 +1,90 @@
|
||||
using System.Net;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Tranga;
|
||||
|
||||
namespace API;
|
||||
|
||||
public class Server
|
||||
{
|
||||
private readonly HttpListener _listener = new ();
|
||||
private readonly RequestHandler _requestHandler;
|
||||
internal readonly Logger? logger;
|
||||
|
||||
private readonly Regex _validUrl =
|
||||
new (@"https?:\/\/(www\.)?[-A-z0-9]{1,256}(\.[-a-zA-Z0-9]{1,6})?(:[0-9]{1,5})?(\/{1}[A-z0-9()@:%_\+.~#?&=]+)*\/?");
|
||||
public Server(int port, TaskManager taskManager, Logger? logger = null)
|
||||
{
|
||||
this.logger = logger;
|
||||
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
this._listener.Prefixes.Add($"http://*:{port}/");
|
||||
else
|
||||
this._listener.Prefixes.Add($"http://localhost:{port}/");
|
||||
this._requestHandler = new RequestHandler(taskManager, this);
|
||||
Listen();
|
||||
}
|
||||
|
||||
private void Listen()
|
||||
{
|
||||
this._listener.Start();
|
||||
foreach (string prefix in this._listener.Prefixes)
|
||||
this.logger?.WriteLine(this.GetType().ToString(), $"Listening on {prefix}");
|
||||
while (this._listener.IsListening)
|
||||
{
|
||||
HttpListenerContext context = this._listener.GetContextAsync().Result;
|
||||
Task t = new (() =>
|
||||
{
|
||||
HandleContext(context);
|
||||
});
|
||||
t.Start();
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleContext(HttpListenerContext context)
|
||||
{
|
||||
HttpListenerRequest request = context.Request;
|
||||
HttpListenerResponse response = context.Response;
|
||||
//logger?.WriteLine(this.GetType().ToString(), $"New request: {request.HttpMethod} {request.Url}");
|
||||
|
||||
if (!_validUrl.IsMatch(request.Url!.ToString()))
|
||||
{
|
||||
SendResponse(HttpStatusCode.BadRequest, response);
|
||||
return;
|
||||
}
|
||||
|
||||
if (request.HttpMethod == "OPTIONS")
|
||||
{
|
||||
SendResponse(HttpStatusCode.OK, response);
|
||||
}
|
||||
else
|
||||
{
|
||||
_requestHandler.HandleRequest(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
internal void SendResponse(HttpStatusCode statusCode, HttpListenerResponse response, object? content = null)
|
||||
{
|
||||
//logger?.WriteLine(this.GetType().ToString(), $"Sending response: {statusCode}");
|
||||
response.StatusCode = (int)statusCode;
|
||||
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
|
||||
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, DELETE");
|
||||
response.AddHeader("Access-Control-Max-Age", "1728000");
|
||||
response.AppendHeader("Access-Control-Allow-Origin", "*");
|
||||
response.ContentType = "application/json";
|
||||
try
|
||||
{
|
||||
response.OutputStream.Write(content is not null
|
||||
? Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(content))
|
||||
: Array.Empty<byte>());
|
||||
}
|
||||
catch (HttpListenerException)
|
||||
{
|
||||
|
||||
}
|
||||
response.OutputStream.Close();
|
||||
|
||||
}
|
||||
}
|
@ -1,4 +1,8 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:7.0 as runtime
|
||||
#FROM mcr.microsoft.com/dotnet/aspnet:7.0 as runtime
|
||||
FROM mcr.microsoft.com/dotnet/runtime:7.0 as runtime
|
||||
WORKDIR /publish
|
||||
RUN apt-get update && apt-get install -y libx11-6 libx11-xcb1 libatk1.0-0 libgtk-3-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2 libxshmfence1 libnss3
|
||||
RUN apt-get update
|
||||
RUN apt-get install -y libx11-6 libx11-xcb1 libatk1.0-0 libgtk-3-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2 libxshmfence1 libnss3
|
||||
RUN apt-get autopurge -y
|
||||
RUN apt-get autoclean -y
|
@ -1,5 +1,4 @@
|
||||
using System.Text;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Logging;
|
||||
|
||||
@ -8,7 +7,7 @@ public class FileLogger : LoggerBase
|
||||
private string logFilePath { get; }
|
||||
private const int MaxNumberOfLogFiles = 5;
|
||||
|
||||
public FileLogger(string logFilePath, TextWriter? stdOut, Encoding? encoding = null) : base (stdOut, encoding)
|
||||
public FileLogger(string logFilePath, Encoding? encoding = null) : base (encoding)
|
||||
{
|
||||
this.logFilePath = logFilePath;
|
||||
|
||||
@ -22,11 +21,11 @@ public class FileLogger : LoggerBase
|
||||
{
|
||||
try
|
||||
{
|
||||
File.AppendAllText(logFilePath, logMessage.ToString());
|
||||
File.AppendAllText(logFilePath, logMessage.formattedMessage);
|
||||
}
|
||||
catch (Exception e)
|
||||
catch (Exception)
|
||||
{
|
||||
stdOut?.WriteLine(e);
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
}
|
@ -4,14 +4,14 @@ namespace Logging;
|
||||
|
||||
public class FormattedConsoleLogger : LoggerBase
|
||||
{
|
||||
|
||||
public FormattedConsoleLogger(TextWriter? stdOut, Encoding? encoding = null) : base(stdOut, encoding)
|
||||
private readonly TextWriter _stdOut;
|
||||
public FormattedConsoleLogger(TextWriter stdOut, Encoding? encoding = null) : base(encoding)
|
||||
{
|
||||
|
||||
this._stdOut = stdOut;
|
||||
}
|
||||
|
||||
protected override void Write(LogMessage message)
|
||||
{
|
||||
//Nothing to do yet
|
||||
this._stdOut.Write(message.formattedMessage);
|
||||
}
|
||||
}
|
23
Logging/LogMessage.cs
Normal file
@ -0,0 +1,23 @@
|
||||
namespace Logging;
|
||||
|
||||
public class LogMessage
|
||||
{
|
||||
public DateTime logTime { get; }
|
||||
public string caller { get; }
|
||||
public string value { get; }
|
||||
public string formattedMessage => ToString();
|
||||
|
||||
public LogMessage(DateTime messageTime, string caller, string value)
|
||||
{
|
||||
this.logTime = messageTime;
|
||||
this.caller = caller;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string dateTimeString = $"{logTime.ToShortDateString()} {logTime.ToLongTimeString()}.{logTime.Millisecond,-3}";
|
||||
string name = caller.Split(new char[] { '.', '+' }).Last();
|
||||
return $"[{dateTimeString}] {name.Substring(0, name.Length >= 13 ? 13 : name.Length),13} | {value}";
|
||||
}
|
||||
}
|
@ -1,5 +1,4 @@
|
||||
using System.Net.Mime;
|
||||
using System.Text;
|
||||
using System.Text;
|
||||
|
||||
namespace Logging;
|
||||
|
||||
@ -12,24 +11,31 @@ public class Logger : TextWriter
|
||||
ConsoleLogger
|
||||
}
|
||||
|
||||
private FileLogger? _fileLogger;
|
||||
private FormattedConsoleLogger? _formattedConsoleLogger;
|
||||
private MemoryLogger _memoryLogger;
|
||||
private TextWriter? stdOut;
|
||||
private readonly FileLogger? _fileLogger;
|
||||
private readonly FormattedConsoleLogger? _formattedConsoleLogger;
|
||||
private readonly MemoryLogger _memoryLogger;
|
||||
|
||||
public Logger(LoggerType[] enabledLoggers, TextWriter? stdOut, Encoding? encoding, string? logFilePath)
|
||||
{
|
||||
this.Encoding = encoding ?? Encoding.ASCII;
|
||||
this.stdOut = stdOut ?? null;
|
||||
if (enabledLoggers.Contains(LoggerType.FileLogger) && logFilePath is not null)
|
||||
_fileLogger = new FileLogger(logFilePath, null, encoding);
|
||||
_fileLogger = new FileLogger(logFilePath, encoding);
|
||||
else
|
||||
{
|
||||
_fileLogger = null;
|
||||
throw new ArgumentException($"logFilePath can not be null for LoggerType {LoggerType.FileLogger}");
|
||||
}
|
||||
_formattedConsoleLogger = enabledLoggers.Contains(LoggerType.ConsoleLogger) ? new FormattedConsoleLogger(null, encoding) : null;
|
||||
_memoryLogger = new MemoryLogger(null, encoding);
|
||||
|
||||
if (enabledLoggers.Contains(LoggerType.ConsoleLogger) && stdOut is not null)
|
||||
{
|
||||
_formattedConsoleLogger = new FormattedConsoleLogger(stdOut, encoding);
|
||||
}
|
||||
else
|
||||
{
|
||||
_formattedConsoleLogger = null;
|
||||
throw new ArgumentException($"stdOut can not be null for LoggerType {LoggerType.ConsoleLogger}");
|
||||
}
|
||||
_memoryLogger = new MemoryLogger(encoding);
|
||||
}
|
||||
|
||||
public void WriteLine(string caller, string? value)
|
||||
@ -46,9 +52,7 @@ public class Logger : TextWriter
|
||||
|
||||
_fileLogger?.Write(caller, value);
|
||||
_formattedConsoleLogger?.Write(caller, value);
|
||||
|
||||
_memoryLogger.Write(caller, value);
|
||||
stdOut?.Write(value);
|
||||
}
|
||||
|
||||
public string[] Tail(uint? lines)
|
||||
|
@ -5,21 +5,10 @@ namespace Logging;
|
||||
public abstract class LoggerBase : TextWriter
|
||||
{
|
||||
public override Encoding Encoding { get; }
|
||||
protected TextWriter? stdOut { get; }
|
||||
|
||||
public LoggerBase(TextWriter? stdOut, Encoding? encoding = null)
|
||||
public LoggerBase(Encoding? encoding = null)
|
||||
{
|
||||
this.Encoding = encoding ?? Encoding.ASCII;
|
||||
this.stdOut = stdOut;
|
||||
}
|
||||
|
||||
public void WriteLine(string caller, string? value)
|
||||
{
|
||||
value = value is null ? Environment.NewLine : string.Join(value, Environment.NewLine);
|
||||
|
||||
LogMessage message = new LogMessage(DateTime.Now, caller, value);
|
||||
|
||||
Write(message);
|
||||
}
|
||||
|
||||
public void Write(string caller, string? value)
|
||||
@ -27,32 +16,10 @@ public abstract class LoggerBase : TextWriter
|
||||
if (value is null)
|
||||
return;
|
||||
|
||||
LogMessage message = new LogMessage(DateTime.Now, caller, value);
|
||||
|
||||
stdOut?.Write(message.ToString());
|
||||
LogMessage message = new (DateTime.Now, caller, value);
|
||||
|
||||
Write(message);
|
||||
}
|
||||
|
||||
protected abstract void Write(LogMessage message);
|
||||
|
||||
public class LogMessage
|
||||
{
|
||||
public DateTime logTime { get; }
|
||||
public string caller { get; }
|
||||
public string value { get; }
|
||||
|
||||
public LogMessage(DateTime now, string caller, string value)
|
||||
{
|
||||
this.logTime = now;
|
||||
this.caller = caller;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string dateTimeString = $"{logTime.ToShortDateString()} {logTime.ToLongTimeString()}";
|
||||
return $"[{dateTimeString}] {caller.Split(new char[]{'.','+'}).Last(),15} | {value}";
|
||||
}
|
||||
}
|
||||
}
|
@ -7,14 +7,15 @@ public class MemoryLogger : LoggerBase
|
||||
private readonly SortedList<DateTime, LogMessage> _logMessages = new();
|
||||
private int _lastLogMessageIndex = 0;
|
||||
|
||||
public MemoryLogger(TextWriter? stdOut, Encoding? encoding = null) : base(stdOut, encoding)
|
||||
public MemoryLogger(Encoding? encoding = null) : base(encoding)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
protected override void Write(LogMessage value)
|
||||
{
|
||||
_logMessages.Add(value.logTime, value);
|
||||
while(!_logMessages.TryAdd(value.logTime, value))
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
|
||||
public string[] GetLogMessage()
|
||||
|
37
README.md
@ -52,14 +52,15 @@
|
||||
<!-- ABOUT THE PROJECT -->
|
||||
## About The Project
|
||||
|
||||
Tranga can download Chapters and Metadata from Scanlation sites such as
|
||||
Tranga can download Chapters and Metadata from "Scanlation" sites such as
|
||||
|
||||
- [MangaDex.org](https://mangadex.org/)
|
||||
- [Manganato.com](https://manganato.com/)
|
||||
- [Mangasee](https://mangasee123.com/)
|
||||
- [MangaKatana](https://mangakatana.com)
|
||||
- ❓ Open an [issue](https://github.com/C9Glax/tranga/issues)
|
||||
|
||||
and automatically start updates in [Komga](https://komga.org/) and [Kavita](https://www.kavitareader.com/) to import them.
|
||||
|
||||
and automatically import them with [Komga](https://komga.org/) and [Kavita](https://www.kavitareader.com/). Also Notifications will be sent to your devices using [Gotify](https://gotify.net/) and [LunaSea](https://www.lunasea.app/).
|
||||
### Inspiration:
|
||||
|
||||
Because [Kaizoku](https://github.com/oae/kaizoku) was relying on [mangal](https://github.com/metafates/mangal) and mangal
|
||||
@ -76,19 +77,18 @@ That is why I wanted to create my own project, in a language I understand, and t
|
||||
- Newtonsoft.JSON
|
||||
- [PuppeteerSharp](https://www.puppeteersharp.com/)
|
||||
- [Html Agility Pack (HAP)](https://html-agility-pack.net/)
|
||||
- Love <3 Blåhaj 🦈
|
||||
- 💙 Blåhaj 🦈
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
|
||||
## Screenshots
|
||||
|
||||

|
||||
|  |  |
|
||||
|-----------------------------------:|:----------------------------------|
|
||||
|
||||

|
||||
|
||||
|  |  |
|
||||
|-----------------------------------:|:-------------------------------------------------:|
|
||||
|  |  |  |
|
||||
|-----------------------------------:|:-------------------------------------------------:|:-----------------------------------|
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
@ -110,39 +110,42 @@ Download [docker-compose.yaml](https://git.bernloehr.eu/glax/Tranga/src/branch/m
|
||||
|
||||
Wherever you are mounting `/usr/share/Tranga-API` you also need to mount that same path + `/imageCache` in the webserver container.
|
||||
|
||||
### Usage
|
||||
### Docker-Website usage
|
||||
|
||||
There is two ways to download Mangas:
|
||||
- Downloading everything and monitor for new Chapters
|
||||
- Selecting specific Volumes/Chapters
|
||||
|
||||
On the website you add new tasks, by selecting the blue '+' field. Next select the connector/site you want to use, and enter a search term.
|
||||
After pressing 'Search', the results will be presented below - this might, depending on the result-size, take a while.
|
||||
Next select the publication and a new popup will open with two options:
|
||||
After clicking 'Search' (or pressing Enter), the results will be presented below - this might, depending on the result-size, take a while because we are already preloading the cover-images.
|
||||
Next select the publication (by selecting the cover) and a new popup will open with two options:
|
||||
- "Monitor" - Download all chapters and monitor for new ones
|
||||
- "Download Chapter" - Download specific chapters only
|
||||
|
||||
When selecting `Monitor` you will be presented with a new window and the selection of the interval you want to check for new chapters.
|
||||
When selecting `Download Chapter` a list will open with all available chapters from which you can then select a range.
|
||||
When selecting `Monitor` you will be presented with a new window and the selection of the interval you want to check for new chapters (Default: Every 3 hours).
|
||||
When selecting `Download Chapter` a list will open with all available chapters - that have not yet been downloaded - from which you can then select a range (see below).
|
||||
|
||||
The syntax for selecting chapters is as follows:
|
||||
- To download a single Chapter enter either the index number (the number at the very start of the line) or its absolute number like so: `c(h)(apter)[number]`, spaces are allowed.
|
||||
- To download a range of chapters enter either a range of index numbers (`3-6`) or chapters (`ch 12-23`).
|
||||
- For volumes the syntax is as follows: `v(ol)[number](-[number])`, again spaces allowed.
|
||||
|
||||
Examples: `2-12`, `c1`, `ch 2`, `chapter 3`, `v 2`, `vol3-4`, `v2c4` (note: you can only specify a single chapter with this syntax).
|
||||
Examples: `2-12`, `c1`, `ch 2`, `chapter 3`, `v 2`, `vol3-4`, `v2c4` (note: you can only specify a single chapter with this last syntax).
|
||||
|
||||
### Prerequisites
|
||||
|
||||
#### To Build
|
||||
[.NET-Core 7.0 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/7.0)
|
||||
#### To Run
|
||||
[.NET-Core 7.0 Runtime](https://dotnet.microsoft.com/en-us/download/dotnet/7.0) scroll down a bit, should be on the right the second item.
|
||||
|
||||
<!-- ROADMAP -->
|
||||
## Roadmap
|
||||
|
||||
- [ ] Docker ARM support
|
||||
- [ ] ?
|
||||
- [ ] ❓
|
||||
|
||||
See the [open issues](https://git.bernloehr.eu/glax/Tranga/issues) for a full list of proposed features (and known issues).
|
||||
See the [open issues](https://github.com/C9Glax/tranga/issues) for a full list of proposed features (and known issues).
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
|
@ -1,243 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Logging;
|
||||
using Tranga;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
string applicationFolderPath = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Tranga-API");
|
||||
string downloadFolderPath = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "/Manga" : Path.Join(applicationFolderPath, "Manga");
|
||||
string logsFolderPath = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "/var/logs/Tranga" : Path.Join(applicationFolderPath, "logs");
|
||||
string logFilePath = Path.Join(logsFolderPath, $"log-{DateTime.Now:dd-M-yyyy-HH-mm-ss}.txt");
|
||||
string settingsFilePath = Path.Join(applicationFolderPath, "settings.json");
|
||||
|
||||
Directory.CreateDirectory(logsFolderPath);
|
||||
Logger logger = new(new[] { Logger.LoggerType.FileLogger, Logger.LoggerType.ConsoleLogger }, Console.Out, Console.Out.Encoding, logFilePath);
|
||||
|
||||
logger.WriteLine("Tranga", "Loading settings.");
|
||||
|
||||
TrangaSettings settings;
|
||||
if (File.Exists(settingsFilePath))
|
||||
settings = TrangaSettings.LoadSettings(settingsFilePath, logger);
|
||||
else
|
||||
settings = new TrangaSettings(downloadFolderPath, applicationFolderPath, new HashSet<LibraryManager>());
|
||||
|
||||
Directory.CreateDirectory(settings.workingDirectory);
|
||||
Directory.CreateDirectory(settings.downloadLocation);
|
||||
Directory.CreateDirectory(settings.coverImageCache);
|
||||
|
||||
logger.WriteLine("Tranga",$"Application-Folder: {settings.workingDirectory}");
|
||||
logger.WriteLine("Tranga",$"Settings-File-Path: {settings.settingsFilePath}");
|
||||
logger.WriteLine("Tranga",$"Download-Folder-Path: {settings.downloadLocation}");
|
||||
logger.WriteLine("Tranga",$"Logfile-Path: {logFilePath}");
|
||||
logger.WriteLine("Tranga",$"Image-Cache-Path: {settings.coverImageCache}");
|
||||
|
||||
logger.WriteLine("Tranga", "Loading Taskmanager.");
|
||||
TaskManager taskManager = new (settings, logger);
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
builder.Services.AddControllers().AddNewtonsoftJson();
|
||||
|
||||
string corsHeader = "Tranga";
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy(name: corsHeader,
|
||||
policy =>
|
||||
{
|
||||
policy.AllowAnyOrigin();
|
||||
policy.WithMethods("GET", "POST", "DELETE");
|
||||
});
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
|
||||
app.UseCors(corsHeader);
|
||||
|
||||
app.MapGet("/Controllers/Get", () => taskManager.GetAvailableConnectors().Keys.ToArray());
|
||||
|
||||
app.MapGet("/Publications/GetKnown", (string? internalId) =>
|
||||
{
|
||||
if(internalId is null)
|
||||
return taskManager.GetAllPublications();
|
||||
|
||||
return new [] { taskManager.GetAllPublications().FirstOrDefault(pub => pub.internalId == internalId) };
|
||||
});
|
||||
|
||||
app.MapGet("/Publications/GetFromConnector", (string connectorName, string title) =>
|
||||
{
|
||||
Connector? connector = taskManager.GetAvailableConnectors().FirstOrDefault(con => con.Key == connectorName).Value;
|
||||
if (connector is null)
|
||||
return Array.Empty<Publication>();
|
||||
if(title.Length < 4)
|
||||
return Array.Empty<Publication>();
|
||||
return taskManager.GetPublicationsFromConnector(connector, title);
|
||||
});
|
||||
|
||||
app.MapGet("/Publications/GetChapters", (string connectorName, string internalId, string? language) =>
|
||||
{
|
||||
Connector? connector = taskManager.GetAvailableConnectors().FirstOrDefault(con => con.Key == connectorName).Value;
|
||||
if (connector is null)
|
||||
return Array.Empty<Chapter>();
|
||||
Publication? publication = taskManager.GetAllPublications().FirstOrDefault(pub => pub.internalId == internalId);
|
||||
if (publication is null)
|
||||
return Array.Empty<Chapter>();
|
||||
return connector.GetChapters((Publication)publication, language??"en");
|
||||
});
|
||||
|
||||
app.MapGet("/Tasks/GetTypes", () => Enum.GetNames(typeof(TrangaTask.Task)));
|
||||
|
||||
|
||||
app.MapPost("/Tasks/CreateMonitorTask",
|
||||
(string connectorName, string internalId, string reoccurrenceTime, string? language) =>
|
||||
{
|
||||
Connector? connector =
|
||||
taskManager.GetAvailableConnectors().FirstOrDefault(con => con.Key == connectorName).Value;
|
||||
if (connector is null)
|
||||
return;
|
||||
Publication? publication = taskManager.GetAllPublications().FirstOrDefault(pub => pub.internalId == internalId);
|
||||
if (publication is null)
|
||||
return;
|
||||
taskManager.AddTask(new DownloadNewChaptersTask(TrangaTask.Task.DownloadNewChapters, connectorName,
|
||||
(Publication)publication,
|
||||
TimeSpan.Parse(reoccurrenceTime), language ?? "en"));
|
||||
});
|
||||
|
||||
app.MapPost("/Tasks/CreateUpdateLibraryTask", (string reoccurrenceTime) =>
|
||||
{
|
||||
taskManager.AddTask(new UpdateLibrariesTask(TrangaTask.Task.UpdateLibraries, TimeSpan.Parse(reoccurrenceTime)));
|
||||
});
|
||||
|
||||
app.MapPost("/Tasks/CreateDownloadChaptersTask", (string connectorName, string internalId, string chapters, string? language) => {
|
||||
|
||||
Connector? connector =
|
||||
taskManager.GetAvailableConnectors().FirstOrDefault(con => con.Key == connectorName).Value;
|
||||
if (connector is null)
|
||||
return;
|
||||
Publication? publication = taskManager.GetAllPublications().FirstOrDefault(pub => pub.internalId == internalId);
|
||||
if (publication is null)
|
||||
return;
|
||||
|
||||
IEnumerable<Chapter> toDownload = connector.SearchChapters((Publication)publication, chapters, language ?? "en");
|
||||
foreach(Chapter chapter in toDownload)
|
||||
taskManager.AddTask(new DownloadChapterTask(TrangaTask.Task.DownloadChapter, connectorName,
|
||||
(Publication)publication, chapter, "en"));
|
||||
});
|
||||
|
||||
app.MapDelete("/Tasks/Delete", (string taskType, string? connectorName, string? publicationId) =>
|
||||
{
|
||||
TrangaTask.Task task = Enum.Parse<TrangaTask.Task>(taskType);
|
||||
taskManager.DeleteTask(task, connectorName, publicationId);
|
||||
});
|
||||
|
||||
app.MapGet("/Tasks/Get", (string taskType, string? connectorName, string? searchString) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
TrangaTask.Task task = Enum.Parse<TrangaTask.Task>(taskType);
|
||||
return taskManager.GetTasksMatching(task, connectorName:connectorName, searchString:searchString);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return Array.Empty<TrangaTask>();
|
||||
}
|
||||
});
|
||||
|
||||
app.MapGet("/Tasks/GetProgress", (string taskType, string connectorName, string publicationId, string? chapterSortNumber) =>
|
||||
{
|
||||
Connector? connector =
|
||||
taskManager.GetAvailableConnectors().FirstOrDefault(con => con.Key == connectorName).Value;
|
||||
if (connector is null)
|
||||
return -1f;
|
||||
try
|
||||
{
|
||||
TrangaTask? task = null;
|
||||
TrangaTask.Task pTask = Enum.Parse<TrangaTask.Task>(taskType);
|
||||
if (pTask is TrangaTask.Task.DownloadNewChapters)
|
||||
{
|
||||
task = taskManager.GetTasksMatching(pTask, connectorName: connectorName, internalId: publicationId).FirstOrDefault();
|
||||
}else if (pTask is TrangaTask.Task.DownloadChapter && chapterSortNumber is not null)
|
||||
{
|
||||
task = taskManager.GetTasksMatching(pTask, connectorName: connectorName, internalId: publicationId,
|
||||
chapterSortNumber: chapterSortNumber).FirstOrDefault();
|
||||
}
|
||||
if (task is null)
|
||||
return -1f;
|
||||
|
||||
return task.progress;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return -1f;
|
||||
}
|
||||
});
|
||||
|
||||
app.MapPost("/Tasks/Start", (string taskType, string? connectorName, string? internalId) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
TrangaTask.Task pTask = Enum.Parse<TrangaTask.Task>(taskType);
|
||||
TrangaTask? task = taskManager
|
||||
.GetTasksMatching(pTask, connectorName: connectorName, internalId: internalId)?.FirstOrDefault();
|
||||
|
||||
if (task is null)
|
||||
return;
|
||||
taskManager.ExecuteTaskNow(task);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
app.MapGet("/Tasks/GetRunningTasks",
|
||||
() => taskManager.GetAllTasks().Where(task => task.state is TrangaTask.ExecutionState.Running));
|
||||
|
||||
app.MapGet("/Queue/GetList",
|
||||
() => taskManager.GetAllTasks().Where(task => task.state is TrangaTask.ExecutionState.Enqueued).OrderBy(task => task.nextExecution));
|
||||
|
||||
app.MapPost("/Queue/Enqueue", (string taskType, string? connectorName, string? publicationId) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
TrangaTask.Task pTask = Enum.Parse<TrangaTask.Task>(taskType);
|
||||
TrangaTask? task = taskManager
|
||||
.GetTasksMatching(pTask, connectorName: connectorName, internalId: publicationId)?.First();
|
||||
|
||||
if (task is null)
|
||||
return;
|
||||
taskManager.AddTaskToQueue(task);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
app.MapDelete("/Queue/Dequeue", (string taskType, string? connectorName, string? publicationId) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
TrangaTask.Task pTask = Enum.Parse<TrangaTask.Task>(taskType);
|
||||
TrangaTask? task = taskManager
|
||||
.GetTasksMatching(pTask, connectorName: connectorName, internalId: publicationId)?.First();
|
||||
|
||||
if (task is null)
|
||||
return;
|
||||
taskManager.RemoveTaskFromQueue(task);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
app.MapGet("/Settings/Get", () => taskManager.settings);
|
||||
|
||||
app.MapPost("/Settings/Update",
|
||||
(string? downloadLocation, string? komgaUrl, string? komgaAuth, string? kavitaUrl, string? kavitaUsername, string? kavitaPassword) =>
|
||||
taskManager.UpdateSettings(downloadLocation, komgaUrl, komgaAuth, kavitaUrl, kavitaUsername, kavitaPassword));
|
||||
|
||||
app.Run();
|
@ -1,28 +0,0 @@
|
||||
{
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:1716",
|
||||
"sslPort": 44391
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "http://localhost:5177"
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "https://localhost:7036;http://localhost:5177"
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true
|
||||
}
|
||||
}
|
||||
}
|
@ -1,8 +0,0 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
@ -9,12 +9,6 @@
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="..\.dockerignore">
|
||||
<Link>.dockerignore</Link>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Tranga\Tranga.csproj" />
|
||||
</ItemGroup>
|
||||
|
@ -1,7 +1,9 @@
|
||||
using System.Globalization;
|
||||
using Logging;
|
||||
using Tranga;
|
||||
using Tranga.Connectors;
|
||||
using Tranga.LibraryManagers;
|
||||
using Tranga.NotificationManagers;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
namespace Tranga_CLI;
|
||||
@ -30,16 +32,16 @@ public static class Tranga_Cli
|
||||
Logger logger = new(new[] { Logger.LoggerType.FileLogger }, null, Console.Out.Encoding, logFilePath);
|
||||
|
||||
logger.WriteLine("Tranga_CLI", "Loading Taskmanager.");
|
||||
TrangaSettings settings = File.Exists(settingsFilePath) ? TrangaSettings.LoadSettings(settingsFilePath, logger) : new TrangaSettings(Directory.GetCurrentDirectory(), applicationFolderPath, new HashSet<LibraryManager>());
|
||||
TrangaSettings settings = File.Exists(settingsFilePath) ? TrangaSettings.LoadSettings(settingsFilePath, logger) : new TrangaSettings(Directory.GetCurrentDirectory(), applicationFolderPath, new HashSet<LibraryManager>(), new HashSet<NotificationManager>(), logger);
|
||||
|
||||
|
||||
logger.WriteLine("Tranga_CLI", "User Input");
|
||||
settings.logger?.WriteLine("Tranga_CLI", "User Input");
|
||||
Console.WriteLine($"Output folder path [{settings.downloadLocation}]:");
|
||||
string? tmpPath = Console.ReadLine();
|
||||
while(tmpPath is null)
|
||||
tmpPath = Console.ReadLine();
|
||||
if (tmpPath.Length > 0)
|
||||
settings.downloadLocation = tmpPath;
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.DownloadLocation, tmpPath);
|
||||
|
||||
Console.WriteLine($"Komga BaseURL [{settings.libraryManagers.FirstOrDefault(lm => lm.GetType() == typeof(Komga))?.baseUrl}]:");
|
||||
string? tmpUrlKomga = Console.ReadLine();
|
||||
@ -72,8 +74,7 @@ public static class Tranga_Cli
|
||||
}
|
||||
} while (key != ConsoleKey.Enter);
|
||||
|
||||
settings.libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Komga));
|
||||
settings.libraryManagers.Add(new Komga(tmpUrlKomga, tmpKomgaUser, tmpKomgaPass, logger));
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Komga, tmpUrlKomga, tmpKomgaUser, tmpKomgaPass);
|
||||
}
|
||||
|
||||
Console.WriteLine($"Kavita BaseURL [{settings.libraryManagers.FirstOrDefault(lm => lm.GetType() == typeof(Kavita))?.baseUrl}]:");
|
||||
@ -107,17 +108,32 @@ public static class Tranga_Cli
|
||||
}
|
||||
} while (key != ConsoleKey.Enter);
|
||||
|
||||
settings.libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Kavita));
|
||||
settings.libraryManagers.Add(new Kavita(tmpUrlKavita, tmpKavitaUser, tmpKavitaPass, logger));
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Kavita, tmpUrlKavita, tmpKavitaUser, tmpKavitaPass);
|
||||
}
|
||||
|
||||
Console.WriteLine($"Gotify BaseURL [{((Gotify?)settings.notificationManagers.FirstOrDefault(lm => lm.GetType() == typeof(Gotify)))?.endpoint}]:");
|
||||
string? tmpGotifyUrl = Console.ReadLine();
|
||||
while (tmpGotifyUrl is null)
|
||||
tmpGotifyUrl = Console.ReadLine();
|
||||
if (tmpGotifyUrl.Length > 0)
|
||||
{
|
||||
Console.WriteLine("AppToken:");
|
||||
string? tmpGotifyAppToken = Console.ReadLine();
|
||||
while (tmpGotifyAppToken is null || tmpGotifyAppToken.Length < 1)
|
||||
tmpGotifyAppToken = Console.ReadLine();
|
||||
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Gotify, tmpGotifyUrl, tmpGotifyAppToken);
|
||||
}
|
||||
|
||||
logger.WriteLine("Tranga_CLI", "Loaded.");
|
||||
foreach(NotificationManager nm in settings.notificationManagers)
|
||||
nm.SendNotification("Tranga", "Loaded.");
|
||||
TaskMode(settings, logger);
|
||||
}
|
||||
|
||||
private static void TaskMode(TrangaSettings settings, Logger logger)
|
||||
{
|
||||
TaskManager taskManager = new (settings, logger);
|
||||
TaskManager taskManager = new (settings);
|
||||
ConsoleKey selection = ConsoleKey.EraseEndOfFile;
|
||||
PrintMenu(taskManager, taskManager.settings.downloadLocation);
|
||||
while (selection != ConsoleKey.Q)
|
||||
@ -320,8 +336,9 @@ public static class Tranga_Cli
|
||||
|
||||
TimeSpan reoccurrence = SelectReoccurrence(logger);
|
||||
logger.WriteLine("Tranga_CLI", "Sending Task to TaskManager");
|
||||
TrangaTask? newTask = taskManager.AddTask(TrangaTask.Task.DownloadNewChapters, connector.name, publication.Value.publicationId, reoccurrence, "en");
|
||||
Console.WriteLine(newTask);
|
||||
TrangaTask nTask = new MonitorPublicationTask(connector.name, (Publication)publication, reoccurrence, "en");
|
||||
taskManager.AddTask(nTask);
|
||||
Console.WriteLine(nTask);
|
||||
}
|
||||
|
||||
private static void AddTaskToQueue(TaskManager taskManager, Logger logger)
|
||||
@ -393,20 +410,19 @@ public static class Tranga_Cli
|
||||
return;
|
||||
}
|
||||
|
||||
if (task is TrangaTask.Task.DownloadNewChapters)
|
||||
if (task is TrangaTask.Task.MonitorPublication)
|
||||
{
|
||||
TimeSpan reoccurrence = SelectReoccurrence(logger);
|
||||
logger.WriteLine("Tranga_CLI", "Sending Task to TaskManager");
|
||||
|
||||
TrangaTask newTask = new DownloadNewChaptersTask(TrangaTask.Task.DownloadNewChapters, connector!.name, (Publication)publication!, reoccurrence, "en");
|
||||
TrangaTask newTask = new MonitorPublicationTask(connector!.name, (Publication)publication!, reoccurrence, "en");
|
||||
taskManager.AddTask(newTask);
|
||||
Console.WriteLine(newTask);
|
||||
}else if (task is TrangaTask.Task.DownloadChapter)
|
||||
{
|
||||
foreach (Chapter chapter in SelectChapters(connector!, (Publication)publication!, logger))
|
||||
{
|
||||
TrangaTask newTask = new DownloadChapterTask(TrangaTask.Task.DownloadChapter, connector!.name,
|
||||
(Publication)publication!, chapter, "en");
|
||||
TrangaTask newTask = new DownloadChapterTask(connector!.name, (Publication)publication, chapter, "en");
|
||||
taskManager.AddTask(newTask);
|
||||
Console.WriteLine(newTask);
|
||||
}
|
||||
@ -489,8 +505,30 @@ public static class Tranga_Cli
|
||||
Chapter[] availableChapters = connector.GetChapters(publication, "en");
|
||||
int cIndex = 0;
|
||||
Console.WriteLine("Chapters:");
|
||||
|
||||
System.Text.StringBuilder sb = new();
|
||||
foreach(Chapter chapter in availableChapters)
|
||||
Console.WriteLine($"{cIndex++}: Vol.{chapter.volumeNumber} Ch.{chapter.chapterNumber} - {chapter.name}");
|
||||
{
|
||||
sb.Append($"{cIndex++}: ");
|
||||
|
||||
if(string.IsNullOrWhiteSpace(chapter.volumeNumber) == false)
|
||||
{
|
||||
sb.Append($"Vol.{chapter.volumeNumber} ");
|
||||
}
|
||||
|
||||
if(string.IsNullOrWhiteSpace(chapter.chapterNumber) == false)
|
||||
{
|
||||
sb.Append($"Ch.{chapter.chapterNumber} ");
|
||||
}
|
||||
|
||||
if(string.IsNullOrWhiteSpace(chapter.name) == false)
|
||||
{
|
||||
sb.Append($" - {chapter.name}");
|
||||
}
|
||||
|
||||
Console.WriteLine(sb.ToString());
|
||||
sb.Clear();
|
||||
}
|
||||
|
||||
Console.WriteLine("Enter q to abort");
|
||||
Console.WriteLine($"Select Chapter(s):");
|
||||
@ -499,7 +537,7 @@ public static class Tranga_Cli
|
||||
while(selectedChapters is null || selectedChapters.Length < 1)
|
||||
selectedChapters = Console.ReadLine();
|
||||
|
||||
return connector.SearchChapters(publication, selectedChapters);
|
||||
return connector.SelectChapters(publication, selectedChapters);
|
||||
}
|
||||
|
||||
private static Connector? SelectConnector(Connector[] connectors, Logger logger)
|
||||
@ -550,7 +588,7 @@ public static class Tranga_Cli
|
||||
Console.WriteLine("Publication search query (leave empty for all):");
|
||||
string? query = Console.ReadLine();
|
||||
|
||||
Publication[] publications = taskManager.GetPublicationsFromConnector(connector, query ?? "");
|
||||
Publication[] publications = connector.GetPublications(ref taskManager.collection, query ?? "");
|
||||
|
||||
if (publications.Length < 1)
|
||||
{
|
||||
|
10
Tranga.sln
@ -6,7 +6,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga-CLI", "Tranga-CLI\Tr
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Logging", "Logging\Logging.csproj", "{415BE889-BB7D-426F-976F-8D977876A462}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga-API", "Tranga-API\Tranga-API.csproj", "{48F4E495-75BC-4402-8E03-DEC5B79D7E83}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API", "API\API.csproj", "{A8AB1F5F-D174-49DC-AED2-0909B93BA7B6}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@ -26,9 +26,9 @@ Global
|
||||
{415BE889-BB7D-426F-976F-8D977876A462}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{415BE889-BB7D-426F-976F-8D977876A462}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{415BE889-BB7D-426F-976F-8D977876A462}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{48F4E495-75BC-4402-8E03-DEC5B79D7E83}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{48F4E495-75BC-4402-8E03-DEC5B79D7E83}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{48F4E495-75BC-4402-8E03-DEC5B79D7E83}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{48F4E495-75BC-4402-8E03-DEC5B79D7E83}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A8AB1F5F-D174-49DC-AED2-0909B93BA7B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A8AB1F5F-D174-49DC-AED2-0909B93BA7B6}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A8AB1F5F-D174-49DC-AED2-0909B93BA7B6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A8AB1F5F-D174-49DC-AED2-0909B93BA7B6}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
@ -1,5 +1,9 @@
|
||||
<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/UserDictionary/Words/=altnames/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=authorsartists/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Gotify/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Komga/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=mangakatana/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Manganato/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Mangasee/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Taskmanager/@EntryIndexedValue">True</s:Boolean>
|
||||
|
@ -1,5 +1,5 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Tranga;
|
||||
|
||||
@ -7,34 +7,84 @@ namespace Tranga;
|
||||
/// Has to be Part of a publication
|
||||
/// Includes the Chapter-Name, -VolumeNumber, -ChapterNumber, the location of the chapter on the internet and the saveName of the local file.
|
||||
/// </summary>
|
||||
public struct Chapter
|
||||
public readonly struct Chapter
|
||||
{
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public Publication parentPublication { get; }
|
||||
public string? name { get; }
|
||||
public string? volumeNumber { get; }
|
||||
public string? chapterNumber { get; }
|
||||
public string chapterNumber { get; }
|
||||
public string url { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string fileName { get; }
|
||||
public string sortNumber { get; }
|
||||
|
||||
private static readonly Regex LegalCharacters = new Regex(@"([A-z]*[0-9]* *\.*-*,*\]*\[*'*\'*\)*\(*~*!*)*");
|
||||
public Chapter(string? name, string? volumeNumber, string? chapterNumber, string url)
|
||||
private static readonly Regex LegalCharacters = new (@"([A-z]*[0-9]* *\.*-*,*\]*\[*'*\'*\)*\(*~*!*)*");
|
||||
private static readonly Regex IllegalStrings = new(@"Vol(ume)?.?", RegexOptions.IgnoreCase);
|
||||
public Chapter(Publication parentPublication, string? name, string? volumeNumber, string chapterNumber, string url)
|
||||
{
|
||||
this.parentPublication = parentPublication;
|
||||
this.name = name;
|
||||
this.volumeNumber = volumeNumber;
|
||||
this.chapterNumber = chapterNumber;
|
||||
this.url = url;
|
||||
NumberFormatInfo nfi = new NumberFormatInfo()
|
||||
{
|
||||
NumberDecimalSeparator = "."
|
||||
};
|
||||
sortNumber = decimal.Round(Convert.ToDecimal(this.volumeNumber ?? "1") * Convert.ToDecimal(this.chapterNumber, nfi), 1)
|
||||
.ToString(nfi);
|
||||
|
||||
string chapterName = string.Concat(LegalCharacters.Matches(name ?? ""));
|
||||
string volStr = this.volumeNumber is not null ? $"Vol.{this.volumeNumber} " : "";
|
||||
string chNumberStr = this.chapterNumber is not null ? $"Ch.{chapterNumber} " : "";
|
||||
string chNumberStr = $"Ch.{chapterNumber} ";
|
||||
string chNameStr = chapterName.Length > 0 ? $"- {chapterName}" : "";
|
||||
chNameStr = chNameStr.Replace("Volume", "").Replace("volume", "");
|
||||
chNameStr = IllegalStrings.Replace(chNameStr, "");
|
||||
this.fileName = $"{volStr}{chNumberStr}{chNameStr}";
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a chapter-archive is already present
|
||||
/// </summary>
|
||||
/// <returns>true if chapter is present</returns>
|
||||
internal bool CheckChapterIsDownloaded(string downloadLocation)
|
||||
{
|
||||
string newFilePath = GetArchiveFilePath(downloadLocation);
|
||||
if (!Directory.Exists(Path.Join(downloadLocation, parentPublication.folderName)))
|
||||
return false;
|
||||
FileInfo[] archives = new DirectoryInfo(Path.Join(downloadLocation, parentPublication.folderName)).GetFiles();
|
||||
Regex chapterInfoRex = new(@"Ch\.[0-9.]+");
|
||||
Regex chapterRex = new(@"[0-9]+(\.[0-9]+)?");
|
||||
|
||||
if (File.Exists(newFilePath))
|
||||
return true;
|
||||
|
||||
string cn = this.chapterNumber;
|
||||
if (archives.FirstOrDefault(archive => chapterRex.Match(chapterInfoRex.Match(archive.Name).Value).Value == cn) is { } path)
|
||||
{
|
||||
File.Move(path.FullName, newFilePath);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/// <summary>
|
||||
/// Creates full file path of chapter-archive
|
||||
/// </summary>
|
||||
/// <returns>Filepath</returns>
|
||||
internal string GetArchiveFilePath(string downloadLocation)
|
||||
{
|
||||
return Path.Join(downloadLocation, parentPublication.folderName, $"{parentPublication.folderName} - {this.fileName}.cbz");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a string containing XML of publication and chapter.
|
||||
/// See ComicInfo.xml
|
||||
/// </summary>
|
||||
/// <returns>XML-string</returns>
|
||||
internal string GetComicInfoXmlString()
|
||||
{
|
||||
XElement comicInfo = new XElement("ComicInfo",
|
||||
new XElement("Tags", string.Join(',', parentPublication.tags)),
|
||||
new XElement("LanguageISO", parentPublication.originalLanguage),
|
||||
new XElement("Title", this.name),
|
||||
new XElement("Writer", string.Join(',', parentPublication.authors)),
|
||||
new XElement("Volume", this.volumeNumber),
|
||||
new XElement("Number", this.chapterNumber)
|
||||
);
|
||||
return comicInfo.ToString();
|
||||
}
|
||||
}
|
@ -1,369 +0,0 @@
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml.Linq;
|
||||
using Logging;
|
||||
using Tranga.TrangaTasks;
|
||||
using static System.IO.UnixFileMode;
|
||||
|
||||
namespace Tranga;
|
||||
|
||||
/// <summary>
|
||||
/// Base-Class for all Connectors
|
||||
/// Provides some methods to be used by all Connectors, as well as a DownloadClient
|
||||
/// </summary>
|
||||
public abstract class Connector
|
||||
{
|
||||
internal string downloadLocation { get; } //Location of local files
|
||||
protected DownloadClient downloadClient { get; init; }
|
||||
|
||||
protected readonly Logger? logger;
|
||||
|
||||
protected readonly string imageCachePath;
|
||||
|
||||
protected Connector(string downloadLocation, string imageCachePath, Logger? logger)
|
||||
{
|
||||
this.downloadLocation = downloadLocation;
|
||||
this.logger = logger;
|
||||
this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
|
||||
{
|
||||
//RequestTypes for RateLimits
|
||||
}, logger);
|
||||
this.imageCachePath = imageCachePath;
|
||||
if (!Directory.Exists(imageCachePath))
|
||||
Directory.CreateDirectory(this.imageCachePath);
|
||||
}
|
||||
|
||||
public abstract string name { get; } //Name of the Connector (e.g. Website)
|
||||
|
||||
/// <summary>
|
||||
/// Returns all Publications with the given string.
|
||||
/// If the string is empty or null, returns all Publication of the Connector
|
||||
/// </summary>
|
||||
/// <param name="publicationTitle">Search-Query</param>
|
||||
/// <returns>Publications matching the query</returns>
|
||||
public abstract Publication[] GetPublications(string publicationTitle = "");
|
||||
|
||||
/// <summary>
|
||||
/// Returns all Chapters of the publication in the provided language.
|
||||
/// If the language is empty or null, returns all Chapters in all Languages.
|
||||
/// </summary>
|
||||
/// <param name="publication">Publication to get Chapters for</param>
|
||||
/// <param name="language">Language of the Chapters</param>
|
||||
/// <returns>Array of Chapters matching Publication and Language</returns>
|
||||
public abstract Chapter[] GetChapters(Publication publication, string language = "");
|
||||
|
||||
public Chapter[] SearchChapters(Publication publication, string searchTerm, string? language = null)
|
||||
{
|
||||
Chapter[] availableChapters = this.GetChapters(publication, language??"en");
|
||||
Regex volumeRegex = new ("((v(ol)*(olume)*)+ *([0-9]+(-[0-9]+)?){1})", RegexOptions.IgnoreCase);
|
||||
Regex chapterRegex = new ("((c(h)*(hapter)*)+ *([0-9]+(-[0-9]+)?){1})", RegexOptions.IgnoreCase);
|
||||
Regex singleResultRegex = new("([0-9]+)", RegexOptions.IgnoreCase);
|
||||
Regex rangeResultRegex = new("([0-9]+(-[0-9]+))", RegexOptions.IgnoreCase);
|
||||
if (volumeRegex.IsMatch(searchTerm) && chapterRegex.IsMatch(searchTerm))
|
||||
{
|
||||
string volume = singleResultRegex.Match(volumeRegex.Match(searchTerm).Value).Value;
|
||||
string chapter = singleResultRegex.Match(chapterRegex.Match(searchTerm).Value).Value;
|
||||
return availableChapters.Where(aCh => aCh.volumeNumber is not null && aCh.chapterNumber is not null &&
|
||||
aCh.volumeNumber.Equals(volume, StringComparison.InvariantCultureIgnoreCase) &&
|
||||
aCh.chapterNumber.Equals(chapter, StringComparison.InvariantCultureIgnoreCase))
|
||||
.ToArray();
|
||||
}
|
||||
else if (volumeRegex.IsMatch(searchTerm))
|
||||
{
|
||||
string volume = volumeRegex.Match(searchTerm).Value;
|
||||
if (rangeResultRegex.IsMatch(volume))
|
||||
{
|
||||
string range = rangeResultRegex.Match(volume).Value;
|
||||
int start = Convert.ToInt32(range.Split('-')[0]);
|
||||
int end = Convert.ToInt32(range.Split('-')[1]);
|
||||
return availableChapters.Where(aCh => aCh.volumeNumber is not null &&
|
||||
Convert.ToInt32(aCh.volumeNumber) >= start &&
|
||||
Convert.ToInt32(aCh.volumeNumber) <= end).ToArray();
|
||||
}
|
||||
else if(singleResultRegex.IsMatch(volume))
|
||||
return availableChapters.Where(aCh =>
|
||||
aCh.volumeNumber is not null &&
|
||||
aCh.volumeNumber.Equals(volume, StringComparison.InvariantCultureIgnoreCase)).ToArray();
|
||||
|
||||
}
|
||||
else if (chapterRegex.IsMatch(searchTerm))
|
||||
{
|
||||
string chapter = volumeRegex.Match(searchTerm).Value;
|
||||
if (rangeResultRegex.IsMatch(chapter))
|
||||
{
|
||||
string range = rangeResultRegex.Match(chapter).Value;
|
||||
int start = Convert.ToInt32(range.Split('-')[0]);
|
||||
int end = Convert.ToInt32(range.Split('-')[1]);
|
||||
return availableChapters.Where(aCh => aCh.chapterNumber is not null &&
|
||||
Convert.ToInt32(aCh.chapterNumber) >= start &&
|
||||
Convert.ToInt32(aCh.chapterNumber) <= end).ToArray();
|
||||
}
|
||||
else if(singleResultRegex.IsMatch(chapter))
|
||||
return availableChapters.Where(aCh =>
|
||||
aCh.chapterNumber is not null &&
|
||||
aCh.chapterNumber.Equals(chapter, StringComparison.InvariantCultureIgnoreCase)).ToArray();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (rangeResultRegex.IsMatch(searchTerm))
|
||||
{
|
||||
int start = Convert.ToInt32(searchTerm.Split('-')[0]);
|
||||
int end = Convert.ToInt32(searchTerm.Split('-')[1]);
|
||||
return availableChapters[start..(end + 1)];
|
||||
}
|
||||
else if(singleResultRegex.IsMatch(searchTerm))
|
||||
return new [] { availableChapters[Convert.ToInt32(searchTerm)] };
|
||||
}
|
||||
|
||||
return Array.Empty<Chapter>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the Chapter (+Images) from the website.
|
||||
/// Should later call DownloadChapterImages to retrieve the individual Images of the Chapter and create .cbz archive.
|
||||
/// </summary>
|
||||
/// <param name="publication">Publication that contains Chapter</param>
|
||||
/// <param name="chapter">Chapter with Images to retrieve</param>
|
||||
/// <param name="parentTask">Will be used for progress-tracking</param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
public abstract void DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask, CancellationToken? cancellationToken = null);
|
||||
|
||||
/// <summary>
|
||||
/// Copies the already downloaded cover from cache to downloadLocation
|
||||
/// </summary>
|
||||
/// <param name="publication">Publication to retrieve Cover for</param>
|
||||
/// <param name="settings">TrangaSettings</param>
|
||||
public void CopyCoverFromCacheToDownloadLocation(Publication publication, TrangaSettings settings)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {publication.sortName} {publication.internalId}");
|
||||
//Check if Publication already has a Folder and cover
|
||||
string publicationFolder = publication.CreatePublicationFolder(downloadLocation);
|
||||
DirectoryInfo dirInfo = new (publicationFolder);
|
||||
if (dirInfo.EnumerateFiles().Any(info => info.Name.Contains("cover.")))
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Cover exists {publication.sortName}");
|
||||
return;
|
||||
}
|
||||
|
||||
string fileInCache = Path.Join(settings.coverImageCache, publication.coverFileNameInCache);
|
||||
string newFilePath = Path.Join(publicationFolder, $"cover.{Path.GetFileName(fileInCache).Split('.')[^1]}" );
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {fileInCache} -> {newFilePath}");
|
||||
File.Copy(fileInCache, newFilePath, true);
|
||||
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
File.SetUnixFileMode(newFilePath, GroupRead | GroupWrite | OtherRead | OtherWrite | UserRead | UserWrite);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a string containing XML of publication and chapter.
|
||||
/// See ComicInfo.xml
|
||||
/// </summary>
|
||||
/// <returns>XML-string</returns>
|
||||
protected static string GetComicInfoXmlString(Publication publication, Chapter chapter, Logger? logger)
|
||||
{
|
||||
logger?.WriteLine("Connector", $"Creating ComicInfo.Xml for {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
|
||||
XElement comicInfo = new XElement("ComicInfo",
|
||||
new XElement("Tags", string.Join(',',publication.tags)),
|
||||
new XElement("LanguageISO", publication.originalLanguage),
|
||||
new XElement("Title", chapter.name),
|
||||
new XElement("Writer", string.Join(',', publication.authors)),
|
||||
new XElement("Volume", chapter.volumeNumber),
|
||||
new XElement("Number", chapter.chapterNumber)
|
||||
);
|
||||
return comicInfo.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a chapter-archive is already present
|
||||
/// </summary>
|
||||
/// <returns>true if chapter is present</returns>
|
||||
public bool CheckChapterIsDownloaded(Publication publication, Chapter chapter)
|
||||
{
|
||||
Regex legalCharacters = new Regex(@"([A-z]*[0-9]* *\.*-*,*\]*\[*'*\'*\)*\(*~*!*)*");
|
||||
string oldFilePath = Path.Join(downloadLocation, publication.folderName, $"{string.Concat(legalCharacters.Matches(chapter.name ?? ""))} - V{chapter.volumeNumber}C{chapter.chapterNumber} - {chapter.sortNumber}.cbz");
|
||||
string oldFilePath2 = Path.Join(downloadLocation, publication.folderName, $"{string.Concat(legalCharacters.Matches(chapter.name ?? ""))} - VC{chapter.chapterNumber} - {chapter.chapterNumber}.cbz");
|
||||
string newFilePath = GetArchiveFilePath(publication, chapter);
|
||||
if (File.Exists(oldFilePath))
|
||||
File.Move(oldFilePath, newFilePath);
|
||||
else if (File.Exists(oldFilePath2))
|
||||
File.Move(oldFilePath2, newFilePath);
|
||||
return File.Exists(newFilePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates full file path of chapter-archive
|
||||
/// </summary>
|
||||
/// <returns>Filepath</returns>
|
||||
protected string GetArchiveFilePath(Publication publication, Chapter chapter)
|
||||
{
|
||||
return Path.Join(downloadLocation, publication.folderName, $"{publication.folderName} - {chapter.fileName}.cbz");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads Image from URL and saves it to the given path(incl. fileName)
|
||||
/// </summary>
|
||||
/// <param name="imageUrl"></param>
|
||||
/// <param name="fullPath"></param>
|
||||
/// <param name="requestType">RequestType for Rate-Limit</param>
|
||||
/// <param name="referrer">referrer used in html request header</param>
|
||||
private void DownloadImage(string imageUrl, string fullPath, byte requestType, string? referrer = null)
|
||||
{
|
||||
DownloadClient.RequestResult requestResult = downloadClient.MakeRequest(imageUrl, requestType, referrer);
|
||||
if (requestResult.result != Stream.Null)
|
||||
{
|
||||
byte[] buffer = new byte[requestResult.result.Length];
|
||||
requestResult.result.ReadExactly(buffer, 0, buffer.Length);
|
||||
File.WriteAllBytes(fullPath, buffer);
|
||||
}else
|
||||
logger?.WriteLine(this.GetType().ToString(), "No Stream-Content in result.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads all Images from URLs, Compresses to zip(cbz) and saves.
|
||||
/// </summary>
|
||||
/// <param name="imageUrls">List of URLs to download Images from</param>
|
||||
/// <param name="saveArchiveFilePath">Full path to save archive to (without file ending .cbz)</param>
|
||||
/// <param name="parentTask">Used for progress tracking</param>
|
||||
/// <param name="comicInfoPath">Path of the generate Chapter ComicInfo.xml, if it was generated</param>
|
||||
/// <param name="requestType">RequestType for RateLimits</param>
|
||||
/// <param name="referrer">Used in http request header</param>
|
||||
protected void DownloadChapterImages(string[] imageUrls, string saveArchiveFilePath, byte requestType, DownloadChapterTask parentTask, string? comicInfoPath = null, string? referrer = null, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested??false)
|
||||
return;
|
||||
logger?.WriteLine("Connector", $"Downloading Images for {saveArchiveFilePath}");
|
||||
//Check if Publication Directory already exists
|
||||
string directoryPath = Path.GetDirectoryName(saveArchiveFilePath)!;
|
||||
if (!Directory.Exists(directoryPath))
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
|
||||
if (File.Exists(saveArchiveFilePath)) //Don't download twice.
|
||||
return;
|
||||
|
||||
//Create a temporary folder to store images
|
||||
string tempFolder = Directory.CreateTempSubdirectory().FullName;
|
||||
|
||||
int chapter = 0;
|
||||
//Download all Images to temporary Folder
|
||||
foreach (string imageUrl in imageUrls)
|
||||
{
|
||||
string[] split = imageUrl.Split('.');
|
||||
string extension = split[^1];
|
||||
logger?.WriteLine("Connector", $"Downloading Image {chapter + 1:000}/{imageUrls.Length:000} {parentTask.publication.sortName} {parentTask.publication.internalId} Vol.{parentTask.chapter.volumeNumber} Ch.{parentTask.chapter.chapterNumber} {parentTask.progress:P2}");
|
||||
DownloadImage(imageUrl, Path.Join(tempFolder, $"{chapter++}.{extension}"), requestType, referrer);
|
||||
parentTask.IncrementProgress(1.0 / imageUrls.Length);
|
||||
if (cancellationToken?.IsCancellationRequested??false)
|
||||
return;
|
||||
}
|
||||
|
||||
if(comicInfoPath is not null)
|
||||
File.Copy(comicInfoPath, Path.Join(tempFolder, "ComicInfo.xml"));
|
||||
|
||||
logger?.WriteLine("Connector", $"Creating archive {saveArchiveFilePath}");
|
||||
//ZIP-it and ship-it
|
||||
ZipFile.CreateFromDirectory(tempFolder, saveArchiveFilePath);
|
||||
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
File.SetUnixFileMode(saveArchiveFilePath, GroupRead | GroupWrite | OtherRead | OtherWrite | UserRead | UserWrite);
|
||||
Directory.Delete(tempFolder, true); //Cleanup
|
||||
}
|
||||
|
||||
protected string SaveCoverImageToCache(string url, byte requestType)
|
||||
{
|
||||
string[] split = url.Split('/');
|
||||
string filename = split[^1];
|
||||
string saveImagePath = Path.Join(imageCachePath, filename);
|
||||
|
||||
if (File.Exists(saveImagePath))
|
||||
return filename;
|
||||
|
||||
DownloadClient.RequestResult coverResult = downloadClient.MakeRequest(url, requestType);
|
||||
using MemoryStream ms = new();
|
||||
coverResult.result.CopyTo(ms);
|
||||
File.WriteAllBytes(saveImagePath, ms.ToArray());
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Saving image to {saveImagePath}");
|
||||
return filename;
|
||||
}
|
||||
|
||||
protected class DownloadClient
|
||||
{
|
||||
private static readonly HttpClient Client = new();
|
||||
|
||||
private readonly Dictionary<byte, DateTime> _lastExecutedRateLimit;
|
||||
private readonly Dictionary<byte, TimeSpan> _rateLimit;
|
||||
private Logger? logger;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a httpClient
|
||||
/// </summary>
|
||||
/// <param name="rateLimitRequestsPerMinute">Rate limits for requests. byte is RequestType, int maximum requests per minute for RequestType</param>
|
||||
/// <param name="logger"></param>
|
||||
public DownloadClient(Dictionary<byte, int> rateLimitRequestsPerMinute, Logger? logger)
|
||||
{
|
||||
this.logger = logger;
|
||||
_lastExecutedRateLimit = new();
|
||||
_rateLimit = new();
|
||||
foreach(KeyValuePair<byte, int> limit in rateLimitRequestsPerMinute)
|
||||
_rateLimit.Add(limit.Key, TimeSpan.FromMinutes(1).Divide(limit.Value));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request Webpage
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="requestType">For RateLimits: Same Endpoints use same type</param>
|
||||
/// <param name="referrer">Used in http request header</param>
|
||||
/// <returns>RequestResult with StatusCode and Stream of received data</returns>
|
||||
public RequestResult MakeRequest(string url, byte requestType, string? referrer = null)
|
||||
{
|
||||
if (_rateLimit.TryGetValue(requestType, out TimeSpan value))
|
||||
_lastExecutedRateLimit.TryAdd(requestType, DateTime.Now.Subtract(value));
|
||||
else
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), "RequestType not configured for rate-limit.");
|
||||
return new RequestResult(HttpStatusCode.NotAcceptable, Stream.Null);
|
||||
}
|
||||
|
||||
TimeSpan rateLimitTimeout = _rateLimit[requestType]
|
||||
.Subtract(DateTime.Now.Subtract(_lastExecutedRateLimit[requestType]));
|
||||
|
||||
if(rateLimitTimeout > TimeSpan.Zero)
|
||||
Thread.Sleep(rateLimitTimeout);
|
||||
|
||||
HttpResponseMessage? response = null;
|
||||
while (response is null)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpRequestMessage requestMessage = new(HttpMethod.Get, url);
|
||||
if(referrer is not null)
|
||||
requestMessage.Headers.Referrer = new Uri(referrer);
|
||||
_lastExecutedRateLimit[requestType] = DateTime.Now;
|
||||
response = Client.Send(requestMessage);
|
||||
}
|
||||
catch (HttpRequestException e)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), e.Message);
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Waiting {_rateLimit[requestType] * 2}... Retrying.");
|
||||
Thread.Sleep(_rateLimit[requestType] * 2);
|
||||
}
|
||||
}
|
||||
Stream resultString = response.IsSuccessStatusCode ? response.Content.ReadAsStream() : Stream.Null;
|
||||
if (!response.IsSuccessStatusCode)
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Request-Error {response.StatusCode}: {response.ReasonPhrase}");
|
||||
return new RequestResult(response.StatusCode, resultString);
|
||||
}
|
||||
|
||||
public struct RequestResult
|
||||
{
|
||||
public HttpStatusCode statusCode { get; }
|
||||
public Stream result { get; }
|
||||
|
||||
public RequestResult(HttpStatusCode statusCode, Stream result)
|
||||
{
|
||||
this.statusCode = statusCode;
|
||||
this.result = result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
269
Tranga/Connectors/Connector.cs
Normal file
@ -0,0 +1,269 @@
|
||||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.RegularExpressions;
|
||||
using Tranga.TrangaTasks;
|
||||
using static System.IO.UnixFileMode;
|
||||
|
||||
namespace Tranga.Connectors;
|
||||
|
||||
/// <summary>
|
||||
/// Base-Class for all Connectors
|
||||
/// Provides some methods to be used by all Connectors, as well as a DownloadClient
|
||||
/// </summary>
|
||||
public abstract class Connector
|
||||
{
|
||||
protected TrangaSettings settings { get; }
|
||||
internal DownloadClient downloadClient { get; init; } = null!;
|
||||
|
||||
protected Connector(TrangaSettings settings)
|
||||
{
|
||||
this.settings = settings;
|
||||
if (!Directory.Exists(settings.coverImageCache))
|
||||
Directory.CreateDirectory(settings.coverImageCache);
|
||||
}
|
||||
|
||||
public abstract string name { get; } //Name of the Connector (e.g. Website)
|
||||
|
||||
public Publication[] GetPublications(ref HashSet<Publication> publicationCollection, string publicationTitle = "")
|
||||
{
|
||||
Publication[] ret = GetPublicationsInternal(publicationTitle);
|
||||
foreach (Publication p in ret)
|
||||
publicationCollection.Add(p);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all Publications with the given string.
|
||||
/// If the string is empty or null, returns all Publication of the Connector
|
||||
/// </summary>
|
||||
/// <param name="publicationTitle">Search-Query</param>
|
||||
/// <returns>Publications matching the query</returns>
|
||||
protected abstract Publication[] GetPublicationsInternal(string publicationTitle = "");
|
||||
|
||||
/// <summary>
|
||||
/// Returns all Chapters of the publication in the provided language.
|
||||
/// If the language is empty or null, returns all Chapters in all Languages.
|
||||
/// </summary>
|
||||
/// <param name="publication">Publication to get Chapters for</param>
|
||||
/// <param name="language">Language of the Chapters</param>
|
||||
/// <returns>Array of Chapters matching Publication and Language</returns>
|
||||
public abstract Chapter[] GetChapters(Publication publication, string language = "");
|
||||
|
||||
/// <summary>
|
||||
/// Updates the available Chapters of a Publication
|
||||
/// </summary>
|
||||
/// <param name="publication">Publication to check</param>
|
||||
/// <param name="language">Language to receive chapters for</param>
|
||||
/// <param name="collection"></param>
|
||||
/// <returns>List of Chapters that were previously not in collection</returns>
|
||||
public List<Chapter> GetNewChaptersList(Publication publication, string language, ref HashSet<Publication> collection)
|
||||
{
|
||||
Chapter[] newChapters = this.GetChapters(publication, language);
|
||||
collection.Add(publication);
|
||||
NumberFormatInfo decimalPoint = new (){ NumberDecimalSeparator = "." };
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Checking for duplicates");
|
||||
List<Chapter> newChaptersList = newChapters.Where(nChapter =>
|
||||
float.Parse(nChapter.chapterNumber, decimalPoint) > publication.ignoreChaptersBelow &&
|
||||
!nChapter.CheckChapterIsDownloaded(settings.downloadLocation)).ToList();
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"{newChaptersList.Count} new chapters.");
|
||||
|
||||
return newChaptersList;
|
||||
}
|
||||
|
||||
public Chapter[] SelectChapters(Publication publication, string searchTerm, string? language = null)
|
||||
{
|
||||
Chapter[] availableChapters = this.GetChapters(publication, language??"en");
|
||||
Regex volumeRegex = new ("((v(ol)*(olume)*)+ *([0-9]+(-[0-9]+)?){1})", RegexOptions.IgnoreCase);
|
||||
Regex chapterRegex = new ("((c(h)*(hapter)*)+ *([0-9]+(-[0-9]+)?){1})", RegexOptions.IgnoreCase);
|
||||
Regex singleResultRegex = new("([0-9]+)", RegexOptions.IgnoreCase);
|
||||
Regex rangeResultRegex = new("([0-9]+(-[0-9]+))", RegexOptions.IgnoreCase);
|
||||
Regex allRegex = new("a(ll)?", RegexOptions.IgnoreCase);
|
||||
if (volumeRegex.IsMatch(searchTerm) && chapterRegex.IsMatch(searchTerm))
|
||||
{
|
||||
string volume = singleResultRegex.Match(volumeRegex.Match(searchTerm).Value).Value;
|
||||
string chapter = singleResultRegex.Match(chapterRegex.Match(searchTerm).Value).Value;
|
||||
return availableChapters.Where(aCh => aCh.volumeNumber is not null &&
|
||||
aCh.volumeNumber.Equals(volume, StringComparison.InvariantCultureIgnoreCase) &&
|
||||
aCh.chapterNumber.Equals(chapter, StringComparison.InvariantCultureIgnoreCase))
|
||||
.ToArray();
|
||||
}
|
||||
else if (volumeRegex.IsMatch(searchTerm))
|
||||
{
|
||||
string volume = volumeRegex.Match(searchTerm).Value;
|
||||
if (rangeResultRegex.IsMatch(volume))
|
||||
{
|
||||
string range = rangeResultRegex.Match(volume).Value;
|
||||
int start = Convert.ToInt32(range.Split('-')[0]);
|
||||
int end = Convert.ToInt32(range.Split('-')[1]);
|
||||
return availableChapters.Where(aCh => aCh.volumeNumber is not null &&
|
||||
Convert.ToInt32(aCh.volumeNumber) >= start &&
|
||||
Convert.ToInt32(aCh.volumeNumber) <= end).ToArray();
|
||||
}
|
||||
else if (singleResultRegex.IsMatch(volume))
|
||||
{
|
||||
string volumeNumber = singleResultRegex.Match(volume).Value;
|
||||
return availableChapters.Where(aCh =>
|
||||
aCh.volumeNumber is not null &&
|
||||
aCh.volumeNumber.Equals(volumeNumber, StringComparison.InvariantCultureIgnoreCase)).ToArray();
|
||||
}
|
||||
|
||||
}
|
||||
else if (chapterRegex.IsMatch(searchTerm))
|
||||
{
|
||||
string chapter = volumeRegex.Match(searchTerm).Value;
|
||||
if (rangeResultRegex.IsMatch(chapter))
|
||||
{
|
||||
string range = rangeResultRegex.Match(chapter).Value;
|
||||
int start = Convert.ToInt32(range.Split('-')[0]);
|
||||
int end = Convert.ToInt32(range.Split('-')[1]);
|
||||
return availableChapters.Where(aCh => Convert.ToInt32(aCh.chapterNumber) >= start &&
|
||||
Convert.ToInt32(aCh.chapterNumber) <= end).ToArray();
|
||||
}
|
||||
else if (singleResultRegex.IsMatch(chapter))
|
||||
{
|
||||
string chapterNumber = singleResultRegex.Match(chapter).Value;
|
||||
return availableChapters.Where(aCh =>
|
||||
aCh.chapterNumber.Equals(chapterNumber, StringComparison.InvariantCultureIgnoreCase)).ToArray();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (rangeResultRegex.IsMatch(searchTerm))
|
||||
{
|
||||
int start = Convert.ToInt32(searchTerm.Split('-')[0]);
|
||||
int end = Convert.ToInt32(searchTerm.Split('-')[1]);
|
||||
return availableChapters[start..(end + 1)];
|
||||
}
|
||||
else if(singleResultRegex.IsMatch(searchTerm))
|
||||
return new [] { availableChapters[Convert.ToInt32(searchTerm)] };
|
||||
else if (allRegex.IsMatch(searchTerm))
|
||||
return availableChapters;
|
||||
}
|
||||
|
||||
return Array.Empty<Chapter>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the Chapter (+Images) from the website.
|
||||
/// Should later call DownloadChapterImages to retrieve the individual Images of the Chapter and create .cbz archive.
|
||||
/// </summary>
|
||||
/// <param name="publication">Publication that contains Chapter</param>
|
||||
/// <param name="chapter">Chapter with Images to retrieve</param>
|
||||
/// <param name="parentTask">Will be used for progress-tracking</param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
public abstract HttpStatusCode DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask, CancellationToken? cancellationToken = null);
|
||||
|
||||
/// <summary>
|
||||
/// Copies the already downloaded cover from cache to downloadLocation
|
||||
/// </summary>
|
||||
/// <param name="publication">Publication to retrieve Cover for</param>
|
||||
public void CopyCoverFromCacheToDownloadLocation(Publication publication)
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {publication.sortName} -> {publication.internalId}");
|
||||
//Check if Publication already has a Folder and cover
|
||||
string publicationFolder = publication.CreatePublicationFolder(settings.downloadLocation);
|
||||
DirectoryInfo dirInfo = new (publicationFolder);
|
||||
if (dirInfo.EnumerateFiles().Any(info => info.Name.Contains("cover", StringComparison.InvariantCultureIgnoreCase)))
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Cover exists {publication.sortName}");
|
||||
return;
|
||||
}
|
||||
|
||||
string fileInCache = Path.Join(settings.coverImageCache, publication.coverFileNameInCache);
|
||||
string newFilePath = Path.Join(publicationFolder, $"cover.{Path.GetFileName(fileInCache).Split('.')[^1]}" );
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {fileInCache} -> {newFilePath}");
|
||||
File.Copy(fileInCache, newFilePath, true);
|
||||
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
File.SetUnixFileMode(newFilePath, GroupRead | GroupWrite | OtherRead | OtherWrite | UserRead | UserWrite);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads Image from URL and saves it to the given path(incl. fileName)
|
||||
/// </summary>
|
||||
/// <param name="imageUrl"></param>
|
||||
/// <param name="fullPath"></param>
|
||||
/// <param name="requestType">RequestType for Rate-Limit</param>
|
||||
/// <param name="referrer">referrer used in html request header</param>
|
||||
private HttpStatusCode DownloadImage(string imageUrl, string fullPath, byte requestType, string? referrer = null)
|
||||
{
|
||||
DownloadClient.RequestResult requestResult = downloadClient.MakeRequest(imageUrl, requestType, referrer);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300 || requestResult.result == Stream.Null)
|
||||
return requestResult.statusCode;
|
||||
byte[] buffer = new byte[requestResult.result.Length];
|
||||
requestResult.result.ReadExactly(buffer, 0, buffer.Length);
|
||||
File.WriteAllBytes(fullPath, buffer);
|
||||
return requestResult.statusCode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads all Images from URLs, Compresses to zip(cbz) and saves.
|
||||
/// </summary>
|
||||
/// <param name="imageUrls">List of URLs to download Images from</param>
|
||||
/// <param name="saveArchiveFilePath">Full path to save archive to (without file ending .cbz)</param>
|
||||
/// <param name="parentTask">Used for progress tracking</param>
|
||||
/// <param name="comicInfoPath">Path of the generate Chapter ComicInfo.xml, if it was generated</param>
|
||||
/// <param name="requestType">RequestType for RateLimits</param>
|
||||
/// <param name="referrer">Used in http request header</param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
protected HttpStatusCode DownloadChapterImages(string[] imageUrls, string saveArchiveFilePath, byte requestType, DownloadChapterTask parentTask, string? comicInfoPath = null, string? referrer = null, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
settings.logger?.WriteLine("Connector", $"Downloading Images for {saveArchiveFilePath}");
|
||||
//Check if Publication Directory already exists
|
||||
string directoryPath = Path.GetDirectoryName(saveArchiveFilePath)!;
|
||||
if (!Directory.Exists(directoryPath))
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
|
||||
if (File.Exists(saveArchiveFilePath)) //Don't download twice.
|
||||
return HttpStatusCode.OK;
|
||||
|
||||
//Create a temporary folder to store images
|
||||
string tempFolder = Directory.CreateTempSubdirectory().FullName;
|
||||
|
||||
int chapter = 0;
|
||||
//Download all Images to temporary Folder
|
||||
foreach (string imageUrl in imageUrls)
|
||||
{
|
||||
string[] split = imageUrl.Split('.');
|
||||
string extension = split[^1];
|
||||
settings.logger?.WriteLine("Connector", $"Downloading Image {chapter + 1:000}/{imageUrls.Length:000} {parentTask.publication.sortName} {parentTask.publication.internalId} Vol.{parentTask.chapter.volumeNumber} Ch.{parentTask.chapter.chapterNumber} {parentTask.progress:P2}");
|
||||
HttpStatusCode status = DownloadImage(imageUrl, Path.Join(tempFolder, $"{chapter++}.{extension}"), requestType, referrer);
|
||||
if ((int)status < 200 || (int)status >= 300)
|
||||
return status;
|
||||
parentTask.IncrementProgress(1.0 / imageUrls.Length);
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
}
|
||||
|
||||
if(comicInfoPath is not null)
|
||||
File.Copy(comicInfoPath, Path.Join(tempFolder, "ComicInfo.xml"));
|
||||
|
||||
settings.logger?.WriteLine("Connector", $"Creating archive {saveArchiveFilePath}");
|
||||
//ZIP-it and ship-it
|
||||
ZipFile.CreateFromDirectory(tempFolder, saveArchiveFilePath);
|
||||
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
File.SetUnixFileMode(saveArchiveFilePath, GroupRead | GroupWrite | OtherRead | OtherWrite | UserRead | UserWrite);
|
||||
Directory.Delete(tempFolder, true); //Cleanup
|
||||
return HttpStatusCode.OK;
|
||||
}
|
||||
|
||||
protected string SaveCoverImageToCache(string url, byte requestType)
|
||||
{
|
||||
string[] split = url.Split('/');
|
||||
string filename = split[^1];
|
||||
string saveImagePath = Path.Join(settings.coverImageCache, filename);
|
||||
|
||||
if (File.Exists(saveImagePath))
|
||||
return filename;
|
||||
|
||||
DownloadClient.RequestResult coverResult = downloadClient.MakeRequest(url, requestType);
|
||||
using MemoryStream ms = new();
|
||||
coverResult.result.CopyTo(ms);
|
||||
File.WriteAllBytes(saveImagePath, ms.ToArray());
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Saving image to {saveImagePath}");
|
||||
return filename;
|
||||
}
|
||||
}
|
@ -2,7 +2,6 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Logging;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
namespace Tranga.Connectors;
|
||||
@ -19,7 +18,7 @@ public class MangaDex : Connector
|
||||
Author,
|
||||
}
|
||||
|
||||
public MangaDex(string downloadLocation, string imageCachePath, Logger? logger) : base(downloadLocation, imageCachePath, logger)
|
||||
public MangaDex(TrangaSettings settings) : base(settings)
|
||||
{
|
||||
name = "MangaDex";
|
||||
this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
|
||||
@ -29,12 +28,12 @@ public class MangaDex : Connector
|
||||
{(byte)RequestType.AtHomeServer, 40},
|
||||
{(byte)RequestType.CoverUrl, 250},
|
||||
{(byte)RequestType.Author, 250}
|
||||
}, logger);
|
||||
}, settings.logger);
|
||||
}
|
||||
|
||||
public override Publication[] GetPublications(string publicationTitle = "")
|
||||
protected override Publication[] GetPublicationsInternal(string publicationTitle = "")
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
const int limit = 100; //How many values we want returned at once
|
||||
int offset = 0; //"Page"
|
||||
int total = int.MaxValue; //How many total results are there, is updated on first request
|
||||
@ -46,7 +45,7 @@ public class MangaDex : Connector
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(
|
||||
$"https://api.mangadex.org/manga?limit={limit}&title={publicationTitle}&offset={offset}", (byte)RequestType.Manga);
|
||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
break;
|
||||
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
||||
|
||||
@ -60,7 +59,7 @@ public class MangaDex : Connector
|
||||
//Loop each Manga and extract information from JSON
|
||||
foreach (JsonNode? mangeNode in mangaInResult)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting publication data. {++loadedPublicationData}/{total}");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting publication data. {++loadedPublicationData}/{total}");
|
||||
JsonObject manga = (JsonObject)mangeNode!;
|
||||
JsonObject attributes = manga["attributes"]!.AsObject();
|
||||
|
||||
@ -98,7 +97,7 @@ public class MangaDex : Connector
|
||||
{
|
||||
JsonArray relationships = manga["relationships"]!.AsArray();
|
||||
posterId = relationships.FirstOrDefault(relationship => relationship!["type"]!.GetValue<string>() == "cover_art")!["id"]!.GetValue<string>();
|
||||
foreach (JsonNode node in relationships.Where(relationship =>
|
||||
foreach (JsonNode? node in relationships.Where(relationship =>
|
||||
relationship!["type"]!.GetValue<string>() == "author"))
|
||||
authorIds.Add(node!["id"]!.GetValue<string>());
|
||||
}
|
||||
@ -147,13 +146,13 @@ public class MangaDex : Connector
|
||||
}
|
||||
}
|
||||
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Done getting publications (title={publicationTitle})");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting publications (title={publicationTitle})");
|
||||
return publications.ToArray();
|
||||
}
|
||||
|
||||
public override Chapter[] GetChapters(Publication publication, string language = "")
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})");
|
||||
const int limit = 100; //How many values we want returned at once
|
||||
int offset = 0; //"Page"
|
||||
int total = int.MaxValue; //How many total results are there, is updated on first request
|
||||
@ -165,7 +164,7 @@ public class MangaDex : Connector
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(
|
||||
$"https://api.mangadex.org/manga/{publication.publicationId}/feed?limit={limit}&offset={offset}&translatedLanguage%5B%5D={language}", (byte)RequestType.Feed);
|
||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
break;
|
||||
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
||||
|
||||
@ -190,11 +189,12 @@ public class MangaDex : Connector
|
||||
? attributes["volume"]!.GetValue<string>()
|
||||
: null;
|
||||
|
||||
string? chapterNum = attributes.ContainsKey("chapter") && attributes["chapter"] is not null
|
||||
string chapterNum = attributes.ContainsKey("chapter") && attributes["chapter"] is not null
|
||||
? attributes["chapter"]!.GetValue<string>()
|
||||
: null;
|
||||
: "null";
|
||||
|
||||
chapters.Add(new Chapter(title, volume, chapterNum, chapterId));
|
||||
if(chapterNum is not "null")
|
||||
chapters.Add(new Chapter(publication, title, volume, chapterNum, chapterId));
|
||||
}
|
||||
}
|
||||
|
||||
@ -203,23 +203,23 @@ public class MangaDex : Connector
|
||||
{
|
||||
NumberDecimalSeparator = "."
|
||||
};
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting {chapters.Count} Chapters for {publication.internalId}");
|
||||
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
|
||||
}
|
||||
|
||||
public override void DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask, CancellationToken? cancellationToken = null)
|
||||
public override HttpStatusCode DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return;
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
|
||||
//Request URLs for Chapter-Images
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest($"https://api.mangadex.org/at-home/server/{chapter.url}?forcePort443=false'", (byte)RequestType.AtHomeServer);
|
||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
||||
return;
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return requestResult.statusCode;
|
||||
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
||||
if (result is null)
|
||||
return;
|
||||
return HttpStatusCode.NoContent;
|
||||
|
||||
string baseUrl = result["baseUrl"]!.GetValue<string>();
|
||||
string hash = result["chapter"]!["hash"]!.GetValue<string>();
|
||||
@ -230,25 +230,25 @@ public class MangaDex : Connector
|
||||
imageUrls.Add($"{baseUrl}/data/{hash}/{image!.GetValue<string>()}");
|
||||
|
||||
string comicInfoPath = Path.GetTempFileName();
|
||||
File.WriteAllText(comicInfoPath, GetComicInfoXmlString(publication, chapter, logger));
|
||||
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());
|
||||
|
||||
//Download Chapter-Images
|
||||
DownloadChapterImages(imageUrls.ToArray(), GetArchiveFilePath(publication, chapter), (byte)RequestType.AtHomeServer, parentTask, comicInfoPath, cancellationToken:cancellationToken);
|
||||
return DownloadChapterImages(imageUrls.ToArray(), chapter.GetArchiveFilePath(settings.downloadLocation), (byte)RequestType.AtHomeServer, parentTask, comicInfoPath, cancellationToken:cancellationToken);
|
||||
}
|
||||
|
||||
private string? GetCoverUrl(string publicationId, string? posterId)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting CoverUrl for {publicationId}");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting CoverUrl for {publicationId}");
|
||||
if (posterId is null)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"No posterId, aborting");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"No posterId, aborting");
|
||||
return null;
|
||||
}
|
||||
|
||||
//Request information where to download Cover
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest($"https://api.mangadex.org/cover/{posterId}", (byte)RequestType.CoverUrl);
|
||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return null;
|
||||
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
||||
if (result is null)
|
||||
@ -257,7 +257,7 @@ public class MangaDex : Connector
|
||||
string fileName = result["data"]!["attributes"]!["fileName"]!.GetValue<string>();
|
||||
|
||||
string coverUrl = $"https://uploads.mangadex.org/covers/{publicationId}/{fileName}";
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Got Cover-Url for {publicationId} -> {coverUrl}");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Got Cover-Url for {publicationId} -> {coverUrl}");
|
||||
return coverUrl;
|
||||
}
|
||||
|
||||
@ -268,7 +268,7 @@ public class MangaDex : Connector
|
||||
{
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest($"https://api.mangadex.org/author/{authorId}", (byte)RequestType.Author);
|
||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return ret;
|
||||
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
||||
if (result is null)
|
||||
@ -276,7 +276,7 @@ public class MangaDex : Connector
|
||||
|
||||
string authorName = result["data"]!["attributes"]!["name"]!.GetValue<string>();
|
||||
ret.Add(authorName);
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Got author {authorId} -> {authorName}");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Got author {authorId} -> {authorName}");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
219
Tranga/Connectors/MangaKatana.cs
Normal file
@ -0,0 +1,219 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using HtmlAgilityPack;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
namespace Tranga.Connectors;
|
||||
|
||||
public class MangaKatana : Connector
|
||||
{
|
||||
public override string name { get; }
|
||||
|
||||
public MangaKatana(TrangaSettings settings) : base(settings)
|
||||
{
|
||||
this.name = "MangaKatana";
|
||||
this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
|
||||
{
|
||||
{1, 60}
|
||||
}, settings.logger);
|
||||
}
|
||||
|
||||
protected override Publication[] GetPublicationsInternal(string publicationTitle = "")
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
string sanitizedTitle = string.Concat(Regex.Matches(publicationTitle, "[A-z]* *")).ToLower().Replace(' ', '_');
|
||||
string requestUrl = $"https://mangakatana.com/?search={sanitizedTitle}&search_by=book_name";
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Publication>();
|
||||
|
||||
// ReSharper disable once MergeIntoPattern
|
||||
// If a single result is found, the user will be redirected to the results directly instead of a result page
|
||||
if(requestResult.hasBeenRedirected
|
||||
&& requestResult.redirectedToUrl is not null
|
||||
&& requestResult.redirectedToUrl.Contains("mangakatana.com/manga"))
|
||||
{
|
||||
return new [] { ParseSinglePublicationFromHtml(requestResult.result, requestResult.redirectedToUrl.Split('/')[^1]) };
|
||||
}
|
||||
|
||||
return ParsePublicationsFromHtml(requestResult.result);
|
||||
}
|
||||
|
||||
private Publication[] ParsePublicationsFromHtml(Stream html)
|
||||
{
|
||||
StreamReader reader = new(html);
|
||||
string htmlString = reader.ReadToEnd();
|
||||
HtmlDocument document = new();
|
||||
document.LoadHtml(htmlString);
|
||||
IEnumerable<HtmlNode> searchResults = document.DocumentNode.SelectNodes("//*[@id='book_list']/div");
|
||||
List<string> urls = new();
|
||||
foreach (HtmlNode mangaResult in searchResults)
|
||||
{
|
||||
urls.Add(mangaResult.Descendants("a").First().GetAttributes()
|
||||
.First(a => a.Name == "href").Value);
|
||||
}
|
||||
|
||||
HashSet<Publication> ret = new();
|
||||
foreach (string url in urls)
|
||||
{
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(url, 1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Publication>();
|
||||
|
||||
ret.Add(ParseSinglePublicationFromHtml(requestResult.result, url.Split('/')[^1]));
|
||||
}
|
||||
|
||||
return ret.ToArray();
|
||||
}
|
||||
|
||||
private Publication ParseSinglePublicationFromHtml(Stream html, string publicationId)
|
||||
{
|
||||
StreamReader reader = new(html);
|
||||
string htmlString = reader.ReadToEnd();
|
||||
HtmlDocument document = new();
|
||||
document.LoadHtml(htmlString);
|
||||
string status = "";
|
||||
Dictionary<string, string> altTitles = new();
|
||||
Dictionary<string, string>? links = null;
|
||||
HashSet<string> tags = new();
|
||||
string[] authors = Array.Empty<string>();
|
||||
string originalLanguage = "";
|
||||
|
||||
HtmlNode infoNode = document.DocumentNode.SelectSingleNode("//*[@id='single_book']");
|
||||
string sortName = infoNode.Descendants("h1").First(n => n.HasClass("heading")).InnerText;
|
||||
HtmlNode infoTable = infoNode.SelectSingleNode("//*[@id='single_book']/div[2]/div/ul");
|
||||
|
||||
foreach (HtmlNode row in infoTable.Descendants("li"))
|
||||
{
|
||||
string key = row.SelectNodes("div").First().InnerText.ToLower();
|
||||
string value = row.SelectNodes("div").Last().InnerText;
|
||||
string keySanitized = string.Concat(Regex.Matches(key, "[a-z]"));
|
||||
|
||||
switch (keySanitized)
|
||||
{
|
||||
case "altnames":
|
||||
string[] alts = value.Split(" ; ");
|
||||
for (int i = 0; i < alts.Length; i++)
|
||||
altTitles.Add(i.ToString(), alts[i]);
|
||||
break;
|
||||
case "authorsartists":
|
||||
authors = value.Split(',');
|
||||
break;
|
||||
case "status":
|
||||
status = value;
|
||||
break;
|
||||
case "genres":
|
||||
tags = row.SelectNodes("div").Last().Descendants("a").Select(a => a.InnerText).ToHashSet();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
string posterUrl = document.DocumentNode.SelectSingleNode("//*[@id='single_book']/div[1]/div").Descendants("img").First()
|
||||
.GetAttributes().First(a => a.Name == "src").Value;
|
||||
|
||||
string coverFileNameInCache = SaveCoverImageToCache(posterUrl, 1);
|
||||
|
||||
string description = document.DocumentNode.SelectSingleNode("//*[@id='single_book']/div[3]/p").InnerText;
|
||||
while (description.StartsWith('\n'))
|
||||
description = description.Substring(1);
|
||||
|
||||
int year = DateTime.Now.Year;
|
||||
string yearString = infoTable.Descendants("div").First(d => d.HasClass("updateAt"))
|
||||
.InnerText.Split('-')[^1];
|
||||
|
||||
if(yearString.Contains("ago") == false)
|
||||
{
|
||||
year = Convert.ToInt32(yearString);
|
||||
}
|
||||
|
||||
return new Publication(sortName, authors.ToList(), description, altTitles, tags.ToArray(), posterUrl, coverFileNameInCache, links,
|
||||
year, originalLanguage, status, publicationId);
|
||||
}
|
||||
|
||||
public override Chapter[] GetChapters(Publication publication, string language = "")
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})");
|
||||
string requestUrl = $"https://mangakatana.com/manga/{publication.publicationId}";
|
||||
// Leaving this in for verification if the page exists
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Chapter>();
|
||||
|
||||
//Return Chapters ordered by Chapter-Number
|
||||
NumberFormatInfo chapterNumberFormatInfo = new()
|
||||
{
|
||||
NumberDecimalSeparator = "."
|
||||
};
|
||||
List<Chapter> chapters = ParseChaptersFromHtml(publication, requestUrl);
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
|
||||
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
|
||||
}
|
||||
|
||||
private List<Chapter> ParseChaptersFromHtml(Publication publication, string mangaUrl)
|
||||
{
|
||||
// Using HtmlWeb will include the chapters since they are loaded with js
|
||||
HtmlWeb web = new();
|
||||
HtmlDocument document = web.Load(mangaUrl);
|
||||
|
||||
List<Chapter> ret = new();
|
||||
|
||||
HtmlNode chapterList = document.DocumentNode.SelectSingleNode("//div[contains(@class, 'chapters')]/table/tbody");
|
||||
|
||||
foreach (HtmlNode chapterInfo in chapterList.Descendants("tr"))
|
||||
{
|
||||
string fullString = chapterInfo.Descendants("a").First().InnerText;
|
||||
|
||||
string? volumeNumber = fullString.Contains("Vol.") ? fullString.Replace("Vol.", "").Split(' ')[0] : null;
|
||||
string chapterNumber = fullString.Split(':')[0].Split("Chapter ")[1].Split(" ")[0].Replace('-', '.');
|
||||
string chapterName = string.Concat(fullString.Split(':')[1..]);
|
||||
string url = chapterInfo.Descendants("a").First()
|
||||
.GetAttributeValue("href", "");
|
||||
ret.Add(new Chapter(publication, chapterName, volumeNumber, chapterNumber, url));
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
public override HttpStatusCode DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
|
||||
string requestUrl = chapter.url;
|
||||
// Leaving this in to check if the page exists
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return requestResult.statusCode;
|
||||
|
||||
string[] imageUrls = ParseImageUrlsFromHtml(requestUrl);
|
||||
|
||||
string comicInfoPath = Path.GetTempFileName();
|
||||
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());
|
||||
|
||||
return DownloadChapterImages(imageUrls, chapter.GetArchiveFilePath(settings.downloadLocation), 1, parentTask, comicInfoPath, "https://mangakatana.com/", cancellationToken);
|
||||
}
|
||||
|
||||
private string[] ParseImageUrlsFromHtml(string mangaUrl)
|
||||
{
|
||||
HtmlWeb web = new();
|
||||
HtmlDocument document = web.Load(mangaUrl);
|
||||
|
||||
// Images are loaded dynamically, but the urls are present in a piece of js code on the page
|
||||
string js = document.DocumentNode.SelectSingleNode("//script[contains(., 'data-src')]").InnerText
|
||||
.Replace("\r", "")
|
||||
.Replace("\n", "")
|
||||
.Replace("\t", "");
|
||||
|
||||
// ReSharper disable once StringLiteralTypo
|
||||
string regexPat = @"(var thzq=\[')(.*)(,];function)";
|
||||
var group = Regex.Matches(js, regexPat).First().Groups[2].Value.Replace("'", "");
|
||||
var urls = group.Split(',');
|
||||
|
||||
return urls;
|
||||
}
|
||||
}
|
@ -2,7 +2,6 @@
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using HtmlAgilityPack;
|
||||
using Logging;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
namespace Tranga.Connectors;
|
||||
@ -11,23 +10,23 @@ public class Manganato : Connector
|
||||
{
|
||||
public override string name { get; }
|
||||
|
||||
public Manganato(string downloadLocation, string imageCachePath, Logger? logger) : base(downloadLocation, imageCachePath, logger)
|
||||
public Manganato(TrangaSettings settings) : base(settings)
|
||||
{
|
||||
this.name = "Manganato";
|
||||
this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
|
||||
{
|
||||
{(byte)1, 60}
|
||||
}, logger);
|
||||
{1, 60}
|
||||
}, settings.logger);
|
||||
}
|
||||
|
||||
public override Publication[] GetPublications(string publicationTitle = "")
|
||||
protected override Publication[] GetPublicationsInternal(string publicationTitle = "")
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
string sanitizedTitle = string.Concat(Regex.Matches(publicationTitle, "[A-z]* *")).ToLower().Replace(' ', '_');
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
string sanitizedTitle = string.Join('_', Regex.Matches(publicationTitle, "[A-z]*")).ToLower();
|
||||
string requestUrl = $"https://manganato.com/search/story/{sanitizedTitle}";
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, (byte)1);
|
||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Publication>();
|
||||
|
||||
return ParsePublicationsFromHtml(requestResult.result);
|
||||
@ -51,8 +50,8 @@ public class Manganato : Connector
|
||||
foreach (string url in urls)
|
||||
{
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(url, (byte)1);
|
||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
||||
downloadClient.MakeRequest(url, 1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Publication>();
|
||||
|
||||
ret.Add(ParseSinglePublicationFromHtml(requestResult.result, url.Split('/')[^1]));
|
||||
@ -103,7 +102,6 @@ public class Manganato : Connector
|
||||
string[] genres = value.Split(" - ");
|
||||
tags = genres.ToHashSet();
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
@ -127,11 +125,11 @@ public class Manganato : Connector
|
||||
|
||||
public override Chapter[] GetChapters(Publication publication, string language = "")
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters for {publication.sortName} {publication.internalId} (language={language})");
|
||||
string requestUrl = $"https://chapmanganato.com/{publication.publicationId}";
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, (byte)1);
|
||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Chapter>();
|
||||
|
||||
//Return Chapters ordered by Chapter-Number
|
||||
@ -139,12 +137,12 @@ public class Manganato : Connector
|
||||
{
|
||||
NumberDecimalSeparator = "."
|
||||
};
|
||||
List<Chapter> chapters = ParseChaptersFromHtml(requestResult.result);
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
|
||||
List<Chapter> chapters = ParseChaptersFromHtml(publication, requestResult.result);
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
|
||||
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
|
||||
}
|
||||
|
||||
private List<Chapter> ParseChaptersFromHtml(Stream html)
|
||||
private List<Chapter> ParseChaptersFromHtml(Publication publication, Stream html)
|
||||
{
|
||||
StreamReader reader = new (html);
|
||||
string htmlString = reader.ReadToEnd();
|
||||
@ -159,33 +157,33 @@ public class Manganato : Connector
|
||||
string fullString = chapterInfo.Descendants("a").First(d => d.HasClass("chapter-name")).InnerText;
|
||||
|
||||
string? volumeNumber = fullString.Contains("Vol.") ? fullString.Replace("Vol.", "").Split(' ')[0] : null;
|
||||
string? chapterNumber = fullString.Split(':')[0].Split("Chapter ")[1].Replace('-','.');
|
||||
string chapterNumber = fullString.Split(':')[0].Split("Chapter ")[1].Replace('-','.');
|
||||
string chapterName = string.Concat(fullString.Split(':')[1..]);
|
||||
string url = chapterInfo.Descendants("a").First(d => d.HasClass("chapter-name"))
|
||||
.GetAttributeValue("href", "");
|
||||
ret.Add(new Chapter(chapterName, volumeNumber, chapterNumber, url));
|
||||
ret.Add(new Chapter(publication, chapterName, volumeNumber, chapterNumber, url));
|
||||
}
|
||||
ret.Reverse();
|
||||
return ret;
|
||||
}
|
||||
|
||||
public override void DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask, CancellationToken? cancellationToken = null)
|
||||
public override HttpStatusCode DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return;
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
|
||||
string requestUrl = chapter.url;
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, (byte)1);
|
||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
||||
return;
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return requestResult.statusCode;
|
||||
|
||||
string[] imageUrls = ParseImageUrlsFromHtml(requestResult.result);
|
||||
|
||||
string comicInfoPath = Path.GetTempFileName();
|
||||
File.WriteAllText(comicInfoPath, GetComicInfoXmlString(publication, chapter, logger));
|
||||
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());
|
||||
|
||||
DownloadChapterImages(imageUrls, GetArchiveFilePath(publication, chapter), (byte)1, parentTask, comicInfoPath, "https://chapmanganato.com/", cancellationToken);
|
||||
return DownloadChapterImages(imageUrls, chapter.GetArchiveFilePath(settings.downloadLocation), 1, parentTask, comicInfoPath, "https://chapmanganato.com/", cancellationToken);
|
||||
}
|
||||
|
||||
private string[] ParseImageUrlsFromHtml(Stream html)
|
||||
|
@ -3,7 +3,6 @@ using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml.Linq;
|
||||
using HtmlAgilityPack;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using PuppeteerSharp;
|
||||
using Tranga.TrangaTasks;
|
||||
@ -13,17 +12,16 @@ namespace Tranga.Connectors;
|
||||
public class Mangasee : Connector
|
||||
{
|
||||
public override string name { get; }
|
||||
private IBrowser? _browser = null;
|
||||
private const string ChromiumVersion = "1153303";
|
||||
private IBrowser? _browser;
|
||||
private const string ChromiumVersion = "1154303";
|
||||
|
||||
public Mangasee(string downloadLocation, string imageCachePath, Logger? logger) : base(downloadLocation,
|
||||
imageCachePath, logger)
|
||||
public Mangasee(TrangaSettings settings) : base(settings)
|
||||
{
|
||||
this.name = "Mangasee";
|
||||
this.downloadClient = new DownloadClient(new Dictionary<byte, int>()
|
||||
{
|
||||
{ (byte)1, 60 }
|
||||
}, logger);
|
||||
{ 1, 60 }
|
||||
}, settings.logger);
|
||||
|
||||
Task d = new Task(DownloadBrowser);
|
||||
d.Start();
|
||||
@ -36,31 +34,31 @@ public class Mangasee : Connector
|
||||
browserFetcher.Remove(rev);
|
||||
if (!browserFetcher.LocalRevisions().Contains(ChromiumVersion))
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), "Downloading headless browser");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Downloading headless browser");
|
||||
DateTime last = DateTime.Now.Subtract(TimeSpan.FromSeconds(5));
|
||||
browserFetcher.DownloadProgressChanged += (sender, args) =>
|
||||
browserFetcher.DownloadProgressChanged += (_, args) =>
|
||||
{
|
||||
double currentBytes = Convert.ToDouble(args.BytesReceived) / Convert.ToDouble(args.TotalBytesToReceive);
|
||||
if (args.TotalBytesToReceive == args.BytesReceived)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), "Browser downloaded.");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Browser downloaded.");
|
||||
}
|
||||
else if (DateTime.Now > last.AddSeconds(5))
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Browser download progress: {currentBytes:P2}");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Browser download progress: {currentBytes:P2}");
|
||||
last = DateTime.Now;
|
||||
}
|
||||
|
||||
};
|
||||
if (!browserFetcher.CanDownloadAsync(ChromiumVersion).Result)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Can't download browser version {ChromiumVersion}");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Can't download browser version {ChromiumVersion}");
|
||||
return;
|
||||
}
|
||||
await browserFetcher.DownloadAsync(ChromiumVersion);
|
||||
}
|
||||
|
||||
logger?.WriteLine(this.GetType().ToString(), "Starting browser.");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Starting browser.");
|
||||
this._browser = await Puppeteer.LaunchAsync(new LaunchOptions
|
||||
{
|
||||
Headless = true,
|
||||
@ -73,14 +71,13 @@ public class Mangasee : Connector
|
||||
});
|
||||
}
|
||||
|
||||
public override Publication[] GetPublications(string publicationTitle = "")
|
||||
protected override Publication[] GetPublicationsInternal(string publicationTitle = "")
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
string sanitizedTitle = string.Concat(Regex.Matches(publicationTitle, "[A-z]* *")).ToLower().Replace(' ', '+');
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Getting Publications (title={publicationTitle})");
|
||||
string requestUrl = $"https://mangasee123.com/_search.php";
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, (byte)1);
|
||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Publication>();
|
||||
|
||||
return ParsePublicationsFromHtml(requestResult.result, publicationTitle);
|
||||
@ -93,27 +90,31 @@ public class Mangasee : Connector
|
||||
Dictionary<SearchResultItem, int> queryFiltered = new();
|
||||
foreach (SearchResultItem resultItem in result)
|
||||
{
|
||||
foreach (string term in publicationTitle.Split(' '))
|
||||
if (resultItem.i.Contains(term, StringComparison.CurrentCultureIgnoreCase))
|
||||
if (!queryFiltered.TryAdd(resultItem, 0))
|
||||
queryFiltered[resultItem]++;
|
||||
int matches = resultItem.GetMatches(publicationTitle);
|
||||
if (matches > 0)
|
||||
queryFiltered.TryAdd(resultItem, matches);
|
||||
}
|
||||
|
||||
queryFiltered = queryFiltered.Where(item => item.Value >= publicationTitle.Split(' ').Length - 1)
|
||||
.ToDictionary(item => item.Key, item => item.Value);
|
||||
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Got {queryFiltered.Count} Publications (title={publicationTitle})");
|
||||
|
||||
HashSet<Publication> ret = new();
|
||||
List<SearchResultItem> orderedFiltered =
|
||||
queryFiltered.OrderBy(item => item.Value).ToDictionary(item => item.Key, item => item.Value).Keys.ToList();
|
||||
|
||||
uint index = 1;
|
||||
foreach (SearchResultItem orderedItem in orderedFiltered)
|
||||
{
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest($"https://mangasee123.com/manga/{orderedItem.i}", (byte)1);
|
||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
||||
return Array.Empty<Publication>();
|
||||
downloadClient.MakeRequest($"https://mangasee123.com/manga/{orderedItem.i}", 1);
|
||||
if ((int)requestResult.statusCode >= 200 || (int)requestResult.statusCode < 300)
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Retrieving Publication info: {orderedItem.s} {index++}/{orderedFiltered.Count}");
|
||||
ret.Add(ParseSinglePublicationFromHtml(requestResult.result, orderedItem.s, orderedItem.i, orderedItem.a));
|
||||
}
|
||||
}
|
||||
return ret.ToArray();
|
||||
}
|
||||
|
||||
@ -121,9 +122,8 @@ public class Mangasee : Connector
|
||||
private Publication ParseSinglePublicationFromHtml(Stream html, string sortName, string publicationId, string[] a)
|
||||
{
|
||||
StreamReader reader = new (html);
|
||||
string htmlString = reader.ReadToEnd();
|
||||
HtmlDocument document = new ();
|
||||
document.LoadHtml(htmlString);
|
||||
document.LoadHtml(reader.ReadToEnd());
|
||||
|
||||
string originalLanguage = "", status = "";
|
||||
Dictionary<string, string> altTitles = new(), links = new();
|
||||
@ -177,11 +177,41 @@ public class Mangasee : Connector
|
||||
// ReSharper disable once ClassNeverInstantiated.Local Will be instantiated during deserialization
|
||||
private class SearchResultItem
|
||||
{
|
||||
#pragma warning disable CS8618 //Will always be set
|
||||
public string i { get; set; }
|
||||
public string s { get; set; }
|
||||
public string[] a { get; set; }
|
||||
#pragma warning restore CS8618
|
||||
public string i { get; init; }
|
||||
public string s { get; init; }
|
||||
public string[] a { get; init; }
|
||||
|
||||
[JsonConstructor]
|
||||
public SearchResultItem(string i, string s, string[] a)
|
||||
{
|
||||
this.i = i;
|
||||
this.s = s;
|
||||
this.a = a;
|
||||
}
|
||||
|
||||
public int GetMatches(string title)
|
||||
{
|
||||
int ret = 0;
|
||||
Regex cleanRex = new("[A-z0-9]*");
|
||||
string[] badWords = { "a", "an", "no", "ni", "so", "as", "and", "the", "of", "that", "in", "is", "for" };
|
||||
|
||||
string[] titleTerms = title.Split(new[] { ' ', '-' }).Where(str => !badWords.Contains(str)).ToArray();
|
||||
|
||||
foreach (Match matchTerm in cleanRex.Matches(this.i))
|
||||
ret += titleTerms.Count(titleTerm =>
|
||||
titleTerm.Equals(matchTerm.Value, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
foreach (Match matchTerm in cleanRex.Matches(this.s))
|
||||
ret += titleTerms.Count(titleTerm =>
|
||||
titleTerm.Equals(matchTerm.Value, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
foreach(string alt in this.a)
|
||||
foreach (Match matchTerm in cleanRex.Matches(alt))
|
||||
ret += titleTerms.Count(titleTerm =>
|
||||
titleTerm.Equals(matchTerm.Value, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
public override Chapter[] GetChapters(Publication publication, string language = "")
|
||||
@ -191,13 +221,13 @@ public class Mangasee : Connector
|
||||
List<Chapter> ret = new();
|
||||
foreach (XElement chapter in chapterItems)
|
||||
{
|
||||
string? volumeNumber = "1";
|
||||
string volumeNumber = "1";
|
||||
string chapterName = chapter.Descendants("title").First().Value;
|
||||
string chapterNumber = Regex.Matches(chapterName, "[0-9]+")[^1].ToString();
|
||||
|
||||
string url = chapter.Descendants("link").First().Value;
|
||||
url = url.Replace(Regex.Matches(url,"(-page-[0-9])")[0].ToString(),"");
|
||||
ret.Add(new Chapter("", volumeNumber, chapterNumber, url));
|
||||
ret.Add(new Chapter(publication, "", volumeNumber, chapterNumber, url));
|
||||
}
|
||||
|
||||
//Return Chapters ordered by Chapter-Number
|
||||
@ -205,23 +235,23 @@ public class Mangasee : Connector
|
||||
{
|
||||
NumberDecimalSeparator = "."
|
||||
};
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Done getting Chapters for {publication.internalId}");
|
||||
return ret.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
|
||||
}
|
||||
|
||||
public override void DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask, CancellationToken? cancellationToken = null)
|
||||
public override HttpStatusCode DownloadChapter(Publication publication, Chapter chapter, DownloadChapterTask parentTask, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return;
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
while (this._browser is null && !(cancellationToken?.IsCancellationRequested??false))
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), "Waiting for headless browser to download...");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Waiting for headless browser to download...");
|
||||
Thread.Sleep(1000);
|
||||
}
|
||||
if (cancellationToken?.IsCancellationRequested??false)
|
||||
return;
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Downloading Chapter-Info {publication.sortName} {publication.internalId} {chapter.volumeNumber}-{chapter.chapterNumber}");
|
||||
IPage page = _browser!.NewPageAsync().Result;
|
||||
IResponse response = page.GoToAsync(chapter.url).Result;
|
||||
if (response.Ok)
|
||||
@ -236,9 +266,10 @@ public class Mangasee : Connector
|
||||
urls.Add(galleryImage.GetAttributeValue("src", ""));
|
||||
|
||||
string comicInfoPath = Path.GetTempFileName();
|
||||
File.WriteAllText(comicInfoPath, GetComicInfoXmlString(publication, chapter, logger));
|
||||
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());
|
||||
|
||||
DownloadChapterImages(urls.ToArray(), GetArchiveFilePath(publication, chapter), (byte)1, parentTask, comicInfoPath, cancellationToken:cancellationToken);
|
||||
}
|
||||
return DownloadChapterImages(urls.ToArray(), chapter.GetArchiveFilePath(settings.downloadLocation), 1, parentTask, comicInfoPath, cancellationToken:cancellationToken);
|
||||
}
|
||||
return response.Status;
|
||||
}
|
||||
}
|
108
Tranga/DownloadClient.cs
Normal file
@ -0,0 +1,108 @@
|
||||
using System.Net;
|
||||
using Logging;
|
||||
|
||||
namespace Tranga;
|
||||
|
||||
internal class DownloadClient
|
||||
{
|
||||
private static readonly HttpClient Client = new()
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(60)
|
||||
};
|
||||
|
||||
private readonly Dictionary<byte, DateTime> _lastExecutedRateLimit;
|
||||
private readonly Dictionary<byte, TimeSpan> _rateLimit;
|
||||
// ReSharper disable once InconsistentNaming
|
||||
private readonly Logger? logger;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a httpClient
|
||||
/// </summary>
|
||||
/// <param name="rateLimitRequestsPerMinute">Rate limits for requests. byte is RequestType, int maximum requests per minute for RequestType</param>
|
||||
/// <param name="logger"></param>
|
||||
public DownloadClient(Dictionary<byte, int> rateLimitRequestsPerMinute, Logger? logger)
|
||||
{
|
||||
this.logger = logger;
|
||||
_lastExecutedRateLimit = new();
|
||||
_rateLimit = new();
|
||||
foreach(KeyValuePair<byte, int> limit in rateLimitRequestsPerMinute)
|
||||
_rateLimit.Add(limit.Key, TimeSpan.FromMinutes(1).Divide(limit.Value));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request Webpage
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="requestType">For RateLimits: Same Endpoints use same type</param>
|
||||
/// <param name="referrer">Used in http request header</param>
|
||||
/// <returns>RequestResult with StatusCode and Stream of received data</returns>
|
||||
public RequestResult MakeRequest(string url, byte requestType, string? referrer = null)
|
||||
{
|
||||
if (_rateLimit.TryGetValue(requestType, out TimeSpan value))
|
||||
_lastExecutedRateLimit.TryAdd(requestType, DateTime.Now.Subtract(value));
|
||||
else
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), "RequestType not configured for rate-limit.");
|
||||
return new RequestResult(HttpStatusCode.NotAcceptable, Stream.Null);
|
||||
}
|
||||
|
||||
TimeSpan rateLimitTimeout = _rateLimit[requestType]
|
||||
.Subtract(DateTime.Now.Subtract(_lastExecutedRateLimit[requestType]));
|
||||
|
||||
if(rateLimitTimeout > TimeSpan.Zero)
|
||||
Thread.Sleep(rateLimitTimeout);
|
||||
|
||||
HttpResponseMessage? response = null;
|
||||
while (response is null)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpRequestMessage requestMessage = new(HttpMethod.Get, url);
|
||||
if(referrer is not null)
|
||||
requestMessage.Headers.Referrer = new Uri(referrer);
|
||||
_lastExecutedRateLimit[requestType] = DateTime.Now;
|
||||
response = Client.Send(requestMessage);
|
||||
}
|
||||
catch (HttpRequestException e)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), e.Message);
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Waiting {_rateLimit[requestType] * 2}... Retrying.");
|
||||
Thread.Sleep(_rateLimit[requestType] * 2);
|
||||
}
|
||||
}
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Request-Error {response.StatusCode}: {response.ReasonPhrase}");
|
||||
return new RequestResult(response.StatusCode, Stream.Null);
|
||||
}
|
||||
|
||||
// Request has been redirected to another page. For example, it redirects directly to the results when there is only 1 result
|
||||
if(response.RequestMessage is not null && response.RequestMessage.RequestUri is not null)
|
||||
{
|
||||
return new RequestResult(response.StatusCode, response.Content.ReadAsStream(), true, response.RequestMessage.RequestUri.AbsoluteUri);
|
||||
}
|
||||
|
||||
return new RequestResult(response.StatusCode, response.Content.ReadAsStream());
|
||||
}
|
||||
|
||||
public struct RequestResult
|
||||
{
|
||||
public HttpStatusCode statusCode { get; }
|
||||
public Stream result { get; }
|
||||
public bool hasBeenRedirected { get; }
|
||||
public string? redirectedToUrl { get; }
|
||||
|
||||
public RequestResult(HttpStatusCode statusCode, Stream result)
|
||||
{
|
||||
this.statusCode = statusCode;
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
public RequestResult(HttpStatusCode statusCode, Stream result, bool hasBeenRedirected, string redirectedTo)
|
||||
: this(statusCode, result)
|
||||
{
|
||||
this.hasBeenRedirected = hasBeenRedirected;
|
||||
redirectedToUrl = redirectedTo;
|
||||
}
|
||||
}
|
||||
}
|
@ -36,7 +36,7 @@ public class Kavita : LibraryManager
|
||||
HttpResponseMessage response = client.Send(requestMessage);
|
||||
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(response.Content.ReadAsStream());
|
||||
if (result is not null)
|
||||
return result!["token"]!.GetValue<string>();
|
||||
return result["token"]!.GetValue<string>();
|
||||
else return "";
|
||||
}
|
||||
|
||||
@ -73,7 +73,7 @@ public class Kavita : LibraryManager
|
||||
{
|
||||
var jObject = (JsonObject?)jsonNode;
|
||||
int libraryId = jObject!["id"]!.GetValue<int>();
|
||||
string libraryName = jObject!["name"]!.GetValue<string>();
|
||||
string libraryName = jObject["name"]!.GetValue<string>();
|
||||
ret.Add(new KavitaLibrary(libraryId, libraryName));
|
||||
}
|
||||
|
||||
@ -83,6 +83,7 @@ public class Kavita : LibraryManager
|
||||
private struct KavitaLibrary
|
||||
{
|
||||
public int id { get; }
|
||||
// ReSharper disable once UnusedAutoPropertyAccessor.Local
|
||||
public string name { get; }
|
||||
|
||||
public KavitaLibrary(int id, string name)
|
||||
|
@ -54,7 +54,7 @@ public class Komga : LibraryManager
|
||||
{
|
||||
var jObject = (JsonObject?)jsonNode;
|
||||
string libraryId = jObject!["id"]!.GetValue<string>();
|
||||
string libraryName = jObject!["name"]!.GetValue<string>();
|
||||
string libraryName = jObject["name"]!.GetValue<string>();
|
||||
ret.Add(new KomgaLibrary(libraryId, libraryName));
|
||||
}
|
||||
|
||||
@ -64,6 +64,7 @@ public class Komga : LibraryManager
|
||||
private struct KomgaLibrary
|
||||
{
|
||||
public string id { get; }
|
||||
// ReSharper disable once UnusedAutoPropertyAccessor.Local
|
||||
public string name { get; }
|
||||
|
||||
public KomgaLibrary(string id, string name)
|
||||
|
@ -3,9 +3,8 @@ using System.Net.Http.Headers;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Tranga.LibraryManagers;
|
||||
|
||||
namespace Tranga;
|
||||
namespace Tranga.LibraryManagers;
|
||||
|
||||
public abstract class LibraryManager
|
||||
{
|
||||
@ -15,14 +14,17 @@ public abstract class LibraryManager
|
||||
Kavita = 1
|
||||
}
|
||||
|
||||
// ReSharper disable once UnusedAutoPropertyAccessor.Global
|
||||
public LibraryType libraryType { get; }
|
||||
public string baseUrl { get; }
|
||||
// ReSharper disable once MemberCanBeProtected.Global
|
||||
public string auth { get; } //Base64 encoded, if you use your password everywhere, you have problems
|
||||
protected Logger? logger;
|
||||
|
||||
/// <param name="baseUrl">Base-URL of Komga instance, no trailing slashes(/)</param>
|
||||
/// <param name="auth">Base64 string of username and password (username):(password)</param>
|
||||
/// <param name="logger"></param>
|
||||
/// <param name="libraryType"></param>
|
||||
protected LibraryManager(string baseUrl, string auth, Logger? logger, LibraryType libraryType)
|
||||
{
|
||||
this.baseUrl = baseUrl;
|
33
Tranga/Migrate.cs
Normal file
@ -0,0 +1,33 @@
|
||||
using Newtonsoft.Json;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
namespace Tranga;
|
||||
|
||||
public static class Migrate
|
||||
{
|
||||
private static readonly ushort CurrentVersion = 16;
|
||||
public static void Files(TrangaSettings settings)
|
||||
{
|
||||
settings.version ??= 15;
|
||||
switch (settings.version)
|
||||
{
|
||||
case 15:
|
||||
RemoveUpdateLibraryTask(settings);
|
||||
break;
|
||||
}
|
||||
|
||||
settings.version = CurrentVersion;
|
||||
settings.ExportSettings();
|
||||
}
|
||||
|
||||
private static void RemoveUpdateLibraryTask(TrangaSettings settings)
|
||||
{
|
||||
if (!File.Exists(settings.tasksFilePath))
|
||||
return;
|
||||
|
||||
string tasksJsonString = File.ReadAllText(settings.tasksFilePath);
|
||||
HashSet<TrangaTask> tasks = JsonConvert.DeserializeObject<HashSet<TrangaTask>>(tasksJsonString, new JsonSerializerSettings { Converters = { new TrangaTask.TrangaTaskJsonConverter() } })!;
|
||||
tasks.RemoveWhere(t => t.task == TrangaTask.Task.UpdateLibraries);
|
||||
File.WriteAllText(settings.tasksFilePath, JsonConvert.SerializeObject(tasks));
|
||||
}
|
||||
}
|
52
Tranga/NotificationManagers/Gotify.cs
Normal file
@ -0,0 +1,52 @@
|
||||
using System.Text;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Tranga.NotificationManagers;
|
||||
|
||||
public class Gotify : NotificationManager
|
||||
{
|
||||
public string endpoint { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string appToken { get; }
|
||||
private readonly HttpClient _client = new();
|
||||
|
||||
[JsonConstructor]
|
||||
public Gotify(string endpoint, string appToken, Logger? logger = null) : base(NotificationManagerType.Gotify, logger)
|
||||
{
|
||||
this.endpoint = endpoint;
|
||||
this.appToken = appToken;
|
||||
}
|
||||
|
||||
public override void SendNotification(string title, string notificationText)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Sending notification: {title} - {notificationText}");
|
||||
MessageData message = new(title, notificationText);
|
||||
HttpRequestMessage request = new(HttpMethod.Post, $"{endpoint}/message");
|
||||
request.Headers.Add("X-Gotify-Key", this.appToken);
|
||||
request.Content = new StringContent(JsonConvert.SerializeObject(message, Formatting.None), Encoding.UTF8, "application/json");
|
||||
HttpResponseMessage response = _client.Send(request);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
StreamReader sr = new (response.Content.ReadAsStream());
|
||||
logger?.WriteLine(this.GetType().ToString(), $"{response.StatusCode}: {sr.ReadToEnd()}");
|
||||
}
|
||||
}
|
||||
|
||||
private class MessageData
|
||||
{
|
||||
// ReSharper disable four times UnusedAutoPropertyAccessor.Local
|
||||
public string message { get; }
|
||||
public long priority { get; }
|
||||
public string title { get; }
|
||||
public Dictionary<string, object> extras { get; }
|
||||
|
||||
public MessageData(string title, string message)
|
||||
{
|
||||
this.title = title;
|
||||
this.message = message;
|
||||
this.extras = new();
|
||||
this.priority = 4;
|
||||
}
|
||||
}
|
||||
}
|
45
Tranga/NotificationManagers/LunaSea.cs
Normal file
@ -0,0 +1,45 @@
|
||||
using System.Text;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Tranga.NotificationManagers;
|
||||
|
||||
public class LunaSea : NotificationManager
|
||||
{
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string id { get; init; }
|
||||
private readonly HttpClient _client = new();
|
||||
|
||||
[JsonConstructor]
|
||||
public LunaSea(string id, Logger? logger = null) : base(NotificationManagerType.LunaSea, logger)
|
||||
{
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public override void SendNotification(string title, string notificationText)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Sending notification: {title} - {notificationText}");
|
||||
MessageData message = new(title, notificationText);
|
||||
HttpRequestMessage request = new(HttpMethod.Post, $"https://notify.lunasea.app/v1/custom/{id}");
|
||||
request.Content = new StringContent(JsonConvert.SerializeObject(message, Formatting.None), Encoding.UTF8, "application/json");
|
||||
HttpResponseMessage response = _client.Send(request);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
StreamReader sr = new (response.Content.ReadAsStream());
|
||||
logger?.WriteLine(this.GetType().ToString(), $"{response.StatusCode}: {sr.ReadToEnd()}");
|
||||
}
|
||||
}
|
||||
|
||||
private class MessageData
|
||||
{
|
||||
// ReSharper disable twice UnusedAutoPropertyAccessor.Local
|
||||
public string title { get; }
|
||||
public string body { get; }
|
||||
|
||||
public MessageData(string title, string body)
|
||||
{
|
||||
this.title = title;
|
||||
this.body = body;
|
||||
}
|
||||
}
|
||||
}
|
56
Tranga/NotificationManagers/NotificationManager.cs
Normal file
@ -0,0 +1,56 @@
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Tranga.NotificationManagers;
|
||||
|
||||
public abstract class NotificationManager
|
||||
{
|
||||
protected Logger? logger;
|
||||
public NotificationManagerType notificationManagerType;
|
||||
|
||||
protected NotificationManager(NotificationManagerType notificationManagerType, Logger? logger = null)
|
||||
{
|
||||
this.notificationManagerType = notificationManagerType;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public enum NotificationManagerType : byte { Gotify = 0, LunaSea = 1 }
|
||||
|
||||
public abstract void SendNotification(string title, string notificationText);
|
||||
|
||||
public void AddLogger(Logger pLogger)
|
||||
{
|
||||
this.logger = pLogger;
|
||||
}
|
||||
|
||||
public class NotificationManagerJsonConverter : JsonConverter
|
||||
{
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return (objectType == typeof(NotificationManager));
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue,
|
||||
JsonSerializer serializer)
|
||||
{
|
||||
JObject jo = JObject.Load(reader);
|
||||
if (jo["notificationManagerType"]!.Value<byte>() == (byte)NotificationManagerType.Gotify)
|
||||
return jo.ToObject<Gotify>(serializer)!;
|
||||
else if (jo["notificationManagerType"]!.Value<byte>() == (byte)NotificationManagerType.LunaSea)
|
||||
return jo.ToObject<LunaSea>(serializer)!;
|
||||
|
||||
throw new Exception();
|
||||
}
|
||||
|
||||
public override bool CanWrite => false;
|
||||
|
||||
/// <summary>
|
||||
/// Don't call this
|
||||
/// </summary>
|
||||
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
|
||||
{
|
||||
throw new Exception("Dont call this");
|
||||
}
|
||||
}
|
||||
}
|
@ -9,39 +9,34 @@ namespace Tranga;
|
||||
/// <summary>
|
||||
/// Contains information on a Publication (Manga)
|
||||
/// </summary>
|
||||
public readonly struct Publication
|
||||
public struct Publication
|
||||
{
|
||||
public string sortName { get; }
|
||||
public List<string> authors { get; }
|
||||
// ReSharper disable once UnusedAutoPropertyAccessor.Global
|
||||
public Dictionary<string,string> altTitles { get; }
|
||||
// ReSharper disable trice MemberCanBePrivate.Global, trust
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string? description { get; }
|
||||
public string[] tags { get; }
|
||||
// ReSharper disable once UnusedAutoPropertyAccessor.Global
|
||||
public string? posterUrl { get; }
|
||||
public string? coverFileNameInCache { get; }
|
||||
// ReSharper disable once UnusedAutoPropertyAccessor.Global
|
||||
public Dictionary<string,string> links { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public int? year { get; }
|
||||
public string? originalLanguage { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string status { get; }
|
||||
public string folderName { get; }
|
||||
public string publicationId { get; }
|
||||
public string internalId { get; }
|
||||
public float ignoreChaptersBelow { get; set; }
|
||||
|
||||
private static readonly Regex LegalCharacters = new Regex(@"[A-Z]*[a-z]*[0-9]* *\.*-*,*'*\'*\)*\(*~*!*");
|
||||
|
||||
[JsonConstructor] //Legacy
|
||||
public Publication(string sortName, string? author, string? description, Dictionary<string, string> altTitles,
|
||||
string[] tags, string? posterUrl, string? coverFileNameInCache, Dictionary<string, string>? links, int? year,
|
||||
string? originalLanguage, string status, string publicationId)
|
||||
{
|
||||
List<string> pAuthors = new();
|
||||
if(author is not null)
|
||||
pAuthors.Add(author);
|
||||
this = new Publication(sortName, pAuthors, description, altTitles, tags, posterUrl,
|
||||
coverFileNameInCache, links, year, originalLanguage, status, publicationId);
|
||||
}
|
||||
|
||||
public Publication(string sortName, List<string> authors, string? description, Dictionary<string,string> altTitles, string[] tags, string? posterUrl, string? coverFileNameInCache, Dictionary<string,string>? links, int? year, string? originalLanguage, string status, string publicationId)
|
||||
[JsonConstructor]
|
||||
public Publication(string sortName, List<string> authors, string? description, Dictionary<string,string> altTitles, string[] tags, string? posterUrl, string? coverFileNameInCache, Dictionary<string,string>? links, int? year, string? originalLanguage, string status, string publicationId, string? folderName = null, float? ignoreChaptersBelow = 0)
|
||||
{
|
||||
this.sortName = sortName;
|
||||
this.authors = authors;
|
||||
@ -55,11 +50,12 @@ public readonly struct Publication
|
||||
this.originalLanguage = originalLanguage;
|
||||
this.status = status;
|
||||
this.publicationId = publicationId;
|
||||
this.folderName = string.Concat(LegalCharacters.Matches(sortName));
|
||||
this.folderName = folderName ?? string.Concat(LegalCharacters.Matches(sortName));
|
||||
while (this.folderName.EndsWith('.'))
|
||||
this.folderName = this.folderName.Substring(0, this.folderName.Length - 1);
|
||||
string onlyLowerLetters = string.Concat(this.sortName.ToLower().Where(Char.IsLetter));
|
||||
this.internalId = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{onlyLowerLetters}{this.year}"));
|
||||
this.ignoreChaptersBelow = ignoreChaptersBelow ?? 0f;
|
||||
}
|
||||
|
||||
public string CreatePublicationFolder(string downloadDirectory)
|
||||
@ -83,7 +79,7 @@ public readonly struct Publication
|
||||
}
|
||||
|
||||
/// <returns>Serialized JSON String for series.json</returns>
|
||||
public string GetSeriesInfoJson()
|
||||
private string GetSeriesInfoJson()
|
||||
{
|
||||
SeriesInfo si = new (new Metadata(this.sortName, this.year.ToString() ?? string.Empty, this.status, this.description ?? ""));
|
||||
return System.Text.Json.JsonSerializer.Serialize(si);
|
||||
|
@ -1,7 +1,5 @@
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json;
|
||||
using Tranga.Connectors;
|
||||
using Tranga.LibraryManagers;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
namespace Tranga;
|
||||
@ -12,66 +10,31 @@ namespace Tranga;
|
||||
/// </summary>
|
||||
public class TaskManager
|
||||
{
|
||||
public Dictionary<Publication, List<Chapter>> chapterCollection = new();
|
||||
public HashSet<Publication> collection = new();
|
||||
private HashSet<TrangaTask> _allTasks = new();
|
||||
private readonly Dictionary<TrangaTask, CancellationTokenSource> _runningTasks = new ();
|
||||
private bool _continueRunning = true;
|
||||
private readonly Connector[] _connectors;
|
||||
public TrangaSettings settings { get; }
|
||||
private Logger? logger { get; }
|
||||
|
||||
private readonly Dictionary<DownloadChapterTask, CancellationTokenSource> _runningDownloadChapterTasks = new();
|
||||
|
||||
/// <param name="downloadFolderPath">Local path to save data (Manga) to</param>
|
||||
/// <param name="workingDirectory">Path to the working directory</param>
|
||||
/// <param name="imageCachePath">Path to the cover-image cache</param>
|
||||
/// <param name="libraryManagers"></param>
|
||||
/// <param name="logger"></param>
|
||||
public TaskManager(string downloadFolderPath, string workingDirectory, string imageCachePath, HashSet<LibraryManager> libraryManagers, Logger? logger = null)
|
||||
public TaskManager(TrangaSettings settings)
|
||||
{
|
||||
this.logger = logger;
|
||||
|
||||
this.settings = new TrangaSettings(downloadFolderPath, workingDirectory, libraryManagers);
|
||||
ExportDataAndSettings();
|
||||
|
||||
settings.logger?.WriteLine("Tranga", value: "\n"+
|
||||
@"-----------------------------------------------------------------"+"\n"+
|
||||
@" |¯¯¯¯¯¯|°|¯¯¯¯¯¯\ /¯¯¯¯¯¯| |¯¯¯\|¯¯¯| /¯¯¯¯¯¯\' /¯¯¯¯¯¯| "+"\n"+
|
||||
@" | | | x <|' / ! | | '| | (/¯¯¯\° / ! | "+ "\n"+
|
||||
@" ¯|__|¯ |__|\\__\\ /___/¯|_'| |___|\\__| \\_____/' /___/¯|_'| "+ "\n"+
|
||||
@"-----------------------------------------------------------------");
|
||||
this._connectors = new Connector[]
|
||||
{
|
||||
new MangaDex(downloadFolderPath, imageCachePath, logger),
|
||||
new Manganato(downloadFolderPath, imageCachePath, logger),
|
||||
new Mangasee(downloadFolderPath, imageCachePath, logger)
|
||||
};
|
||||
|
||||
Thread taskChecker = new(TaskCheckerThread);
|
||||
taskChecker.Start();
|
||||
}
|
||||
|
||||
public void UpdateSettings(string? downloadLocation, string? komgaUrl, string? komgaAuth, string? kavitaUrl, string? kavitaUsername, string? kavitaPassword)
|
||||
{
|
||||
if (komgaUrl is not null && komgaAuth is not null && komgaUrl.Length > 0 && komgaAuth.Length > 0)
|
||||
{
|
||||
settings.libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Komga));
|
||||
settings.libraryManagers.Add(new Komga(komgaUrl, komgaAuth, logger));
|
||||
}
|
||||
if (kavitaUrl is not null && kavitaUsername is not null && kavitaPassword is not null && kavitaUrl.Length > 0 && kavitaUsername.Length > 0 && kavitaPassword.Length > 0)
|
||||
{
|
||||
settings.libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Kavita));
|
||||
settings.libraryManagers.Add(new Kavita(kavitaUrl, kavitaUsername, kavitaPassword, logger));
|
||||
}
|
||||
if (downloadLocation is not null && downloadLocation.Length > 0)
|
||||
settings.downloadLocation = downloadLocation;
|
||||
ExportDataAndSettings();
|
||||
}
|
||||
|
||||
public TaskManager(TrangaSettings settings, Logger? logger = null)
|
||||
{
|
||||
this.logger = logger;
|
||||
this._connectors = new Connector[]
|
||||
{
|
||||
new MangaDex(settings.downloadLocation, settings.coverImageCache, logger),
|
||||
new Manganato(settings.downloadLocation, settings.coverImageCache, logger),
|
||||
new Mangasee(settings.downloadLocation, settings.coverImageCache, logger)
|
||||
new MangaDex(settings),
|
||||
new Manganato(settings),
|
||||
new Mangasee(settings),
|
||||
new MangaKatana(settings)
|
||||
};
|
||||
|
||||
this.settings = settings;
|
||||
Migrate.Files(settings);
|
||||
ImportData();
|
||||
ExportDataAndSettings();
|
||||
Thread taskChecker = new(TaskCheckerThread);
|
||||
@ -84,68 +47,79 @@ public class TaskManager
|
||||
/// </summary>
|
||||
private void TaskCheckerThread()
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), "Starting TaskCheckerThread.");
|
||||
int allTasksWaitingLength = _allTasks.Count(task => task.state is TrangaTask.ExecutionState.Waiting);
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Starting TaskCheckerThread.");
|
||||
int waitingTasksCount = _allTasks.Count(task => task.state is TrangaTask.ExecutionState.Waiting);
|
||||
while (_continueRunning)
|
||||
{
|
||||
TrangaTask[] tmp = _allTasks.Where(taskQuery =>
|
||||
foreach (TrangaTask waitingButExecute in _allTasks.Where(taskQuery =>
|
||||
taskQuery.nextExecution < DateTime.Now &&
|
||||
taskQuery.state is TrangaTask.ExecutionState.Waiting or TrangaTask.ExecutionState.Enqueued)
|
||||
.OrderBy(tmpTask => tmpTask.nextExecution).ToArray();
|
||||
foreach (TrangaTask task in tmp)
|
||||
taskQuery.state is TrangaTask.ExecutionState.Waiting))
|
||||
{
|
||||
task.state = TrangaTask.ExecutionState.Enqueued;
|
||||
switch (task.task)
|
||||
{
|
||||
case TrangaTask.Task.DownloadNewChapters:
|
||||
if (!_allTasks.Any(taskQuery => taskQuery.task == TrangaTask.Task.DownloadNewChapters &&
|
||||
taskQuery.state is TrangaTask.ExecutionState.Running &&
|
||||
((DownloadNewChaptersTask)taskQuery).connectorName == ((DownloadNewChaptersTask)task).connectorName))
|
||||
{
|
||||
ExecuteTaskNow(task);
|
||||
waitingButExecute.state = TrangaTask.ExecutionState.Enqueued;
|
||||
}
|
||||
break;
|
||||
case TrangaTask.Task.DownloadChapter:
|
||||
if (!_allTasks.Any(taskQuery =>
|
||||
taskQuery.task == TrangaTask.Task.DownloadChapter &&
|
||||
taskQuery.state is TrangaTask.ExecutionState.Running &&
|
||||
((DownloadChapterTask)taskQuery).connectorName ==
|
||||
((DownloadChapterTask)task).connectorName))
|
||||
|
||||
foreach (TrangaTask enqueuedTask in _allTasks.Where(enqueuedTask => enqueuedTask.state is TrangaTask.ExecutionState.Enqueued).OrderBy(enqueuedTask => enqueuedTask.nextExecution))
|
||||
{
|
||||
ExecuteTaskNow(task);
|
||||
switch (enqueuedTask.task)
|
||||
{
|
||||
case TrangaTask.Task.DownloadChapter:
|
||||
case TrangaTask.Task.MonitorPublication:
|
||||
if (!_allTasks.Any(taskQuery =>
|
||||
{
|
||||
if (taskQuery.state is not TrangaTask.ExecutionState.Running) return false;
|
||||
switch (taskQuery)
|
||||
{
|
||||
case DownloadChapterTask dct when enqueuedTask is DownloadChapterTask eDct && dct.connectorName == eDct.connectorName:
|
||||
case MonitorPublicationTask mpt when enqueuedTask is MonitorPublicationTask eMpt && mpt.connectorName == eMpt.connectorName:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}))
|
||||
{
|
||||
ExecuteTaskNow(enqueuedTask);
|
||||
}
|
||||
break;
|
||||
case TrangaTask.Task.UpdateLibraries:
|
||||
ExecuteTaskNow(task);
|
||||
ExecuteTaskNow(enqueuedTask);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
HashSet<DownloadChapterTask> toRemove = new();
|
||||
foreach (KeyValuePair<DownloadChapterTask, CancellationTokenSource> removeTask in _runningDownloadChapterTasks)
|
||||
foreach (TrangaTask timedOutTask in _runningTasks.Keys
|
||||
.Where(taskQuery => taskQuery.lastChange < DateTime.Now.Subtract(TimeSpan.FromMinutes(3))))
|
||||
{
|
||||
if (removeTask.Key.GetType() == typeof(DownloadChapterTask) &&
|
||||
DateTime.Now.Subtract(removeTask.Key.lastChange) > TimeSpan.FromMinutes(3))//3 Minutes since last update to task -> remove
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Disposing failed task {removeTask.Key}.");
|
||||
removeTask.Key.parentTask?.DecrementProgress(removeTask.Key.progress);
|
||||
removeTask.Value.Cancel();
|
||||
toRemove.Add(removeTask.Key);
|
||||
}
|
||||
}
|
||||
foreach (DownloadChapterTask taskToRemove in toRemove)
|
||||
{
|
||||
DeleteTask(taskToRemove);
|
||||
DownloadChapterTask newTask = new DownloadChapterTask(taskToRemove.task, taskToRemove.connectorName,
|
||||
taskToRemove.publication, taskToRemove.chapter, taskToRemove.language,
|
||||
taskToRemove.parentTask);
|
||||
AddTask(newTask);
|
||||
taskToRemove.parentTask?.ReplaceFailedChildTask(taskToRemove, newTask);
|
||||
_runningTasks[timedOutTask].Cancel();
|
||||
timedOutTask.state = TrangaTask.ExecutionState.Failed;
|
||||
}
|
||||
|
||||
if(allTasksWaitingLength != _allTasks.Count(task => task.state is TrangaTask.ExecutionState.Waiting))
|
||||
foreach (TrangaTask finishedTask in _allTasks
|
||||
.Where(taskQuery => taskQuery.state is TrangaTask.ExecutionState.Success).ToArray())
|
||||
{
|
||||
if(finishedTask is DownloadChapterTask)
|
||||
{
|
||||
DeleteTask(finishedTask);
|
||||
finishedTask.state = TrangaTask.ExecutionState.Success;
|
||||
}
|
||||
else
|
||||
{
|
||||
finishedTask.state = TrangaTask.ExecutionState.Waiting;
|
||||
this._runningTasks.Remove(finishedTask);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (TrangaTask failedTask in _allTasks.Where(taskQuery =>
|
||||
taskQuery.state is TrangaTask.ExecutionState.Failed).ToArray())
|
||||
{
|
||||
DeleteTask(failedTask);
|
||||
TrangaTask newTask = failedTask.Clone();
|
||||
failedTask.parentTask?.AddChildTask(newTask);
|
||||
AddTask(newTask);
|
||||
}
|
||||
|
||||
if(waitingTasksCount != _allTasks.Count(task => task.state is TrangaTask.ExecutionState.Waiting))
|
||||
ExportDataAndSettings();
|
||||
allTasksWaitingLength = _allTasks.Count(task => task.state is TrangaTask.ExecutionState.Waiting);
|
||||
waitingTasksCount = _allTasks.Count(task => task.state is TrangaTask.ExecutionState.Waiting);
|
||||
Thread.Sleep(1000);
|
||||
}
|
||||
}
|
||||
@ -160,171 +134,118 @@ public class TaskManager
|
||||
CancellationTokenSource cToken = new ();
|
||||
Task t = new(() =>
|
||||
{
|
||||
task.Execute(this, this.logger, cToken.Token);
|
||||
task.Execute(this, cToken.Token);
|
||||
}, cToken.Token);
|
||||
if(task.GetType() == typeof(DownloadChapterTask))
|
||||
_runningDownloadChapterTasks.Add((DownloadChapterTask)task, cToken);
|
||||
_runningTasks.Add(task, cToken);
|
||||
t.Start();
|
||||
}
|
||||
|
||||
public void AddTask(TrangaTask newTask)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Adding new Task {newTask}");
|
||||
|
||||
switch (newTask.task)
|
||||
{
|
||||
case TrangaTask.Task.UpdateLibraries:
|
||||
//Only one UpdateKomgaLibrary Task
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Removing old {newTask.task}-Task.");
|
||||
_allTasks.RemoveWhere(trangaTask => trangaTask.task is TrangaTask.Task.UpdateLibraries);
|
||||
break;
|
||||
case TrangaTask.Task.DownloadNewChapters:
|
||||
IEnumerable<TrangaTask> matchingdnc =
|
||||
_allTasks.Where(mTask => mTask.GetType() == typeof(DownloadNewChaptersTask));
|
||||
if (!matchingdnc.Any(mTask =>
|
||||
((DownloadNewChaptersTask)mTask).publication.internalId == ((DownloadNewChaptersTask)newTask).publication.internalId &&
|
||||
((DownloadNewChaptersTask)mTask).connectorName == ((DownloadNewChaptersTask)newTask).connectorName))
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Replacing old {newTask.task}-Task.");
|
||||
if (GetTasksMatching(newTask).FirstOrDefault() is { } exists)
|
||||
_allTasks.Remove(exists);
|
||||
_allTasks.Add(newTask);
|
||||
else
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Task already exists {newTask}");
|
||||
ExportDataAndSettings();
|
||||
break;
|
||||
case TrangaTask.Task.DownloadChapter:
|
||||
IEnumerable<TrangaTask> matchingdc =
|
||||
_allTasks.Where(mTask => mTask.GetType() == typeof(DownloadChapterTask));
|
||||
if (!matchingdc.Any(mTask =>
|
||||
((DownloadChapterTask)mTask).publication.internalId == ((DownloadChapterTask)newTask).publication.internalId &&
|
||||
((DownloadChapterTask)mTask).connectorName == ((DownloadChapterTask)newTask).connectorName &&
|
||||
((DownloadChapterTask)mTask).chapter.sortNumber == ((DownloadChapterTask)newTask).chapter.sortNumber))
|
||||
default:
|
||||
if (!GetTasksMatching(newTask).Any())
|
||||
{
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Adding new Task {newTask}");
|
||||
_allTasks.Add(newTask);
|
||||
ExportDataAndSettings();
|
||||
}
|
||||
else
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Task already exists {newTask}");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Task already exists {newTask}");
|
||||
break;
|
||||
}
|
||||
ExportDataAndSettings();
|
||||
}
|
||||
|
||||
public void DeleteTask(TrangaTask removeTask)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Removing Task {removeTask}");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Removing Task {removeTask}");
|
||||
if(_allTasks.Contains(removeTask))
|
||||
_allTasks.Remove(removeTask);
|
||||
if (removeTask.GetType() == typeof(DownloadChapterTask))
|
||||
_runningDownloadChapterTasks.Remove((DownloadChapterTask)removeTask);
|
||||
}
|
||||
|
||||
public TrangaTask? AddTask(TrangaTask.Task taskType, string? connectorName, string? internalId,
|
||||
TimeSpan reoccurrenceTime, string? language = "en")
|
||||
removeTask.parentTask?.RemoveChildTask(removeTask);
|
||||
if (_runningTasks.ContainsKey(removeTask))
|
||||
{
|
||||
TrangaTask? newTask = null;
|
||||
switch (taskType)
|
||||
{
|
||||
case TrangaTask.Task.UpdateLibraries:
|
||||
newTask = new UpdateLibrariesTask(taskType, reoccurrenceTime);
|
||||
break;
|
||||
case TrangaTask.Task.DownloadNewChapters:
|
||||
if (connectorName is null)
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Value connectorName can not be null.");
|
||||
if(internalId is null)
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Value internalId can not be null.");
|
||||
if(language is null)
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Value language can not be null.");
|
||||
if (connectorName is null || internalId is null || language is null)
|
||||
return null;
|
||||
GetConnector(connectorName); //Check if connectorName is valid
|
||||
Publication publication = GetAllPublications().First(pub => pub.internalId == internalId);
|
||||
newTask = new DownloadNewChaptersTask(taskType, connectorName!, publication, reoccurrenceTime, language!);
|
||||
break;
|
||||
}
|
||||
if(newTask is not null)
|
||||
AddTask(newTask);
|
||||
return newTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes Task from task-collection
|
||||
/// </summary>
|
||||
/// <param name="task">TrangaTask.Task type</param>
|
||||
/// <param name="connectorName">Name of Connector that was used</param>
|
||||
/// <param name="publicationId">Publication that was used</param>
|
||||
public void DeleteTask(TrangaTask.Task task, string? connectorName, string? publicationId)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Removing Task {task} {publicationId}");
|
||||
|
||||
switch (task)
|
||||
{
|
||||
case TrangaTask.Task.UpdateLibraries:
|
||||
//Only one UpdateKomgaLibrary Task
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Removing old {task}-Task.");
|
||||
_allTasks.RemoveWhere(trangaTask => trangaTask.task is TrangaTask.Task.UpdateLibraries);
|
||||
break;
|
||||
case TrangaTask.Task.DownloadNewChapters:
|
||||
if (connectorName is null || publicationId is null)
|
||||
logger?.WriteLine(this.GetType().ToString(), "connectorName and publication can not be null");
|
||||
else
|
||||
{
|
||||
_allTasks.RemoveWhere(mTask =>
|
||||
mTask.GetType() == typeof(DownloadNewChaptersTask) &&
|
||||
((DownloadNewChaptersTask)mTask).publication.internalId == publicationId &&
|
||||
((DownloadNewChaptersTask)mTask).connectorName == connectorName!);
|
||||
_allTasks.RemoveWhere(mTask =>
|
||||
mTask.GetType() == typeof(DownloadChapterTask) &&
|
||||
((DownloadChapterTask)mTask).publication.internalId == publicationId &&
|
||||
((DownloadChapterTask)mTask).connectorName == connectorName!);
|
||||
}
|
||||
break;
|
||||
_runningTasks[removeTask].Cancel();
|
||||
_runningTasks.Remove(removeTask);
|
||||
}
|
||||
foreach(TrangaTask childTask in removeTask.childTasks)
|
||||
DeleteTask(childTask);
|
||||
ExportDataAndSettings();
|
||||
}
|
||||
|
||||
public IEnumerable<TrangaTask> GetTasksMatching(TrangaTask.Task taskType, string? connectorName = null, string? searchString = null, string? internalId = null, string? chapterSortNumber = null)
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public IEnumerable<TrangaTask> GetTasksMatching(TrangaTask mTask)
|
||||
{
|
||||
switch (mTask.task)
|
||||
{
|
||||
case TrangaTask.Task.UpdateLibraries:
|
||||
return GetTasksMatching(TrangaTask.Task.UpdateLibraries);
|
||||
case TrangaTask.Task.DownloadChapter:
|
||||
DownloadChapterTask dct = (DownloadChapterTask)mTask;
|
||||
return GetTasksMatching(TrangaTask.Task.DownloadChapter, connectorName: dct.connectorName,
|
||||
internalId: dct.publication.internalId, chapterNumber: dct.chapter.chapterNumber);
|
||||
case TrangaTask.Task.MonitorPublication:
|
||||
MonitorPublicationTask mpt = (MonitorPublicationTask)mTask;
|
||||
return GetTasksMatching(TrangaTask.Task.MonitorPublication, connectorName: mpt.connectorName,
|
||||
internalId: mpt.publication.internalId);
|
||||
}
|
||||
return Array.Empty<TrangaTask>();
|
||||
}
|
||||
|
||||
public IEnumerable<TrangaTask> GetTasksMatching(TrangaTask.Task taskType, string? connectorName = null, string? searchString = null, string? internalId = null, string? chapterNumber = null)
|
||||
{
|
||||
switch (taskType)
|
||||
{
|
||||
case TrangaTask.Task.UpdateLibraries:
|
||||
return _allTasks.Where(tTask => tTask.task == TrangaTask.Task.UpdateLibraries);
|
||||
case TrangaTask.Task.DownloadNewChapters:
|
||||
case TrangaTask.Task.MonitorPublication:
|
||||
if(connectorName is null)
|
||||
return _allTasks.Where(tTask => tTask.task == taskType);
|
||||
GetConnector(connectorName);//Name check
|
||||
IEnumerable<TrangaTask> matchingdnc = _allTasks.Where(tTask => tTask.GetType() == typeof(DownloadNewChaptersTask));
|
||||
if (searchString is not null)
|
||||
{
|
||||
return matchingdnc.Where(mTask =>
|
||||
((DownloadNewChaptersTask)mTask).connectorName == connectorName &&
|
||||
((DownloadNewChaptersTask)mTask).ToString().Contains(searchString, StringComparison.InvariantCultureIgnoreCase));
|
||||
return _allTasks.Where(mTask =>
|
||||
mTask is MonitorPublicationTask mpt && mpt.connectorName == connectorName &&
|
||||
mpt.ToString().Contains(searchString, StringComparison.InvariantCultureIgnoreCase));
|
||||
}
|
||||
else if (internalId is not null)
|
||||
{
|
||||
return matchingdnc.Where(mTask =>
|
||||
((DownloadNewChaptersTask)mTask).connectorName == connectorName &&
|
||||
((DownloadNewChaptersTask)mTask).publication.internalId == internalId);
|
||||
return _allTasks.Where(mTask =>
|
||||
mTask is MonitorPublicationTask mpt && mpt.connectorName == connectorName &&
|
||||
mpt.publication.internalId == internalId);
|
||||
}
|
||||
else
|
||||
return _allTasks.Where(tTask =>
|
||||
tTask.GetType() == typeof(DownloadNewChaptersTask) &&
|
||||
((DownloadNewChaptersTask)tTask).connectorName == connectorName);
|
||||
tTask is MonitorPublicationTask mpt && mpt.connectorName == connectorName);
|
||||
|
||||
case TrangaTask.Task.DownloadChapter:
|
||||
if(connectorName is null)
|
||||
return _allTasks.Where(tTask => tTask.task == taskType);
|
||||
GetConnector(connectorName);//Name check
|
||||
IEnumerable<TrangaTask> matchingdc = _allTasks.Where(tTask => tTask.GetType() == typeof(DownloadChapterTask));
|
||||
if (searchString is not null)
|
||||
{
|
||||
return matchingdc.Where(mTask =>
|
||||
((DownloadChapterTask)mTask).connectorName == connectorName &&
|
||||
((DownloadChapterTask)mTask).ToString().Contains(searchString, StringComparison.InvariantCultureIgnoreCase));
|
||||
return _allTasks.Where(mTask =>
|
||||
mTask is DownloadChapterTask dct && dct.connectorName == connectorName &&
|
||||
dct.ToString().Contains(searchString, StringComparison.InvariantCultureIgnoreCase));
|
||||
}
|
||||
else if (internalId is not null && chapterSortNumber is not null)
|
||||
else if (internalId is not null && chapterNumber is not null)
|
||||
{
|
||||
return matchingdc.Where(mTask =>
|
||||
((DownloadChapterTask)mTask).connectorName == connectorName &&
|
||||
((DownloadChapterTask)mTask).publication.publicationId == internalId &&
|
||||
((DownloadChapterTask)mTask).chapter.sortNumber == chapterSortNumber);
|
||||
return _allTasks.Where(mTask =>
|
||||
mTask is DownloadChapterTask dct && dct.connectorName == connectorName &&
|
||||
dct.publication.internalId == internalId &&
|
||||
dct.chapter.chapterNumber == chapterNumber);
|
||||
}
|
||||
else
|
||||
return _allTasks.Where(tTask =>
|
||||
tTask.GetType() == typeof(DownloadChapterTask) &&
|
||||
((DownloadChapterTask)tTask).connectorName == connectorName);
|
||||
return _allTasks.Where(mTask =>
|
||||
mTask is DownloadChapterTask dct && dct.connectorName == connectorName);
|
||||
|
||||
default:
|
||||
return Array.Empty<TrangaTask>();
|
||||
@ -365,21 +286,16 @@ public class TaskManager
|
||||
return ret;
|
||||
}
|
||||
|
||||
public Publication[] GetPublicationsFromConnector(Connector connector, string? title = null)
|
||||
{
|
||||
Publication[] ret = connector.GetPublications(title ?? "");
|
||||
foreach (Publication publication in ret)
|
||||
{
|
||||
if(chapterCollection.All(pub => pub.Key.internalId != publication.internalId))
|
||||
this.chapterCollection.TryAdd(publication, new List<Chapter>());
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// <returns>All added Publications</returns>
|
||||
public Publication[] GetAllPublications()
|
||||
{
|
||||
return this.chapterCollection.Keys.ToArray();
|
||||
return this.collection.ToArray();
|
||||
}
|
||||
|
||||
public List<Chapter> GetExistingChaptersList(Connector connector, Publication publication, string language)
|
||||
{
|
||||
Chapter[] newChapters = connector.GetChapters(publication, language);
|
||||
return newChapters.Where(nChapter => nChapter.CheckChapterIsDownloaded(settings.downloadLocation)).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -403,7 +319,7 @@ public class TaskManager
|
||||
/// <param name="force">If force is true, tasks are aborted.</param>
|
||||
public void Shutdown(bool force = false)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Shutting down (forced={force})");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Shutting down (forced={force})");
|
||||
_continueRunning = false;
|
||||
ExportDataAndSettings();
|
||||
|
||||
@ -413,38 +329,28 @@ public class TaskManager
|
||||
//Wait for tasks to finish
|
||||
while(_allTasks.Any(task => task.state is TrangaTask.ExecutionState.Running or TrangaTask.ExecutionState.Enqueued))
|
||||
Thread.Sleep(10);
|
||||
logger?.WriteLine(this.GetType().ToString(), "Tasks finished. Bye!");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Tasks finished. Bye!");
|
||||
Environment.Exit(0);
|
||||
}
|
||||
|
||||
private void ImportData()
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), "Importing Data");
|
||||
string buffer;
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Importing Data");
|
||||
if (File.Exists(settings.tasksFilePath))
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Importing tasks from {settings.tasksFilePath}");
|
||||
buffer = File.ReadAllText(settings.tasksFilePath);
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Importing tasks from {settings.tasksFilePath}");
|
||||
string buffer = File.ReadAllText(settings.tasksFilePath);
|
||||
this._allTasks = JsonConvert.DeserializeObject<HashSet<TrangaTask>>(buffer, new JsonSerializerSettings() { Converters = { new TrangaTask.TrangaTaskJsonConverter() } })!;
|
||||
}
|
||||
|
||||
foreach (TrangaTask task in this._allTasks.Where(task => task.GetType() == typeof(DownloadChapterTask)))
|
||||
foreach (TrangaTask task in this._allTasks.Where(tTask => tTask.parentTaskId is not null).ToArray())
|
||||
{
|
||||
DownloadChapterTask dcTask = (DownloadChapterTask)task;
|
||||
IEnumerable<TrangaTask> dncTasks = this._allTasks.Where(pTask => pTask.GetType() == typeof(DownloadNewChaptersTask));
|
||||
DownloadNewChaptersTask? parentTask = (DownloadNewChaptersTask?)dncTasks.FirstOrDefault(pTask => pTask.taskId.Equals(dcTask.parentTaskId));
|
||||
dcTask.parentTask = parentTask;
|
||||
parentTask?.AddChildTask(dcTask);
|
||||
TrangaTask? parentTask = this._allTasks.FirstOrDefault(pTask => pTask.taskId == task.parentTaskId);
|
||||
if (parentTask is not null)
|
||||
{
|
||||
this.DeleteTask(task);
|
||||
parentTask.lastExecuted = DateTime.UnixEpoch;
|
||||
}
|
||||
|
||||
|
||||
if (File.Exists(settings.knownPublicationsPath))
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Importing known publications from {settings.knownPublicationsPath}");
|
||||
buffer = File.ReadAllText(settings.knownPublicationsPath);
|
||||
Publication[] publications = JsonConvert.DeserializeObject<Publication[]>(buffer)!;
|
||||
foreach (Publication publication in publications)
|
||||
this.chapterCollection.TryAdd(publication, new List<Chapter>());
|
||||
}
|
||||
}
|
||||
|
||||
@ -453,20 +359,13 @@ public class TaskManager
|
||||
/// </summary>
|
||||
private void ExportDataAndSettings()
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Exporting settings to {settings.settingsFilePath}");
|
||||
while(IsFileInUse(settings.settingsFilePath))
|
||||
Thread.Sleep(50);
|
||||
File.WriteAllText(settings.settingsFilePath, JsonConvert.SerializeObject(settings));
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Exporting settings to {settings.settingsFilePath}");
|
||||
settings.ExportSettings();
|
||||
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Exporting tasks to {settings.tasksFilePath}");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Exporting tasks to {settings.tasksFilePath}");
|
||||
while(IsFileInUse(settings.tasksFilePath))
|
||||
Thread.Sleep(50);
|
||||
File.WriteAllText(settings.tasksFilePath, JsonConvert.SerializeObject(this._allTasks));
|
||||
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Exporting known publications to {settings.knownPublicationsPath}");
|
||||
while(IsFileInUse(settings.knownPublicationsPath))
|
||||
Thread.Sleep(50);
|
||||
File.WriteAllText(settings.knownPublicationsPath, JsonConvert.SerializeObject(this.chapterCollection.Keys.ToArray()));
|
||||
}
|
||||
|
||||
private bool IsFileInUse(string path)
|
||||
|
@ -1,39 +1,117 @@
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Tranga.LibraryManagers;
|
||||
using Tranga.NotificationManagers;
|
||||
|
||||
namespace Tranga;
|
||||
|
||||
public class TrangaSettings
|
||||
{
|
||||
public string downloadLocation { get; set; }
|
||||
public string workingDirectory { get; set; }
|
||||
public string downloadLocation { get; private set; }
|
||||
public string workingDirectory { get; init; }
|
||||
[JsonIgnore] public string settingsFilePath => Path.Join(workingDirectory, "settings.json");
|
||||
[JsonIgnore] public string tasksFilePath => Path.Join(workingDirectory, "tasks.json");
|
||||
[JsonIgnore]public string knownPublicationsPath => Path.Join(workingDirectory, "knownPublications.json");
|
||||
[JsonIgnore] public string coverImageCache => Path.Join(workingDirectory, "imageCache");
|
||||
public HashSet<LibraryManager> libraryManagers { get; }
|
||||
public HashSet<NotificationManager> notificationManagers { get; }
|
||||
public ushort? version { get; set; }
|
||||
[JsonIgnore] public Logger? logger { get; init; }
|
||||
|
||||
public TrangaSettings(string downloadLocation, string workingDirectory, HashSet<LibraryManager> libraryManagers)
|
||||
public TrangaSettings(string downloadLocation, string workingDirectory, HashSet<LibraryManager>? libraryManagers,
|
||||
HashSet<NotificationManager>? notificationManagers, Logger? logger)
|
||||
{
|
||||
if (downloadLocation.Length < 1 || workingDirectory.Length < 1)
|
||||
throw new ArgumentException("Download-location and working-directory paths can not be empty!");
|
||||
this.workingDirectory = workingDirectory;
|
||||
this.downloadLocation = downloadLocation;
|
||||
this.libraryManagers = libraryManagers;
|
||||
this.libraryManagers = libraryManagers??new();
|
||||
this.notificationManagers = notificationManagers??new();
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public static TrangaSettings LoadSettings(string importFilePath, Logger? logger)
|
||||
{
|
||||
if (!File.Exists(importFilePath))
|
||||
return new TrangaSettings(Path.Join(Directory.GetCurrentDirectory(), "Downloads"), Directory.GetCurrentDirectory(), new HashSet<LibraryManager>());
|
||||
return new TrangaSettings(Path.Join(Directory.GetCurrentDirectory(), "Downloads"),
|
||||
Directory.GetCurrentDirectory(), new HashSet<LibraryManager>(), new HashSet<NotificationManager>(), logger);
|
||||
|
||||
string toRead = File.ReadAllText(importFilePath);
|
||||
TrangaSettings settings = JsonConvert.DeserializeObject<TrangaSettings>(toRead, new JsonSerializerSettings() { Converters = { new LibraryManager.LibraryManagerJsonConverter()} })!;
|
||||
TrangaSettings settings = JsonConvert.DeserializeObject<TrangaSettings>(toRead,
|
||||
new JsonSerializerSettings { Converters = { new NotificationManager.NotificationManagerJsonConverter(), new LibraryManager.LibraryManagerJsonConverter() } })!;
|
||||
if (logger is not null)
|
||||
{
|
||||
foreach (LibraryManager lm in settings.libraryManagers)
|
||||
lm.AddLogger(logger);
|
||||
foreach(NotificationManager nm in settings.notificationManagers)
|
||||
nm.AddLogger(logger);
|
||||
}
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
public void ExportSettings()
|
||||
{
|
||||
if (File.Exists(settingsFilePath))
|
||||
{
|
||||
bool inUse = true;
|
||||
while (inUse)
|
||||
{
|
||||
try
|
||||
{
|
||||
using FileStream stream = new (settingsFilePath, FileMode.Open, FileAccess.Read, FileShare.None);
|
||||
stream.Close();
|
||||
inUse = false;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
inUse = true;
|
||||
Thread.Sleep(50);
|
||||
}
|
||||
}
|
||||
}
|
||||
File.WriteAllText(settingsFilePath, JsonConvert.SerializeObject(this));
|
||||
}
|
||||
|
||||
public void UpdateSettings(UpdateField field, params string[] values)
|
||||
{
|
||||
switch (field)
|
||||
{
|
||||
case UpdateField.DownloadLocation:
|
||||
if (values.Length != 1)
|
||||
return;
|
||||
this.downloadLocation = values[0];
|
||||
break;
|
||||
case UpdateField.Komga:
|
||||
if (values.Length != 2)
|
||||
return;
|
||||
libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Komga));
|
||||
libraryManagers.Add(new Komga(values[0], values[1], this.logger));
|
||||
break;
|
||||
case UpdateField.Kavita:
|
||||
if (values.Length != 3)
|
||||
return;
|
||||
libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Kavita));
|
||||
libraryManagers.Add(new Kavita(values[0], values[1], values[2], this.logger));
|
||||
break;
|
||||
case UpdateField.Gotify:
|
||||
if (values.Length != 2)
|
||||
return;
|
||||
notificationManagers.RemoveWhere(nm => nm.GetType() == typeof(Gotify));
|
||||
Gotify newGotify = new(values[0], values[1], this.logger);
|
||||
notificationManagers.Add(newGotify);
|
||||
newGotify.SendNotification("Success!", "Gotify was added to Tranga!");
|
||||
break;
|
||||
case UpdateField.LunaSea:
|
||||
if(values.Length != 1)
|
||||
return;
|
||||
notificationManagers.RemoveWhere(nm => nm.GetType() == typeof(LunaSea));
|
||||
LunaSea newLunaSea = new(values[0], this.logger);
|
||||
notificationManagers.Add(newLunaSea);
|
||||
newLunaSea.SendNotification("Success!", "LunaSea was added to Tranga!");
|
||||
break;
|
||||
}
|
||||
ExportSettings();
|
||||
}
|
||||
|
||||
public enum UpdateField { DownloadLocation, Komga, Kavita, Gotify, LunaSea}
|
||||
}
|
@ -1,148 +0,0 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json.Serialization;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Tranga.TrangaTasks;
|
||||
using JsonConverter = Newtonsoft.Json.JsonConverter;
|
||||
|
||||
namespace Tranga;
|
||||
|
||||
/// <summary>
|
||||
/// Stores information on Task, when implementing new Tasks also update the serializer
|
||||
/// </summary>
|
||||
[JsonDerivedType(typeof(DownloadNewChaptersTask), 2)]
|
||||
[JsonDerivedType(typeof(UpdateLibrariesTask), 3)]
|
||||
[JsonDerivedType(typeof(DownloadChapterTask), 4)]
|
||||
public abstract class TrangaTask
|
||||
{
|
||||
// ReSharper disable once CommentTypo ...Tell me why!
|
||||
// ReSharper disable once MemberCanBePrivate.Global I want it thaaat way
|
||||
public TimeSpan reoccurrence { get; }
|
||||
public DateTime lastExecuted { get; set; }
|
||||
public Task task { get; }
|
||||
public string taskId { get; set; }
|
||||
[Newtonsoft.Json.JsonIgnore]public ExecutionState state { get; set; }
|
||||
[Newtonsoft.Json.JsonIgnore]public double progress { get; protected set; }
|
||||
[Newtonsoft.Json.JsonIgnore]public DateTime nextExecution => lastExecuted.Add(reoccurrence);
|
||||
[Newtonsoft.Json.JsonIgnore]public DateTime executionStarted { get; private set; }
|
||||
|
||||
[Newtonsoft.Json.JsonIgnore]
|
||||
public DateTime executionApproximatelyFinished => this.progress != 0
|
||||
? this.executionStarted.Add(DateTime.Now.Subtract(this.executionStarted) / this.progress)
|
||||
: DateTime.MaxValue;
|
||||
|
||||
[Newtonsoft.Json.JsonIgnore]
|
||||
public TimeSpan executionApproximatelyRemaining => this.executionApproximatelyFinished.Subtract(DateTime.Now);
|
||||
|
||||
[Newtonsoft.Json.JsonIgnore]public DateTime lastChange { get; private set; }
|
||||
|
||||
public enum ExecutionState
|
||||
{
|
||||
Waiting,
|
||||
Enqueued,
|
||||
Running
|
||||
};
|
||||
|
||||
protected TrangaTask(Task task, TimeSpan reoccurrence)
|
||||
{
|
||||
this.reoccurrence = reoccurrence;
|
||||
this.lastExecuted = DateTime.Now.Subtract(reoccurrence);
|
||||
this.task = task;
|
||||
this.progress = 0f;
|
||||
this.executionStarted = DateTime.Now;
|
||||
this.lastChange = DateTime.MaxValue;
|
||||
this.taskId = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(this.executionStarted.ToString(CultureInfo.InvariantCulture)));
|
||||
}
|
||||
|
||||
public double IncrementProgress(double amount)
|
||||
{
|
||||
this.progress += amount;
|
||||
this.lastChange = DateTime.Now;
|
||||
return this.progress;
|
||||
}
|
||||
|
||||
public double DecrementProgress(double amount)
|
||||
{
|
||||
this.progress -= amount;
|
||||
this.lastChange = DateTime.Now;
|
||||
return this.progress;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// BL for concrete Tasks
|
||||
/// </summary>
|
||||
/// <param name="taskManager"></param>
|
||||
/// <param name="logger"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
protected abstract void ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null);
|
||||
|
||||
/// <summary>
|
||||
/// Execute the task
|
||||
/// </summary>
|
||||
/// <param name="taskManager">Should be the parent taskManager</param>
|
||||
/// <param name="logger"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
public void Execute(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Executing Task {this}");
|
||||
this.state = ExecutionState.Running;
|
||||
this.executionStarted = DateTime.Now;
|
||||
this.lastChange = DateTime.Now;
|
||||
ExecuteTask(taskManager, logger, cancellationToken);
|
||||
this.lastExecuted = DateTime.Now;
|
||||
this.state = ExecutionState.Waiting;
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Finished Executing Task {this}");
|
||||
}
|
||||
|
||||
/// <returns>True if elapsed time since last execution is greater than set interval</returns>
|
||||
public bool ShouldExecute()
|
||||
{
|
||||
return nextExecution < DateTime.Now && state is ExecutionState.Waiting;
|
||||
}
|
||||
|
||||
public enum Task : byte
|
||||
{
|
||||
DownloadNewChapters = 2,
|
||||
UpdateLibraries = 3,
|
||||
DownloadChapter = 4
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"{task}, {lastExecuted}, {reoccurrence}, {state}, {progress:P2}, {executionApproximatelyFinished}, {executionApproximatelyRemaining}";
|
||||
}
|
||||
|
||||
public class TrangaTaskJsonConverter : JsonConverter
|
||||
{
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return (objectType == typeof(TrangaTask));
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
|
||||
{
|
||||
JObject jo = JObject.Load(reader);
|
||||
if (jo["task"]!.Value<Int64>() == (Int64)Task.DownloadNewChapters)
|
||||
return jo.ToObject<DownloadNewChaptersTask>(serializer)!;
|
||||
|
||||
if (jo["task"]!.Value<Int64>() == (Int64)Task.UpdateLibraries)
|
||||
return jo.ToObject<UpdateLibrariesTask>(serializer)!;
|
||||
|
||||
if (jo["task"]!.Value<Int64>() == (Int64)Task.DownloadChapter)
|
||||
return jo.ToObject<DownloadChapterTask>(serializer)!;
|
||||
|
||||
throw new Exception();
|
||||
}
|
||||
|
||||
public override bool CanWrite => false;
|
||||
|
||||
/// <summary>
|
||||
/// Don't call this
|
||||
/// </summary>
|
||||
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
|
||||
{
|
||||
throw new Exception("Dont call this");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,5 +1,7 @@
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using System.Net;
|
||||
using Tranga.Connectors;
|
||||
using Tranga.NotificationManagers;
|
||||
using Tranga.LibraryManagers;
|
||||
|
||||
namespace Tranga.TrangaTasks;
|
||||
|
||||
@ -7,33 +9,55 @@ public class DownloadChapterTask : TrangaTask
|
||||
{
|
||||
public string connectorName { get; }
|
||||
public Publication publication { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string language { get; }
|
||||
public Chapter chapter { get; }
|
||||
[JsonIgnore]public DownloadNewChaptersTask? parentTask { get; set; }
|
||||
public string? parentTaskId { get; set; }
|
||||
|
||||
private double _dctProgress;
|
||||
|
||||
public DownloadChapterTask(Task task, string connectorName, Publication publication, Chapter chapter, string language = "en", DownloadNewChaptersTask? parentTask = null) : base(task, TimeSpan.Zero)
|
||||
public DownloadChapterTask(string connectorName, Publication publication, Chapter chapter, string language = "en", MonitorPublicationTask? parentTask = null) : base(Task.DownloadChapter, TimeSpan.Zero, parentTask)
|
||||
{
|
||||
this.chapter = chapter;
|
||||
this.connectorName = connectorName;
|
||||
this.publication = publication;
|
||||
this.language = language;
|
||||
this.parentTask = parentTask;
|
||||
this.parentTaskId = parentTask?.taskId;
|
||||
}
|
||||
|
||||
protected override void ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null)
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return;
|
||||
if(this.parentTask is not null)
|
||||
this.parentTask.state = ExecutionState.Running;
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
Connector connector = taskManager.GetConnector(this.connectorName);
|
||||
connector.DownloadChapter(this.publication, this.chapter, this, cancellationToken);
|
||||
connector.CopyCoverFromCacheToDownloadLocation(this.publication);
|
||||
HttpStatusCode downloadSuccess = connector.DownloadChapter(this.publication, this.chapter, this, cancellationToken);
|
||||
if ((int)downloadSuccess >= 200 && (int)downloadSuccess < 300)
|
||||
{
|
||||
foreach(NotificationManager nm in taskManager.settings.notificationManagers)
|
||||
nm.SendNotification("Chapter downloaded", $"{this.publication.sortName} {this.chapter.chapterNumber} {this.chapter.name}");
|
||||
|
||||
foreach (LibraryManager lm in taskManager.settings.libraryManagers)
|
||||
lm.UpdateLibrary();
|
||||
}
|
||||
return downloadSuccess;
|
||||
}
|
||||
|
||||
public override TrangaTask Clone()
|
||||
{
|
||||
return new DownloadChapterTask(this.connectorName, this.publication, this.chapter,
|
||||
this.language, (MonitorPublicationTask?)this.parentTask);
|
||||
}
|
||||
|
||||
protected override double GetProgress()
|
||||
{
|
||||
return _dctProgress;
|
||||
}
|
||||
|
||||
internal void IncrementProgress(double amount)
|
||||
{
|
||||
this._dctProgress += amount;
|
||||
this.lastChange = DateTime.Now;
|
||||
if(this.parentTask is not null)
|
||||
this.parentTask.state = ExecutionState.Waiting;
|
||||
taskManager.DeleteTask(this);
|
||||
this.parentTask.lastChange = DateTime.Now;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
|
@ -1,81 +0,0 @@
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Tranga.TrangaTasks;
|
||||
|
||||
public class DownloadNewChaptersTask : TrangaTask
|
||||
{
|
||||
public string connectorName { get; }
|
||||
public Publication publication { get; }
|
||||
public string language { get; }
|
||||
[JsonIgnore]private HashSet<DownloadChapterTask> childTasks { get; }
|
||||
[JsonIgnore]public new double progress => childTasks.Count > 0 ? childTasks.Sum(childTask => childTask.progress) / childTasks.Count : 0;
|
||||
|
||||
public DownloadNewChaptersTask(Task task, string connectorName, Publication publication, TimeSpan reoccurrence, string language = "en") : base(task, reoccurrence)
|
||||
{
|
||||
this.connectorName = connectorName;
|
||||
this.publication = publication;
|
||||
this.language = language;
|
||||
this.childTasks = new();
|
||||
}
|
||||
|
||||
protected override void ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested??false)
|
||||
return;
|
||||
Publication pub = publication!;
|
||||
Connector connector = taskManager.GetConnector(this.connectorName);
|
||||
|
||||
//Check if Publication already has a Folder
|
||||
pub.CreatePublicationFolder(taskManager.settings.downloadLocation);
|
||||
List<Chapter> newChapters = GetNewChaptersList(connector, pub, language!, ref taskManager.chapterCollection);
|
||||
|
||||
connector.CopyCoverFromCacheToDownloadLocation(pub, taskManager.settings);
|
||||
|
||||
pub.SaveSeriesInfoJson(connector.downloadLocation);
|
||||
|
||||
foreach (Chapter newChapter in newChapters)
|
||||
{
|
||||
DownloadChapterTask newTask = new (Task.DownloadChapter, this.connectorName!, pub, newChapter, this.language, this);
|
||||
taskManager.AddTask(newTask);
|
||||
this.childTasks.Add(newTask);
|
||||
}
|
||||
}
|
||||
|
||||
public void ReplaceFailedChildTask(DownloadChapterTask failed, DownloadChapterTask newTask)
|
||||
{
|
||||
if (!this.childTasks.Contains(failed))
|
||||
throw new ArgumentException($"Task {failed} is not childTask of {this}");
|
||||
this.childTasks.Remove(failed);
|
||||
this.childTasks.Add(newTask);
|
||||
}
|
||||
|
||||
public void AddChildTask(DownloadChapterTask childTask)
|
||||
{
|
||||
this.childTasks.Add(childTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the available Chapters of a Publication
|
||||
/// </summary>
|
||||
/// <param name="connector">Connector to use</param>
|
||||
/// <param name="publication">Publication to check</param>
|
||||
/// <param name="language">Language to receive chapters for</param>
|
||||
/// <param name="chapterCollection"></param>
|
||||
/// <returns>List of Chapters that were previously not in collection</returns>
|
||||
private static List<Chapter> GetNewChaptersList(Connector connector, Publication publication, string language, ref Dictionary<Publication, List<Chapter>> chapterCollection)
|
||||
{
|
||||
List<Chapter> newChaptersList = new();
|
||||
chapterCollection.TryAdd(publication, newChaptersList); //To ensure publication is actually in collection
|
||||
|
||||
Chapter[] newChapters = connector.GetChapters(publication, language);
|
||||
newChaptersList = newChapters.Where(nChapter => !connector.CheckChapterIsDownloaded(publication, nChapter)).ToList();
|
||||
|
||||
return newChaptersList;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"{base.ToString()}, {connectorName}, {publication.sortName} {publication.internalId}";
|
||||
}
|
||||
}
|
61
Tranga/TrangaTasks/MonitorPublicationTask.cs
Normal file
@ -0,0 +1,61 @@
|
||||
using System.Net;
|
||||
using Tranga.Connectors;
|
||||
|
||||
namespace Tranga.TrangaTasks;
|
||||
|
||||
public class MonitorPublicationTask : TrangaTask
|
||||
{
|
||||
public string connectorName { get; }
|
||||
public Publication publication { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string language { get; }
|
||||
public MonitorPublicationTask(string connectorName, Publication publication, TimeSpan reoccurrence, string language = "en") : base(Task.MonitorPublication, reoccurrence)
|
||||
{
|
||||
this.connectorName = connectorName;
|
||||
this.publication = publication;
|
||||
this.language = language;
|
||||
}
|
||||
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
Connector connector = taskManager.GetConnector(this.connectorName);
|
||||
|
||||
//Check if Publication already has a Folder
|
||||
publication.CreatePublicationFolder(taskManager.settings.downloadLocation);
|
||||
List<Chapter> newChapters = connector.GetNewChaptersList(publication, language, ref taskManager.collection);
|
||||
|
||||
connector.CopyCoverFromCacheToDownloadLocation(publication);
|
||||
|
||||
publication.SaveSeriesInfoJson(taskManager.settings.downloadLocation);
|
||||
|
||||
foreach (Chapter newChapter in newChapters)
|
||||
{
|
||||
DownloadChapterTask newTask = new (this.connectorName, publication, newChapter, this.language, this);
|
||||
this.childTasks.Add(newTask);
|
||||
newTask.state = ExecutionState.Enqueued;
|
||||
taskManager.AddTask(newTask);
|
||||
}
|
||||
|
||||
return HttpStatusCode.OK;
|
||||
}
|
||||
|
||||
public override TrangaTask Clone()
|
||||
{
|
||||
return new MonitorPublicationTask(this.connectorName, this.publication, this.reoccurrence,
|
||||
this.language);
|
||||
}
|
||||
|
||||
protected override double GetProgress()
|
||||
{
|
||||
if (this.childTasks.Count > 0)
|
||||
return this.childTasks.Sum(ct => ct.progress) / childTasks.Count;
|
||||
return 1;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"{base.ToString()}, {connectorName}, {publication.sortName} {publication.internalId}";
|
||||
}
|
||||
}
|
157
Tranga/TrangaTasks/TrangaTask.cs
Normal file
@ -0,0 +1,157 @@
|
||||
using System.Net;
|
||||
using System.Text.Json.Serialization;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using JsonConverter = Newtonsoft.Json.JsonConverter;
|
||||
|
||||
namespace Tranga.TrangaTasks;
|
||||
|
||||
/// <summary>
|
||||
/// Stores information on Task, when implementing new Tasks also update the serializer
|
||||
/// </summary>
|
||||
[JsonDerivedType(typeof(MonitorPublicationTask), 2)]
|
||||
[JsonDerivedType(typeof(UpdateLibrariesTask), 3)]
|
||||
[JsonDerivedType(typeof(DownloadChapterTask), 4)]
|
||||
public abstract class TrangaTask
|
||||
{
|
||||
// ReSharper disable once MemberCanBeProtected.Global
|
||||
public TimeSpan reoccurrence { get; }
|
||||
public DateTime lastExecuted { get; set; }
|
||||
[Newtonsoft.Json.JsonIgnore] public ExecutionState state { get; set; }
|
||||
public Task task { get; }
|
||||
public string taskId { get; init; }
|
||||
[Newtonsoft.Json.JsonIgnore] public TrangaTask? parentTask { get; set; }
|
||||
public string? parentTaskId { get; set; }
|
||||
[Newtonsoft.Json.JsonIgnore] internal HashSet<TrangaTask> childTasks { get; }
|
||||
public double progress => GetProgress();
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
[Newtonsoft.Json.JsonIgnore]public DateTime executionStarted { get; private set; }
|
||||
[Newtonsoft.Json.JsonIgnore]public DateTime lastChange { get; internal set; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
[Newtonsoft.Json.JsonIgnore]public DateTime executionApproximatelyFinished => lastChange.Add(GetRemainingTime());
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public TimeSpan executionApproximatelyRemaining => executionApproximatelyFinished.Subtract(DateTime.Now);
|
||||
[Newtonsoft.Json.JsonIgnore]public DateTime nextExecution => lastExecuted.Add(reoccurrence);
|
||||
|
||||
public enum ExecutionState { Waiting, Enqueued, Running, Failed, Success }
|
||||
|
||||
protected TrangaTask(Task task, TimeSpan reoccurrence, TrangaTask? parentTask = null)
|
||||
{
|
||||
this.reoccurrence = reoccurrence;
|
||||
this.lastExecuted = DateTime.Now.Subtract(reoccurrence);
|
||||
this.task = task;
|
||||
this.executionStarted = DateTime.UnixEpoch;
|
||||
this.lastChange = DateTime.MaxValue;
|
||||
this.taskId = Convert.ToBase64String(BitConverter.GetBytes(new Random().Next()));
|
||||
this.childTasks = new();
|
||||
this.parentTask = parentTask;
|
||||
this.parentTaskId = parentTask?.taskId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// BL for concrete Tasks
|
||||
/// </summary>
|
||||
/// <param name="taskManager"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
protected abstract HttpStatusCode ExecuteTask(TaskManager taskManager, CancellationToken? cancellationToken = null);
|
||||
|
||||
public abstract TrangaTask Clone();
|
||||
|
||||
protected abstract double GetProgress();
|
||||
|
||||
/// <summary>
|
||||
/// Execute the task
|
||||
/// </summary>
|
||||
/// <param name="taskManager">Should be the parent taskManager</param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
public void Execute(TaskManager taskManager, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
taskManager.settings.logger?.WriteLine(this.GetType().ToString(), $"Executing Task {this}");
|
||||
this.state = ExecutionState.Running;
|
||||
this.executionStarted = DateTime.Now;
|
||||
this.lastChange = DateTime.Now;
|
||||
if(parentTask is not null && parentTask.childTasks.All(ct => ct.state is ExecutionState.Waiting or ExecutionState.Failed))
|
||||
parentTask.executionStarted = DateTime.Now;
|
||||
|
||||
HttpStatusCode statusCode = ExecuteTask(taskManager, cancellationToken);
|
||||
|
||||
if ((int)statusCode >= 200 && (int)statusCode < 300)
|
||||
{
|
||||
this.lastExecuted = DateTime.Now;
|
||||
this.state = ExecutionState.Success;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.state = ExecutionState.Failed;
|
||||
this.lastExecuted = DateTime.MaxValue;
|
||||
}
|
||||
|
||||
if (this is DownloadChapterTask)
|
||||
taskManager.DeleteTask(this);
|
||||
|
||||
taskManager.settings.logger?.WriteLine(this.GetType().ToString(), $"Finished Executing Task {this}");
|
||||
}
|
||||
|
||||
public void AddChildTask(TrangaTask childTask)
|
||||
{
|
||||
this.childTasks.Add(childTask);
|
||||
}
|
||||
|
||||
public void RemoveChildTask(TrangaTask childTask)
|
||||
{
|
||||
this.childTasks.Remove(childTask);
|
||||
}
|
||||
|
||||
private TimeSpan GetRemainingTime()
|
||||
{
|
||||
if(progress == 0 || state is ExecutionState.Enqueued or ExecutionState.Waiting or ExecutionState.Failed || lastChange == DateTime.MaxValue)
|
||||
return DateTime.MaxValue.Subtract(lastChange).Subtract(TimeSpan.FromHours(1));
|
||||
TimeSpan elapsed = lastChange.Subtract(executionStarted);
|
||||
return elapsed.Divide(progress).Multiply(1 - progress);
|
||||
}
|
||||
|
||||
public enum Task : byte
|
||||
{
|
||||
MonitorPublication = 2,
|
||||
UpdateLibraries = 3,
|
||||
DownloadChapter = 4,
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"{task}, {lastExecuted}, {reoccurrence}, {state}, {progress:P2}, {executionApproximatelyFinished}, {executionApproximatelyRemaining}";
|
||||
}
|
||||
|
||||
public class TrangaTaskJsonConverter : JsonConverter
|
||||
{
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return objectType == typeof(TrangaTask);
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
|
||||
{
|
||||
JObject jo = JObject.Load(reader);
|
||||
if (jo["task"]!.Value<Int64>() == (Int64)Task.MonitorPublication)
|
||||
return jo.ToObject<MonitorPublicationTask>(serializer)!;
|
||||
|
||||
if (jo["task"]!.Value<Int64>() == (Int64)Task.UpdateLibraries)
|
||||
return jo.ToObject<UpdateLibrariesTask>(serializer)!;
|
||||
|
||||
if (jo["task"]!.Value<Int64>() == (Int64)Task.DownloadChapter)
|
||||
return jo.ToObject<DownloadChapterTask>(serializer)!;
|
||||
|
||||
throw new Exception();
|
||||
}
|
||||
|
||||
public override bool CanWrite => false;
|
||||
|
||||
/// <summary>
|
||||
/// Don't call this
|
||||
/// </summary>
|
||||
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
|
||||
{
|
||||
throw new Exception("Dont call this");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,19 +1,28 @@
|
||||
using Logging;
|
||||
using System.Net;
|
||||
|
||||
namespace Tranga.TrangaTasks;
|
||||
|
||||
/// <summary>
|
||||
/// LEGACY DEPRECATED
|
||||
/// </summary>
|
||||
public class UpdateLibrariesTask : TrangaTask
|
||||
{
|
||||
public UpdateLibrariesTask(Task task, TimeSpan reoccurrence) : base(task, reoccurrence)
|
||||
public UpdateLibrariesTask(TimeSpan reoccurrence) : base(Task.UpdateLibraries, reoccurrence)
|
||||
{
|
||||
}
|
||||
|
||||
protected override void ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null)
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested??false)
|
||||
return;
|
||||
foreach(LibraryManager lm in taskManager.settings.libraryManagers)
|
||||
lm.UpdateLibrary();
|
||||
this.progress = 1f;
|
||||
return HttpStatusCode.BadRequest;
|
||||
}
|
||||
|
||||
public override TrangaTask Clone()
|
||||
{
|
||||
return new UpdateLibrariesTask(this.reoccurrence);
|
||||
}
|
||||
|
||||
protected override double GetProgress()
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
}
|
@ -43,60 +43,60 @@ function DeleteData(uri){
|
||||
}
|
||||
|
||||
async function GetAvailableControllers(){
|
||||
var uri = apiUri + "/Controllers/Get";
|
||||
var uri = apiUri + "/Connectors";
|
||||
let json = await GetData(uri);
|
||||
return json;
|
||||
}
|
||||
|
||||
async function GetPublicationFromConnector(connectorName, title){
|
||||
var uri = apiUri + `/Publications/GetFromConnector?connectorName=${connectorName}&title=${title}`;
|
||||
var uri = apiUri + `/Publications/FromConnector?connectorName=${connectorName}&title=${title}`;
|
||||
let json = await GetData(uri);
|
||||
return json;
|
||||
}
|
||||
|
||||
async function GetKnownPublications(){
|
||||
var uri = apiUri + "/Publications/GetKnown";
|
||||
var uri = apiUri + "/Publications/Known";
|
||||
let json = await GetData(uri);
|
||||
return json;
|
||||
}
|
||||
|
||||
async function GetPublication(internalId){
|
||||
var uri = apiUri + `/Publications/GetKnown?internalId=${internalId}`;
|
||||
var uri = apiUri + `/Publications/Known?internalId=${internalId}`;
|
||||
let json = await GetData(uri);
|
||||
return json;
|
||||
}
|
||||
|
||||
async function GetChapters(internalId, connectorName, language){
|
||||
var uri = apiUri + `/Publications/GetChapters?internalId=${internalId}&connectorName=${connectorName}&language=${language}`;
|
||||
async function GetChapters(internalId, connectorName, onlyNew, language){
|
||||
var uri = apiUri + `/Publications/Chapters?internalId=${internalId}&connectorName=${connectorName}&onlyNew=${onlyNew}&language=${language}`;
|
||||
let json = await GetData(uri);
|
||||
return json;
|
||||
}
|
||||
|
||||
async function GetTaskTypes(){
|
||||
var uri = apiUri + "/Tasks/GetTypes";
|
||||
var uri = apiUri + "/Tasks/Types";
|
||||
let json = await GetData(uri);
|
||||
return json;
|
||||
}
|
||||
async function GetRunningTasks(){
|
||||
var uri = apiUri + "/Tasks/GetRunningTasks";
|
||||
var uri = apiUri + "/Tasks/RunningTasks";
|
||||
let json = await GetData(uri);
|
||||
return json;
|
||||
}
|
||||
|
||||
async function GetDownloadTasks(){
|
||||
var uri = apiUri + "/Tasks/Get?taskType=DownloadNewChapters";
|
||||
var uri = apiUri + "/Tasks?taskType=MonitorPublication";
|
||||
let json = await GetData(uri);
|
||||
return json;
|
||||
}
|
||||
|
||||
async function GetSettings(){
|
||||
var uri = apiUri + "/Settings/Get";
|
||||
var uri = apiUri + "/Settings";
|
||||
let json = await GetData(uri);
|
||||
return json;
|
||||
}
|
||||
|
||||
async function GetKomgaTask(){
|
||||
var uri = apiUri + "/Tasks/Get?taskType=UpdateLibraries";
|
||||
var uri = apiUri + "/Tasks?taskType=UpdateLibraries";
|
||||
let json = await GetData(uri);
|
||||
return json;
|
||||
}
|
||||
@ -106,11 +106,6 @@ function CreateMonitorTask(connectorName, internalId, reoccurrence, language){
|
||||
PostData(uri);
|
||||
}
|
||||
|
||||
function CreateUpdateLibraryTask(reoccurrence){
|
||||
var uri = apiUri + `/Tasks/CreateUpdateLibraryTask?reoccurrenceTime=${reoccurrence}`;
|
||||
PostData(uri);
|
||||
}
|
||||
|
||||
function CreateDownloadChaptersTask(connectorName, internalId, chapters, language){
|
||||
var uri = apiUri + `/Tasks/CreateDownloadChaptersTask?connectorName=${connectorName}&internalId=${internalId}&chapters=${chapters}&language=${language}`;
|
||||
PostData(uri);
|
||||
@ -126,22 +121,38 @@ function EnqueueTask(taskType, connectorName, publicationId){
|
||||
PostData(uri);
|
||||
}
|
||||
|
||||
function UpdateSettings(downloadLocation, komgaUrl, komgaAuth, kavitaUrl, kavitaUser, kavitaPass){
|
||||
function UpdateDownloadLocation(downloadLocation){
|
||||
var uri = apiUri + "/Settings/Update?"
|
||||
if(downloadLocation != ""){
|
||||
uri += "&downloadLocation="+downloadLocation;
|
||||
PostData(uri);
|
||||
}
|
||||
if(komgaUrl != "" && komgaAuth != ""){
|
||||
|
||||
function UpdateKomga(komgaUrl, komgaAuth){
|
||||
var uri = apiUri + "/Settings/Update?"
|
||||
uri += `&komgaUrl=${komgaUrl}&komgaAuth=${komgaAuth}`;
|
||||
PostData(uri);
|
||||
}
|
||||
if(kavitaUrl != "" && kavitaUser != "" && kavitaPass != ""){
|
||||
|
||||
function UpdateKavita(kavitaUrl, kavitaUser, kavitaPass){
|
||||
var uri = apiUri + "/Settings/Update?"
|
||||
uri += `&kavitaUrl=${kavitaUrl}&kavitaUsername=${kavitaUser}&kavitaPassword=${kavitaPass}`;
|
||||
PostData(uri);
|
||||
}
|
||||
|
||||
function UpdateGotify(gotifyUrl, gotifyAppToken){
|
||||
var uri = apiUri + "/Settings/Update?"
|
||||
uri += `&gotifyUrl=${gotifyUrl}&gotifyAppToken=${gotifyAppToken}`;
|
||||
PostData(uri);
|
||||
}
|
||||
|
||||
function UpdateLunaSea(lunaseaWebhook){
|
||||
var uri = apiUri + "/Settings/Update?"
|
||||
uri += `&lunaseaWebhook=${lunaseaWebhook}`;
|
||||
PostData(uri);
|
||||
}
|
||||
|
||||
function DeleteTask(taskType, connectorName, publicationId){
|
||||
var uri = apiUri + `/Tasks/Delete?taskType=${taskType}&connectorName=${connectorName}&publicationId=${publicationId}`;
|
||||
var uri = apiUri + `/Tasks?taskType=${taskType}&connectorName=${connectorName}&publicationId=${publicationId}`;
|
||||
DeleteData(uri);
|
||||
}
|
||||
|
||||
@ -151,7 +162,7 @@ function DequeueTask(taskType, connectorName, publicationId){
|
||||
}
|
||||
|
||||
async function GetQueue(){
|
||||
var uri = apiUri + "/Queue/GetList";
|
||||
var uri = apiUri + "/Queue/List";
|
||||
let json = await GetData(uri);
|
||||
return json;
|
||||
}
|
@ -133,6 +133,17 @@
|
||||
<label for="kavitaUsername"></label><input placeholder="Username" id="kavitaUsername" type="text">
|
||||
<label for="kavitaPassword"></label><input placeholder="Password" id="kavitaPassword" type="password">
|
||||
</div>
|
||||
<div>
|
||||
<span class="title">Gotify</span>
|
||||
<div>Configured: <span id="gotifyConfigured">✅❌</span></div>
|
||||
<label for="gotifyUrl"></label><input placeholder="URL" id="gotifyUrl" type="text">
|
||||
<label for="gotifyAppToken"></label><input placeholder="App-Token" id="gotifyAppToken" type="text">
|
||||
</div>
|
||||
<div>
|
||||
<span class="title">LunaSea</span>
|
||||
<div>Configured: <span id="lunaseaConfigured">✅❌</span></div>
|
||||
<label for="lunaseaWebhook"></label><input placeholder="device/:id or user/:id" id="lunaseaWebhook" type="text">
|
||||
</div>
|
||||
<div>
|
||||
<label for="libraryUpdateTime" style="margin-right: 5px;">Update Time</label><input id="libraryUpdateTime" type="time" value="00:01:00" step="10">
|
||||
<input type="submit" value="Update" onclick="UpdateLibrarySettings()">
|
||||
|
@ -33,9 +33,14 @@ const settingKomgaPass = document.querySelector("#komgaPassword");
|
||||
const settingKavitaUrl = document.querySelector("#kavitaUrl");
|
||||
const settingKavitaUser = document.querySelector("#kavitaUsername");
|
||||
const settingKavitaPass = document.querySelector("#kavitaPassword");
|
||||
const settingGotifyUrl = document.querySelector("#gotifyUrl");
|
||||
const settingGotifyAppToken = document.querySelector("#gotifyAppToken");
|
||||
const settingLunaseaWebhook = document.querySelector("#lunaseaWebhook");
|
||||
const libraryUpdateTime = document.querySelector("#libraryUpdateTime");
|
||||
const settingKomgaConfigured = document.querySelector("#komgaConfigured");
|
||||
const settingKavitaConfigured = document.querySelector("#kavitaConfigured");
|
||||
const settingGotifyConfigured = document.querySelector("#gotifyConfigured");
|
||||
const settingLunaseaConfigured = document.querySelector("#lunaseaConfigured");
|
||||
const settingApiUri = document.querySelector("#settingApiUri");
|
||||
const tagTasksRunning = document.querySelector("#tasksRunningTag");
|
||||
const tagTasksQueued = document.querySelector("#tasksQueuedTag");
|
||||
@ -65,13 +70,6 @@ createDownloadChapterTaskButton.addEventListener("click", () => {
|
||||
OpenDownloadChapterTaskPopup();
|
||||
});
|
||||
publicationTaskStart.addEventListener("click", () => StartTaskClick());
|
||||
settingApiUri.addEventListener("keypress", (event) => {
|
||||
if(event.key === "Enter"){
|
||||
apiUri = settingApiUri.value;
|
||||
setTimeout(() => GetSettingsClick(), 100);
|
||||
document.cookie = `apiUri=${apiUri};`;
|
||||
}
|
||||
});
|
||||
searchPublicationQuery.addEventListener("keypress", (event) => {
|
||||
if(event.key === "Enter"){
|
||||
NewSearch();
|
||||
@ -154,7 +152,7 @@ function OpenDownloadChapterTaskPopup(){
|
||||
selectedChapters.value = "";
|
||||
chapterOutput.replaceChildren();
|
||||
createDownloadChaptersTask.style.display = "block";
|
||||
GetChapters(toEditId, connectorSelect.value, "en").then((json) => {
|
||||
GetChapters(toEditId, connectorSelect.value, true, "en").then((json) => {
|
||||
var i = 0;
|
||||
json.forEach(chapter => {
|
||||
var chapterDom = document.createElement("div");
|
||||
@ -190,13 +188,13 @@ function DownloadChapterTaskClick(){
|
||||
|
||||
function DeleteTaskClick(){
|
||||
taskToDelete = tasks.filter(tTask => tTask.publication.internalId === toEditId)[0];
|
||||
DeleteTask("DownloadNewChapters", taskToDelete.connectorName, toEditId);
|
||||
DeleteTask("MonitorPublication", taskToDelete.connectorName, toEditId);
|
||||
HidePublicationPopup();
|
||||
}
|
||||
|
||||
function StartTaskClick(){
|
||||
var toEditTask = tasks.filter(task => task.publication.internalId == toEditId)[0];
|
||||
StartTask("DownloadNewChapters", toEditTask.connectorName, toEditId);
|
||||
StartTask("MonitorPublication", toEditTask.connectorName, toEditId);
|
||||
HidePublicationPopup();
|
||||
}
|
||||
|
||||
@ -284,11 +282,16 @@ function GetSettingsClick(){
|
||||
settingKomgaUrl.value = "";
|
||||
settingKomgaUser.value = "";
|
||||
settingKomgaPass.value = "";
|
||||
settingKomgaConfigured.innerText = "❌";
|
||||
settingKavitaUrl.value = "";
|
||||
settingKavitaUser.value = "";
|
||||
settingKavitaPass.value = "";
|
||||
settingKomgaConfigured.innerText = "❌";
|
||||
settingKavitaConfigured.innerText = "❌";
|
||||
settingGotifyUrl.value = "";
|
||||
settingGotifyAppToken.value = "";
|
||||
settingGotifyConfigured.innerText = "❌";
|
||||
settingLunaseaWebhook.value = "";
|
||||
settingLunaseaConfigured.innerText = "❌";
|
||||
|
||||
settingApiUri.placeholder = apiUri;
|
||||
|
||||
@ -307,6 +310,13 @@ function GetSettingsClick(){
|
||||
settingKavitaConfigured.innerText = "✅";
|
||||
}
|
||||
});
|
||||
json.notificationManagers.forEach(nm => {
|
||||
if(nm.notificationManagerType == 0){
|
||||
settingGotifyConfigured.innerText = "✅";
|
||||
} else if(nm.notificationManagerType == 1){
|
||||
settingLunaseaConfigured.innerText = "✅";
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
GetKomgaTask().then(json => {
|
||||
@ -316,20 +326,29 @@ function GetSettingsClick(){
|
||||
}
|
||||
|
||||
function UpdateLibrarySettings(){
|
||||
if(settingKomgaUser.value != "" && settingKomgaPass != ""){
|
||||
if(settingKomgaUrl.value != "" && settingKomgaUser.value != "" && settingKomgaPass.value != ""){
|
||||
var auth = utf8_to_b64(`${settingKomgaUser.value}:${settingKomgaPass.value}`);
|
||||
console.log(auth);
|
||||
|
||||
if(settingKomgaUrl.value != "")
|
||||
UpdateSettings("", settingKomgaUrl.value, auth, "", "");
|
||||
else
|
||||
UpdateSettings("", settingKomgaUrl.placeholder, auth, "", "");
|
||||
UpdateKomga(settingKomgaUrl.value, auth);
|
||||
}
|
||||
|
||||
if(settingKavitaUrl.value != "" && settingKavitaUser.value != "" && settingKavitaPass.value != ""){
|
||||
UpdateSettings("", "", "", settingKavitaUrl.value, settingKavitaUser.value, settingKavitaPass.value);
|
||||
UpdateKavita(settingKavitaUrl.value, settingKavitaUser.value, settingKavitaPass.value);
|
||||
}
|
||||
CreateUpdateLibraryTask(libraryUpdateTime.value);
|
||||
|
||||
if(settingGotifyUrl.value != "" && settingGotifyAppToken.value != ""){
|
||||
UpdateGotify(settingGotifyUrl.value, settingGotifyAppToken.value);
|
||||
}
|
||||
|
||||
if(settingLunaseaWebhook.value != ""){
|
||||
UpdateLunaSea(settingLunaseaWebhook.value);
|
||||
}
|
||||
|
||||
if(settingApiUri.value != ""){
|
||||
apiUri = settingApiUri.value;
|
||||
document.cookie = `apiUri=${apiUri};`;
|
||||
}
|
||||
|
||||
setTimeout(() => GetSettingsClick(), 200);
|
||||
}
|
||||
|
||||
@ -366,9 +385,14 @@ function ShowTasksQueue(){
|
||||
.then(json => {
|
||||
tagTasksRunning.innerText = json.length;
|
||||
json.forEach(task => {
|
||||
if(task.task == 2 || task.task == 4) {
|
||||
downloadTasksOutput.appendChild(CreateProgressChild(task));
|
||||
document.querySelector(`#progress${task.taskId.replaceAll('=','')}`).value = task.progress;
|
||||
document.querySelector(`#progressStr${task.taskId.replaceAll('=','')}`).innerText = task.progress.toLocaleString(undefined,{style: 'percent', minimumFractionDigits:2});
|
||||
document.querySelector(`#progress${GetValidSelector(task.taskId)}`).value = task.progress;
|
||||
var finishedHours = task.executionApproximatelyRemaining.split(':')[0];
|
||||
var finishedMinutes = task.executionApproximatelyRemaining.split(':')[1];
|
||||
var finishedSeconds = task.executionApproximatelyRemaining.split(':')[2].split('.')[0];
|
||||
document.querySelector(`#progressStr${GetValidSelector(task.taskId)}`).innerText = `${finishedHours}:${finishedMinutes}:${finishedSeconds}`;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@ -395,13 +419,13 @@ function CreateProgressChild(task){
|
||||
|
||||
|
||||
var progress = document.createElement("progress");
|
||||
progress.id = `progress${task.taskId.replaceAll('=','')}`;
|
||||
progress.id = `progress${GetValidSelector(task.taskId)}`;
|
||||
child.appendChild(progress);
|
||||
|
||||
var progressStr = document.createElement("span");
|
||||
progressStr.innerText = "00.00%";
|
||||
progressStr.innerText = " \t∞";
|
||||
progressStr.className = "progressStr";
|
||||
progressStr.id = `progressStr${task.taskId.replaceAll('=','')}`;
|
||||
progressStr.id = `progressStr${GetValidSelector(task.taskId)}`;
|
||||
child.appendChild(progressStr);
|
||||
|
||||
if(task.chapter != undefined){
|
||||
@ -484,8 +508,18 @@ setInterval(() => {
|
||||
setInterval(() => {
|
||||
GetRunningTasks().then((json) => {
|
||||
json.forEach(task => {
|
||||
document.querySelector(`#progress${task.taskId.replaceAll('=','')}`).value = task.progress;
|
||||
document.querySelector(`#progressStr${task.taskId.replaceAll('=','')}`).innerText = task.progress.toLocaleString(undefined,{style: 'percent', minimumFractionDigits:2});
|
||||
if(task.task == 2 || task.task == 4){
|
||||
document.querySelector(`#progress${GetValidSelector(task.taskId)}`).value = task.progress;
|
||||
var finishedHours = task.executionApproximatelyRemaining.split(':')[0];
|
||||
var finishedMinutes = task.executionApproximatelyRemaining.split(':')[1];
|
||||
var finishedSeconds = task.executionApproximatelyRemaining.split(':')[2].split('.')[0];
|
||||
document.querySelector(`#progressStr${GetValidSelector(task.taskId)}`).innerText = `${finishedHours}:${finishedMinutes}:${finishedSeconds}`;
|
||||
}
|
||||
});
|
||||
});
|
||||
},500);
|
||||
|
||||
function GetValidSelector(str){
|
||||
var clean = [...str.matchAll(/[a-zA-Z0-9]*-*_*/g)];
|
||||
return clean.join('');
|
||||
}
|
@ -454,6 +454,8 @@ blur-background {
|
||||
flex-wrap: wrap;
|
||||
justify-content: start;
|
||||
align-content: start;
|
||||
max-height: 70vh;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
#publicationViewerPopup{
|
||||
|
@ -7,7 +7,7 @@ services:
|
||||
- ./tranga:/usr/share/Tranga-API #1 when replacing ./tranga replace #2 with same value
|
||||
- ./Manga:/Manga
|
||||
ports:
|
||||
- 6531:80
|
||||
- "6531:6531"
|
||||
restart: unless-stopped
|
||||
tranga-website:
|
||||
image: glax/tranga-website:latest
|
||||
@ -15,7 +15,7 @@ services:
|
||||
volumes:
|
||||
- ./tranga/imageCache:/usr/share/nginx/html/imageCache:ro #2 when replacing Point to same value as #1/imageCache
|
||||
ports:
|
||||
- 9555:80
|
||||
- "9555:80"
|
||||
depends_on:
|
||||
- tranga-api
|
||||
restart: unless-stopped
|
Before Width: | Height: | Size: 1.0 MiB After Width: | Height: | Size: 2.1 MiB |
Before Width: | Height: | Size: 2.6 MiB After Width: | Height: | Size: 2.5 MiB |
BIN
screenshots/progress.png
Normal file
After Width: | Height: | Size: 354 KiB |
Before Width: | Height: | Size: 2.2 MiB After Width: | Height: | Size: 1.8 MiB |
Before Width: | Height: | Size: 1.7 MiB After Width: | Height: | Size: 1.5 MiB |