Compare commits
111 Commits
1.5
...
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 |
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
|
@ -3,10 +3,10 @@
|
||||
FROM mcr.microsoft.com/dotnet/sdk:7.0 as build-env
|
||||
WORKDIR /src
|
||||
COPY . /src/
|
||||
RUN dotnet restore API/API.csproj
|
||||
RUN dotnet restore /src/API/API.csproj
|
||||
RUN dotnet publish -c Release -o /publish
|
||||
|
||||
FROM glax/tranga-base:dev as runtime
|
||||
FROM glax/tranga-base:latest as runtime
|
||||
WORKDIR /publish
|
||||
COPY --from=build-env /publish .
|
||||
EXPOSE 6531
|
||||
|
@ -1,10 +1,12 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Logging;
|
||||
using Tranga;
|
||||
using Tranga.NotificationManagers;
|
||||
using Tranga.LibraryManagers;
|
||||
|
||||
namespace API;
|
||||
|
||||
public class Program
|
||||
public static class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
@ -17,28 +19,32 @@ public class Program
|
||||
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>());
|
||||
settings = new TrangaSettings(downloadFolderPath, applicationFolderPath, new HashSet<LibraryManager>(), new HashSet<NotificationManager>(), logger);
|
||||
|
||||
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}");
|
||||
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}");
|
||||
|
||||
logger.WriteLine("Tranga", "Loading Taskmanager.");
|
||||
TaskManager taskManager = new (settings, logger);
|
||||
settings.logger?.WriteLine("Tranga", "Loading Taskmanager.");
|
||||
TaskManager taskManager = new (settings);
|
||||
|
||||
Server server = new (6531, taskManager, logger);
|
||||
Server server = new (6531, taskManager);
|
||||
foreach(NotificationManager nm in taskManager.settings.notificationManagers)
|
||||
nm.SendNotification("Tranga-API", "Started Tranga-API");
|
||||
}
|
||||
|
@ -1,6 +1,8 @@
|
||||
using System.Net;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using Tranga;
|
||||
using Tranga.Connectors;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
namespace API;
|
||||
@ -20,8 +22,7 @@ public class RequestHandler
|
||||
new[] { "connectorName", "internalId", "onlyNew?", "onlyExisting?", "language?" }),
|
||||
new(HttpMethod.Get, "/Tasks/Types", Array.Empty<string>()),
|
||||
new(HttpMethod.Post, "/Tasks/CreateMonitorTask",
|
||||
new[] { "connectorName", "internalId", "reoccurrenceTime", "language?" }),
|
||||
new(HttpMethod.Post, "/Tasks/CreateUpdateLibraryTask", new[] { "reoccurrenceTime" }),
|
||||
new[] { "connectorName", "internalId", "reoccurrenceTime", "language?", "ignoreChaptersBelow?" }),
|
||||
new(HttpMethod.Post, "/Tasks/CreateDownloadChaptersTask",
|
||||
new[] { "connectorName", "internalId", "chapters", "language?" }),
|
||||
new(HttpMethod.Get, "/Tasks", new[] { "taskType", "connectorName?", "publicationId?" }),
|
||||
@ -80,12 +81,17 @@ public class RequestHandler
|
||||
private Dictionary<string, string> GetRequestVariables(string query)
|
||||
{
|
||||
Dictionary<string, string> ret = new();
|
||||
Regex queryRex = new (@"\?{1}([A-z]+=[A-z]+)+(&[A-z]+=[A-z]+)*");
|
||||
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('&'))
|
||||
ret.Add(kvpair.Split('=')[0], kvpair.Split('=')[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;
|
||||
}
|
||||
|
||||
@ -146,6 +152,7 @@ public class RequestHandler
|
||||
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 =
|
||||
@ -153,15 +160,12 @@ public class RequestHandler
|
||||
if (connector1 is null)
|
||||
return;
|
||||
Publication? publication1 = _taskManager.GetAllPublications().FirstOrDefault(pub => pub.internalId == internalId1);
|
||||
if (publication1 is null)
|
||||
if (!publication1.HasValue)
|
||||
return;
|
||||
_taskManager.AddTask(new MonitorPublicationTask(connectorName1, (Publication)publication1, TimeSpan.Parse(reoccurrenceTime1), language1 ?? "en"));
|
||||
break;
|
||||
case "/Tasks/CreateUpdateLibraryTask":
|
||||
variables.TryGetValue("reoccurrenceTime", out string? reoccurrenceTime2);
|
||||
if (reoccurrenceTime2 is null)
|
||||
return;
|
||||
_taskManager.AddTask(new UpdateLibrariesTask(TimeSpan.Parse(reoccurrenceTime2)));
|
||||
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);
|
||||
@ -178,7 +182,7 @@ public class RequestHandler
|
||||
if (publication2 is null)
|
||||
return;
|
||||
|
||||
IEnumerable<Chapter> toDownload = connector2.SearchChapters((Publication)publication2, chapters, language2 ?? "en");
|
||||
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;
|
||||
@ -236,17 +240,17 @@ public class RequestHandler
|
||||
variables.TryGetValue("lunaseaWebhook", out string? lunaseaWebhook);
|
||||
|
||||
if (downloadLocation is not null && downloadLocation.Length > 0)
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.DownloadLocation, _parent.logger, downloadLocation);
|
||||
_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, _parent.logger, komgaUrl, komgaAuth);
|
||||
_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, _parent.logger, kavitaUrl, kavitaUsername,
|
||||
_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, _parent.logger, gotifyUrl, gotifyAppToken);
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.Gotify, gotifyUrl, gotifyAppToken);
|
||||
if(lunaseaWebhook is not null && lunaseaWebhook.Length > 5)
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.LunaSea, _parent.logger, lunaseaWebhook);
|
||||
_taskManager.settings.UpdateSettings(TrangaSettings.UpdateField.LunaSea, lunaseaWebhook);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@ -272,7 +276,7 @@ public class RequestHandler
|
||||
return null;
|
||||
if(title.Length < 4)
|
||||
return null;
|
||||
return _taskManager.GetPublicationsFromConnector(connector1, title);
|
||||
return connector1.GetPublications(ref _taskManager.collection, title);
|
||||
case "/Publications/Chapters":
|
||||
string[] yes = { "true", "yes", "1", "y" };
|
||||
variables.TryGetValue("connectorName", out string? connectorName2);
|
||||
@ -293,7 +297,7 @@ public class RequestHandler
|
||||
return null;
|
||||
|
||||
if(newOnly)
|
||||
return _taskManager.GetNewChaptersList(connector2, (Publication)publication, language??"en").ToArray();
|
||||
return connector2.GetNewChaptersList((Publication)publication, language??"en", ref _taskManager.collection).ToArray();
|
||||
else if (existingOnly)
|
||||
return _taskManager.GetExistingChaptersList(connector2, (Publication)publication, language ?? "en").ToArray();
|
||||
else
|
||||
@ -319,7 +323,7 @@ public class RequestHandler
|
||||
variables.TryGetValue("taskType", out string? taskType2);
|
||||
variables.TryGetValue("connectorName", out string? connectorName4);
|
||||
variables.TryGetValue("publicationId", out string? publicationId);
|
||||
variables.TryGetValue("chapterSortNumber", out string? chapterSortNumber);
|
||||
variables.TryGetValue("chapterNumber", out string? chapterNumber);
|
||||
if (taskType2 is null || connectorName4 is null || publicationId is null)
|
||||
return null;
|
||||
Connector? connector =
|
||||
@ -333,10 +337,10 @@ public class RequestHandler
|
||||
if (pTask is TrangaTask.Task.MonitorPublication)
|
||||
{
|
||||
task = _taskManager.GetTasksMatching(pTask, connectorName: connectorName4, internalId: publicationId).FirstOrDefault();
|
||||
}else if (pTask is TrangaTask.Task.DownloadChapter && chapterSortNumber is not null)
|
||||
}else if (pTask is TrangaTask.Task.DownloadChapter && chapterNumber is not null)
|
||||
{
|
||||
task = _taskManager.GetTasksMatching(pTask, connectorName: connectorName4, internalId: publicationId,
|
||||
chapterSortNumber: chapterSortNumber).FirstOrDefault();
|
||||
chapterNumber: chapterNumber).FirstOrDefault();
|
||||
}
|
||||
if (task is null)
|
||||
return null;
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System.Net;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Logging;
|
||||
@ -18,7 +19,10 @@ public class Server
|
||||
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();
|
||||
}
|
||||
@ -51,8 +55,15 @@ public class Server
|
||||
return;
|
||||
}
|
||||
|
||||
if (request.HttpMethod == "OPTIONS")
|
||||
{
|
||||
SendResponse(HttpStatusCode.OK, response);
|
||||
}
|
||||
else
|
||||
{
|
||||
_requestHandler.HandleRequest(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
internal void SendResponse(HttpStatusCode statusCode, HttpListenerResponse response, object? content = null)
|
||||
{
|
||||
@ -63,9 +74,16 @@ public class Server
|
||||
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();
|
||||
|
||||
}
|
||||
|
14
Dockerfile
@ -1,14 +0,0 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
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 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"]
|
@ -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,7 +7,7 @@ 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)
|
||||
{
|
||||
|
||||
}
|
||||
|
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,6 +1,7 @@
|
||||
using System.Globalization;
|
||||
using Logging;
|
||||
using Tranga;
|
||||
using Tranga.Connectors;
|
||||
using Tranga.LibraryManagers;
|
||||
using Tranga.NotificationManagers;
|
||||
using Tranga.TrangaTasks;
|
||||
@ -31,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>(), new HashSet<NotificationManager>());
|
||||
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.UpdateSettings(TrangaSettings.UpdateField.DownloadLocation, logger, tmpPath);
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.DownloadLocation, tmpPath);
|
||||
|
||||
Console.WriteLine($"Komga BaseURL [{settings.libraryManagers.FirstOrDefault(lm => lm.GetType() == typeof(Komga))?.baseUrl}]:");
|
||||
string? tmpUrlKomga = Console.ReadLine();
|
||||
@ -73,7 +74,7 @@ public static class Tranga_Cli
|
||||
}
|
||||
} while (key != ConsoleKey.Enter);
|
||||
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Komga, logger, tmpUrlKomga, tmpKomgaUser, tmpKomgaPass);
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Komga, tmpUrlKomga, tmpKomgaUser, tmpKomgaPass);
|
||||
}
|
||||
|
||||
Console.WriteLine($"Kavita BaseURL [{settings.libraryManagers.FirstOrDefault(lm => lm.GetType() == typeof(Kavita))?.baseUrl}]:");
|
||||
@ -107,7 +108,7 @@ public static class Tranga_Cli
|
||||
}
|
||||
} while (key != ConsoleKey.Enter);
|
||||
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Kavita, logger, tmpUrlKavita, tmpKavitaUser, tmpKavitaPass);
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Kavita, tmpUrlKavita, tmpKavitaUser, tmpKavitaPass);
|
||||
}
|
||||
|
||||
Console.WriteLine($"Gotify BaseURL [{((Gotify?)settings.notificationManagers.FirstOrDefault(lm => lm.GetType() == typeof(Gotify)))?.endpoint}]:");
|
||||
@ -121,7 +122,7 @@ public static class Tranga_Cli
|
||||
while (tmpGotifyAppToken is null || tmpGotifyAppToken.Length < 1)
|
||||
tmpGotifyAppToken = Console.ReadLine();
|
||||
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Gotify, logger, tmpGotifyUrl, tmpGotifyAppToken);
|
||||
settings.UpdateSettings(TrangaSettings.UpdateField.Gotify, tmpGotifyUrl, tmpGotifyAppToken);
|
||||
}
|
||||
|
||||
logger.WriteLine("Tranga_CLI", "Loaded.");
|
||||
@ -132,7 +133,7 @@ public static class Tranga_Cli
|
||||
|
||||
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)
|
||||
@ -504,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):");
|
||||
@ -514,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)
|
||||
@ -565,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)
|
||||
{
|
||||
|
@ -1,6 +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,13 +1,12 @@
|
||||
using System.IO.Compression;
|
||||
using System.Globalization;
|
||||
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;
|
||||
namespace Tranga.Connectors;
|
||||
|
||||
/// <summary>
|
||||
/// Base-Class for all Connectors
|
||||
@ -15,35 +14,33 @@ namespace Tranga;
|
||||
/// </summary>
|
||||
public abstract class Connector
|
||||
{
|
||||
internal string downloadLocation { get; } //Location of local files
|
||||
protected DownloadClient downloadClient { get; init; }
|
||||
protected TrangaSettings settings { get; }
|
||||
internal DownloadClient downloadClient { get; init; } = null!;
|
||||
|
||||
protected readonly Logger? logger;
|
||||
|
||||
private readonly string _imageCachePath;
|
||||
|
||||
protected Connector(string downloadLocation, string imageCachePath, Logger? logger)
|
||||
protected Connector(TrangaSettings settings)
|
||||
{
|
||||
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);
|
||||
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>
|
||||
public abstract Publication[] GetPublications(string publicationTitle = "");
|
||||
protected abstract Publication[] GetPublicationsInternal(string publicationTitle = "");
|
||||
|
||||
/// <summary>
|
||||
/// Returns all Chapters of the publication in the provided language.
|
||||
@ -54,18 +51,40 @@ public abstract class Connector
|
||||
/// <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)
|
||||
/// <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.chapterNumber is not null &&
|
||||
return availableChapters.Where(aCh => aCh.volumeNumber is not null &&
|
||||
aCh.volumeNumber.Equals(volume, StringComparison.InvariantCultureIgnoreCase) &&
|
||||
aCh.chapterNumber.Equals(chapter, StringComparison.InvariantCultureIgnoreCase))
|
||||
.ToArray();
|
||||
@ -99,15 +118,13 @@ public abstract class Connector
|
||||
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 &&
|
||||
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 is not null &&
|
||||
aCh.chapterNumber.Equals(chapterNumber, StringComparison.InvariantCultureIgnoreCase)).ToArray();
|
||||
}
|
||||
}
|
||||
@ -121,6 +138,8 @@ public abstract class Connector
|
||||
}
|
||||
else if(singleResultRegex.IsMatch(searchTerm))
|
||||
return new [] { availableChapters[Convert.ToInt32(searchTerm)] };
|
||||
else if (allRegex.IsMatch(searchTerm))
|
||||
return availableChapters;
|
||||
}
|
||||
|
||||
return Array.Empty<Chapter>();
|
||||
@ -140,72 +159,26 @@ public abstract class Connector
|
||||
/// 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)
|
||||
public void CopyCoverFromCacheToDownloadLocation(Publication publication)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {publication.sortName} -> {publication.internalId}");
|
||||
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);
|
||||
string publicationFolder = publication.CreatePublicationFolder(settings.downloadLocation);
|
||||
DirectoryInfo dirInfo = new (publicationFolder);
|
||||
if (dirInfo.EnumerateFiles().Any(info => info.Name.Contains("cover", StringComparison.InvariantCultureIgnoreCase)))
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Cover exists {publication.sortName}");
|
||||
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]}" );
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Cloning cover {fileInCache} -> {newFilePath}");
|
||||
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>
|
||||
/// 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>
|
||||
@ -238,7 +211,7 @@ public abstract class Connector
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
logger?.WriteLine("Connector", $"Downloading Images for {saveArchiveFilePath}");
|
||||
settings.logger?.WriteLine("Connector", $"Downloading Images for {saveArchiveFilePath}");
|
||||
//Check if Publication Directory already exists
|
||||
string directoryPath = Path.GetDirectoryName(saveArchiveFilePath)!;
|
||||
if (!Directory.Exists(directoryPath))
|
||||
@ -256,7 +229,7 @@ public abstract class Connector
|
||||
{
|
||||
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}");
|
||||
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;
|
||||
@ -268,7 +241,7 @@ public abstract class Connector
|
||||
if(comicInfoPath is not null)
|
||||
File.Copy(comicInfoPath, Path.Join(tempFolder, "ComicInfo.xml"));
|
||||
|
||||
logger?.WriteLine("Connector", $"Creating archive {saveArchiveFilePath}");
|
||||
settings.logger?.WriteLine("Connector", $"Creating archive {saveArchiveFilePath}");
|
||||
//ZIP-it and ship-it
|
||||
ZipFile.CreateFromDirectory(tempFolder, saveArchiveFilePath);
|
||||
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
@ -281,7 +254,7 @@ public abstract class Connector
|
||||
{
|
||||
string[] split = url.Split('/');
|
||||
string filename = split[^1];
|
||||
string saveImagePath = Path.Join(_imageCachePath, filename);
|
||||
string saveImagePath = Path.Join(settings.coverImageCache, filename);
|
||||
|
||||
if (File.Exists(saveImagePath))
|
||||
return filename;
|
||||
@ -290,95 +263,7 @@ public abstract class Connector
|
||||
using MemoryStream ms = new();
|
||||
coverResult.result.CopyTo(ms);
|
||||
File.WriteAllBytes(saveImagePath, ms.ToArray());
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Saving image to {saveImagePath}");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Saving image to {saveImagePath}");
|
||||
return filename;
|
||||
}
|
||||
|
||||
protected 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);
|
||||
}
|
||||
return new RequestResult(response.StatusCode, response.Content.ReadAsStream());
|
||||
}
|
||||
|
||||
public struct RequestResult
|
||||
{
|
||||
public HttpStatusCode statusCode { get; }
|
||||
public Stream result { get; }
|
||||
|
||||
public RequestResult(HttpStatusCode statusCode, Stream result)
|
||||
{
|
||||
this.statusCode = statusCode;
|
||||
this.result = result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -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
|
||||
@ -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();
|
||||
|
||||
@ -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
|
||||
@ -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,7 +203,7 @@ 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();
|
||||
}
|
||||
|
||||
@ -211,7 +211,7 @@ public class MangaDex : Connector
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
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}");
|
||||
//Request URLs for Chapter-Images
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest($"https://api.mangadex.org/at-home/server/{chapter.url}?forcePort443=false'", (byte)RequestType.AtHomeServer);
|
||||
@ -230,18 +230,18 @@ 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
|
||||
return 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;
|
||||
}
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
@ -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,22 +10,22 @@ 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);
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Publication>();
|
||||
|
||||
@ -51,7 +50,7 @@ public class Manganato : Connector
|
||||
foreach (string url in urls)
|
||||
{
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(url, (byte)1);
|
||||
downloadClient.MakeRequest(url, 1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Publication>();
|
||||
|
||||
@ -103,7 +102,6 @@ public class Manganato : Connector
|
||||
string[] genres = value.Split(" - ");
|
||||
tags = genres.ToHashSet();
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
@ -127,10 +125,10 @@ 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);
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Chapter>();
|
||||
|
||||
@ -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,11 +157,11 @@ 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;
|
||||
@ -173,19 +171,19 @@ public class Manganato : Connector
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
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}");
|
||||
string requestUrl = chapter.url;
|
||||
DownloadClient.RequestResult requestResult =
|
||||
downloadClient.MakeRequest(requestUrl, (byte)1);
|
||||
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());
|
||||
|
||||
return 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 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,13 +71,12 @@ 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);
|
||||
downloadClient.MakeRequest(requestUrl, 1);
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return Array.Empty<Publication>();
|
||||
|
||||
@ -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 ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
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,7 +235,7 @@ 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();
|
||||
}
|
||||
|
||||
@ -215,13 +245,13 @@ public class Mangasee : Connector
|
||||
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 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,9 @@ 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());
|
||||
|
||||
return 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,8 +14,10 @@ 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;
|
||||
|
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));
|
||||
}
|
||||
}
|
@ -7,9 +7,11 @@ 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;
|
||||
@ -33,6 +35,7 @@ public class Gotify : NotificationManager
|
||||
|
||||
private class MessageData
|
||||
{
|
||||
// ReSharper disable four times UnusedAutoPropertyAccessor.Local
|
||||
public string message { get; }
|
||||
public long priority { get; }
|
||||
public string title { get; }
|
||||
|
@ -6,18 +6,21 @@ namespace Tranga.NotificationManagers;
|
||||
|
||||
public class LunaSea : NotificationManager
|
||||
{
|
||||
public string webhook { get; }
|
||||
// ReSharper disable once MemberCanBePrivate.Global
|
||||
public string id { get; init; }
|
||||
private readonly HttpClient _client = new();
|
||||
public LunaSea(string webhook, Logger? logger = null) : base(NotificationManagerType.LunaSea, logger)
|
||||
|
||||
[JsonConstructor]
|
||||
public LunaSea(string id, Logger? logger = null) : base(NotificationManagerType.LunaSea, logger)
|
||||
{
|
||||
this.webhook = webhook;
|
||||
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, webhook);
|
||||
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)
|
||||
@ -29,15 +32,14 @@ public class LunaSea : NotificationManager
|
||||
|
||||
private class MessageData
|
||||
{
|
||||
// ReSharper disable twice UnusedAutoPropertyAccessor.Local
|
||||
public string title { get; }
|
||||
public string body { get; }
|
||||
public string image { get; }
|
||||
|
||||
public MessageData(string title, string body)
|
||||
{
|
||||
this.title = title;
|
||||
this.body = body;
|
||||
this.image = "";
|
||||
}
|
||||
}
|
||||
}
|
@ -1,13 +1,12 @@
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Tranga.NotificationManagers;
|
||||
|
||||
namespace Tranga;
|
||||
namespace Tranga.NotificationManagers;
|
||||
|
||||
public abstract class NotificationManager
|
||||
{
|
||||
protected readonly Logger? logger;
|
||||
protected Logger? logger;
|
||||
public NotificationManagerType notificationManagerType;
|
||||
|
||||
protected NotificationManager(NotificationManagerType notificationManagerType, Logger? logger = null)
|
||||
@ -20,6 +19,11 @@ public abstract class NotificationManager
|
||||
|
||||
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)
|
@ -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,5 +1,4 @@
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json;
|
||||
using Tranga.Connectors;
|
||||
using Tranga.TrangaTasks;
|
||||
|
||||
@ -11,26 +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();
|
||||
|
||||
public TaskManager(TrangaSettings settings, Logger? logger = null)
|
||||
public TaskManager(TrangaSettings settings)
|
||||
{
|
||||
this.logger = logger;
|
||||
settings.logger?.WriteLine("Tranga", value: "\n"+
|
||||
@"-----------------------------------------------------------------"+"\n"+
|
||||
@" |¯¯¯¯¯¯|°|¯¯¯¯¯¯\ /¯¯¯¯¯¯| |¯¯¯\|¯¯¯| /¯¯¯¯¯¯\' /¯¯¯¯¯¯| "+"\n"+
|
||||
@" | | | x <|' / ! | | '| | (/¯¯¯\° / ! | "+ "\n"+
|
||||
@" ¯|__|¯ |__|\\__\\ /___/¯|_'| |___|\\__| \\_____/' /___/¯|_'| "+ "\n"+
|
||||
@"-----------------------------------------------------------------");
|
||||
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);
|
||||
@ -43,7 +47,7 @@ public class TaskManager
|
||||
/// </summary>
|
||||
private void TaskCheckerThread()
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), "Starting TaskCheckerThread.");
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), "Starting TaskCheckerThread.");
|
||||
int waitingTasksCount = _allTasks.Count(task => task.state is TrangaTask.ExecutionState.Waiting);
|
||||
while (_continueRunning)
|
||||
{
|
||||
@ -54,7 +58,7 @@ public class TaskManager
|
||||
waitingButExecute.state = TrangaTask.ExecutionState.Enqueued;
|
||||
}
|
||||
|
||||
foreach (TrangaTask enqueuedTask in _allTasks.Where(enqueuedTask => enqueuedTask.state is TrangaTask.ExecutionState.Enqueued))
|
||||
foreach (TrangaTask enqueuedTask in _allTasks.Where(enqueuedTask => enqueuedTask.state is TrangaTask.ExecutionState.Enqueued).OrderBy(enqueuedTask => enqueuedTask.nextExecution))
|
||||
{
|
||||
switch (enqueuedTask.task)
|
||||
{
|
||||
@ -82,21 +86,35 @@ public class TaskManager
|
||||
}
|
||||
}
|
||||
|
||||
TrangaTask[] failedDownloadChapterTasks = _allTasks.Where(taskQuery =>
|
||||
taskQuery.state is TrangaTask.ExecutionState.Failed && taskQuery is DownloadChapterTask).ToArray();
|
||||
foreach (TrangaTask failedDownloadChapterTask in failedDownloadChapterTasks)
|
||||
foreach (TrangaTask timedOutTask in _runningTasks.Keys
|
||||
.Where(taskQuery => taskQuery.lastChange < DateTime.Now.Subtract(TimeSpan.FromMinutes(3))))
|
||||
{
|
||||
DeleteTask(failedDownloadChapterTask);
|
||||
TrangaTask newTask = failedDownloadChapterTask.Clone();
|
||||
failedDownloadChapterTask.parentTask?.AddChildTask(newTask);
|
||||
AddTask(newTask);
|
||||
_runningTasks[timedOutTask].Cancel();
|
||||
timedOutTask.state = TrangaTask.ExecutionState.Failed;
|
||||
}
|
||||
|
||||
TrangaTask[] successfulDownloadChapterTasks = _allTasks.Where(taskQuery =>
|
||||
taskQuery.state is TrangaTask.ExecutionState.Success && taskQuery is DownloadChapterTask).ToArray();
|
||||
foreach(TrangaTask successfulDownloadChapterTask in successfulDownloadChapterTasks)
|
||||
foreach (TrangaTask finishedTask in _allTasks
|
||||
.Where(taskQuery => taskQuery.state is TrangaTask.ExecutionState.Success).ToArray())
|
||||
{
|
||||
DeleteTask(successfulDownloadChapterTask);
|
||||
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))
|
||||
@ -116,59 +134,73 @@ 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 is DownloadChapterTask chapterTask)
|
||||
_runningDownloadChapterTasks.Add(chapterTask, 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(), $"Replacing old {newTask.task}-Task.");
|
||||
_allTasks.RemoveWhere(trangaTask => trangaTask.task is TrangaTask.Task.UpdateLibraries);
|
||||
settings.logger?.WriteLine(this.GetType().ToString(), $"Replacing old {newTask.task}-Task.");
|
||||
if (GetTasksMatching(newTask).FirstOrDefault() is { } exists)
|
||||
_allTasks.Remove(exists);
|
||||
_allTasks.Add(newTask);
|
||||
ExportDataAndSettings();
|
||||
break;
|
||||
case TrangaTask.Task.MonitorPublication:
|
||||
if (!_allTasks.Any(mTask => mTask is MonitorPublicationTask mpt && newTask is MonitorPublicationTask nMpt &&
|
||||
mpt.publication.internalId == nMpt.publication.internalId &&
|
||||
mpt.connectorName == nMpt.connectorName))
|
||||
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}");
|
||||
break;
|
||||
case TrangaTask.Task.DownloadChapter:
|
||||
if (!_allTasks.Any(mTask => mTask is DownloadChapterTask dct && newTask is DownloadChapterTask nDct &&
|
||||
dct.publication.internalId == nDct.publication.internalId &&
|
||||
dct.connectorName == nDct.connectorName &&
|
||||
dct.chapter.sortNumber == nDct.chapter.sortNumber))
|
||||
_allTasks.Add(newTask);
|
||||
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);
|
||||
removeTask.parentTask?.RemoveChildTask(removeTask);
|
||||
if (removeTask is DownloadChapterTask cRemoveTask && _runningDownloadChapterTasks.ContainsKey(cRemoveTask))
|
||||
if (_runningTasks.ContainsKey(removeTask))
|
||||
{
|
||||
_runningDownloadChapterTasks[cRemoveTask].Cancel();
|
||||
_runningDownloadChapterTasks.Remove(cRemoveTask);
|
||||
_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)
|
||||
{
|
||||
@ -204,12 +236,12 @@ public class TaskManager
|
||||
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 _allTasks.Where(mTask =>
|
||||
mTask is DownloadChapterTask dct && dct.connectorName == connectorName &&
|
||||
dct.publication.publicationId == internalId &&
|
||||
dct.chapter.sortNumber == chapterSortNumber);
|
||||
dct.publication.internalId == internalId &&
|
||||
dct.chapter.chapterNumber == chapterNumber);
|
||||
}
|
||||
else
|
||||
return _allTasks.Where(mTask =>
|
||||
@ -254,46 +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();
|
||||
}
|
||||
|
||||
|
||||
/// <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>
|
||||
/// <returns>List of Chapters that were previously not in collection</returns>
|
||||
public List<Chapter> GetNewChaptersList(Connector connector, Publication publication, string language)
|
||||
{
|
||||
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;
|
||||
return this.collection.ToArray();
|
||||
}
|
||||
|
||||
public List<Chapter> GetExistingChaptersList(Connector connector, Publication publication, string language)
|
||||
{
|
||||
Chapter[] newChapters = connector.GetChapters(publication, language);
|
||||
return newChapters.Where(nChapter => connector.CheckChapterIsDownloaded(publication, nChapter)).ToList();
|
||||
return newChapters.Where(nChapter => nChapter.CheckChapterIsDownloaded(settings.downloadLocation)).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -317,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();
|
||||
|
||||
@ -327,40 +329,29 @@ 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(tTask => tTask.parentTaskId is not null))
|
||||
foreach (TrangaTask task in this._allTasks.Where(tTask => tTask.parentTaskId is not null).ToArray())
|
||||
{
|
||||
TrangaTask? parentTask = this._allTasks.FirstOrDefault(pTask => pTask.taskId == task.parentTaskId);
|
||||
if (parentTask is not null)
|
||||
{
|
||||
task.parentTask = parentTask;
|
||||
parentTask.AddChildTask(task);
|
||||
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>());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -368,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)
|
||||
|
@ -7,17 +7,18 @@ 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,
|
||||
HashSet<NotificationManager>? notificationManagers)
|
||||
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!");
|
||||
@ -25,25 +26,53 @@ public class TrangaSettings
|
||||
this.downloadLocation = downloadLocation;
|
||||
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>(), new HashSet<NotificationManager>());
|
||||
Directory.GetCurrentDirectory(), new HashSet<LibraryManager>(), new HashSet<NotificationManager>(), logger);
|
||||
|
||||
string toRead = File.ReadAllText(importFilePath);
|
||||
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 UpdateSettings(UpdateField field, Logger? logger = null, params string[] values)
|
||||
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)
|
||||
{
|
||||
@ -56,19 +85,19 @@ public class TrangaSettings
|
||||
if (values.Length != 2)
|
||||
return;
|
||||
libraryManagers.RemoveWhere(lm => lm.GetType() == typeof(Komga));
|
||||
libraryManagers.Add(new Komga(values[0], values[1], logger));
|
||||
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], logger));
|
||||
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], logger);
|
||||
Gotify newGotify = new(values[0], values[1], this.logger);
|
||||
notificationManagers.Add(newGotify);
|
||||
newGotify.SendNotification("Success!", "Gotify was added to Tranga!");
|
||||
break;
|
||||
@ -76,11 +105,12 @@ public class TrangaSettings
|
||||
if(values.Length != 1)
|
||||
return;
|
||||
notificationManagers.RemoveWhere(nm => nm.GetType() == typeof(LunaSea));
|
||||
LunaSea newLunaSea = new(values[0], logger);
|
||||
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,5 +1,7 @@
|
||||
using System.Net;
|
||||
using Logging;
|
||||
using Tranga.Connectors;
|
||||
using Tranga.NotificationManagers;
|
||||
using Tranga.LibraryManagers;
|
||||
|
||||
namespace Tranga.TrangaTasks;
|
||||
|
||||
@ -7,10 +9,11 @@ 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; }
|
||||
|
||||
private double _dctProgress = 0;
|
||||
private double _dctProgress;
|
||||
|
||||
public DownloadChapterTask(string connectorName, Publication publication, Chapter chapter, string language = "en", MonitorPublicationTask? parentTask = null) : base(Task.DownloadChapter, TimeSpan.Zero, parentTask)
|
||||
{
|
||||
@ -20,16 +23,21 @@ public class DownloadChapterTask : TrangaTask
|
||||
this.language = language;
|
||||
}
|
||||
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null)
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
Connector connector = taskManager.GetConnector(this.connectorName);
|
||||
connector.CopyCoverFromCacheToDownloadLocation(this.publication, taskManager.settings);
|
||||
connector.CopyCoverFromCacheToDownloadLocation(this.publication);
|
||||
HttpStatusCode downloadSuccess = connector.DownloadChapter(this.publication, this.chapter, this, cancellationToken);
|
||||
if((int)downloadSuccess >= 200 && (int)downloadSuccess < 300 && parentTask is not null)
|
||||
if ((int)downloadSuccess >= 200 && (int)downloadSuccess < 300)
|
||||
{
|
||||
foreach(NotificationManager nm in taskManager.settings.notificationManagers)
|
||||
nm.SendNotification("New Chapter downloaded", $"{this.publication.sortName} {this.chapter.chapterNumber} {this.chapter.name}");
|
||||
nm.SendNotification("Chapter downloaded", $"{this.publication.sortName} {this.chapter.chapterNumber} {this.chapter.name}");
|
||||
|
||||
foreach (LibraryManager lm in taskManager.settings.libraryManagers)
|
||||
lm.UpdateLibrary();
|
||||
}
|
||||
return downloadSuccess;
|
||||
}
|
||||
|
||||
@ -47,6 +55,9 @@ public class DownloadChapterTask : TrangaTask
|
||||
internal void IncrementProgress(double amount)
|
||||
{
|
||||
this._dctProgress += amount;
|
||||
this.lastChange = DateTime.Now;
|
||||
if(this.parentTask is not null)
|
||||
this.parentTask.lastChange = DateTime.Now;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
|
@ -1,5 +1,5 @@
|
||||
using System.Net;
|
||||
using Logging;
|
||||
using Tranga.Connectors;
|
||||
|
||||
namespace Tranga.TrangaTasks;
|
||||
|
||||
@ -7,6 +7,7 @@ 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)
|
||||
{
|
||||
@ -15,7 +16,7 @@ public class MonitorPublicationTask : TrangaTask
|
||||
this.language = language;
|
||||
}
|
||||
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null)
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
@ -23,11 +24,11 @@ public class MonitorPublicationTask : TrangaTask
|
||||
|
||||
//Check if Publication already has a Folder
|
||||
publication.CreatePublicationFolder(taskManager.settings.downloadLocation);
|
||||
List<Chapter> newChapters = taskManager.GetNewChaptersList(connector, publication, language);
|
||||
List<Chapter> newChapters = connector.GetNewChaptersList(publication, language, ref taskManager.collection);
|
||||
|
||||
connector.CopyCoverFromCacheToDownloadLocation(publication, taskManager.settings);
|
||||
connector.CopyCoverFromCacheToDownloadLocation(publication);
|
||||
|
||||
publication.SaveSeriesInfoJson(connector.downloadLocation);
|
||||
publication.SaveSeriesInfoJson(taskManager.settings.downloadLocation);
|
||||
|
||||
foreach (Chapter newChapter in newChapters)
|
||||
{
|
||||
|
@ -1,12 +1,10 @@
|
||||
using System.Net;
|
||||
using System.Text.Json.Serialization;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Tranga.TrangaTasks;
|
||||
using JsonConverter = Newtonsoft.Json.JsonConverter;
|
||||
|
||||
namespace Tranga;
|
||||
namespace Tranga.TrangaTasks;
|
||||
|
||||
/// <summary>
|
||||
/// Stores information on Task, when implementing new Tasks also update the serializer
|
||||
@ -16,20 +14,22 @@ namespace Tranga;
|
||||
[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
|
||||
// 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; }
|
||||
public string taskId { get; init; }
|
||||
[Newtonsoft.Json.JsonIgnore] public TrangaTask? parentTask { get; set; }
|
||||
public string? parentTaskId { get; set; }
|
||||
[Newtonsoft.Json.JsonIgnore] protected HashSet<TrangaTask> childTasks { get; }
|
||||
[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; private set; }
|
||||
[Newtonsoft.Json.JsonIgnore]public DateTime executionApproximatelyFinished => progress != 0 ? lastChange.Add(GetRemainingTime()) : DateTime.MaxValue;
|
||||
[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);
|
||||
|
||||
@ -52,9 +52,8 @@ public abstract class TrangaTask
|
||||
/// BL for concrete Tasks
|
||||
/// </summary>
|
||||
/// <param name="taskManager"></param>
|
||||
/// <param name="logger"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
protected abstract HttpStatusCode ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null);
|
||||
protected abstract HttpStatusCode ExecuteTask(TaskManager taskManager, CancellationToken? cancellationToken = null);
|
||||
|
||||
public abstract TrangaTask Clone();
|
||||
|
||||
@ -64,34 +63,33 @@ public abstract class TrangaTask
|
||||
/// 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)
|
||||
public void Execute(TaskManager taskManager, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Executing Task {this}");
|
||||
taskManager.settings.logger?.WriteLine(this.GetType().ToString(), $"Executing Task {this}");
|
||||
this.state = ExecutionState.Running;
|
||||
this.executionStarted = DateTime.Now;
|
||||
this.lastChange = DateTime.Now;
|
||||
HttpStatusCode statusCode = ExecuteTask(taskManager, logger, cancellationToken);
|
||||
while(childTasks.Any(ct => ct.state is ExecutionState.Enqueued or ExecutionState.Running))
|
||||
Thread.Sleep(1000);
|
||||
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;
|
||||
if (this is DownloadChapterTask)
|
||||
this.state = ExecutionState.Success;
|
||||
else
|
||||
this.state = ExecutionState.Waiting;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this is DownloadChapterTask && statusCode == HttpStatusCode.NotFound)
|
||||
this.state = ExecutionState.Success;
|
||||
else
|
||||
this.state = ExecutionState.Failed;
|
||||
this.lastExecuted = DateTime.MaxValue;
|
||||
}
|
||||
logger?.WriteLine(this.GetType().ToString(), $"Finished Executing Task {this}");
|
||||
|
||||
if (this is DownloadChapterTask)
|
||||
taskManager.DeleteTask(this);
|
||||
|
||||
taskManager.settings.logger?.WriteLine(this.GetType().ToString(), $"Finished Executing Task {this}");
|
||||
}
|
||||
|
||||
public void AddChildTask(TrangaTask childTask)
|
||||
@ -106,10 +104,10 @@ public abstract class TrangaTask
|
||||
|
||||
private TimeSpan GetRemainingTime()
|
||||
{
|
||||
if(progress == 0 || lastChange == DateTime.MaxValue || executionStarted == DateTime.UnixEpoch)
|
||||
return TimeSpan.Zero;
|
||||
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).Subtract(elapsed);
|
||||
return elapsed.Divide(progress).Multiply(1 - progress);
|
||||
}
|
||||
|
||||
public enum Task : byte
|
||||
@ -117,7 +115,6 @@ public abstract class TrangaTask
|
||||
MonitorPublication = 2,
|
||||
UpdateLibraries = 3,
|
||||
DownloadChapter = 4,
|
||||
DownloadNewChapters = 2 //legacy
|
||||
}
|
||||
|
||||
public override string ToString()
|
@ -1,21 +1,19 @@
|
||||
using System.Net;
|
||||
using Logging;
|
||||
|
||||
namespace Tranga.TrangaTasks;
|
||||
|
||||
/// <summary>
|
||||
/// LEGACY DEPRECATED
|
||||
/// </summary>
|
||||
public class UpdateLibrariesTask : TrangaTask
|
||||
{
|
||||
public UpdateLibrariesTask(TimeSpan reoccurrence) : base(Task.UpdateLibraries, reoccurrence)
|
||||
{
|
||||
}
|
||||
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, Logger? logger, CancellationToken? cancellationToken = null)
|
||||
protected override HttpStatusCode ExecuteTask(TaskManager taskManager, CancellationToken? cancellationToken = null)
|
||||
{
|
||||
if (cancellationToken?.IsCancellationRequested ?? false)
|
||||
return HttpStatusCode.RequestTimeout;
|
||||
foreach(LibraryManager lm in taskManager.settings.libraryManagers)
|
||||
lm.UpdateLibrary();
|
||||
return HttpStatusCode.OK;
|
||||
return HttpStatusCode.BadRequest;
|
||||
}
|
||||
|
||||
public override TrangaTask Clone()
|
||||
|
@ -84,7 +84,7 @@ async function GetRunningTasks(){
|
||||
}
|
||||
|
||||
async function GetDownloadTasks(){
|
||||
var uri = apiUri + "/Tasks?taskType=DownloadNewChapters";
|
||||
var uri = apiUri + "/Tasks?taskType=MonitorPublication";
|
||||
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);
|
||||
|
@ -142,7 +142,7 @@
|
||||
<div>
|
||||
<span class="title">LunaSea</span>
|
||||
<div>Configured: <span id="lunaseaConfigured">✅❌</span></div>
|
||||
<label for="lunaseaWebhook"></label><input placeholder="Webhook-Url" id="lunaseaWebhook" type="text">
|
||||
<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">
|
||||
|
@ -70,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();
|
||||
@ -195,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();
|
||||
}
|
||||
|
||||
@ -337,12 +330,10 @@ function UpdateLibrarySettings(){
|
||||
var auth = utf8_to_b64(`${settingKomgaUser.value}:${settingKomgaPass.value}`);
|
||||
console.log(auth);
|
||||
UpdateKomga(settingKomgaUrl.value, auth);
|
||||
CreateUpdateLibraryTask(libraryUpdateTime.value);
|
||||
}
|
||||
|
||||
if(settingKavitaUrl.value != "" && settingKavitaUser.value != "" && settingKavitaPass.value != ""){
|
||||
UpdateKavita(settingKavitaUrl.value, settingKavitaUser.value, settingKavitaPass.value);
|
||||
CreateUpdateLibraryTask(libraryUpdateTime.value);
|
||||
}
|
||||
|
||||
if(settingGotifyUrl.value != "" && settingGotifyAppToken.value != ""){
|
||||
@ -353,6 +344,11 @@ function UpdateLibrarySettings(){
|
||||
UpdateLunaSea(settingLunaseaWebhook.value);
|
||||
}
|
||||
|
||||
if(settingApiUri.value != ""){
|
||||
apiUri = settingApiUri.value;
|
||||
document.cookie = `apiUri=${apiUri};`;
|
||||
}
|
||||
|
||||
setTimeout(() => GetSettingsClick(), 200);
|
||||
}
|
||||
|
||||
|
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 |