mirror of
https://github.com/C9Glax/tranga.git
synced 2025-07-01 16:34:17 +02:00
Compare commits
591 Commits
0.5
...
67c23b357f
Author | SHA1 | Date | |
---|---|---|---|
67c23b357f | |||
4a5271e2a7 | |||
fec5ad664c | |||
3cea5fb431 | |||
7fa44fba54 | |||
d6b5a29fdc | |||
a4a49d40f0 | |||
28fa85f05c | |||
1066e1ca2e | |||
39307f4313 | |||
a316ee3d48 | |||
569622099d | |||
017701867d | |||
c3d62bd337 | |||
dc9e9e705c | |||
9eee6683fa | |||
1265c7a072 | |||
c601541249 | |||
ae1184320f | |||
384e4c4f43 | |||
76a2b2498a | |||
5f2c66b729 | |||
e030f02431 | |||
bdeb75f4e4 | |||
4ce114986d | |||
8035bf3fcd | |||
85bf3ec7e8 | |||
0f17615b10 | |||
0c8145803e | |||
b2e0c3db97 | |||
ca283fcfff | |||
1d55070daf | |||
32fd75bdae | |||
99ad702163 | |||
6e3a9c2a78 | |||
ad1d4dfe23 | |||
14ba71005f | |||
22c4c0eb2c | |||
44f8d369c3 | |||
c0e6da144e | |||
51a1ae72ca | |||
79bbc92467 | |||
ae5be31c89 | |||
eebe25a378 | |||
0f3da4ec81 | |||
0b77dc1172 | |||
37cf47bc17 | |||
4cce2e04cb | |||
5465ac4e5c | |||
dd4d5a81ee | |||
a05e1914e3 | |||
ed79ee5d0f | |||
28e05e549d | |||
eaab7c5235 | |||
0552b3db82 | |||
c813e1854d | |||
32036df057 | |||
394829ee36 | |||
2a389f1ede | |||
3167f6c3e6 | |||
89c5f4b820 | |||
1c1169e5ce | |||
d5d34c5381 | |||
c0efbb22cc | |||
9f30e52713 | |||
1fd36c91d6 | |||
e663163de8 | |||
e274c864f9 | |||
f4bc182954 | |||
3365be219c | |||
10708b3abd | |||
c1e939f1e3 | |||
21d53dabec | |||
a9417dbba6 | |||
61024bcee9 | |||
ea1b8749a6 | |||
2fcab1f1b1 | |||
bbd716383a | |||
6e1a0ab06c | |||
181942153b | |||
fe04af4a2b | |||
4240a1eb6a | |||
32349c1ddf | |||
a94d3d6b40 | |||
f916cda0f1 | |||
a8f0f1af15 | |||
0cf3a95f58 | |||
a89a526fda | |||
4d1e43e7b3 | |||
4f9749d09e | |||
7614f9aad3 | |||
97c0e42512 | |||
565bc0775d | |||
e6a3fa2899 | |||
2d82279d98 | |||
c5559a4ceb | |||
2572a537ab | |||
58db049496 | |||
8f309fcfd7 | |||
11461051f3 | |||
a4aa571870 | |||
e4086a8892 | |||
c45e4ddf90 | |||
675effd317 | |||
a4f67c9ab4 | |||
2538a29788 | |||
81d5802092 | |||
436edfde66 | |||
00c1cd56b8 | |||
a63154b581 | |||
53fe7ee983 | |||
6fb4098c16 | |||
7a024e8733 | |||
835e239be5 | |||
df8538c3b4 | |||
f832fe0de3 | |||
ebdb38bd57 | |||
e3201a9b99 | |||
eb50b84266 | |||
b3d778ff56 | |||
00861c406a | |||
01c8784bab | |||
3aa299e48a | |||
d1ce244135 | |||
c91754614b | |||
70b1ae4812 | |||
336e08aebf | |||
18134cdf01 | |||
5b89cbd042 | |||
74aca86b62 | |||
e5abaa4549 | |||
eb0eb71e86 | |||
4e73b0a4cf | |||
140074208f | |||
fa19d3da14 | |||
3d6657b483 | |||
f9b5e05974 | |||
ad4027779f | |||
98ec0b837f | |||
1afa3df316 | |||
d83aa1ef5b | |||
b610ec734e | |||
abf587377c | |||
437349bd27 | |||
000539d6a6 | |||
b4bef25a22 | |||
579e400a5d | |||
8af2b12fc0 | |||
bad4330330 | |||
42596752d3 | |||
16238c590b | |||
9f38dc3b6a | |||
485637d99a | |||
de14ff0b75 | |||
f947c37bd6 | |||
77eec0f696 | |||
18323f9f51 | |||
2cd2b6842d | |||
09f815903f | |||
c108478039 | |||
74289e43b7 | |||
2779f9ba09 | |||
59a8e556f0 | |||
074b137b5c | |||
3cb2540794 | |||
02c9934896 | |||
b2e1c95bca | |||
8c9e3ea6b6 | |||
db441607ad | |||
91c56783dc | |||
2c288eeeea | |||
57a1ea91fc | |||
06138a3927 | |||
84b053e672 | |||
0fe0cbc4ad | |||
62e6ce8363 | |||
a4f3ec6580 | |||
8b4e996b7e | |||
964540d30f | |||
fa69f4488f | |||
42c2876188 | |||
715244ff1b | |||
2333cd9095 | |||
c8225db4fe | |||
6741ca096b | |||
a897a7b3a2 | |||
0f8932e712 | |||
78023ef0fd | |||
d171f34e4e | |||
aa0dc4fa35 | |||
25f48592c0 | |||
398ac304d2 | |||
58a62f8272 | |||
86752c9a7e | |||
f9a7828d02 | |||
c97ff69148 | |||
1735bbcf8a | |||
9ae8ca65df | |||
00599cd24e | |||
6d5618a1f7 | |||
a1202a875d | |||
98946b4aa3 | |||
41b6bb77b6 | |||
e70a14ca56 | |||
b099da1156 | |||
01d1f922c2 | |||
47a80d67a8 | |||
16e3549455 | |||
be8c6b50ba | |||
a38fcf50ca | |||
82f6c7b3fe | |||
5586d2c104 | |||
62dc9fee2a | |||
ac96fca6dc | |||
25a6ceff10 | |||
b3e1d39d0f | |||
2833b7f22a | |||
cbdd305b69 | |||
b88890817e | |||
f66ab7d40b | |||
4cb3694cd5 | |||
a05d4c8bd9 | |||
22f87a74b2 | |||
ba57282879 | |||
9ccba6fba6 | |||
4f01c1166f | |||
0a51e7ad3d | |||
e541b922dc | |||
604abd5f9a | |||
7b311eae75 | |||
d4eb72cd99 | |||
b515215f4b | |||
a16686dfbf | |||
4275703941 | |||
c3342984ea | |||
ed4bdb5b33 | |||
0f0902c932 | |||
6508055b43 | |||
abc66511d8 | |||
9ed36c47b5 | |||
fd1b2a8470 | |||
8058749ab5 | |||
8737617e5f | |||
7e4f43f1e2 | |||
12b1b2afd6 | |||
0f9ac60fcd | |||
8c87f2948c | |||
e0fb817256 | |||
cdd2d94ba1 | |||
d5b7645cd2 | |||
9af5c1603e | |||
1035939309 | |||
3b542c04f6 | |||
a809b7c285 | |||
e883277400 | |||
23dfdc0933 | |||
edc24fff5b | |||
6cdccdf66b | |||
a4c9168551 | |||
821a1b7c3a | |||
b2b4256972 | |||
d2f46e4637 | |||
303fc293ba | |||
36c145da26 | |||
c822c74f42 | |||
dda4054d34 | |||
5b2546fdbc | |||
c11e3993ea | |||
02a382a99a | |||
c6c8f5cdf6 | |||
84842aed3c | |||
d9ced11cd1 | |||
25c90782dc | |||
e789c429cd | |||
93de471836 | |||
8b58e7dd13 | |||
b571bfa43d | |||
088d1c4647 | |||
f280c01802 | |||
1be10b310d | |||
a0469f3145 | |||
fcd81f03b3 | |||
76604d84d8 | |||
af822febbe | |||
8e207c3119 | |||
b6f8c8aab5 | |||
36f7cbd3e9 | |||
3b2643d949 | |||
9fd8bf1741 | |||
d5c9c5ba96 | |||
c8e27921ab | |||
6eaba07801 | |||
41929e0c72 | |||
4fcaca1a6e | |||
0e3c7f32d7 | |||
1c94625840 | |||
32f89f9dce | |||
234735a562 | |||
8b916eb854 | |||
29e1790c93 | |||
ac4c799a74 | |||
7c62883c37 | |||
02018253bf | |||
2aec884009 | |||
b3321ff030 | |||
16c1094875 | |||
5763d50409 | |||
ad43297358 | |||
b17800e0ef | |||
89c80d2997 | |||
6485b8744f | |||
a3a96b6b55 | |||
5bce3c6fdd | |||
5fa0c98d05 | |||
b166013770 | |||
02fe849046 | |||
d42393c83a | |||
c685bd622f | |||
dc83cc2194 | |||
7784f2024e | |||
4895079887 | |||
ab1ddc6dc8 | |||
87eade10cf | |||
1f3ac41b30 | |||
6a304bb330 | |||
b0642d1251 | |||
63b5139e93 | |||
e938784388 | |||
c436389426 | |||
5099e25f3f | |||
cf6fc3b8f6 | |||
f5141d0f8e | |||
5c753e7a7d | |||
17ce820cf3 | |||
5b4a3b9d7c | |||
f73997e563 | |||
437136804d | |||
e14683d21a | |||
5ae02ee0ed | |||
a2e9a3f34a | |||
bbf05e3dec | |||
d95839e5df | |||
5a303598fe | |||
db2103963e | |||
2c1105527a | |||
ed19dcb5c3 | |||
46f06c2685 | |||
d4f47e057c | |||
61712d0537 | |||
1f8f8c09e3 | |||
0522fa6215 | |||
0383a7d686 | |||
bd189984a9 | |||
58c01b2174 | |||
459558a514 | |||
721b316209 | |||
b1befa2ecc | |||
57a4cc4ab5 | |||
655e8db2b6 | |||
7cdf77cbb9 | |||
5a9aed4969 | |||
5b41f687d0 | |||
d6a62dc315 | |||
6d91788655 | |||
14785e5672 | |||
496d502cd2 | |||
7612411917 | |||
ed1402b5ec | |||
5adaee4821 | |||
2d82fe1489 | |||
783fd8129e | |||
4f29eff48e | |||
e0e7abb62b | |||
ae63a216a5 | |||
5d98295c59 | |||
0c580933f9 | |||
06f735aadd | |||
439d69d8e0 | |||
933df58712 | |||
165bbc412e | |||
6158fa072b | |||
0d3799e00d | |||
e977bed5a5 | |||
cacd5fede2 | |||
1bca99cb6a | |||
15fc367263 | |||
8bb6fb902b | |||
a57903cd5a | |||
1cd819b21d | |||
27afedc1b4 | |||
fac0a3f7eb | |||
03ca480fe8 | |||
c2915468a5 | |||
8805c53cb8 | |||
adbbe3f6cc | |||
14b694d3be | |||
72ce75c6e0 | |||
8381951168 | |||
b24032d124 | |||
8bc23f7c69 | |||
48b7371a18 | |||
61ecefb615 | |||
8ff65bf400 | |||
932057cca0 | |||
67d06cd887 | |||
cbb012a659 | |||
e4f33bcca9 | |||
fbba7c45b9 | |||
d9b6062767 | |||
d477cd1ccd | |||
f892db7dda | |||
16c1b5c506 | |||
d5ecc1c37d | |||
1b9ebd096b | |||
8619630269 | |||
2bc92556e3 | |||
f1ab823e7f | |||
8261d02cc7 | |||
8d3b8be95c | |||
60519910de | |||
0940afe41f | |||
3dc376c19f | |||
3e56ef842b | |||
5a44e3b8b9 | |||
732c2f119c | |||
81638f4b4a | |||
c547aa6422 | |||
d80980512e | |||
f9f802155d | |||
eef0955009 | |||
ec25900ac0 | |||
e5fe14a09e | |||
5dc91095f8 | |||
985ac8fc7a | |||
c9537a9963 | |||
4fd3c03804 | |||
a1e9dd0232 | |||
aa1f9b1b56 | |||
6069578b6e | |||
a84b768e24 | |||
d1a21af15d | |||
7423ae6ace | |||
3aa7ba9d96 | |||
fdbb4570be | |||
b643a0c2a9 | |||
6fa6f897aa | |||
2bfab0298d | |||
147a20385b | |||
afa18d6a2c | |||
66980eef23 | |||
65f468a30a | |||
a91c33ee4f | |||
f39482fe4c | |||
41f47b4d6b | |||
be40091102 | |||
665092be6a | |||
653cb699d0 | |||
8dbc5446ad | |||
750df4ed52 | |||
4772ae0756 | |||
23f703d5a5 | |||
6aa0ea277b | |||
780df1cd6e | |||
0b7da2e9cb | |||
01a059d26b | |||
a8dbece237 | |||
5efa00e059 | |||
02075ed1b1 | |||
fabd16ccea | |||
79928075b0 | |||
9b8eb6a197 | |||
1d263ef45a | |||
e0877add30 | |||
046cad8072 | |||
b2ce55be96 | |||
a6e9013495 | |||
14c69631a6 | |||
ccc4e42a49 | |||
d6e75fda31 | |||
fc89537f63 | |||
fd3423d03c | |||
878f77766f | |||
08001fd684 | |||
e2917d2f2e | |||
32dc58715e | |||
add0583776 | |||
6fed0e5473 | |||
a0636ac7a2 | |||
7aeb78e2f6 | |||
5cf512f2b2 | |||
7d96b0901f | |||
68e80bc066 | |||
ad971fb065 | |||
86052472bc | |||
ec30bb40fa | |||
2fa96e9793 | |||
78e44b7704 | |||
8bf9df4419 | |||
4bd54f096d | |||
877daf0a1e | |||
6d0fcc13fb | |||
f0256494fd | |||
39fa905733 | |||
c557389967 | |||
201773af50 | |||
f85e02fb0a | |||
73d98b9c0f | |||
b0ee888c82 | |||
5c4431778e | |||
ccfa213b77 | |||
22d6389d38 | |||
f53dfb0822 | |||
a966bd788d | |||
dd651adc15 | |||
ba5ae67aa7 | |||
da4a5bed09 | |||
947b521163 | |||
5674adbd5e | |||
290819de09 | |||
0d0b68a8f9 | |||
87d2357b41 | |||
e3186aebb0 | |||
1cd37e2b1b | |||
9c267f395f | |||
e2b8888130 | |||
b6ac2682f6 | |||
eddf50483f | |||
a71d65e666 | |||
9a640aed27 | |||
30b6c4680b | |||
7b6253de0f | |||
5aa3214ce5 | |||
9b70994f71 | |||
93cf341f2d | |||
01cb74c088 | |||
ec480dffad | |||
b7014cbff5 | |||
0cab921402 | |||
0e0ba1796e | |||
27d8565dc1 | |||
79dc44d707 | |||
bb6a0ad0d4 | |||
43db463ba6 | |||
9eb8ddbc40 | |||
972cba69ec | |||
962fe9529e | |||
da1b0cb1cd | |||
7f88e57e47 | |||
8865bf284f | |||
5fc2de5fcb | |||
4bae223d95 | |||
0486168b43 | |||
b64ab5c6d4 | |||
578fa5e6be | |||
4d33e78123 | |||
52ac3e4e4e | |||
8b99a98e24 | |||
cf171d5c38 | |||
6d49b4b934 | |||
b55d2a2d06 | |||
737eebf599 | |||
aef01b684c | |||
53bff61174 | |||
431a602a40 | |||
9afb81cee2 | |||
ea69b355b5 | |||
84dbc36bbf | |||
455c87b2e1 | |||
df991e3da6 | |||
13c96fd09a | |||
6f1a6a43ee | |||
e2afc09c4a | |||
e9db7cfacc | |||
755167c39a | |||
1cff93fbac | |||
6c775d6e0c | |||
876b1ab78b | |||
a321ecb1bc | |||
674c8fc37b | |||
e24652b83e | |||
5dee13c402 | |||
942a552c8e | |||
b5bd5d6126 | |||
715cf1f4f3 | |||
168bf5a358 | |||
636d17d287 | |||
294b819ff0 | |||
d763610383 | |||
2910473fec | |||
ca2d13226f | |||
95c65c981e |
7
.github/dependabot.yml
vendored
Normal file
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
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
|
45
.github/workflows/docker-image-cuttingedge.yml
vendored
Normal file
45
.github/workflows/docker-image-cuttingedge.yml
vendored
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
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: ./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
|
47
.github/workflows/docker-image-master.yml
vendored
Normal file
47
.github/workflows/docker-image-master.yml
vendored
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
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: ./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
|
2
.gitignore
vendored
2
.gitignore
vendored
@ -17,3 +17,5 @@ riderModule.iml
|
|||||||
/dataSources/
|
/dataSources/
|
||||||
/dataSources.local.xml
|
/dataSources.local.xml
|
||||||
/.idea
|
/.idea
|
||||||
|
cover.jpg
|
||||||
|
cover.png
|
@ -3,16 +3,12 @@
|
|||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
<TargetFramework>net7.0</TargetFramework>
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
<RootNamespace>Tranga_CLI</RootNamespace>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Content Include="..\.dockerignore">
|
<PackageReference Include="Spectre.Console.Cli" Version="0.47.1-preview.0.11" />
|
||||||
<Link>.dockerignore</Link>
|
|
||||||
</Content>
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
155
CLI/Program.cs
Normal file
155
CLI/Program.cs
Normal file
@ -0,0 +1,155 @@
|
|||||||
|
using System.ComponentModel;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using Logging;
|
||||||
|
using Spectre.Console;
|
||||||
|
using Spectre.Console.Cli;
|
||||||
|
using Tranga;
|
||||||
|
|
||||||
|
var app = new CommandApp<TrangaCli>();
|
||||||
|
return app.Run(args);
|
||||||
|
|
||||||
|
internal sealed class TrangaCli : Command<TrangaCli.Settings>
|
||||||
|
{
|
||||||
|
public sealed class Settings : CommandSettings
|
||||||
|
{
|
||||||
|
[Description("Directory to which downloaded Manga are saved")]
|
||||||
|
[CommandOption("-d|--downloadLocation")]
|
||||||
|
[DefaultValue(null)]
|
||||||
|
public string? downloadLocation { get; init; }
|
||||||
|
|
||||||
|
[Description("Directory in which application-data is saved")]
|
||||||
|
[CommandOption("-w|--workingDirectory")]
|
||||||
|
[DefaultValue(null)]
|
||||||
|
public string? workingDirectory { get; init; }
|
||||||
|
|
||||||
|
[Description("Enables the file-logger")]
|
||||||
|
[CommandOption("-f")]
|
||||||
|
[DefaultValue(null)]
|
||||||
|
public bool? fileLogger { get; init; }
|
||||||
|
|
||||||
|
[Description("Path to save logfile to")]
|
||||||
|
[CommandOption("-l|--fPath")]
|
||||||
|
[DefaultValue(null)]
|
||||||
|
public string? fileLoggerPath { get; init; }
|
||||||
|
|
||||||
|
[Description("Port on which to run API on")]
|
||||||
|
[CommandOption("-p|--port")]
|
||||||
|
[DefaultValue(null)]
|
||||||
|
public int? apiPort { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public override int Execute([NotNull] CommandContext context, [NotNull] Settings settings)
|
||||||
|
{
|
||||||
|
List<Logger.LoggerType> enabledLoggers = new();
|
||||||
|
if(settings.fileLogger is true)
|
||||||
|
enabledLoggers.Add(Logger.LoggerType.FileLogger);
|
||||||
|
|
||||||
|
string? logFilePath = settings.fileLoggerPath ?? "";
|
||||||
|
Logger logger = new(enabledLoggers.ToArray(), Console.Out, Console.OutputEncoding, logFilePath);
|
||||||
|
|
||||||
|
TrangaSettings trangaSettings = new (settings.downloadLocation, settings.workingDirectory, settings.apiPort);
|
||||||
|
|
||||||
|
Directory.CreateDirectory(trangaSettings.downloadLocation);
|
||||||
|
Directory.CreateDirectory(trangaSettings.workingDirectory);
|
||||||
|
|
||||||
|
Tranga.Tranga? api = null;
|
||||||
|
|
||||||
|
Thread trangaApi = new Thread(() =>
|
||||||
|
{
|
||||||
|
api = new(logger, trangaSettings);
|
||||||
|
});
|
||||||
|
trangaApi.Start();
|
||||||
|
|
||||||
|
HttpClient client = new();
|
||||||
|
|
||||||
|
bool exit = false;
|
||||||
|
while (!exit)
|
||||||
|
{
|
||||||
|
string menuSelect = AnsiConsole.Prompt(
|
||||||
|
new SelectionPrompt<string>()
|
||||||
|
.Title("Menu")
|
||||||
|
.PageSize(10)
|
||||||
|
.MoreChoicesText("Up/Down")
|
||||||
|
.AddChoices(new[]
|
||||||
|
{
|
||||||
|
"CustomRequest",
|
||||||
|
"Log",
|
||||||
|
"Exit"
|
||||||
|
}));
|
||||||
|
|
||||||
|
switch (menuSelect)
|
||||||
|
{
|
||||||
|
case "CustomRequest":
|
||||||
|
HttpMethod requestMethod = AnsiConsole.Prompt(
|
||||||
|
new SelectionPrompt<HttpMethod>()
|
||||||
|
.Title("Request Type")
|
||||||
|
.AddChoices(new[]
|
||||||
|
{
|
||||||
|
HttpMethod.Get,
|
||||||
|
HttpMethod.Delete,
|
||||||
|
HttpMethod.Post
|
||||||
|
}));
|
||||||
|
string requestPath = AnsiConsole.Prompt(
|
||||||
|
new TextPrompt<string>("Request Path:"));
|
||||||
|
List<ValueTuple<string, string>> parameters = new();
|
||||||
|
while (AnsiConsole.Confirm("Add Parameter?"))
|
||||||
|
{
|
||||||
|
string name = AnsiConsole.Ask<string>("Parameter Name:");
|
||||||
|
string value = AnsiConsole.Ask<string>("Parameter Value:");
|
||||||
|
parameters.Add(new ValueTuple<string, string>(name, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
string requestString = $"http://localhost:{trangaSettings.apiPortNumber}/{requestPath}";
|
||||||
|
if (parameters.Any())
|
||||||
|
{
|
||||||
|
requestString += "?";
|
||||||
|
foreach (ValueTuple<string, string> parameter in parameters)
|
||||||
|
requestString += $"{parameter.Item1}={parameter.Item2}&";
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpRequestMessage request = new (requestMethod, requestString);
|
||||||
|
AnsiConsole.WriteLine($"Request: {request.Method} {request.RequestUri}");
|
||||||
|
HttpResponseMessage response;
|
||||||
|
if (AnsiConsole.Confirm("Send Request?"))
|
||||||
|
response = client.Send(request);
|
||||||
|
else break;
|
||||||
|
AnsiConsole.WriteLine($"Response: {(int)response.StatusCode} {response.StatusCode}");
|
||||||
|
AnsiConsole.WriteLine(response.Content.ReadAsStringAsync().Result);
|
||||||
|
break;
|
||||||
|
case "Log":
|
||||||
|
List<string> lines = logger.Tail(10).ToList();
|
||||||
|
Rows rows = new Rows(lines.Select(line => new Text(line)));
|
||||||
|
|
||||||
|
AnsiConsole.Live(rows).Start(context =>
|
||||||
|
{
|
||||||
|
bool running = true;
|
||||||
|
while (running)
|
||||||
|
{
|
||||||
|
string[] newLines = logger.GetNewLines();
|
||||||
|
if (newLines.Length > 0)
|
||||||
|
{
|
||||||
|
lines.AddRange(newLines);
|
||||||
|
rows = new Rows(lines.Select(line => new Text(line)));
|
||||||
|
context.UpdateTarget(rows);
|
||||||
|
}
|
||||||
|
Thread.Sleep(100);
|
||||||
|
if (AnsiConsole.Console.Input.IsKeyAvailable())
|
||||||
|
{
|
||||||
|
AnsiConsole.Console.Input.ReadKey(true); //Do not process input
|
||||||
|
running = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case "Exit":
|
||||||
|
exit = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (api is not null)
|
||||||
|
api.keepRunning = false;
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
16
Dockerfile
Normal file
16
Dockerfile
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
|
FROM mcr.microsoft.com/dotnet/sdk:7.0 as build-env
|
||||||
|
WORKDIR /src
|
||||||
|
COPY CLI /src/CLI
|
||||||
|
COPY Tranga /src/Tranga
|
||||||
|
COPY Logging /src/Logging
|
||||||
|
COPY Tranga.sln /src
|
||||||
|
RUN dotnet restore /src/Tranga/Tranga.csproj
|
||||||
|
RUN dotnet publish -c Release -o /publish
|
||||||
|
|
||||||
|
FROM glax/tranga-base:latest as runtime
|
||||||
|
WORKDIR /publish
|
||||||
|
COPY --from=build-env /publish .
|
||||||
|
EXPOSE 6531
|
||||||
|
ENTRYPOINT ["dotnet", "/publish/Tranga.dll", "-c"]
|
8
Dockerfile-base
Normal file
8
Dockerfile-base
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
#FROM mcr.microsoft.com/dotnet/aspnet:7.0 as runtime
|
||||||
|
FROM mcr.microsoft.com/dotnet/runtime:7.0 as runtime
|
||||||
|
WORKDIR /publish
|
||||||
|
RUN apt-get update
|
||||||
|
RUN apt-get install -y libx11-6 libx11-xcb1 libatk1.0-0 libgtk-3-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2 libxshmfence1 libnss3
|
||||||
|
RUN apt-get autopurge -y
|
||||||
|
RUN apt-get autoclean -y
|
@ -1,26 +1,32 @@
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Json.Serialization;
|
|
||||||
|
|
||||||
namespace Logging;
|
namespace Logging;
|
||||||
|
|
||||||
public class FileLogger : LoggerBase
|
public class FileLogger : LoggerBase
|
||||||
{
|
{
|
||||||
private string logFilePath { get; }
|
internal 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;
|
this.logFilePath = logFilePath;
|
||||||
|
|
||||||
|
DirectoryInfo dir = Directory.CreateDirectory(new FileInfo(logFilePath).DirectoryName!);
|
||||||
|
|
||||||
|
//Remove oldest logfile if more than MaxNumberOfLogFiles
|
||||||
|
for (int fileCount = dir.EnumerateFiles().Count(); fileCount > MaxNumberOfLogFiles - 1; fileCount--) //-1 because we create own logfile later
|
||||||
|
File.Delete(dir.EnumerateFiles().MinBy(file => file.LastWriteTime)!.FullName);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void Write(LogMessage logMessage)
|
protected override void Write(LogMessage logMessage)
|
||||||
{
|
{
|
||||||
try
|
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 class FormattedConsoleLogger : LoggerBase
|
||||||
{
|
{
|
||||||
|
private readonly TextWriter _stdOut;
|
||||||
public FormattedConsoleLogger(TextWriter? stdOut, Encoding? encoding = null) : base(stdOut, encoding)
|
public FormattedConsoleLogger(TextWriter stdOut, Encoding? encoding = null) : base(encoding)
|
||||||
{
|
{
|
||||||
|
this._stdOut = stdOut;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void Write(LogMessage message)
|
protected override void Write(LogMessage message)
|
||||||
{
|
{
|
||||||
//Nothing to do yet
|
this._stdOut.Write(message.formattedMessage);
|
||||||
}
|
}
|
||||||
}
|
}
|
23
Logging/LogMessage.cs
Normal file
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,10 +1,14 @@
|
|||||||
using System.Net.Mime;
|
using System.Runtime.InteropServices;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
namespace Logging;
|
namespace Logging;
|
||||||
|
|
||||||
public class Logger : TextWriter
|
public class Logger : TextWriter
|
||||||
{
|
{
|
||||||
|
private static readonly string LogDirectoryPath = RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
|
||||||
|
? "/var/log/tranga-api"
|
||||||
|
: Path.Join(Directory.GetCurrentDirectory(), "logs");
|
||||||
|
public string? logFilePath => _fileLogger?.logFilePath;
|
||||||
public override Encoding Encoding { get; }
|
public override Encoding Encoding { get; }
|
||||||
public enum LoggerType
|
public enum LoggerType
|
||||||
{
|
{
|
||||||
@ -12,24 +16,33 @@ public class Logger : TextWriter
|
|||||||
ConsoleLogger
|
ConsoleLogger
|
||||||
}
|
}
|
||||||
|
|
||||||
private FileLogger? _fileLogger;
|
private readonly FileLogger? _fileLogger;
|
||||||
private FormattedConsoleLogger? _formattedConsoleLogger;
|
private readonly FormattedConsoleLogger? _formattedConsoleLogger;
|
||||||
private MemoryLogger _memoryLogger;
|
private readonly MemoryLogger _memoryLogger;
|
||||||
private TextWriter? stdOut;
|
|
||||||
|
|
||||||
public Logger(LoggerType[] enabledLoggers, TextWriter? stdOut, Encoding? encoding, string? logFilePath)
|
public Logger(LoggerType[] enabledLoggers, TextWriter? stdOut, Encoding? encoding, string? logFilePath)
|
||||||
{
|
{
|
||||||
this.Encoding = encoding ?? Encoding.ASCII;
|
this.Encoding = encoding ?? Encoding.UTF8;
|
||||||
this.stdOut = stdOut ?? null;
|
if(enabledLoggers.Contains(LoggerType.FileLogger) && (logFilePath is null || logFilePath == ""))
|
||||||
if (enabledLoggers.Contains(LoggerType.FileLogger) && logFilePath is not null)
|
|
||||||
_fileLogger = new FileLogger(logFilePath, null, encoding);
|
|
||||||
else
|
|
||||||
{
|
{
|
||||||
_fileLogger = null;
|
DateTime now = DateTime.Now;
|
||||||
throw new ArgumentException($"logFilePath can not be null for LoggerType {LoggerType.FileLogger}");
|
logFilePath = Path.Join(LogDirectoryPath,
|
||||||
|
$"{now.ToShortDateString()}_{now.Hour}-{now.Minute}-{now.Second}.log");
|
||||||
|
_fileLogger = new FileLogger(logFilePath, encoding);
|
||||||
|
}else if (enabledLoggers.Contains(LoggerType.FileLogger) && logFilePath is not null)
|
||||||
|
_fileLogger = new FileLogger(logFilePath, encoding);
|
||||||
|
|
||||||
|
|
||||||
|
if (enabledLoggers.Contains(LoggerType.ConsoleLogger) && stdOut is not null)
|
||||||
|
{
|
||||||
|
_formattedConsoleLogger = new FormattedConsoleLogger(stdOut, encoding);
|
||||||
}
|
}
|
||||||
_formattedConsoleLogger = enabledLoggers.Contains(LoggerType.ConsoleLogger) ? new FormattedConsoleLogger(null, encoding) : null;
|
else if (enabledLoggers.Contains(LoggerType.ConsoleLogger) && stdOut is null)
|
||||||
_memoryLogger = new MemoryLogger(null, encoding);
|
{
|
||||||
|
_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)
|
public void WriteLine(string caller, string? value)
|
||||||
@ -46,13 +59,21 @@ public class Logger : TextWriter
|
|||||||
|
|
||||||
_fileLogger?.Write(caller, value);
|
_fileLogger?.Write(caller, value);
|
||||||
_formattedConsoleLogger?.Write(caller, value);
|
_formattedConsoleLogger?.Write(caller, value);
|
||||||
|
|
||||||
_memoryLogger.Write(caller, value);
|
_memoryLogger.Write(caller, value);
|
||||||
stdOut?.Write(value);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public string[] Tail(uint? lines)
|
public string[] Tail(uint? lines)
|
||||||
{
|
{
|
||||||
return _memoryLogger.Tail(lines);
|
return _memoryLogger.Tail(lines);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public string[] GetNewLines()
|
||||||
|
{
|
||||||
|
return _memoryLogger.GetNewLines();
|
||||||
|
}
|
||||||
|
|
||||||
|
public string[] GetLog()
|
||||||
|
{
|
||||||
|
return _memoryLogger.GetLogMessages();
|
||||||
|
}
|
||||||
}
|
}
|
@ -5,21 +5,10 @@ namespace Logging;
|
|||||||
public abstract class LoggerBase : TextWriter
|
public abstract class LoggerBase : TextWriter
|
||||||
{
|
{
|
||||||
public override Encoding Encoding { get; }
|
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.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)
|
public void Write(string caller, string? value)
|
||||||
@ -27,32 +16,10 @@ public abstract class LoggerBase : TextWriter
|
|||||||
if (value is null)
|
if (value is null)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
LogMessage message = new LogMessage(DateTime.Now, caller, value);
|
LogMessage message = new (DateTime.Now, caller, value);
|
||||||
|
|
||||||
stdOut?.Write(message.ToString());
|
|
||||||
|
|
||||||
Write(message);
|
Write(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected abstract void Write(LogMessage 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,30} | {value}";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
@ -4,36 +4,79 @@ namespace Logging;
|
|||||||
|
|
||||||
public class MemoryLogger : LoggerBase
|
public class MemoryLogger : LoggerBase
|
||||||
{
|
{
|
||||||
private SortedList<DateTime, LogMessage> logMessages = new();
|
private readonly SortedList<DateTime, LogMessage> _logMessages = new();
|
||||||
|
private int _lastLogMessageIndex = 0;
|
||||||
|
private bool _lockLogMessages = false;
|
||||||
|
|
||||||
public MemoryLogger(TextWriter? stdOut, Encoding? encoding = null) : base(stdOut, encoding)
|
public MemoryLogger(Encoding? encoding = null) : base(encoding)
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void Write(LogMessage value)
|
protected override void Write(LogMessage value)
|
||||||
{
|
{
|
||||||
logMessages.Add(value.logTime, value);
|
if (!_lockLogMessages)
|
||||||
|
{
|
||||||
|
_lockLogMessages = true;
|
||||||
|
while(!_logMessages.TryAdd(DateTime.Now, value))
|
||||||
|
Thread.Sleep(10);
|
||||||
|
_lockLogMessages = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public string[] GetLogMessage()
|
public string[] GetLogMessages()
|
||||||
{
|
{
|
||||||
return Tail(Convert.ToUInt32(logMessages.Count));
|
return Tail(Convert.ToUInt32(_logMessages.Count));
|
||||||
}
|
}
|
||||||
|
|
||||||
public string[] Tail(uint? length)
|
public string[] Tail(uint? length)
|
||||||
{
|
{
|
||||||
int retLength;
|
int retLength;
|
||||||
if (length is null || length > logMessages.Count)
|
if (length is null || length > _logMessages.Count)
|
||||||
retLength = logMessages.Count;
|
retLength = _logMessages.Count;
|
||||||
else
|
else
|
||||||
retLength = (int)length;
|
retLength = (int)length;
|
||||||
|
|
||||||
string[] ret = new string[retLength];
|
string[] ret = new string[retLength];
|
||||||
|
|
||||||
for (int logMessageIndex = logMessages.Count - retLength; logMessageIndex < logMessages.Count; logMessageIndex++)
|
for (int retIndex = 0; retIndex < ret.Length; retIndex++)
|
||||||
ret[logMessageIndex + retLength - logMessages.Count] = logMessages.GetValueAtIndex(logMessageIndex).ToString();
|
{
|
||||||
|
if (!_lockLogMessages)
|
||||||
|
{
|
||||||
|
_lockLogMessages = true;
|
||||||
|
ret[retIndex] = _logMessages.GetValueAtIndex(_logMessages.Count - retLength + retIndex).ToString();
|
||||||
|
_lockLogMessages = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_lastLogMessageIndex = _logMessages.Count - 1;
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public string[] GetNewLines()
|
||||||
|
{
|
||||||
|
int logMessageCount = _logMessages.Count;
|
||||||
|
List<string> ret = new();
|
||||||
|
|
||||||
|
int retIndex = 0;
|
||||||
|
for (; retIndex < logMessageCount - _lastLogMessageIndex; retIndex++)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!_lockLogMessages)
|
||||||
|
{
|
||||||
|
_lockLogMessages = true;
|
||||||
|
ret.Add(_logMessages.GetValueAtIndex(_lastLogMessageIndex + retIndex).ToString());
|
||||||
|
_lockLogMessages = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (NullReferenceException e)//Called when LogMessage has not finished writing
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_lastLogMessageIndex = _lastLogMessageIndex + retIndex;
|
||||||
|
return ret.ToArray();
|
||||||
|
}
|
||||||
}
|
}
|
68
README.md
68
README.md
@ -16,6 +16,9 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
Automatic Manga and Metadata downloader
|
Automatic Manga and Metadata downloader
|
||||||
</p>
|
</p>
|
||||||
|
<p align="center">
|
||||||
|
This is the API for <a href="https://github.com/C9Glax/tranga-website">Tranga-Website</a>
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
@ -33,6 +36,7 @@
|
|||||||
<li>
|
<li>
|
||||||
<a href="#getting-started">Getting Started</a>
|
<a href="#getting-started">Getting Started</a>
|
||||||
<ul>
|
<ul>
|
||||||
|
<li><a href="#prerequisites">Usage</a></li>
|
||||||
<li><a href="#prerequisites">Prerequisites</a></li>
|
<li><a href="#prerequisites">Prerequisites</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
@ -48,11 +52,31 @@
|
|||||||
<!-- ABOUT THE PROJECT -->
|
<!-- ABOUT THE PROJECT -->
|
||||||
## 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/)
|
- [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 trigger an scan with [Komga](https://komga.org/) and [Kavita](https://www.kavitareader.com/).
|
||||||
|
Notifications will can sent to your devices using [Gotify](https://gotify.net/) and [LunaSea](https://www.lunasea.app/).
|
||||||
|
|
||||||
|
### What this does and doesn't do
|
||||||
|
|
||||||
|
Tranga (this git-repo) will open a port (standard 6531) and listen for requests to add Jobs to Monitor and/or download specific Manga.
|
||||||
|
The configuration is all done through HTTP-Requests.
|
||||||
|
The frontend in this repo is **CLI**-based.
|
||||||
|
_**For a web-frontend use [tranga-website](https://github.com/C9Glax/tranga-website).**_
|
||||||
|
|
||||||
|
This project downloads the images for a Manga from the specified Scanlation-Website and packages them with some metadata - from that same website - in a .cbz-archive (per chapter).
|
||||||
|
It does this on an interval, and checks for any Chapters (.cbz-Archive) not already existing in your specified Download-Location. (If you rename or move files, it will download those again)
|
||||||
|
Tranga can (if configured) trigger a scan in Komga or Kavita, however the directory in which the Manga reside has to be available to both Tranga and Komga/Kavita.
|
||||||
|
|
||||||
|
The project doesn't manage metadata, doesn't curate, change or enhance any information that isn't available on the selected Scanlation-Site.
|
||||||
|
It will blindly use whatever is scrapes (yes this is a glorified Web-scraper).
|
||||||
|
|
||||||
and automatically start updates in [Komga](https://komga.org/) to import them.
|
|
||||||
|
|
||||||
### Inspiration:
|
### Inspiration:
|
||||||
|
|
||||||
@ -64,38 +88,52 @@ That is why I wanted to create my own project, in a language I understand, and t
|
|||||||
|
|
||||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### Built With
|
### Built With
|
||||||
|
|
||||||
- .NET-Core
|
- .NET-Core
|
||||||
- Newtonsoft.JSON
|
- Newtonsoft.JSON
|
||||||
- Love <3
|
- [PuppeteerSharp](https://www.puppeteersharp.com/) for Mangasee
|
||||||
|
- [Html Agility Pack (HAP)](https://html-agility-pack.net/)
|
||||||
|
- 💙 Blåhaj 🦈
|
||||||
|
|
||||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<!-- GETTING STARTED -->
|
<!-- GETTING STARTED -->
|
||||||
## Getting Started
|
## Getting Started
|
||||||
|
|
||||||
To use head over to [releases](https://git.bernloehr.eu/glax/Tranga/releases) and download a release.
|
There is two release types:
|
||||||
|
|
||||||
A CLI will guide you through setup.
|
- CLI
|
||||||
|
- Docker
|
||||||
|
|
||||||
|
### CLI
|
||||||
|
|
||||||
|
Head over to [releases](https://git.bernloehr.eu/glax/Tranga/releases) and download.
|
||||||
|
|
||||||
|
|
||||||
|
~~The CLI will guide you through setup.~~ Not in the current version.
|
||||||
|
Right now it is barebones with options to view logs and make HTTP-Requests
|
||||||
|
|
||||||
|
### Docker
|
||||||
|
|
||||||
|
Download [docker-compose.yaml](https://git.bernloehr.eu/glax/Tranga/src/branch/master/docker-compose.yaml) and configure to your needs.
|
||||||
|
Mount `/Manga` to wherever you want your chapters (`.cbz`-Archives) downloaded (for exampled where Komga/Kavita can access them).
|
||||||
|
The `docker-compose` also includes [tranga-website](https://github.com/C9Glax/tranga-website) as frontend. For its configuration refer to the repo README.
|
||||||
|
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
|
|
||||||
[.NET-Core 7.0](https://dotnet.microsoft.com/en-us/download/dotnet/7.0)
|
#### 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 -->
|
||||||
## Roadmap
|
## Roadmap
|
||||||
|
|
||||||
- [ ] Web-UI #1
|
- [ ] Docker ARM support
|
||||||
- [ ] More Connectors
|
- [ ] ❓
|
||||||
- [ ] Manganato #2
|
|
||||||
- [ ] ?
|
|
||||||
|
|
||||||
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>
|
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||||
|
|
||||||
|
@ -1,20 +0,0 @@
|
|||||||
FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
|
|
||||||
WORKDIR /app
|
|
||||||
EXPOSE 80
|
|
||||||
EXPOSE 443
|
|
||||||
|
|
||||||
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
|
|
||||||
WORKDIR /src
|
|
||||||
COPY ["Tranga-API/Tranga-API.csproj", "Tranga-API/"]
|
|
||||||
RUN dotnet restore "Tranga-API/Tranga-API.csproj"
|
|
||||||
COPY . .
|
|
||||||
WORKDIR "/src/Tranga-API"
|
|
||||||
RUN dotnet build "Tranga-API.csproj" -c Release -o /app/build
|
|
||||||
|
|
||||||
FROM build AS publish
|
|
||||||
RUN dotnet publish "Tranga-API.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
|
||||||
|
|
||||||
FROM base AS final
|
|
||||||
WORKDIR /app
|
|
||||||
COPY --from=publish /app/publish .
|
|
||||||
ENTRYPOINT ["dotnet", "Tranga-API.dll"]
|
|
@ -1,81 +0,0 @@
|
|||||||
using System.Text.Json;
|
|
||||||
using Tranga;
|
|
||||||
|
|
||||||
TaskManager taskManager = new (Directory.GetCurrentDirectory());
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
|
||||||
var app = builder.Build();
|
|
||||||
|
|
||||||
app.MapGet("/GetConnectors", () => JsonSerializer.Serialize(taskManager.GetAvailableConnectors().Values.ToArray()));
|
|
||||||
|
|
||||||
app.MapGet("/GetPublications", (string connectorName, string? publicationName) =>
|
|
||||||
{
|
|
||||||
Connector connector = taskManager.GetConnector(connectorName);
|
|
||||||
|
|
||||||
Publication[] publications;
|
|
||||||
if (publicationName is not null)
|
|
||||||
publications = connector.GetPublications(publicationName);
|
|
||||||
else
|
|
||||||
publications = connector.GetPublications();
|
|
||||||
|
|
||||||
return JsonSerializer.Serialize(publications);
|
|
||||||
});
|
|
||||||
|
|
||||||
app.MapGet("/ListTasks", () => JsonSerializer.Serialize(taskManager.GetAllTasks()));
|
|
||||||
|
|
||||||
app.MapGet("/CreateTask",
|
|
||||||
(TrangaTask.Task task, string? connectorName, string? publicationName, TimeSpan reoccurrence, string? language) =>
|
|
||||||
{
|
|
||||||
switch (task)
|
|
||||||
{
|
|
||||||
case TrangaTask.Task.UpdateKomgaLibrary:
|
|
||||||
taskManager.AddTask(TrangaTask.Task.UpdateKomgaLibrary, null, null, reoccurrence);
|
|
||||||
break;
|
|
||||||
case TrangaTask.Task.DownloadNewChapters:
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Connector connector = taskManager.GetConnector(connectorName);
|
|
||||||
|
|
||||||
Publication[] publications;
|
|
||||||
if (publicationName is not null)
|
|
||||||
publications = connector.GetPublications(publicationName);
|
|
||||||
else
|
|
||||||
publications = connector.GetPublications();
|
|
||||||
|
|
||||||
Publication? publication = publications.FirstOrDefault(pub => pub.downloadUrl == publicationName);
|
|
||||||
if (publication is null)
|
|
||||||
JsonSerializer.Serialize($"Publication {publicationName} is unknown.");
|
|
||||||
taskManager.AddTask(TrangaTask.Task.DownloadNewChapters, connectorName, publication, reoccurrence, language ?? "");
|
|
||||||
return JsonSerializer.Serialize("Success");
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
return JsonSerializer.Serialize(e.Message);
|
|
||||||
}
|
|
||||||
|
|
||||||
default: return JsonSerializer.Serialize("Not Implemented");
|
|
||||||
}
|
|
||||||
|
|
||||||
return JsonSerializer.Serialize("Not Implemented");
|
|
||||||
});
|
|
||||||
|
|
||||||
app.MapGet("/RemoveTask", (TrangaTask.Task task, string? connectorName, string? publicationName) =>
|
|
||||||
{
|
|
||||||
switch (task)
|
|
||||||
{
|
|
||||||
case TrangaTask.Task.UpdateKomgaLibrary:
|
|
||||||
taskManager.RemoveTask(TrangaTask.Task.UpdateKomgaLibrary, null, null);
|
|
||||||
return JsonSerializer.Serialize("Success");
|
|
||||||
case TrangaTask.Task.DownloadNewChapters:
|
|
||||||
Publication? publication = taskManager.GetAllPublications().FirstOrDefault(pub => pub.downloadUrl == publicationName);
|
|
||||||
if (publication is null)
|
|
||||||
JsonSerializer.Serialize($"Publication {publicationName} is unknown.");
|
|
||||||
|
|
||||||
taskManager.RemoveTask(TrangaTask.Task.DownloadNewChapters, connectorName, publication);
|
|
||||||
|
|
||||||
return JsonSerializer.Serialize("Success");
|
|
||||||
|
|
||||||
default: return JsonSerializer.Serialize("Not Implemented");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.Run();
|
|
@ -1,37 +0,0 @@
|
|||||||
{
|
|
||||||
"iisSettings": {
|
|
||||||
"windowsAuthentication": false,
|
|
||||||
"anonymousAuthentication": true,
|
|
||||||
"iisExpress": {
|
|
||||||
"applicationUrl": "http://localhost:14826",
|
|
||||||
"sslPort": 44333
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"profiles": {
|
|
||||||
"http": {
|
|
||||||
"commandName": "Project",
|
|
||||||
"dotnetRunMessages": true,
|
|
||||||
"launchBrowser": true,
|
|
||||||
"applicationUrl": "http://localhost:5119",
|
|
||||||
"environmentVariables": {
|
|
||||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"https": {
|
|
||||||
"commandName": "Project",
|
|
||||||
"dotnetRunMessages": true,
|
|
||||||
"launchBrowser": true,
|
|
||||||
"applicationUrl": "https://localhost:7070;http://localhost:5119",
|
|
||||||
"environmentVariables": {
|
|
||||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"IIS Express": {
|
|
||||||
"commandName": "IISExpress",
|
|
||||||
"launchBrowser": true,
|
|
||||||
"environmentVariables": {
|
|
||||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,21 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>net7.0</TargetFramework>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<RootNamespace>Tranga_API</RootNamespace>
|
|
||||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<Content Include="..\.dockerignore">
|
|
||||||
<Link>.dockerignore</Link>
|
|
||||||
</Content>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\Tranga\Tranga.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
@ -1,8 +0,0 @@
|
|||||||
{
|
|
||||||
"Logging": {
|
|
||||||
"LogLevel": {
|
|
||||||
"Default": "Information",
|
|
||||||
"Microsoft.AspNetCore": "Warning"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,9 +0,0 @@
|
|||||||
{
|
|
||||||
"Logging": {
|
|
||||||
"LogLevel": {
|
|
||||||
"Default": "Information",
|
|
||||||
"Microsoft.AspNetCore": "Warning"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"AllowedHosts": "*"
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
[{"reoccurrence":"00:00:00","lastExecuted":"2023-05-19T17:34:40.5349215+02:00","connectorName":"MangaDex","task":0,"publication":{"sortName":null,"description":null,"tags":null,"posterUrl":null,"year":null,"originalLanguage":null,"status":null,"folderName":null,"downloadUrl":null},"language":"en"}]
|
|
@ -1,18 +0,0 @@
|
|||||||
FROM mcr.microsoft.com/dotnet/runtime:7.0 AS base
|
|
||||||
WORKDIR /app
|
|
||||||
|
|
||||||
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
|
|
||||||
WORKDIR /src
|
|
||||||
COPY ["Tranga-CLI/Tranga-CLI.csproj", "Tranga-CLI/"]
|
|
||||||
RUN dotnet restore "Tranga-CLI/Tranga-CLI.csproj"
|
|
||||||
COPY . .
|
|
||||||
WORKDIR "/src/Tranga-CLI"
|
|
||||||
RUN dotnet build "Tranga-CLI.csproj" -c Release -o /app/build
|
|
||||||
|
|
||||||
FROM build AS publish
|
|
||||||
RUN dotnet publish "Tranga-CLI.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
|
||||||
|
|
||||||
FROM base AS final
|
|
||||||
WORKDIR /app
|
|
||||||
COPY --from=publish /app/publish .
|
|
||||||
ENTRYPOINT ["dotnet", "Tranga-CLI.dll"]
|
|
@ -1,471 +0,0 @@
|
|||||||
using System.Globalization;
|
|
||||||
using Logging;
|
|
||||||
using Tranga;
|
|
||||||
|
|
||||||
namespace Tranga_CLI;
|
|
||||||
|
|
||||||
/*
|
|
||||||
* This is written with pure hatred for readability.
|
|
||||||
* At some point do this properly.
|
|
||||||
* Read at own risk.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public static class Tranga_Cli
|
|
||||||
{
|
|
||||||
public static void Main(string[] args)
|
|
||||||
{
|
|
||||||
Logger logger = new(new[] { Logger.LoggerType.FileLogger }, null, null,
|
|
||||||
Path.Join(Directory.GetCurrentDirectory(), $"log-{DateTime.Now:dd-M-yyyy-HH-mm-ss}.txt"));
|
|
||||||
|
|
||||||
logger.WriteLine("Tranga_CLI", "Loading Settings.");
|
|
||||||
TaskManager.SettingsData settings;
|
|
||||||
string settingsPath = Path.Join(Directory.GetCurrentDirectory(), "data.json");
|
|
||||||
if (File.Exists(settingsPath))
|
|
||||||
settings = TaskManager.LoadData(Directory.GetCurrentDirectory());
|
|
||||||
else
|
|
||||||
settings = new TaskManager.SettingsData(Directory.GetCurrentDirectory(), null, new HashSet<TrangaTask>());
|
|
||||||
|
|
||||||
|
|
||||||
logger.WriteLine("Tranga_CLI", "User Input");
|
|
||||||
Console.WriteLine($"Output folder path [{settings.downloadLocation}]:");
|
|
||||||
string? tmpPath = Console.ReadLine();
|
|
||||||
while(tmpPath is null)
|
|
||||||
tmpPath = Console.ReadLine();
|
|
||||||
if(tmpPath.Length > 0)
|
|
||||||
settings.downloadLocation = tmpPath;
|
|
||||||
|
|
||||||
Console.WriteLine($"Komga BaseURL [{settings.komga?.baseUrl}]:");
|
|
||||||
string? tmpUrl = Console.ReadLine();
|
|
||||||
while (tmpUrl is null)
|
|
||||||
tmpUrl = Console.ReadLine();
|
|
||||||
if (tmpUrl.Length > 0)
|
|
||||||
{
|
|
||||||
Console.WriteLine("Username:");
|
|
||||||
string? tmpUser = Console.ReadLine();
|
|
||||||
while (tmpUser is null || tmpUser.Length < 1)
|
|
||||||
tmpUser = Console.ReadLine();
|
|
||||||
|
|
||||||
Console.WriteLine("Password:");
|
|
||||||
string tmpPass = string.Empty;
|
|
||||||
ConsoleKey key;
|
|
||||||
do
|
|
||||||
{
|
|
||||||
var keyInfo = Console.ReadKey(intercept: true);
|
|
||||||
key = keyInfo.Key;
|
|
||||||
|
|
||||||
if (key == ConsoleKey.Backspace && tmpPass.Length > 0)
|
|
||||||
{
|
|
||||||
Console.Write("\b \b");
|
|
||||||
tmpPass = tmpPass[0..^1];
|
|
||||||
}
|
|
||||||
else if (!char.IsControl(keyInfo.KeyChar))
|
|
||||||
{
|
|
||||||
Console.Write("*");
|
|
||||||
tmpPass += keyInfo.KeyChar;
|
|
||||||
}
|
|
||||||
} while (key != ConsoleKey.Enter);
|
|
||||||
|
|
||||||
settings.komga = new Komga(tmpUrl, tmpUser, tmpPass, logger);
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.WriteLine("Tranga_CLI", "Loaded.");
|
|
||||||
TaskMode(settings, logger);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void TaskMode(TaskManager.SettingsData settings, Logger logger)
|
|
||||||
{
|
|
||||||
TaskManager taskManager = new (settings, logger);
|
|
||||||
ConsoleKey selection = PrintMenu(taskManager, settings.downloadLocation, logger);
|
|
||||||
while (selection != ConsoleKey.Q)
|
|
||||||
{
|
|
||||||
switch (selection)
|
|
||||||
{
|
|
||||||
case ConsoleKey.L:
|
|
||||||
PrintTasks(taskManager.GetAllTasks(), logger);
|
|
||||||
Console.WriteLine("Press any key.");
|
|
||||||
Console.ReadKey();
|
|
||||||
break;
|
|
||||||
case ConsoleKey.C:
|
|
||||||
CreateTask(taskManager, settings, logger);
|
|
||||||
Console.WriteLine("Press any key.");
|
|
||||||
Console.ReadKey();
|
|
||||||
break;
|
|
||||||
case ConsoleKey.D:
|
|
||||||
RemoveTask (taskManager, logger);
|
|
||||||
Console.WriteLine("Press any key.");
|
|
||||||
Console.ReadKey();
|
|
||||||
break;
|
|
||||||
case ConsoleKey.E:
|
|
||||||
ExecuteTaskNow(taskManager, logger);
|
|
||||||
Console.WriteLine("Press any key.");
|
|
||||||
Console.ReadKey();
|
|
||||||
break;
|
|
||||||
case ConsoleKey.S:
|
|
||||||
SearchTasks(taskManager, logger);
|
|
||||||
Console.WriteLine("Press any key.");
|
|
||||||
Console.ReadKey();
|
|
||||||
break;
|
|
||||||
case ConsoleKey.R:
|
|
||||||
PrintTasks(taskManager.GetAllTasks().Where(eTask => eTask.state == TrangaTask.ExecutionState.Running).ToArray(), logger);
|
|
||||||
Console.WriteLine("Press any key.");
|
|
||||||
Console.ReadKey();
|
|
||||||
break;
|
|
||||||
case ConsoleKey.K:
|
|
||||||
PrintTasks(taskManager.GetAllTasks().Where(qTask => qTask.state is TrangaTask.ExecutionState.Enqueued).ToArray(), logger);
|
|
||||||
Console.WriteLine("Press any key.");
|
|
||||||
Console.ReadKey();
|
|
||||||
break;
|
|
||||||
case ConsoleKey.F:
|
|
||||||
ShowLastLoglines(logger);
|
|
||||||
Console.WriteLine("Press any key.");
|
|
||||||
Console.ReadKey();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
selection = PrintMenu(taskManager, settings.downloadLocation, logger);
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.WriteLine("Tranga_CLI", "Exiting.");
|
|
||||||
if (taskManager.GetAllTasks().Any(task => task.state == TrangaTask.ExecutionState.Running))
|
|
||||||
{
|
|
||||||
Console.WriteLine("Force quit (Even with running tasks?) y/N");
|
|
||||||
selection = Console.ReadKey().Key;
|
|
||||||
while(selection != ConsoleKey.Y && selection != ConsoleKey.N)
|
|
||||||
selection = Console.ReadKey().Key;
|
|
||||||
taskManager.Shutdown(selection == ConsoleKey.Y);
|
|
||||||
}else
|
|
||||||
// ReSharper disable once RedundantArgumentDefaultValue Better readability
|
|
||||||
taskManager.Shutdown(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static ConsoleKey PrintMenu(TaskManager taskManager, string folderPath, Logger logger)
|
|
||||||
{
|
|
||||||
int taskCount = taskManager.GetAllTasks().Length;
|
|
||||||
int taskRunningCount = taskManager.GetAllTasks().Count(task => task.state == TrangaTask.ExecutionState.Running);
|
|
||||||
int taskEnqueuedCount =
|
|
||||||
taskManager.GetAllTasks().Count(task => task.state == TrangaTask.ExecutionState.Enqueued);
|
|
||||||
Console.Clear();
|
|
||||||
Console.WriteLine($"Download Folder: {folderPath}");
|
|
||||||
Console.WriteLine($"Tasks (Running/Queue/Total)): {taskRunningCount}/{taskEnqueuedCount}/{taskCount}");
|
|
||||||
Console.WriteLine();
|
|
||||||
Console.WriteLine($"{"C: Create Task",-30}{"L: List tasks",-30}");
|
|
||||||
Console.WriteLine($"{"D: Delete Task",-30}{"R: List Running Tasks", -30}");
|
|
||||||
Console.WriteLine($"{"E: Execute Task now",-30}{"S: Search Tasks", -30}");
|
|
||||||
Console.WriteLine($"{"",-30}{"K: List Task Queue", -30}");
|
|
||||||
//Console.WriteLine();
|
|
||||||
Console.WriteLine($"{"F: Show Log",-30}{"",-30}");
|
|
||||||
Console.WriteLine($"{"U: Update this Screen",-30}{"Q: Exit",-30}");
|
|
||||||
ConsoleKey selection = Console.ReadKey().Key;
|
|
||||||
logger.WriteLine("Tranga_CLI", $"Menu selection: {selection}");
|
|
||||||
return selection;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void PrintTasks(TrangaTask[] tasks, Logger logger)
|
|
||||||
{
|
|
||||||
logger.WriteLine("Tranga_CLI", "Printing Tasks");
|
|
||||||
int taskCount = tasks.Length;
|
|
||||||
int taskRunningCount = tasks.Count(task => task.state == TrangaTask.ExecutionState.Running);
|
|
||||||
int taskEnqueuedCount = tasks.Count(task => task.state == TrangaTask.ExecutionState.Enqueued);
|
|
||||||
Console.Clear();
|
|
||||||
int tIndex = 0;
|
|
||||||
Console.WriteLine($"Tasks (Running/Queue/Total): {taskRunningCount}/{taskEnqueuedCount}/{taskCount}");
|
|
||||||
string header =
|
|
||||||
$"{"",-5}{"Task",-20} | {"Last Executed",-20} | {"Reoccurrence",-12} | {"State",-10} | {"Connector",-15} | Publication/Manga";
|
|
||||||
Console.WriteLine(header);
|
|
||||||
Console.WriteLine(new string('-', header.Length));
|
|
||||||
foreach(TrangaTask trangaTask in tasks)
|
|
||||||
Console.WriteLine($"{tIndex++:000}: {trangaTask}");
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void ShowLastLoglines(Logger logger)
|
|
||||||
{
|
|
||||||
Console.Clear();
|
|
||||||
logger.WriteLine("Tranga_CLI", "Menu: Show Log-lines");
|
|
||||||
|
|
||||||
Console.WriteLine("Enter q to abort");
|
|
||||||
Console.WriteLine($"Number of lines:");
|
|
||||||
|
|
||||||
string? chosenNumber = Console.ReadLine();
|
|
||||||
while(chosenNumber is null || chosenNumber.Length < 1)
|
|
||||||
chosenNumber = Console.ReadLine();
|
|
||||||
|
|
||||||
if (chosenNumber.Length == 1 && chosenNumber.ToLower() == "q")
|
|
||||||
{
|
|
||||||
Console.Clear();
|
|
||||||
Console.WriteLine("aborted.");
|
|
||||||
logger.WriteLine("Tranga_CLI", "aborted");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
string[] lines = logger.Tail(Convert.ToUInt32(chosenNumber));
|
|
||||||
Console.Clear();
|
|
||||||
foreach (string message in lines)
|
|
||||||
Console.Write(message);
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Exception: {e.Message}");
|
|
||||||
logger.WriteLine("Tranga_CLI", e.Message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void CreateTask(TaskManager taskManager, TaskManager.SettingsData settings, Logger logger)
|
|
||||||
{
|
|
||||||
logger.WriteLine("Tranga_CLI", "Menu: Creating Task");
|
|
||||||
TrangaTask.Task? tmpTask = SelectTaskType(logger);
|
|
||||||
if (tmpTask is null)
|
|
||||||
return;
|
|
||||||
TrangaTask.Task task = (TrangaTask.Task)tmpTask!;
|
|
||||||
|
|
||||||
Connector? connector = null;
|
|
||||||
if (task != TrangaTask.Task.UpdateKomgaLibrary)
|
|
||||||
{
|
|
||||||
connector = SelectConnector(settings.downloadLocation, taskManager.GetAvailableConnectors().Values.ToArray(), logger);
|
|
||||||
if (connector is null)
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Publication? publication = null;
|
|
||||||
if (task != TrangaTask.Task.UpdatePublications && task != TrangaTask.Task.UpdateKomgaLibrary)
|
|
||||||
{
|
|
||||||
publication = SelectPublication(connector!, logger);
|
|
||||||
if (publication is null)
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
TimeSpan reoccurrence = SelectReoccurrence(logger);
|
|
||||||
logger.WriteLine("Tranga_CLI", "Sending Task to TaskManager");
|
|
||||||
TrangaTask newTask = taskManager.AddTask(task, connector?.name, publication, reoccurrence, "en");
|
|
||||||
Console.WriteLine(newTask);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void ExecuteTaskNow(TaskManager taskManager, Logger logger)
|
|
||||||
{
|
|
||||||
logger.WriteLine("Tranga_CLI", "Menu: Executing Task");
|
|
||||||
TrangaTask[] tasks = taskManager.GetAllTasks();
|
|
||||||
if (tasks.Length < 1)
|
|
||||||
{
|
|
||||||
Console.Clear();
|
|
||||||
Console.WriteLine("There are no available Tasks.");
|
|
||||||
logger.WriteLine("Tranga_CLI", "No available Tasks.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
PrintTasks(tasks, logger);
|
|
||||||
|
|
||||||
logger.WriteLine("Tranga_CLI", "Selecting Task to Execute");
|
|
||||||
Console.WriteLine("Enter q to abort");
|
|
||||||
Console.WriteLine($"Select Task (0-{tasks.Length - 1}):");
|
|
||||||
|
|
||||||
string? selectedTask = Console.ReadLine();
|
|
||||||
while(selectedTask is null || selectedTask.Length < 1)
|
|
||||||
selectedTask = Console.ReadLine();
|
|
||||||
|
|
||||||
if (selectedTask.Length == 1 && selectedTask.ToLower() == "q")
|
|
||||||
{
|
|
||||||
Console.Clear();
|
|
||||||
Console.WriteLine("aborted.");
|
|
||||||
logger.WriteLine("Tranga_CLI", "aborted");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
int selectedTaskIndex = Convert.ToInt32(selectedTask);
|
|
||||||
logger.WriteLine("Tranga_CLI", "Sending Task to TaskManager");
|
|
||||||
taskManager.ExecuteTaskNow(tasks[selectedTaskIndex]);
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Exception: {e.Message}");
|
|
||||||
logger.WriteLine("Tranga_CLI", e.Message);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void RemoveTask(TaskManager taskManager, Logger logger)
|
|
||||||
{
|
|
||||||
logger.WriteLine("Tranga_CLI", "Menu: Remove Task");
|
|
||||||
TrangaTask[] tasks = taskManager.GetAllTasks();
|
|
||||||
if (tasks.Length < 1)
|
|
||||||
{
|
|
||||||
Console.Clear();
|
|
||||||
Console.WriteLine("There are no available Tasks.");
|
|
||||||
logger.WriteLine("Tranga_CLI", "No available Tasks");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
PrintTasks(tasks, logger);
|
|
||||||
|
|
||||||
logger.WriteLine("Tranga_CLI", "Selecting Task");
|
|
||||||
Console.WriteLine("Enter q to abort");
|
|
||||||
Console.WriteLine($"Select Task (0-{tasks.Length - 1}):");
|
|
||||||
|
|
||||||
string? selectedTask = Console.ReadLine();
|
|
||||||
while(selectedTask is null || selectedTask.Length < 1)
|
|
||||||
selectedTask = Console.ReadLine();
|
|
||||||
|
|
||||||
if (selectedTask.Length == 1 && selectedTask.ToLower() == "q")
|
|
||||||
{
|
|
||||||
Console.Clear();
|
|
||||||
Console.WriteLine("aborted.");
|
|
||||||
logger.WriteLine("Tranga_CLI", "aborted.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
int selectedTaskIndex = Convert.ToInt32(selectedTask);
|
|
||||||
logger.WriteLine("Tranga_CLI", "Sending Task to TaskManager");
|
|
||||||
taskManager.RemoveTask(tasks[selectedTaskIndex].task, tasks[selectedTaskIndex].connectorName, tasks[selectedTaskIndex].publication);
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Exception: {e.Message}");
|
|
||||||
logger.WriteLine("Tranga_CLI", e.Message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static TrangaTask.Task? SelectTaskType(Logger logger)
|
|
||||||
{
|
|
||||||
logger.WriteLine("Tranga_CLI", "Menu: Select TaskType");
|
|
||||||
Console.Clear();
|
|
||||||
string[] taskNames = Enum.GetNames<TrangaTask.Task>();
|
|
||||||
|
|
||||||
int tIndex = 0;
|
|
||||||
Console.WriteLine("Available Tasks:");
|
|
||||||
foreach (string taskName in taskNames)
|
|
||||||
Console.WriteLine($"{tIndex++}: {taskName}");
|
|
||||||
|
|
||||||
Console.WriteLine("Enter q to abort");
|
|
||||||
Console.WriteLine($"Select Task (0-{taskNames.Length - 1}):");
|
|
||||||
|
|
||||||
string? selectedTask = Console.ReadLine();
|
|
||||||
while(selectedTask is null || selectedTask.Length < 1)
|
|
||||||
selectedTask = Console.ReadLine();
|
|
||||||
|
|
||||||
if (selectedTask.Length == 1 && selectedTask.ToLower() == "q")
|
|
||||||
{
|
|
||||||
Console.Clear();
|
|
||||||
Console.WriteLine("aborted.");
|
|
||||||
logger.WriteLine("Tranga_CLI", "aborted.");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
int selectedTaskIndex = Convert.ToInt32(selectedTask);
|
|
||||||
string selectedTaskName = taskNames[selectedTaskIndex];
|
|
||||||
return Enum.Parse<TrangaTask.Task>(selectedTaskName);
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Exception: {e.Message}");
|
|
||||||
logger.WriteLine("Tranga_CLI", e.Message);
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static TimeSpan SelectReoccurrence(Logger logger)
|
|
||||||
{
|
|
||||||
logger.WriteLine("Tranga_CLI", "Menu: Select Reoccurrence");
|
|
||||||
Console.WriteLine("Select reoccurrence Timer (Format hh:mm:ss):");
|
|
||||||
return TimeSpan.Parse(Console.ReadLine()!, new CultureInfo("en-US"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Connector? SelectConnector(string folderPath, Connector[] connectors, Logger logger)
|
|
||||||
{
|
|
||||||
logger.WriteLine("Tranga_CLI", "Menu: Select Connector");
|
|
||||||
Console.Clear();
|
|
||||||
|
|
||||||
int cIndex = 0;
|
|
||||||
Console.WriteLine("Connectors:");
|
|
||||||
foreach (Connector connector in connectors)
|
|
||||||
Console.WriteLine($"{cIndex++}: {connector.name}");
|
|
||||||
|
|
||||||
Console.WriteLine("Enter q to abort");
|
|
||||||
Console.WriteLine($"Select Connector (0-{connectors.Length - 1}):");
|
|
||||||
|
|
||||||
string? selectedConnector = Console.ReadLine();
|
|
||||||
while(selectedConnector is null || selectedConnector.Length < 1)
|
|
||||||
selectedConnector = Console.ReadLine();
|
|
||||||
|
|
||||||
if (selectedConnector.Length == 1 && selectedConnector.ToLower() == "q")
|
|
||||||
{
|
|
||||||
Console.Clear();
|
|
||||||
Console.WriteLine("aborted.");
|
|
||||||
logger.WriteLine("Tranga_CLI", "aborted.");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
int selectedConnectorIndex = Convert.ToInt32(selectedConnector);
|
|
||||||
return connectors[selectedConnectorIndex];
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Exception: {e.Message}");
|
|
||||||
logger.WriteLine("Tranga_CLI", e.Message);
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Publication? SelectPublication(Connector connector, Logger logger)
|
|
||||||
{
|
|
||||||
logger.WriteLine("Tranga_CLI", "Menu: Select Publication");
|
|
||||||
|
|
||||||
Console.Clear();
|
|
||||||
Console.WriteLine($"Connector: {connector.name}");
|
|
||||||
Console.WriteLine("Publication search query (leave empty for all):");
|
|
||||||
string? query = Console.ReadLine();
|
|
||||||
|
|
||||||
Publication[] publications = connector.GetPublications(query ?? "");
|
|
||||||
|
|
||||||
int pIndex = 0;
|
|
||||||
Console.WriteLine("Publications:");
|
|
||||||
foreach(Publication publication in publications)
|
|
||||||
Console.WriteLine($"{pIndex++}: {publication.sortName}");
|
|
||||||
|
|
||||||
Console.WriteLine("Enter q to abort");
|
|
||||||
Console.WriteLine($"Select publication to Download (0-{publications.Length - 1}):");
|
|
||||||
|
|
||||||
string? selectedPublication = Console.ReadLine();
|
|
||||||
while(selectedPublication is null || selectedPublication.Length < 1)
|
|
||||||
selectedPublication = Console.ReadLine();
|
|
||||||
|
|
||||||
if (selectedPublication.Length == 1 && selectedPublication.ToLower() == "q")
|
|
||||||
{
|
|
||||||
Console.Clear();
|
|
||||||
Console.WriteLine("aborted.");
|
|
||||||
logger.WriteLine("Tranga_CLI", "aborted.");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
int selectedPublicationIndex = Convert.ToInt32(selectedPublication);
|
|
||||||
return publications[selectedPublicationIndex];
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Exception: {e.Message}");
|
|
||||||
logger.WriteLine("Tranga_CLI", e.Message);
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void SearchTasks(TaskManager taskManager, Logger logger)
|
|
||||||
{
|
|
||||||
logger.WriteLine("Tranga_CLI", "Menu: Search task");
|
|
||||||
Console.Clear();
|
|
||||||
Console.WriteLine("Enter search query:");
|
|
||||||
string? query = Console.ReadLine();
|
|
||||||
while (query is null || query.Length < 4)
|
|
||||||
query = Console.ReadLine();
|
|
||||||
PrintTasks(taskManager.GetAllTasks().Where(qTask =>
|
|
||||||
qTask.ToString().ToLower().Contains(query, StringComparison.OrdinalIgnoreCase)).ToArray(), logger);
|
|
||||||
}
|
|
||||||
}
|
|
18
Tranga.sln
18
Tranga.sln
@ -2,12 +2,10 @@
|
|||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga", ".\Tranga\Tranga.csproj", "{545E81B9-D96B-4C8F-A97F-2C02414DE566}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga", ".\Tranga\Tranga.csproj", "{545E81B9-D96B-4C8F-A97F-2C02414DE566}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga-CLI", "Tranga-CLI\Tranga-CLI.csproj", "{4899E3B2-B259-479A-B43E-042D043E9501}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tranga-API", "Tranga-API\Tranga-API.csproj", "{6284C936-4E90-486B-BC46-0AFAD85AD8EE}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Logging", "Logging\Logging.csproj", "{415BE889-BB7D-426F-976F-8D977876A462}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Logging", "Logging\Logging.csproj", "{415BE889-BB7D-426F-976F-8D977876A462}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CLI", "CLI\CLI.csproj", "{4324C816-F9D2-468F-8ED6-397FE2F0DCB3}"
|
||||||
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@ -18,17 +16,13 @@ Global
|
|||||||
{545E81B9-D96B-4C8F-A97F-2C02414DE566}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{545E81B9-D96B-4C8F-A97F-2C02414DE566}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{545E81B9-D96B-4C8F-A97F-2C02414DE566}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{545E81B9-D96B-4C8F-A97F-2C02414DE566}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{545E81B9-D96B-4C8F-A97F-2C02414DE566}.Release|Any CPU.Build.0 = Release|Any CPU
|
{545E81B9-D96B-4C8F-A97F-2C02414DE566}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
{4899E3B2-B259-479A-B43E-042D043E9501}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{4899E3B2-B259-479A-B43E-042D043E9501}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{4899E3B2-B259-479A-B43E-042D043E9501}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{4899E3B2-B259-479A-B43E-042D043E9501}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{6284C936-4E90-486B-BC46-0AFAD85AD8EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{6284C936-4E90-486B-BC46-0AFAD85AD8EE}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{6284C936-4E90-486B-BC46-0AFAD85AD8EE}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{6284C936-4E90-486B-BC46-0AFAD85AD8EE}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{415BE889-BB7D-426F-976F-8D977876A462}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
{415BE889-BB7D-426F-976F-8D977876A462}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
{415BE889-BB7D-426F-976F-8D977876A462}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{415BE889-BB7D-426F-976F-8D977876A462}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{415BE889-BB7D-426F-976F-8D977876A462}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{415BE889-BB7D-426F-976F-8D977876A462}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{415BE889-BB7D-426F-976F-8D977876A462}.Release|Any CPU.Build.0 = Release|Any CPU
|
{415BE889-BB7D-426F-976F-8D977876A462}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{4324C816-F9D2-468F-8ED6-397FE2F0DCB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{4324C816-F9D2-468F-8ED6-397FE2F0DCB3}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{4324C816-F9D2-468F-8ED6-397FE2F0DCB3}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{4324C816-F9D2-468F-8ED6-397FE2F0DCB3}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
EndGlobal
|
EndGlobal
|
||||||
|
@ -1,3 +1,12 @@
|
|||||||
<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">
|
<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/=jjob/@EntryIndexedValue">True</s:Boolean>
|
||||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Komga/@EntryIndexedValue">True</s:Boolean>
|
<s:Boolean x:Key="/Default/UserDictionary/Words/=Komga/@EntryIndexedValue">True</s:Boolean>
|
||||||
|
<s:Boolean x:Key="/Default/UserDictionary/Words/=lunasea/@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>
|
||||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Tranga/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
|
<s:Boolean x:Key="/Default/UserDictionary/Words/=Tranga/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
|
@ -1,4 +1,5 @@
|
|||||||
using System.Globalization;
|
using System.Text.RegularExpressions;
|
||||||
|
using System.Xml.Linq;
|
||||||
|
|
||||||
namespace Tranga;
|
namespace Tranga;
|
||||||
|
|
||||||
@ -6,28 +7,88 @@ namespace Tranga;
|
|||||||
/// Has to be Part of a publication
|
/// 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.
|
/// Includes the Chapter-Name, -VolumeNumber, -ChapterNumber, the location of the chapter on the internet and the saveName of the local file.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public struct Chapter
|
public readonly struct Chapter
|
||||||
{
|
{
|
||||||
|
// ReSharper disable once MemberCanBePrivate.Global
|
||||||
|
public Manga parentManga { get; }
|
||||||
public string? name { get; }
|
public string? name { get; }
|
||||||
public string? volumeNumber { get; }
|
public string? volumeNumber { get; }
|
||||||
public string? chapterNumber { get; }
|
public string chapterNumber { get; }
|
||||||
public string url { get; }
|
public string url { get; }
|
||||||
|
// ReSharper disable once MemberCanBePrivate.Global
|
||||||
public string fileName { get; }
|
public string fileName { get; }
|
||||||
public string sortNumber { get; }
|
|
||||||
|
|
||||||
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(Manga parentManga, string? name, string? volumeNumber, string chapterNumber, string url)
|
||||||
{
|
{
|
||||||
|
this.parentManga = parentManga;
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.volumeNumber = volumeNumber is { Length: > 0 } ? volumeNumber : "1";
|
this.volumeNumber = volumeNumber;
|
||||||
this.chapterNumber = chapterNumber;
|
this.chapterNumber = chapterNumber;
|
||||||
this.url = url;
|
this.url = url;
|
||||||
string chapterName = string.Concat((name ?? "").Split(Path.GetInvalidFileNameChars()));
|
|
||||||
NumberFormatInfo nfi = new NumberFormatInfo()
|
string chapterName = string.Concat(LegalCharacters.Matches(name ?? ""));
|
||||||
|
string volStr = this.volumeNumber is not null ? $"Vol.{this.volumeNumber} " : "";
|
||||||
|
string chNumberStr = $"Ch.{chapterNumber} ";
|
||||||
|
string chNameStr = chapterName.Length > 0 ? $"- {chapterName}" : "";
|
||||||
|
chNameStr = IllegalStrings.Replace(chNameStr, "");
|
||||||
|
this.fileName = $"{volStr}{chNumberStr}{chNameStr}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString()
|
||||||
|
{
|
||||||
|
return $"Chapter {parentManga.sortName} {parentManga.internalId} {chapterNumber} {name}";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <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, parentManga.folderName)))
|
||||||
|
return false;
|
||||||
|
FileInfo[] archives = new DirectoryInfo(Path.Join(downloadLocation, parentManga.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)
|
||||||
{
|
{
|
||||||
NumberDecimalSeparator = "."
|
File.Move(path.FullName, newFilePath);
|
||||||
};
|
return true;
|
||||||
sortNumber = decimal.Round(Convert.ToDecimal(this.volumeNumber) * Convert.ToDecimal(this.chapterNumber, nfi), 1)
|
}
|
||||||
.ToString(nfi);
|
return false;
|
||||||
this.fileName = $"{chapterName} - V{volumeNumber}C{chapterNumber} - {sortNumber}";
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// Creates full file path of chapter-archive
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>Filepath</returns>
|
||||||
|
internal string GetArchiveFilePath(string downloadLocation)
|
||||||
|
{
|
||||||
|
return Path.Join(downloadLocation, parentManga.folderName, $"{parentManga.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(',', parentManga.tags)),
|
||||||
|
new XElement("LanguageISO", parentManga.originalLanguage),
|
||||||
|
new XElement("Title", this.name),
|
||||||
|
new XElement("Writer", string.Join(',', parentManga.authors)),
|
||||||
|
new XElement("Volume", this.volumeNumber),
|
||||||
|
new XElement("Number", this.chapterNumber)
|
||||||
|
);
|
||||||
|
return comicInfo.ToString();
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,212 +0,0 @@
|
|||||||
using System.IO.Compression;
|
|
||||||
using System.Net;
|
|
||||||
using System.Xml.Linq;
|
|
||||||
using Logging;
|
|
||||||
|
|
||||||
namespace Tranga;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Base-Class for all Connectors
|
|
||||||
/// Provides some methods to be used by all Connectors, as well as a DownloadClient
|
|
||||||
/// </summary>
|
|
||||||
public abstract class Connector
|
|
||||||
{
|
|
||||||
internal string downloadLocation { get; } //Location of local files
|
|
||||||
protected DownloadClient downloadClient { get; }
|
|
||||||
|
|
||||||
protected Logger? logger;
|
|
||||||
|
|
||||||
protected Connector(string downloadLocation, uint downloadDelay, Logger? logger)
|
|
||||||
{
|
|
||||||
this.downloadLocation = downloadLocation;
|
|
||||||
this.downloadClient = new DownloadClient(downloadDelay);
|
|
||||||
this.logger = logger;
|
|
||||||
}
|
|
||||||
|
|
||||||
public abstract string name { get; } //Name of the Connector (e.g. Website)
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns all Publications with the given string.
|
|
||||||
/// If the string is empty or null, returns all Publication of the Connector
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="publicationTitle">Search-Query</param>
|
|
||||||
/// <returns>Publications matching the query</returns>
|
|
||||||
public abstract Publication[] GetPublications(string publicationTitle = "");
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns all Chapters of the publication in the provided language.
|
|
||||||
/// If the language is empty or null, returns all Chapters in all Languages.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="publication">Publication to get Chapters for</param>
|
|
||||||
/// <param name="language">Language of the Chapters</param>
|
|
||||||
/// <returns>Array of Chapters matching Publication and Language</returns>
|
|
||||||
public abstract Chapter[] GetChapters(Publication publication, string language = "");
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Retrieves the Chapter (+Images) from the website.
|
|
||||||
/// Should later call DownloadChapterImages to retrieve the individual Images of the Chapter.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="publication">Publication that contains Chapter</param>
|
|
||||||
/// <param name="chapter">Chapter with Images to retrieve</param>
|
|
||||||
public abstract void DownloadChapter(Publication publication, Chapter chapter);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Retrieves the Cover from the Website
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="publication">Publication to retrieve Cover for</param>
|
|
||||||
public abstract void DownloadCover(Publication publication);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Saves the series-info to series.json in the Publication Folder
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="publication">Publication to save series.json for</param>
|
|
||||||
public void SaveSeriesInfo(Publication publication)
|
|
||||||
{
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Saving series.json for {publication.sortName}");
|
|
||||||
//Check if Publication already has a Folder and a series.json
|
|
||||||
string publicationFolder = Path.Join(downloadLocation, publication.folderName);
|
|
||||||
if(!Directory.Exists(publicationFolder))
|
|
||||||
Directory.CreateDirectory(publicationFolder);
|
|
||||||
|
|
||||||
string seriesInfoPath = Path.Join(publicationFolder, "series.json");
|
|
||||||
if(!File.Exists(seriesInfoPath))
|
|
||||||
File.WriteAllText(seriesInfoPath,publication.GetSeriesInfoJson());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Creates a string containing XML of publication and chapter.
|
|
||||||
/// See ComicInfo.xml
|
|
||||||
/// </summary>
|
|
||||||
/// <returns>XML-string</returns>
|
|
||||||
protected static string CreateComicInfo(Publication publication, Chapter chapter, Logger? logger)
|
|
||||||
{
|
|
||||||
logger?.WriteLine("Connector", $"Creating ComicInfo.Xml for {publication.sortName} Chapter {chapter.sortNumber}");
|
|
||||||
XElement comicInfo = new XElement("ComicInfo",
|
|
||||||
new XElement("Tags", string.Join(',',publication.tags)),
|
|
||||||
new XElement("LanguageISO", publication.originalLanguage),
|
|
||||||
new XElement("Title", chapter.name),
|
|
||||||
new XElement("Volume", chapter.volumeNumber),
|
|
||||||
new XElement("Number", chapter.chapterNumber) //TODO check if this is correct at some point
|
|
||||||
);
|
|
||||||
return comicInfo.ToString();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Checks if a chapter-archive is already present
|
|
||||||
/// </summary>
|
|
||||||
/// <returns>true if chapter is present</returns>
|
|
||||||
public bool ChapterIsDownloaded(Publication publication, Chapter chapter)
|
|
||||||
{
|
|
||||||
return File.Exists(CreateFullFilepath(publication, chapter));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Creates full file path of chapter-archive
|
|
||||||
/// </summary>
|
|
||||||
/// <returns>Filepath</returns>
|
|
||||||
protected string CreateFullFilepath(Publication publication, Chapter chapter)
|
|
||||||
{
|
|
||||||
return Path.Join(downloadLocation, publication.folderName, chapter.fileName);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Downloads Image from URL and saves it to the given path(incl. fileName)
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="imageUrl"></param>
|
|
||||||
/// <param name="fullPath"></param>
|
|
||||||
/// <param name="downloadClient">DownloadClient of the connector</param>
|
|
||||||
protected static void DownloadImage(string imageUrl, string fullPath, DownloadClient downloadClient)
|
|
||||||
{
|
|
||||||
DownloadClient.RequestResult requestResult = downloadClient.MakeRequest(imageUrl);
|
|
||||||
byte[] buffer = new byte[requestResult.result.Length];
|
|
||||||
requestResult.result.ReadExactly(buffer, 0, buffer.Length);
|
|
||||||
File.WriteAllBytes(fullPath, buffer);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Downloads all Images from URLs, Compresses to zip(cbz) and saves.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="imageUrls">List of URLs to download Images from</param>
|
|
||||||
/// <param name="saveArchiveFilePath">Full path to save archive to (without file ending .cbz)</param>
|
|
||||||
/// <param name="downloadClient">DownloadClient of the connector</param>
|
|
||||||
/// <param name="comicInfoPath">Path of the generate Chapter ComicInfo.xml, if it was generated</param>
|
|
||||||
protected static void DownloadChapterImages(string[] imageUrls, string saveArchiveFilePath, DownloadClient downloadClient, Logger? logger, string? comicInfoPath = null)
|
|
||||||
{
|
|
||||||
logger?.WriteLine("Connector", "Downloading Images");
|
|
||||||
//Check if Publication Directory already exists
|
|
||||||
string[] splitPath = saveArchiveFilePath.Split(Path.DirectorySeparatorChar);
|
|
||||||
string directoryPath = Path.Combine(splitPath.Take(splitPath.Length - 1).ToArray());
|
|
||||||
if (!Directory.Exists(directoryPath))
|
|
||||||
Directory.CreateDirectory(directoryPath);
|
|
||||||
|
|
||||||
string fullPath = $"{saveArchiveFilePath}.cbz";
|
|
||||||
if (File.Exists(fullPath)) //Don't download twice.
|
|
||||||
return;
|
|
||||||
|
|
||||||
//Create a temporary folder to store images
|
|
||||||
string tempFolder = Directory.CreateTempSubdirectory().FullName;
|
|
||||||
|
|
||||||
int chapter = 0;
|
|
||||||
//Download all Images to temporary Folder
|
|
||||||
foreach (string imageUrl in imageUrls)
|
|
||||||
{
|
|
||||||
string[] split = imageUrl.Split('.');
|
|
||||||
string extension = split[^1];
|
|
||||||
DownloadImage(imageUrl, Path.Join(tempFolder, $"{chapter++}.{extension}"), downloadClient);
|
|
||||||
}
|
|
||||||
|
|
||||||
if(comicInfoPath is not null)
|
|
||||||
File.Copy(comicInfoPath, Path.Join(tempFolder, "ComicInfo.xml"));
|
|
||||||
|
|
||||||
logger?.WriteLine("Connector", "Creating archive");
|
|
||||||
//ZIP-it and ship-it
|
|
||||||
ZipFile.CreateFromDirectory(tempFolder, fullPath);
|
|
||||||
Directory.Delete(tempFolder, true); //Cleanup
|
|
||||||
}
|
|
||||||
|
|
||||||
protected class DownloadClient
|
|
||||||
{
|
|
||||||
private readonly TimeSpan _requestSpeed;
|
|
||||||
private DateTime _lastRequest;
|
|
||||||
private static readonly HttpClient Client = new();
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Creates a httpClient
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="delay">minimum delay between requests (to avoid spam)</param>
|
|
||||||
public DownloadClient(uint delay)
|
|
||||||
{
|
|
||||||
_requestSpeed = TimeSpan.FromMilliseconds(delay);
|
|
||||||
_lastRequest = DateTime.Now.Subtract(_requestSpeed);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Request Webpage
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="url"></param>
|
|
||||||
/// <returns>RequestResult with StatusCode and Stream of received data</returns>
|
|
||||||
public RequestResult MakeRequest(string url)
|
|
||||||
{
|
|
||||||
while((DateTime.Now - _lastRequest) < _requestSpeed)
|
|
||||||
Thread.Sleep(10);
|
|
||||||
_lastRequest = DateTime.Now;
|
|
||||||
|
|
||||||
HttpRequestMessage requestMessage = new(HttpMethod.Get, url);
|
|
||||||
HttpResponseMessage response = Client.Send(requestMessage);
|
|
||||||
Stream resultString = response.IsSuccessStatusCode ? response.Content.ReadAsStream() : Stream.Null;
|
|
||||||
return new RequestResult(response.StatusCode, resultString);
|
|
||||||
}
|
|
||||||
|
|
||||||
public struct RequestResult
|
|
||||||
{
|
|
||||||
public HttpStatusCode statusCode { get; }
|
|
||||||
public Stream result { get; }
|
|
||||||
|
|
||||||
public RequestResult(HttpStatusCode statusCode, Stream result)
|
|
||||||
{
|
|
||||||
this.statusCode = statusCode;
|
|
||||||
this.result = result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,246 +0,0 @@
|
|||||||
using System.Globalization;
|
|
||||||
using System.Net;
|
|
||||||
using System.Text.Json;
|
|
||||||
using System.Text.Json.Nodes;
|
|
||||||
using Logging;
|
|
||||||
|
|
||||||
namespace Tranga.Connectors;
|
|
||||||
public class MangaDex : Connector
|
|
||||||
{
|
|
||||||
public override string name { get; }
|
|
||||||
|
|
||||||
public MangaDex(string downloadLocation, uint downloadDelay, Logger? logger) : base(downloadLocation, downloadDelay, logger)
|
|
||||||
{
|
|
||||||
name = "MangaDex";
|
|
||||||
}
|
|
||||||
|
|
||||||
public MangaDex(string downloadLocation, Logger? logger) : base(downloadLocation, 750, logger)
|
|
||||||
{
|
|
||||||
name = "MangaDex";
|
|
||||||
}
|
|
||||||
|
|
||||||
public override Publication[] GetPublications(string publicationTitle = "")
|
|
||||||
{
|
|
||||||
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
|
|
||||||
HashSet<Publication> publications = new();
|
|
||||||
while (offset < total) //As long as we haven't requested all "Pages"
|
|
||||||
{
|
|
||||||
//Request next Page
|
|
||||||
DownloadClient.RequestResult requestResult =
|
|
||||||
downloadClient.MakeRequest(
|
|
||||||
$"https://api.mangadex.org/manga?limit={limit}&title={publicationTitle}&offset={offset}");
|
|
||||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
|
||||||
break;
|
|
||||||
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
|
||||||
|
|
||||||
offset += limit;
|
|
||||||
if (result is null)
|
|
||||||
break;
|
|
||||||
|
|
||||||
total = result["total"]!.GetValue<int>(); //Update the total number of Publications
|
|
||||||
|
|
||||||
JsonArray mangaInResult = result["data"]!.AsArray(); //Manga-data-Array
|
|
||||||
//Loop each Manga and extract information from JSON
|
|
||||||
foreach (JsonNode? mangeNode in mangaInResult)
|
|
||||||
{
|
|
||||||
JsonObject manga = (JsonObject)mangeNode!;
|
|
||||||
JsonObject attributes = manga["attributes"]!.AsObject();
|
|
||||||
|
|
||||||
string title = attributes["title"]!.AsObject().ContainsKey("en") && attributes["title"]!["en"] is not null
|
|
||||||
? attributes["title"]!["en"]!.GetValue<string>()
|
|
||||||
: attributes["title"]![((IDictionary<string, JsonNode?>)attributes["title"]!.AsObject()).Keys.First()]!.GetValue<string>();
|
|
||||||
|
|
||||||
string? description = attributes["description"]!.AsObject().ContainsKey("en") && attributes["description"]!["en"] is not null
|
|
||||||
? attributes["description"]!["en"]!.GetValue<string?>()
|
|
||||||
: null;
|
|
||||||
|
|
||||||
JsonArray altTitlesObject = attributes["altTitles"]!.AsArray();
|
|
||||||
string[,] altTitles = new string[altTitlesObject.Count, 2];
|
|
||||||
int titleIndex = 0;
|
|
||||||
foreach (JsonNode? altTitleNode in altTitlesObject)
|
|
||||||
{
|
|
||||||
JsonObject altTitleObject = (JsonObject)altTitleNode!;
|
|
||||||
string key = ((IDictionary<string, JsonNode?>)altTitleObject).Keys.ToArray()[0];
|
|
||||||
altTitles[titleIndex, 0] = key;
|
|
||||||
altTitles[titleIndex++, 1] = altTitleObject[key]!.GetValue<string>();
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonArray tagsObject = attributes["tags"]!.AsArray();
|
|
||||||
HashSet<string> tags = new();
|
|
||||||
foreach (JsonNode? tagNode in tagsObject)
|
|
||||||
{
|
|
||||||
JsonObject tagObject = (JsonObject)tagNode!;
|
|
||||||
if(tagObject["attributes"]!["name"]!.AsObject().ContainsKey("en"))
|
|
||||||
tags.Add(tagObject["attributes"]!["name"]!["en"]!.GetValue<string>());
|
|
||||||
}
|
|
||||||
|
|
||||||
string? poster = null;
|
|
||||||
if (manga.ContainsKey("relationships") && manga["relationships"] is not null)
|
|
||||||
{
|
|
||||||
JsonArray relationships = manga["relationships"]!.AsArray();
|
|
||||||
poster = relationships.FirstOrDefault(relationship => relationship!["type"]!.GetValue<string>() == "cover_art")!["id"]!.GetValue<string>();
|
|
||||||
}
|
|
||||||
|
|
||||||
string[,]? links = null;
|
|
||||||
if (attributes.ContainsKey("links") && attributes["links"] is not null)
|
|
||||||
{
|
|
||||||
JsonObject linksObject = attributes["links"]!.AsObject();
|
|
||||||
links = new string[linksObject.Count, 2];
|
|
||||||
int linkIndex = 0;
|
|
||||||
foreach (string key in ((IDictionary<string, JsonNode?>)linksObject).Keys)
|
|
||||||
{
|
|
||||||
links[linkIndex, 0] = key;
|
|
||||||
links[linkIndex++, 1] = linksObject[key]!.GetValue<string>();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int? year = attributes.ContainsKey("year") && attributes["year"] is not null
|
|
||||||
? attributes["year"]!.GetValue<int?>()
|
|
||||||
: null;
|
|
||||||
|
|
||||||
string? originalLanguage = attributes.ContainsKey("originalLanguage") && attributes["originalLanguage"] is not null
|
|
||||||
? attributes["originalLanguage"]!.GetValue<string?>()
|
|
||||||
: null;
|
|
||||||
|
|
||||||
string status = attributes["status"]!.GetValue<string>();
|
|
||||||
|
|
||||||
Publication pub = new Publication(
|
|
||||||
title,
|
|
||||||
description,
|
|
||||||
altTitles,
|
|
||||||
tags.ToArray(),
|
|
||||||
poster,
|
|
||||||
links,
|
|
||||||
year,
|
|
||||||
originalLanguage,
|
|
||||||
status,
|
|
||||||
manga["id"]!.GetValue<string>()
|
|
||||||
);
|
|
||||||
publications.Add(pub); //Add Publication (Manga) to result
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return publications.ToArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
public override Chapter[] GetChapters(Publication publication, string language = "")
|
|
||||||
{
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Getting Chapters {publication.sortName} (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
|
|
||||||
List<Chapter> chapters = new();
|
|
||||||
//As long as we haven't requested all "Pages"
|
|
||||||
while (offset < total)
|
|
||||||
{
|
|
||||||
//Request next "Page"
|
|
||||||
DownloadClient.RequestResult requestResult =
|
|
||||||
downloadClient.MakeRequest(
|
|
||||||
$"https://api.mangadex.org/manga/{publication.downloadUrl}/feed?limit={limit}&offset={offset}&translatedLanguage%5B%5D={language}");
|
|
||||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
|
||||||
break;
|
|
||||||
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
|
||||||
|
|
||||||
offset += limit;
|
|
||||||
if (result is null)
|
|
||||||
break;
|
|
||||||
|
|
||||||
total = result["total"]!.GetValue<int>();
|
|
||||||
JsonArray chaptersInResult = result["data"]!.AsArray();
|
|
||||||
//Loop through all Chapters in result and extract information from JSON
|
|
||||||
foreach (JsonNode? jsonNode in chaptersInResult)
|
|
||||||
{
|
|
||||||
JsonObject chapter = (JsonObject)jsonNode!;
|
|
||||||
JsonObject attributes = chapter["attributes"]!.AsObject();
|
|
||||||
string chapterId = chapter["id"]!.GetValue<string>();
|
|
||||||
|
|
||||||
string? title = attributes.ContainsKey("title") && attributes["title"] is not null
|
|
||||||
? attributes["title"]!.GetValue<string>()
|
|
||||||
: null;
|
|
||||||
|
|
||||||
string? volume = attributes.ContainsKey("volume") && attributes["volume"] is not null
|
|
||||||
? attributes["volume"]!.GetValue<string>()
|
|
||||||
: null;
|
|
||||||
|
|
||||||
string? chapterNum = attributes.ContainsKey("chapter") && attributes["chapter"] is not null
|
|
||||||
? attributes["chapter"]!.GetValue<string>()
|
|
||||||
: null;
|
|
||||||
|
|
||||||
chapters.Add(new Chapter(title, volume, chapterNum, chapterId));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//Return Chapters ordered by Chapter-Number
|
|
||||||
NumberFormatInfo chapterNumberFormatInfo = new()
|
|
||||||
{
|
|
||||||
NumberDecimalSeparator = "."
|
|
||||||
};
|
|
||||||
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, chapterNumberFormatInfo)).ToArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
public override void DownloadChapter(Publication publication, Chapter chapter)
|
|
||||||
{
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Download Chapter {publication.sortName} {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'");
|
|
||||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
|
||||||
return;
|
|
||||||
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
|
||||||
if (result is null)
|
|
||||||
return;
|
|
||||||
|
|
||||||
string baseUrl = result["baseUrl"]!.GetValue<string>();
|
|
||||||
string hash = result["chapter"]!["hash"]!.GetValue<string>();
|
|
||||||
JsonArray imageFileNames = result["chapter"]!["data"]!.AsArray();
|
|
||||||
//Loop through all imageNames and construct urls (imageUrl)
|
|
||||||
HashSet<string> imageUrls = new();
|
|
||||||
foreach (JsonNode? image in imageFileNames)
|
|
||||||
imageUrls.Add($"{baseUrl}/data/{hash}/{image!.GetValue<string>()}");
|
|
||||||
|
|
||||||
string comicInfoPath = Path.GetTempFileName();
|
|
||||||
File.WriteAllText(comicInfoPath, CreateComicInfo(publication, chapter, logger));
|
|
||||||
|
|
||||||
//Download Chapter-Images
|
|
||||||
DownloadChapterImages(imageUrls.ToArray(), CreateFullFilepath(publication, chapter), downloadClient, logger, comicInfoPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
public override void DownloadCover(Publication publication)
|
|
||||||
{
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Download cover {publication.sortName}");
|
|
||||||
//Check if Publication already has a Folder and cover
|
|
||||||
string publicationFolder = Path.Join(downloadLocation, publication.folderName);
|
|
||||||
if(!Directory.Exists(publicationFolder))
|
|
||||||
Directory.CreateDirectory(publicationFolder);
|
|
||||||
DirectoryInfo dirInfo = new (publicationFolder);
|
|
||||||
foreach(FileInfo fileInfo in dirInfo.EnumerateFiles())
|
|
||||||
if (fileInfo.Name.Contains("cover."))
|
|
||||||
return;
|
|
||||||
|
|
||||||
//Request information where to download Cover
|
|
||||||
DownloadClient.RequestResult requestResult =
|
|
||||||
downloadClient.MakeRequest($"https://api.mangadex.org/cover/{publication.posterUrl}");
|
|
||||||
if (requestResult.statusCode != HttpStatusCode.OK)
|
|
||||||
return;
|
|
||||||
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
|
||||||
if (result is null)
|
|
||||||
return;
|
|
||||||
|
|
||||||
string fileName = result["data"]!["attributes"]!["fileName"]!.GetValue<string>();
|
|
||||||
|
|
||||||
string coverUrl = $"https://uploads.mangadex.org/covers/{publication.downloadUrl}/{fileName}";
|
|
||||||
|
|
||||||
//Get file-extension (jpg, png)
|
|
||||||
string[] split = coverUrl.Split('.');
|
|
||||||
string extension = split[^1];
|
|
||||||
|
|
||||||
string outFolderPath = Path.Join(downloadLocation, publication.folderName);
|
|
||||||
Directory.CreateDirectory(outFolderPath);
|
|
||||||
|
|
||||||
//Download cover-Image
|
|
||||||
DownloadImage(coverUrl, Path.Join(downloadLocation, publication.folderName, $"cover.{extension}"), this.downloadClient);
|
|
||||||
}
|
|
||||||
}
|
|
108
Tranga/GlobalBase.cs
Normal file
108
Tranga/GlobalBase.cs
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Logging;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Tranga.LibraryConnectors;
|
||||||
|
using Tranga.NotificationConnectors;
|
||||||
|
|
||||||
|
namespace Tranga;
|
||||||
|
|
||||||
|
public abstract class GlobalBase
|
||||||
|
{
|
||||||
|
protected Logger? logger { get; init; }
|
||||||
|
protected TrangaSettings settings { get; init; }
|
||||||
|
protected HashSet<NotificationConnector> notificationConnectors { get; init; }
|
||||||
|
protected HashSet<LibraryConnector> libraryConnectors { get; init; }
|
||||||
|
protected List<Manga> cachedPublications { get; init; }
|
||||||
|
protected static readonly NumberFormatInfo numberFormatDecimalPoint = new (){ NumberDecimalSeparator = "." };
|
||||||
|
|
||||||
|
protected GlobalBase(GlobalBase clone)
|
||||||
|
{
|
||||||
|
this.logger = clone.logger;
|
||||||
|
this.settings = clone.settings;
|
||||||
|
this.notificationConnectors = clone.notificationConnectors;
|
||||||
|
this.libraryConnectors = clone.libraryConnectors;
|
||||||
|
this.cachedPublications = clone.cachedPublications;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected GlobalBase(Logger? logger, TrangaSettings settings)
|
||||||
|
{
|
||||||
|
this.logger = logger;
|
||||||
|
this.settings = settings;
|
||||||
|
this.notificationConnectors = settings.LoadNotificationConnectors(this);
|
||||||
|
this.libraryConnectors = settings.LoadLibraryConnectors(this);
|
||||||
|
this.cachedPublications = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void Log(string message)
|
||||||
|
{
|
||||||
|
logger?.WriteLine(this.GetType().Name, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void Log(string fStr, params object?[] replace)
|
||||||
|
{
|
||||||
|
Log(string.Format(fStr, replace));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void SendNotifications(string title, string text)
|
||||||
|
{
|
||||||
|
foreach (NotificationConnector nc in notificationConnectors)
|
||||||
|
nc.SendNotification(title, text);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void AddNotificationConnector(NotificationConnector notificationConnector)
|
||||||
|
{
|
||||||
|
Log($"Adding {notificationConnector}");
|
||||||
|
notificationConnectors.RemoveWhere(nc => nc.GetType() == notificationConnector.GetType());
|
||||||
|
notificationConnectors.Add(notificationConnector);
|
||||||
|
|
||||||
|
while(IsFileInUse(settings.notificationConnectorsFilePath))
|
||||||
|
Thread.Sleep(100);
|
||||||
|
File.WriteAllText(settings.notificationConnectorsFilePath, JsonConvert.SerializeObject(notificationConnectors));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void DeleteNotificationConnector(NotificationConnector.NotificationConnectorType notificationConnectorType)
|
||||||
|
{
|
||||||
|
Log($"Removing {notificationConnectorType}");
|
||||||
|
notificationConnectors.RemoveWhere(nc => nc.notificationConnectorType == notificationConnectorType);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void UpdateLibraries()
|
||||||
|
{
|
||||||
|
foreach(LibraryConnector lc in libraryConnectors)
|
||||||
|
lc.UpdateLibrary();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void AddLibraryConnector(LibraryConnector libraryConnector)
|
||||||
|
{
|
||||||
|
Log($"Adding {libraryConnector}");
|
||||||
|
libraryConnectors.RemoveWhere(lc => lc.GetType() == libraryConnector.GetType());
|
||||||
|
libraryConnectors.Add(libraryConnector);
|
||||||
|
|
||||||
|
while(IsFileInUse(settings.libraryConnectorsFilePath))
|
||||||
|
Thread.Sleep(100);
|
||||||
|
File.WriteAllText(settings.libraryConnectorsFilePath, JsonConvert.SerializeObject(libraryConnectors));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void DeleteLibraryConnector(LibraryConnector.LibraryType libraryType)
|
||||||
|
{
|
||||||
|
Log($"Removing {libraryType}");
|
||||||
|
libraryConnectors.RemoveWhere(lc => lc.libraryType == libraryType);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected bool IsFileInUse(string filePath)
|
||||||
|
{
|
||||||
|
if (!File.Exists(filePath))
|
||||||
|
return false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using FileStream stream = new (filePath, FileMode.Open, FileAccess.Read, FileShare.None);
|
||||||
|
stream.Close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
|
{
|
||||||
|
Log($"File is in use {filePath}");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
41
Tranga/Jobs/DownloadChapter.cs
Normal file
41
Tranga/Jobs/DownloadChapter.cs
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
using System.Text;
|
||||||
|
using Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
namespace Tranga.Jobs;
|
||||||
|
|
||||||
|
public class DownloadChapter : Job
|
||||||
|
{
|
||||||
|
public Chapter chapter { get; init; }
|
||||||
|
|
||||||
|
public DownloadChapter(GlobalBase clone, MangaConnector connector, Chapter chapter, DateTime lastExecution, string? parentJobId = null) : base(clone, connector, lastExecution, parentJobId: parentJobId)
|
||||||
|
{
|
||||||
|
this.chapter = chapter;
|
||||||
|
}
|
||||||
|
|
||||||
|
public DownloadChapter(GlobalBase clone, MangaConnector connector, Chapter chapter, string? parentJobId = null) : base(clone, connector, parentJobId: parentJobId)
|
||||||
|
{
|
||||||
|
this.chapter = chapter;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override string GetId()
|
||||||
|
{
|
||||||
|
return $"{GetType()}-{chapter.parentManga.internalId}-{chapter.chapterNumber}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString()
|
||||||
|
{
|
||||||
|
return $"DownloadChapter {id} {chapter}";
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override IEnumerable<Job> ExecuteReturnSubTasksInternal()
|
||||||
|
{
|
||||||
|
Task downloadTask = new(delegate
|
||||||
|
{
|
||||||
|
mangaConnector.DownloadChapter(chapter, this.progressToken);
|
||||||
|
UpdateLibraries();
|
||||||
|
SendNotifications("Chapter downloaded", $"{chapter.parentManga.sortName} - {chapter.chapterNumber}");
|
||||||
|
});
|
||||||
|
downloadTask.Start();
|
||||||
|
return Array.Empty<Job>();
|
||||||
|
}
|
||||||
|
}
|
47
Tranga/Jobs/DownloadNewChapters.cs
Normal file
47
Tranga/Jobs/DownloadNewChapters.cs
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
using Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
namespace Tranga.Jobs;
|
||||||
|
|
||||||
|
public class DownloadNewChapters : Job
|
||||||
|
{
|
||||||
|
public Manga manga { get; init; }
|
||||||
|
public string translatedLanguage { get; init; }
|
||||||
|
|
||||||
|
public DownloadNewChapters(GlobalBase clone, MangaConnector connector, Manga manga, DateTime lastExecution,
|
||||||
|
bool recurring = false, TimeSpan? recurrence = null, string? parentJobId = null, string translatedLanguage = "en") : base(clone, connector, lastExecution, recurring,
|
||||||
|
recurrence, parentJobId)
|
||||||
|
{
|
||||||
|
this.manga = manga;
|
||||||
|
this.translatedLanguage = translatedLanguage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public DownloadNewChapters(GlobalBase clone, MangaConnector connector, Manga manga, bool recurring = false, TimeSpan? recurrence = null, string? parentJobId = null, string translatedLanguage = "en") : base (clone, connector, recurring, recurrence, parentJobId)
|
||||||
|
{
|
||||||
|
this.manga = manga;
|
||||||
|
this.translatedLanguage = translatedLanguage;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override string GetId()
|
||||||
|
{
|
||||||
|
return $"{GetType()}-{manga.internalId}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString()
|
||||||
|
{
|
||||||
|
return $"DownloadChapter {id} {manga}";
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override IEnumerable<Job> ExecuteReturnSubTasksInternal()
|
||||||
|
{
|
||||||
|
Chapter[] chapters = mangaConnector.GetNewChapters(manga, this.translatedLanguage);
|
||||||
|
this.progressToken.increments = chapters.Length;
|
||||||
|
List<Job> jobs = new();
|
||||||
|
foreach (Chapter chapter in chapters)
|
||||||
|
{
|
||||||
|
DownloadChapter downloadChapterJob = new(this, this.mangaConnector, chapter, parentJobId: this.id);
|
||||||
|
jobs.Add(downloadChapterJob);
|
||||||
|
}
|
||||||
|
progressToken.Complete();
|
||||||
|
return jobs;
|
||||||
|
}
|
||||||
|
}
|
93
Tranga/Jobs/Job.cs
Normal file
93
Tranga/Jobs/Job.cs
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
using Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
namespace Tranga.Jobs;
|
||||||
|
|
||||||
|
public abstract class Job : GlobalBase
|
||||||
|
{
|
||||||
|
public MangaConnector mangaConnector { get; init; }
|
||||||
|
public ProgressToken progressToken { get; private set; }
|
||||||
|
public bool recurring { get; init; }
|
||||||
|
public TimeSpan? recurrenceTime { get; set; }
|
||||||
|
public DateTime? lastExecution { get; private set; }
|
||||||
|
public DateTime nextExecution => NextExecution();
|
||||||
|
public string id => GetId();
|
||||||
|
internal IEnumerable<Job>? subJobs { get; private set; }
|
||||||
|
public string? parentJobId { get; init; }
|
||||||
|
|
||||||
|
internal Job(GlobalBase clone, MangaConnector connector, bool recurring = false, TimeSpan? recurrenceTime = null, string? parentJobId = null) : base(clone)
|
||||||
|
{
|
||||||
|
this.mangaConnector = connector;
|
||||||
|
this.progressToken = new ProgressToken(0);
|
||||||
|
this.recurring = recurring;
|
||||||
|
if (recurring && recurrenceTime is null)
|
||||||
|
throw new ArgumentException("If recurrence is set to true, a recurrence time has to be provided.");
|
||||||
|
else if(recurring && recurrenceTime is not null)
|
||||||
|
this.lastExecution = DateTime.Now.Subtract((TimeSpan)recurrenceTime);
|
||||||
|
this.recurrenceTime = recurrenceTime ?? TimeSpan.Zero;
|
||||||
|
this.parentJobId = parentJobId;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal Job(GlobalBase clone, MangaConnector connector, DateTime lastExecution, bool recurring = false,
|
||||||
|
TimeSpan? recurrenceTime = null, string? parentJobId = null) : base(clone)
|
||||||
|
{
|
||||||
|
this.mangaConnector = connector;
|
||||||
|
this.progressToken = new ProgressToken(0);
|
||||||
|
this.recurring = recurring;
|
||||||
|
if (recurring && recurrenceTime is null)
|
||||||
|
throw new ArgumentException("If recurrence is set to true, a recurrence time has to be provided.");
|
||||||
|
this.lastExecution = lastExecution;
|
||||||
|
this.recurrenceTime = recurrenceTime ?? TimeSpan.Zero;
|
||||||
|
this.parentJobId = parentJobId;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract string GetId();
|
||||||
|
|
||||||
|
public void AddSubJob(Job job)
|
||||||
|
{
|
||||||
|
subJobs ??= new List<Job>();
|
||||||
|
subJobs = subJobs.Append(job);
|
||||||
|
}
|
||||||
|
|
||||||
|
private DateTime NextExecution()
|
||||||
|
{
|
||||||
|
if(recurrenceTime.HasValue && lastExecution.HasValue)
|
||||||
|
return lastExecution.Value.Add(recurrenceTime.Value);
|
||||||
|
if(recurrenceTime.HasValue && !lastExecution.HasValue)
|
||||||
|
return DateTime.Now;
|
||||||
|
return DateTime.MaxValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ResetProgress()
|
||||||
|
{
|
||||||
|
this.progressToken.increments = this.progressToken.increments - this.progressToken.incrementsCompleted;
|
||||||
|
this.lastExecution = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ExecutionEnqueue()
|
||||||
|
{
|
||||||
|
this.progressToken.increments = this.progressToken.increments - this.progressToken.incrementsCompleted;
|
||||||
|
this.lastExecution = recurrenceTime is not null ? DateTime.Now.Subtract((TimeSpan)recurrenceTime) : DateTime.UnixEpoch;
|
||||||
|
this.progressToken.Standby();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Cancel()
|
||||||
|
{
|
||||||
|
Log($"Cancelling {this}");
|
||||||
|
this.progressToken.cancellationRequested = true;
|
||||||
|
this.progressToken.Cancel();
|
||||||
|
this.lastExecution = DateTime.Now;
|
||||||
|
if(subJobs is not null)
|
||||||
|
foreach(Job subJob in subJobs)
|
||||||
|
subJob.Cancel();
|
||||||
|
}
|
||||||
|
|
||||||
|
public IEnumerable<Job> ExecuteReturnSubTasks()
|
||||||
|
{
|
||||||
|
progressToken.Start();
|
||||||
|
subJobs = ExecuteReturnSubTasksInternal();
|
||||||
|
lastExecution = DateTime.Now;
|
||||||
|
return subJobs;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract IEnumerable<Job> ExecuteReturnSubTasksInternal();
|
||||||
|
}
|
232
Tranga/Jobs/JobBoss.cs
Normal file
232
Tranga/Jobs/JobBoss.cs
Normal file
@ -0,0 +1,232 @@
|
|||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
namespace Tranga.Jobs;
|
||||||
|
|
||||||
|
public class JobBoss : GlobalBase
|
||||||
|
{
|
||||||
|
public HashSet<Job> jobs { get; init; }
|
||||||
|
private Dictionary<MangaConnector, Queue<Job>> mangaConnectorJobQueue { get; init; }
|
||||||
|
|
||||||
|
public JobBoss(GlobalBase clone, HashSet<MangaConnector> connectors) : base(clone)
|
||||||
|
{
|
||||||
|
this.jobs = new();
|
||||||
|
LoadJobsList(connectors);
|
||||||
|
this.mangaConnectorJobQueue = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AddJob(Job job)
|
||||||
|
{
|
||||||
|
if (ContainsJobLike(job))
|
||||||
|
{
|
||||||
|
Log($"Already Contains Job {job}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Log($"Added {job}");
|
||||||
|
this.jobs.Add(job);
|
||||||
|
ExportJobsList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AddJobs(IEnumerable<Job> jobsToAdd)
|
||||||
|
{
|
||||||
|
foreach (Job job in jobsToAdd)
|
||||||
|
AddJob(job);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool ContainsJobLike(Job job)
|
||||||
|
{
|
||||||
|
if (job is DownloadChapter dcJob)
|
||||||
|
{
|
||||||
|
return this.GetJobsLike(dcJob.mangaConnector, chapter: dcJob.chapter).Any();
|
||||||
|
}else if (job is DownloadNewChapters ncJob)
|
||||||
|
{
|
||||||
|
return this.GetJobsLike(ncJob.mangaConnector, ncJob.manga).Any();
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RemoveJob(Job job)
|
||||||
|
{
|
||||||
|
Log($"Removing {job}");
|
||||||
|
job.Cancel();
|
||||||
|
this.jobs.Remove(job);
|
||||||
|
if(job.subJobs is not null)
|
||||||
|
RemoveJobs(job.subJobs);
|
||||||
|
ExportJobsList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RemoveJobs(IEnumerable<Job?> jobsToRemove)
|
||||||
|
{
|
||||||
|
Log($"Removing {jobsToRemove.Count()} jobs.");
|
||||||
|
foreach (Job? job in jobsToRemove)
|
||||||
|
if(job is not null)
|
||||||
|
RemoveJob(job);
|
||||||
|
}
|
||||||
|
|
||||||
|
public IEnumerable<Job> GetJobsLike(string? connectorName = null, string? internalId = null, string? chapterNumber = null)
|
||||||
|
{
|
||||||
|
IEnumerable<Job> ret = this.jobs;
|
||||||
|
if (connectorName is not null)
|
||||||
|
ret = ret.Where(job => job.mangaConnector.name == connectorName);
|
||||||
|
|
||||||
|
if (internalId is not null && chapterNumber is not null)
|
||||||
|
ret = ret.Where(jjob =>
|
||||||
|
{
|
||||||
|
if (jjob is not DownloadChapter job)
|
||||||
|
return false;
|
||||||
|
return job.chapter.parentManga.internalId == internalId &&
|
||||||
|
job.chapter.chapterNumber == chapterNumber;
|
||||||
|
});
|
||||||
|
else if (internalId is not null)
|
||||||
|
ret = ret.Where(jjob =>
|
||||||
|
{
|
||||||
|
if (jjob is not DownloadNewChapters job)
|
||||||
|
return false;
|
||||||
|
return job.manga.internalId == internalId;
|
||||||
|
});
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IEnumerable<Job> GetJobsLike(MangaConnector? mangaConnector = null, Manga? publication = null,
|
||||||
|
Chapter? chapter = null)
|
||||||
|
{
|
||||||
|
if (chapter is not null)
|
||||||
|
return GetJobsLike(mangaConnector?.name, chapter.Value.parentManga.internalId, chapter?.chapterNumber);
|
||||||
|
else
|
||||||
|
return GetJobsLike(mangaConnector?.name, publication?.internalId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Job? GetJobById(string jobId)
|
||||||
|
{
|
||||||
|
if (this.jobs.FirstOrDefault(jjob => jjob.id == jobId) is { } job)
|
||||||
|
return job;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryGetJobById(string jobId, out Job? job)
|
||||||
|
{
|
||||||
|
if (this.jobs.FirstOrDefault(jjob => jjob.id == jobId) is { } ret)
|
||||||
|
{
|
||||||
|
job = ret;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
job = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool QueueContainsJob(Job job)
|
||||||
|
{
|
||||||
|
mangaConnectorJobQueue.TryAdd(job.mangaConnector, new Queue<Job>());
|
||||||
|
return mangaConnectorJobQueue[job.mangaConnector].Contains(job);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AddJobToQueue(Job job)
|
||||||
|
{
|
||||||
|
Log($"Adding Job to Queue. {job}");
|
||||||
|
mangaConnectorJobQueue.TryAdd(job.mangaConnector, new Queue<Job>());
|
||||||
|
Queue<Job> connectorJobQueue = mangaConnectorJobQueue[job.mangaConnector];
|
||||||
|
if(!connectorJobQueue.Contains(job))
|
||||||
|
connectorJobQueue.Enqueue(job);
|
||||||
|
job.ExecutionEnqueue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AddJobsToQueue(IEnumerable<Job> jobs)
|
||||||
|
{
|
||||||
|
foreach(Job job in jobs)
|
||||||
|
AddJobToQueue(job);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void LoadJobsList(HashSet<MangaConnector> connectors)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(settings.jobsFolderPath);
|
||||||
|
Regex idRex = new (@"(.*)\.json");
|
||||||
|
|
||||||
|
foreach (FileInfo file in new DirectoryInfo(settings.jobsFolderPath).EnumerateFiles())
|
||||||
|
if (idRex.IsMatch(file.Name))
|
||||||
|
{
|
||||||
|
Job job = JsonConvert.DeserializeObject<Job>(File.ReadAllText(file.FullName),
|
||||||
|
new JobJsonConverter(this, new MangaConnectorJsonConverter(this, connectors)))!;
|
||||||
|
this.jobs.Add(job);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (Job job in this.jobs)
|
||||||
|
this.jobs.FirstOrDefault(jjob => jjob.id == job.parentJobId)?.AddSubJob(job);
|
||||||
|
|
||||||
|
foreach (DownloadNewChapters ncJob in this.jobs.Where(job => job is DownloadNewChapters))
|
||||||
|
cachedPublications.Add(ncJob.manga);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ExportJobsList()
|
||||||
|
{
|
||||||
|
Log("Exporting Jobs");
|
||||||
|
foreach (Job job in this.jobs)
|
||||||
|
{
|
||||||
|
string jobFilePath = Path.Join(settings.jobsFolderPath, $"{job.id}.json");
|
||||||
|
if (!File.Exists(jobFilePath))
|
||||||
|
{
|
||||||
|
string jobStr = JsonConvert.SerializeObject(job);
|
||||||
|
while(IsFileInUse(jobFilePath))
|
||||||
|
Thread.Sleep(10);
|
||||||
|
Log($"Exporting Job {jobFilePath}");
|
||||||
|
File.WriteAllText(jobFilePath, jobStr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Remove files with jobs not in this.jobs-list
|
||||||
|
Regex idRex = new (@"(.*)\.json");
|
||||||
|
foreach (FileInfo file in new DirectoryInfo(settings.jobsFolderPath).EnumerateFiles())
|
||||||
|
{
|
||||||
|
if (idRex.IsMatch(file.Name))
|
||||||
|
{
|
||||||
|
string id = idRex.Match(file.Name).Groups[1].Value;
|
||||||
|
if (!this.jobs.Any(job => job.id == id))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
file.Delete();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Log(e.ToString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void CheckJobs()
|
||||||
|
{
|
||||||
|
foreach (Job job in jobs.Where(job => job.nextExecution < DateTime.Now && !QueueContainsJob(job)).OrderBy(job => job.nextExecution))
|
||||||
|
AddJobToQueue(job);
|
||||||
|
foreach (Queue<Job> jobQueue in mangaConnectorJobQueue.Values)
|
||||||
|
{
|
||||||
|
if(jobQueue.Count < 1)
|
||||||
|
continue;
|
||||||
|
Job queueHead = jobQueue.Peek();
|
||||||
|
if (queueHead.progressToken.state is ProgressToken.State.Complete or ProgressToken.State.Cancelled)
|
||||||
|
{
|
||||||
|
switch (queueHead)
|
||||||
|
{
|
||||||
|
case DownloadChapter:
|
||||||
|
RemoveJob(queueHead);
|
||||||
|
break;
|
||||||
|
case DownloadNewChapters:
|
||||||
|
if(queueHead.recurring)
|
||||||
|
queueHead.progressToken.Complete();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
jobQueue.Dequeue();
|
||||||
|
}else if (queueHead.progressToken.state is ProgressToken.State.Standby)
|
||||||
|
{
|
||||||
|
Job[] subJobs = jobQueue.Peek().ExecuteReturnSubTasks().ToArray();
|
||||||
|
AddJobs(subJobs);
|
||||||
|
AddJobsToQueue(subJobs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
70
Tranga/Jobs/JobJsonConverter.cs
Normal file
70
Tranga/Jobs/JobJsonConverter.cs
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
using Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
namespace Tranga.Jobs;
|
||||||
|
|
||||||
|
public class JobJsonConverter : JsonConverter
|
||||||
|
{
|
||||||
|
private GlobalBase _clone;
|
||||||
|
private MangaConnectorJsonConverter _mangaConnectorJsonConverter;
|
||||||
|
|
||||||
|
internal JobJsonConverter(GlobalBase clone, MangaConnectorJsonConverter mangaConnectorJsonConverter)
|
||||||
|
{
|
||||||
|
this._clone = clone;
|
||||||
|
this._mangaConnectorJsonConverter = mangaConnectorJsonConverter;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool CanConvert(Type objectType)
|
||||||
|
{
|
||||||
|
return (objectType == typeof(Job));
|
||||||
|
}
|
||||||
|
|
||||||
|
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
|
||||||
|
{
|
||||||
|
JObject jo = JObject.Load(reader);
|
||||||
|
if (jo.ContainsKey("manga"))//DownloadNewChapters
|
||||||
|
{
|
||||||
|
return new DownloadNewChapters(this._clone,
|
||||||
|
jo.GetValue("mangaConnector")!.ToObject<MangaConnector>(JsonSerializer.Create(new JsonSerializerSettings()
|
||||||
|
{
|
||||||
|
Converters =
|
||||||
|
{
|
||||||
|
this._mangaConnectorJsonConverter
|
||||||
|
}
|
||||||
|
}))!,
|
||||||
|
jo.GetValue("manga")!.ToObject<Manga>(),
|
||||||
|
jo.GetValue("lastExecution")!.ToObject<DateTime>(),
|
||||||
|
jo.GetValue("recurring")!.Value<bool>(),
|
||||||
|
jo.GetValue("recurrenceTime")!.ToObject<TimeSpan?>(),
|
||||||
|
jo.GetValue("parentJobId")!.Value<string?>());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (jo.ContainsKey("chapter"))//DownloadChapter
|
||||||
|
{
|
||||||
|
return new DownloadChapter(this._clone,
|
||||||
|
jo.GetValue("mangaConnector")!.ToObject<MangaConnector>(JsonSerializer.Create(new JsonSerializerSettings()
|
||||||
|
{
|
||||||
|
Converters =
|
||||||
|
{
|
||||||
|
this._mangaConnectorJsonConverter
|
||||||
|
}
|
||||||
|
}))!,
|
||||||
|
jo.GetValue("chapter")!.ToObject<Chapter>(),
|
||||||
|
DateTime.UnixEpoch,
|
||||||
|
jo.GetValue("parentJobId")!.Value<string?>());
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Exception();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool CanWrite => false;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Don't call this
|
||||||
|
/// </summary>
|
||||||
|
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
|
||||||
|
{
|
||||||
|
throw new Exception("Dont call this");
|
||||||
|
}
|
||||||
|
}
|
66
Tranga/Jobs/ProgressToken.cs
Normal file
66
Tranga/Jobs/ProgressToken.cs
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
namespace Tranga.Jobs;
|
||||||
|
|
||||||
|
public class ProgressToken
|
||||||
|
{
|
||||||
|
public bool cancellationRequested { get; set; }
|
||||||
|
public int increments { get; set; }
|
||||||
|
public int incrementsCompleted { get; set; }
|
||||||
|
public float progress => GetProgress();
|
||||||
|
|
||||||
|
public DateTime executionStarted { get; private set; }
|
||||||
|
public TimeSpan timeRemaining => GetTimeRemaining();
|
||||||
|
|
||||||
|
public enum State { Running, Complete, Standby, Cancelled }
|
||||||
|
public State state { get; private set; }
|
||||||
|
|
||||||
|
public ProgressToken(int increments)
|
||||||
|
{
|
||||||
|
this.cancellationRequested = false;
|
||||||
|
this.increments = increments;
|
||||||
|
this.incrementsCompleted = 0;
|
||||||
|
this.state = State.Complete;
|
||||||
|
this.executionStarted = DateTime.UnixEpoch;
|
||||||
|
}
|
||||||
|
|
||||||
|
private float GetProgress()
|
||||||
|
{
|
||||||
|
if(increments > 0 && incrementsCompleted > 0)
|
||||||
|
return (float)incrementsCompleted / (float)increments;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private TimeSpan GetTimeRemaining()
|
||||||
|
{
|
||||||
|
if (increments > 0 && incrementsCompleted > 0)
|
||||||
|
return DateTime.Now.Subtract(this.executionStarted).Divide(incrementsCompleted).Multiply(increments - incrementsCompleted);
|
||||||
|
return TimeSpan.MaxValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Increment()
|
||||||
|
{
|
||||||
|
this.incrementsCompleted++;
|
||||||
|
if (incrementsCompleted > increments)
|
||||||
|
state = State.Complete;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Standby()
|
||||||
|
{
|
||||||
|
state = State.Standby;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Start()
|
||||||
|
{
|
||||||
|
state = State.Running;
|
||||||
|
this.executionStarted = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Complete()
|
||||||
|
{
|
||||||
|
state = State.Complete;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Cancel()
|
||||||
|
{
|
||||||
|
state = State.Cancelled;
|
||||||
|
}
|
||||||
|
}
|
125
Tranga/Komga.cs
125
Tranga/Komga.cs
@ -1,125 +0,0 @@
|
|||||||
using System.Net.Http.Headers;
|
|
||||||
using System.Text.Json.Nodes;
|
|
||||||
using Logging;
|
|
||||||
using Newtonsoft.Json;
|
|
||||||
using JsonSerializer = System.Text.Json.JsonSerializer;
|
|
||||||
|
|
||||||
namespace Tranga;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Provides connectivity to Komga-API
|
|
||||||
/// Can fetch and update libraries
|
|
||||||
/// </summary>
|
|
||||||
public class Komga
|
|
||||||
{
|
|
||||||
public string baseUrl { get; }
|
|
||||||
public string auth { get; } //Base64 encoded, if you use your password everywhere, you have problems
|
|
||||||
|
|
||||||
private Logger? logger;
|
|
||||||
|
|
||||||
/// <param name="baseUrl">Base-URL of Komga instance, no trailing slashes(/)</param>
|
|
||||||
/// <param name="username">Komga Username</param>
|
|
||||||
/// <param name="password">Komga password, will be base64 encoded. yea</param>
|
|
||||||
public Komga(string baseUrl, string username, string password, Logger? logger)
|
|
||||||
{
|
|
||||||
this.baseUrl = baseUrl;
|
|
||||||
this.auth = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}"));
|
|
||||||
this.logger = logger;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <param name="baseUrl">Base-URL of Komga instance, no trailing slashes(/)</param>
|
|
||||||
/// <param name="auth">Base64 string of username and password (username):(password)</param>
|
|
||||||
[JsonConstructor]
|
|
||||||
public Komga(string baseUrl, string auth, Logger? logger)
|
|
||||||
{
|
|
||||||
this.baseUrl = baseUrl;
|
|
||||||
this.auth = auth;
|
|
||||||
this.logger = logger;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Fetches all libraries available to the user
|
|
||||||
/// </summary>
|
|
||||||
/// <returns>Array of KomgaLibraries</returns>
|
|
||||||
public KomgaLibrary[] GetLibraries()
|
|
||||||
{
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Getting Libraries");
|
|
||||||
Stream data = NetClient.MakeRequest($"{baseUrl}/api/v1/libraries", auth);
|
|
||||||
JsonArray? result = JsonSerializer.Deserialize<JsonArray>(data);
|
|
||||||
if (result is null)
|
|
||||||
return Array.Empty<KomgaLibrary>();
|
|
||||||
|
|
||||||
HashSet<KomgaLibrary> ret = new();
|
|
||||||
|
|
||||||
foreach (JsonNode? jsonNode in result)
|
|
||||||
{
|
|
||||||
var jObject = (JsonObject?)jsonNode;
|
|
||||||
string libraryId = jObject!["id"]!.GetValue<string>();
|
|
||||||
string libraryName = jObject!["name"]!.GetValue<string>();
|
|
||||||
ret.Add(new KomgaLibrary(libraryId, libraryName));
|
|
||||||
}
|
|
||||||
|
|
||||||
return ret.ToArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Updates library with given id
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="libraryId">Id of the Komga-Library</param>
|
|
||||||
/// <returns>true if successful</returns>
|
|
||||||
public bool UpdateLibrary(string libraryId)
|
|
||||||
{
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Updating Libraries");
|
|
||||||
return NetClient.MakePost($"{baseUrl}/api/v1/libraries/{libraryId}/scan", auth);
|
|
||||||
}
|
|
||||||
|
|
||||||
public struct KomgaLibrary
|
|
||||||
{
|
|
||||||
public string id { get; }
|
|
||||||
public string name { get; }
|
|
||||||
|
|
||||||
public KomgaLibrary(string id, string name)
|
|
||||||
{
|
|
||||||
this.id = id;
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static class NetClient
|
|
||||||
{
|
|
||||||
public static Stream MakeRequest(string url, string auth)
|
|
||||||
{
|
|
||||||
HttpClient client = new();
|
|
||||||
HttpRequestMessage requestMessage = new HttpRequestMessage
|
|
||||||
{
|
|
||||||
Method = HttpMethod.Get,
|
|
||||||
RequestUri = new Uri(url),
|
|
||||||
Headers =
|
|
||||||
{
|
|
||||||
{ "Accept", "application/json" },
|
|
||||||
{ "Authorization", new AuthenticationHeaderValue("Basic", auth).ToString() }
|
|
||||||
}
|
|
||||||
};
|
|
||||||
HttpResponseMessage response = client.Send(requestMessage);
|
|
||||||
Stream resultString = response.IsSuccessStatusCode ? response.Content.ReadAsStream() : Stream.Null;
|
|
||||||
return resultString;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static bool MakePost(string url, string auth)
|
|
||||||
{
|
|
||||||
HttpClient client = new();
|
|
||||||
HttpRequestMessage requestMessage = new HttpRequestMessage
|
|
||||||
{
|
|
||||||
Method = HttpMethod.Post,
|
|
||||||
RequestUri = new Uri(url),
|
|
||||||
Headers =
|
|
||||||
{
|
|
||||||
{ "Accept", "application/json" },
|
|
||||||
{ "Authorization", new AuthenticationHeaderValue("Basic", auth).ToString() }
|
|
||||||
}
|
|
||||||
};
|
|
||||||
HttpResponseMessage response = client.Send(requestMessage);
|
|
||||||
return response.IsSuccessStatusCode;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
100
Tranga/LibraryConnectors/Kavita.cs
Normal file
100
Tranga/LibraryConnectors/Kavita.cs
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
using System.Text.Json.Nodes;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using JsonSerializer = System.Text.Json.JsonSerializer;
|
||||||
|
|
||||||
|
namespace Tranga.LibraryConnectors;
|
||||||
|
|
||||||
|
public class Kavita : LibraryConnector
|
||||||
|
{
|
||||||
|
|
||||||
|
public Kavita(GlobalBase clone, string baseUrl, string username, string password) :
|
||||||
|
base(clone, baseUrl, GetToken(baseUrl, username, password), LibraryType.Kavita)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonConstructor]
|
||||||
|
public Kavita(GlobalBase clone, string baseUrl, string auth) : base(clone, baseUrl, auth, LibraryType.Kavita)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString()
|
||||||
|
{
|
||||||
|
return $"Kavita {baseUrl}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GetToken(string baseUrl, string username, string password)
|
||||||
|
{
|
||||||
|
HttpClient client = new()
|
||||||
|
{
|
||||||
|
DefaultRequestHeaders =
|
||||||
|
{
|
||||||
|
{ "Accept", "application/json" }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
HttpRequestMessage requestMessage = new ()
|
||||||
|
{
|
||||||
|
Method = HttpMethod.Post,
|
||||||
|
RequestUri = new Uri($"{baseUrl}/api/Account/login"),
|
||||||
|
Content = new StringContent($"{{\"username\":\"{username}\",\"password\":\"{password}\"}}", System.Text.Encoding.UTF8, "application/json")
|
||||||
|
};
|
||||||
|
|
||||||
|
HttpResponseMessage response = client.Send(requestMessage);
|
||||||
|
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(response.Content.ReadAsStream());
|
||||||
|
if (result is not null)
|
||||||
|
return result["token"]!.GetValue<string>();
|
||||||
|
else throw new Exception("Did not receive token.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void UpdateLibrary()
|
||||||
|
{
|
||||||
|
Log("Updating libraries.");
|
||||||
|
foreach (KavitaLibrary lib in GetLibraries())
|
||||||
|
NetClient.MakePost($"{baseUrl}/api/Library/scan?libraryId={lib.id}", "Bearer", auth, logger);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Fetches all libraries available to the user
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>Array of KavitaLibrary</returns>
|
||||||
|
private IEnumerable<KavitaLibrary> GetLibraries()
|
||||||
|
{
|
||||||
|
Log("Getting libraries.");
|
||||||
|
Stream data = NetClient.MakeRequest($"{baseUrl}/api/Library", "Bearer", auth, logger);
|
||||||
|
if (data == Stream.Null)
|
||||||
|
{
|
||||||
|
Log("No libraries returned");
|
||||||
|
return Array.Empty<KavitaLibrary>();
|
||||||
|
}
|
||||||
|
JsonArray? result = JsonSerializer.Deserialize<JsonArray>(data);
|
||||||
|
if (result is null)
|
||||||
|
{
|
||||||
|
Log("No libraries returned");
|
||||||
|
return Array.Empty<KavitaLibrary>();
|
||||||
|
}
|
||||||
|
|
||||||
|
HashSet<KavitaLibrary> ret = new();
|
||||||
|
|
||||||
|
foreach (JsonNode? jsonNode in result)
|
||||||
|
{
|
||||||
|
var jObject = (JsonObject?)jsonNode;
|
||||||
|
int libraryId = jObject!["id"]!.GetValue<int>();
|
||||||
|
string libraryName = jObject["name"]!.GetValue<string>();
|
||||||
|
ret.Add(new KavitaLibrary(libraryId, libraryName));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct KavitaLibrary
|
||||||
|
{
|
||||||
|
public int id { get; }
|
||||||
|
// ReSharper disable once UnusedAutoPropertyAccessor.Local
|
||||||
|
public string name { get; }
|
||||||
|
|
||||||
|
public KavitaLibrary(int id, string name)
|
||||||
|
{
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
80
Tranga/LibraryConnectors/Komga.cs
Normal file
80
Tranga/LibraryConnectors/Komga.cs
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
using System.Text.Json.Nodes;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using JsonSerializer = System.Text.Json.JsonSerializer;
|
||||||
|
|
||||||
|
namespace Tranga.LibraryConnectors;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Provides connectivity to Komga-API
|
||||||
|
/// Can fetch and update libraries
|
||||||
|
/// </summary>
|
||||||
|
public class Komga : LibraryConnector
|
||||||
|
{
|
||||||
|
public Komga(GlobalBase clone, string baseUrl, string username, string password)
|
||||||
|
: base(clone, baseUrl, Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}")), LibraryType.Komga)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonConstructor]
|
||||||
|
public Komga(GlobalBase clone, string baseUrl, string auth) : base(clone, baseUrl, auth, LibraryType.Komga)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString()
|
||||||
|
{
|
||||||
|
return $"Komga {baseUrl}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void UpdateLibrary()
|
||||||
|
{
|
||||||
|
Log("Updating libraries.");
|
||||||
|
foreach (KomgaLibrary lib in GetLibraries())
|
||||||
|
NetClient.MakePost($"{baseUrl}/api/v1/libraries/{lib.id}/scan", "Basic", auth, logger);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Fetches all libraries available to the user
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>Array of KomgaLibraries</returns>
|
||||||
|
private IEnumerable<KomgaLibrary> GetLibraries()
|
||||||
|
{
|
||||||
|
Log("Getting Libraries");
|
||||||
|
Stream data = NetClient.MakeRequest($"{baseUrl}/api/v1/libraries", "Basic", auth, logger);
|
||||||
|
if (data == Stream.Null)
|
||||||
|
{
|
||||||
|
Log("No libraries returned");
|
||||||
|
return Array.Empty<KomgaLibrary>();
|
||||||
|
}
|
||||||
|
JsonArray? result = JsonSerializer.Deserialize<JsonArray>(data);
|
||||||
|
if (result is null)
|
||||||
|
{
|
||||||
|
Log("No libraries returned");
|
||||||
|
return Array.Empty<KomgaLibrary>();
|
||||||
|
}
|
||||||
|
|
||||||
|
HashSet<KomgaLibrary> ret = new();
|
||||||
|
|
||||||
|
foreach (JsonNode? jsonNode in result)
|
||||||
|
{
|
||||||
|
var jObject = (JsonObject?)jsonNode;
|
||||||
|
string libraryId = jObject!["id"]!.GetValue<string>();
|
||||||
|
string libraryName = jObject["name"]!.GetValue<string>();
|
||||||
|
ret.Add(new KomgaLibrary(libraryId, libraryName));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct KomgaLibrary
|
||||||
|
{
|
||||||
|
public string id { get; }
|
||||||
|
// ReSharper disable once UnusedAutoPropertyAccessor.Local
|
||||||
|
public string name { get; }
|
||||||
|
|
||||||
|
public KomgaLibrary(string id, string name)
|
||||||
|
{
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
78
Tranga/LibraryConnectors/LibraryConnector.cs
Normal file
78
Tranga/LibraryConnectors/LibraryConnector.cs
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using Logging;
|
||||||
|
|
||||||
|
namespace Tranga.LibraryConnectors;
|
||||||
|
|
||||||
|
public abstract class LibraryConnector : GlobalBase
|
||||||
|
{
|
||||||
|
public enum LibraryType : byte
|
||||||
|
{
|
||||||
|
Komga = 0,
|
||||||
|
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 LibraryConnector(GlobalBase clone, string baseUrl, string auth, LibraryType libraryType) : base(clone)
|
||||||
|
{
|
||||||
|
this.baseUrl = baseUrl;
|
||||||
|
this.auth = auth;
|
||||||
|
this.libraryType = libraryType;
|
||||||
|
}
|
||||||
|
public abstract void UpdateLibrary();
|
||||||
|
|
||||||
|
protected static class NetClient
|
||||||
|
{
|
||||||
|
public static Stream MakeRequest(string url, string authScheme, string auth, Logger? logger)
|
||||||
|
{
|
||||||
|
HttpClient client = new();
|
||||||
|
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, auth);
|
||||||
|
|
||||||
|
HttpRequestMessage requestMessage = new ()
|
||||||
|
{
|
||||||
|
Method = HttpMethod.Get,
|
||||||
|
RequestUri = new Uri(url)
|
||||||
|
};
|
||||||
|
HttpResponseMessage response = client.Send(requestMessage);
|
||||||
|
logger?.WriteLine("LibraryManager.NetClient", $"GET {url} -> {(int)response.StatusCode}: {response.ReasonPhrase}");
|
||||||
|
|
||||||
|
if(response.StatusCode is HttpStatusCode.Unauthorized && response.RequestMessage!.RequestUri!.AbsoluteUri != url)
|
||||||
|
return MakeRequest(response.RequestMessage!.RequestUri!.AbsoluteUri, authScheme, auth, logger);
|
||||||
|
else if (response.IsSuccessStatusCode)
|
||||||
|
return response.Content.ReadAsStream();
|
||||||
|
else
|
||||||
|
return Stream.Null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool MakePost(string url, string authScheme, string auth, Logger? logger)
|
||||||
|
{
|
||||||
|
HttpClient client = new()
|
||||||
|
{
|
||||||
|
DefaultRequestHeaders =
|
||||||
|
{
|
||||||
|
{ "Accept", "application/json" },
|
||||||
|
{ "Authorization", new AuthenticationHeaderValue(authScheme, auth).ToString() }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
HttpRequestMessage requestMessage = new ()
|
||||||
|
{
|
||||||
|
Method = HttpMethod.Post,
|
||||||
|
RequestUri = new Uri(url)
|
||||||
|
};
|
||||||
|
HttpResponseMessage response = client.Send(requestMessage);
|
||||||
|
logger?.WriteLine("LibraryManager.NetClient", $"POST {url} -> {(int)response.StatusCode}: {response.ReasonPhrase}");
|
||||||
|
|
||||||
|
if(response.StatusCode is HttpStatusCode.Unauthorized && response.RequestMessage!.RequestUri!.AbsoluteUri != url)
|
||||||
|
return MakePost(response.RequestMessage!.RequestUri!.AbsoluteUri, authScheme, auth, logger);
|
||||||
|
else if (response.IsSuccessStatusCode)
|
||||||
|
return true;
|
||||||
|
else
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
45
Tranga/LibraryConnectors/LibraryManagerJsonConverter.cs
Normal file
45
Tranga/LibraryConnectors/LibraryManagerJsonConverter.cs
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
|
||||||
|
namespace Tranga.LibraryConnectors;
|
||||||
|
|
||||||
|
public class LibraryManagerJsonConverter : JsonConverter
|
||||||
|
{
|
||||||
|
private GlobalBase _clone;
|
||||||
|
|
||||||
|
internal LibraryManagerJsonConverter(GlobalBase clone)
|
||||||
|
{
|
||||||
|
this._clone = clone;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool CanConvert(Type objectType)
|
||||||
|
{
|
||||||
|
return (objectType == typeof(LibraryConnector));
|
||||||
|
}
|
||||||
|
|
||||||
|
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
|
||||||
|
{
|
||||||
|
JObject jo = JObject.Load(reader);
|
||||||
|
if (jo["libraryType"]!.Value<byte>() == (byte)LibraryConnector.LibraryType.Komga)
|
||||||
|
return new Komga(this._clone,
|
||||||
|
jo.GetValue("baseUrl")!.Value<string>()!,
|
||||||
|
jo.GetValue("auth")!.Value<string>()!);
|
||||||
|
|
||||||
|
if (jo["libraryType"]!.Value<byte>() == (byte)LibraryConnector.LibraryType.Kavita)
|
||||||
|
return new Kavita(this._clone,
|
||||||
|
jo.GetValue("baseUrl")!.Value<string>()!,
|
||||||
|
jo.GetValue("auth")!.Value<string>()!);
|
||||||
|
|
||||||
|
throw new Exception();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool CanWrite => false;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Don't call this
|
||||||
|
/// </summary>
|
||||||
|
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
|
||||||
|
{
|
||||||
|
throw new Exception("Dont call this");
|
||||||
|
}
|
||||||
|
}
|
166
Tranga/Manga.cs
Normal file
166
Tranga/Manga.cs
Normal file
@ -0,0 +1,166 @@
|
|||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using static System.IO.UnixFileMode;
|
||||||
|
|
||||||
|
namespace Tranga;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Contains information on a Publication (Manga)
|
||||||
|
/// </summary>
|
||||||
|
public struct Manga
|
||||||
|
{
|
||||||
|
public string sortName { get; }
|
||||||
|
public List<string> authors { get; }
|
||||||
|
// ReSharper disable once UnusedAutoPropertyAccessor.Global
|
||||||
|
public Dictionary<string,string> altTitles { get; }
|
||||||
|
// ReSharper disable once MemberCanBePrivate.Global
|
||||||
|
public string? description { get; }
|
||||||
|
public string[] tags { get; }
|
||||||
|
// ReSharper disable once UnusedAutoPropertyAccessor.Global
|
||||||
|
public string? coverUrl { get; }
|
||||||
|
public string? coverFileNameInCache { get; set; }
|
||||||
|
// 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; private set; }
|
||||||
|
public string publicationId { get; }
|
||||||
|
public string internalId { get; }
|
||||||
|
public float ignoreChaptersBelow { get; set; }
|
||||||
|
|
||||||
|
private static readonly Regex LegalCharacters = new (@"[A-Z]*[a-z]*[0-9]* *\.*-*,*'*\'*\)*\(*~*!*");
|
||||||
|
|
||||||
|
[JsonConstructor]
|
||||||
|
public Manga(string sortName, List<string> authors, string? description, Dictionary<string,string> altTitles, string[] tags, string? coverUrl, 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;
|
||||||
|
this.description = description;
|
||||||
|
this.altTitles = altTitles;
|
||||||
|
this.tags = tags;
|
||||||
|
this.coverFileNameInCache = coverFileNameInCache;
|
||||||
|
this.coverUrl = coverUrl;
|
||||||
|
this.links = links ?? new Dictionary<string, string>();
|
||||||
|
this.year = year;
|
||||||
|
this.originalLanguage = originalLanguage;
|
||||||
|
this.status = status;
|
||||||
|
this.publicationId = publicationId;
|
||||||
|
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 override string ToString()
|
||||||
|
{
|
||||||
|
return $"Publication {sortName} {internalId}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public string CreatePublicationFolder(string downloadDirectory)
|
||||||
|
{
|
||||||
|
string publicationFolder = Path.Join(downloadDirectory, this.folderName);
|
||||||
|
if(!Directory.Exists(publicationFolder))
|
||||||
|
Directory.CreateDirectory(publicationFolder);
|
||||||
|
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||||
|
File.SetUnixFileMode(publicationFolder, GroupRead | GroupWrite | GroupExecute | OtherRead | OtherWrite | OtherExecute | UserRead | UserWrite | UserExecute);
|
||||||
|
return publicationFolder;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void MovePublicationFolder(string downloadDirectory, string newFolderName)
|
||||||
|
{
|
||||||
|
string oldPath = Path.Join(downloadDirectory, this.folderName);
|
||||||
|
this.folderName = newFolderName;
|
||||||
|
string newPath = CreatePublicationFolder(downloadDirectory);
|
||||||
|
if(Directory.Exists(oldPath))
|
||||||
|
Directory.Move(oldPath, newPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SaveSeriesInfoJson(string downloadDirectory)
|
||||||
|
{
|
||||||
|
string publicationFolder = CreatePublicationFolder(downloadDirectory);
|
||||||
|
string seriesInfoPath = Path.Join(publicationFolder, "series.json");
|
||||||
|
if(!File.Exists(seriesInfoPath))
|
||||||
|
File.WriteAllText(seriesInfoPath,this.GetSeriesInfoJson());
|
||||||
|
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||||
|
File.SetUnixFileMode(seriesInfoPath, GroupRead | GroupWrite | OtherRead | OtherWrite | UserRead | UserWrite);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <returns>Serialized JSON String for series.json</returns>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
//Only for series.json
|
||||||
|
private struct SeriesInfo
|
||||||
|
{
|
||||||
|
// ReSharper disable once UnusedAutoPropertyAccessor.Local we need it, trust
|
||||||
|
[JsonRequired]public Metadata metadata { get; }
|
||||||
|
public SeriesInfo(Metadata metadata) => this.metadata = metadata;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Only for series.json what an abomination, why are all the fields not-null????
|
||||||
|
private struct Metadata
|
||||||
|
{
|
||||||
|
// ReSharper disable UnusedAutoPropertyAccessor.Local we need them all, trust me
|
||||||
|
[JsonRequired] public string type { get; }
|
||||||
|
[JsonRequired] public string publisher { get; }
|
||||||
|
// ReSharper disable twice IdentifierTypo
|
||||||
|
[JsonRequired] public int comicid { get; }
|
||||||
|
[JsonRequired] public string booktype { get; }
|
||||||
|
// ReSharper disable InconsistentNaming This one property is capitalized. Why?
|
||||||
|
[JsonRequired] public string ComicImage { get; }
|
||||||
|
[JsonRequired] public int total_issues { get; }
|
||||||
|
[JsonRequired] public string publication_run { get; }
|
||||||
|
[JsonRequired]public string name { get; }
|
||||||
|
[JsonRequired]public string year { get; }
|
||||||
|
[JsonRequired]public string status { get; }
|
||||||
|
[JsonRequired]public string description_text { get; }
|
||||||
|
[JsonIgnore] public static string[] continuing = new[]
|
||||||
|
{
|
||||||
|
"ongoing",
|
||||||
|
"hiatus",
|
||||||
|
"in corso",
|
||||||
|
"in pausa"
|
||||||
|
};
|
||||||
|
[JsonIgnore] public static string[] ended = new[]
|
||||||
|
{
|
||||||
|
"completed",
|
||||||
|
"cancelled",
|
||||||
|
"discontinued",
|
||||||
|
"finito",
|
||||||
|
"cancellato",
|
||||||
|
"droppato"
|
||||||
|
};
|
||||||
|
|
||||||
|
public Metadata(string name, string year, string status, string description_text)
|
||||||
|
{
|
||||||
|
this.name = name;
|
||||||
|
this.year = year;
|
||||||
|
if(continuing.Contains(status.ToLower()))
|
||||||
|
this.status = "Continuing";
|
||||||
|
else if(ended.Contains(status.ToLower()))
|
||||||
|
this.status = "Ended";
|
||||||
|
else
|
||||||
|
this.status = status;
|
||||||
|
this.description_text = description_text;
|
||||||
|
|
||||||
|
//kill it with fire, but otherwise Komga will not parse
|
||||||
|
type = "Manga";
|
||||||
|
publisher = "";
|
||||||
|
comicid = 0;
|
||||||
|
booktype = "";
|
||||||
|
ComicImage = "";
|
||||||
|
total_issues = 0;
|
||||||
|
publication_run = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
95
Tranga/MangaConnectors/ChromiumDownloadClient.cs
Normal file
95
Tranga/MangaConnectors/ChromiumDownloadClient.cs
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using HtmlAgilityPack;
|
||||||
|
using PuppeteerSharp;
|
||||||
|
|
||||||
|
namespace Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
internal class ChromiumDownloadClient : DownloadClient
|
||||||
|
{
|
||||||
|
private IBrowser browser { get; set; }
|
||||||
|
private const string ChromiumVersion = "1154303";
|
||||||
|
|
||||||
|
private async Task<IBrowser> DownloadBrowser()
|
||||||
|
{
|
||||||
|
BrowserFetcher browserFetcher = new BrowserFetcher();
|
||||||
|
foreach(string rev in browserFetcher.LocalRevisions().Where(rev => rev != ChromiumVersion))
|
||||||
|
browserFetcher.Remove(rev);
|
||||||
|
if (!browserFetcher.LocalRevisions().Contains(ChromiumVersion))
|
||||||
|
{
|
||||||
|
Log("Downloading headless browser");
|
||||||
|
DateTime last = DateTime.Now.Subtract(TimeSpan.FromSeconds(5));
|
||||||
|
browserFetcher.DownloadProgressChanged += (_, args) =>
|
||||||
|
{
|
||||||
|
double currentBytes = Convert.ToDouble(args.BytesReceived) / Convert.ToDouble(args.TotalBytesToReceive);
|
||||||
|
if (args.TotalBytesToReceive == args.BytesReceived)
|
||||||
|
Log("Browser downloaded.");
|
||||||
|
else if (DateTime.Now > last.AddSeconds(1))
|
||||||
|
{
|
||||||
|
Log($"Browser download progress: {currentBytes:P2}");
|
||||||
|
last = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
};
|
||||||
|
if (!browserFetcher.CanDownloadAsync(ChromiumVersion).Result)
|
||||||
|
{
|
||||||
|
Log($"Can't download browser version {ChromiumVersion}");
|
||||||
|
throw new Exception();
|
||||||
|
}
|
||||||
|
await browserFetcher.DownloadAsync(ChromiumVersion);
|
||||||
|
}
|
||||||
|
|
||||||
|
Log("Starting Browser.");
|
||||||
|
return await Puppeteer.LaunchAsync(new LaunchOptions
|
||||||
|
{
|
||||||
|
Headless = true,
|
||||||
|
ExecutablePath = browserFetcher.GetExecutablePath(ChromiumVersion),
|
||||||
|
Args = new [] {
|
||||||
|
"--disable-gpu",
|
||||||
|
"--disable-dev-shm-usage",
|
||||||
|
"--disable-setuid-sandbox",
|
||||||
|
"--no-sandbox"}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public ChromiumDownloadClient(GlobalBase clone, Dictionary<byte, int> rateLimitRequestsPerMinute) : base(clone, rateLimitRequestsPerMinute)
|
||||||
|
{
|
||||||
|
this.browser = DownloadBrowser().Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override RequestResult MakeRequestInternal(string url, string? referrer = null)
|
||||||
|
{
|
||||||
|
IPage page = this.browser!.NewPageAsync().Result;
|
||||||
|
IResponse response = page.GoToAsync(url, WaitUntilNavigation.DOMContentLoaded).Result;
|
||||||
|
|
||||||
|
Stream stream = Stream.Null;
|
||||||
|
HtmlDocument? document = null;
|
||||||
|
|
||||||
|
if (response.Headers.TryGetValue("Content-Type", out string? content))
|
||||||
|
{
|
||||||
|
if (content.Contains("text/html"))
|
||||||
|
{
|
||||||
|
string htmlString = page.GetContentAsync().Result;
|
||||||
|
stream = new MemoryStream(Encoding.Default.GetBytes(htmlString));
|
||||||
|
document = new ();
|
||||||
|
document.LoadHtml(htmlString);
|
||||||
|
}else if (content.Contains("image"))
|
||||||
|
{
|
||||||
|
stream = new MemoryStream(response.BufferAsync().Result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
page.CloseAsync();
|
||||||
|
return new RequestResult(HttpStatusCode.InternalServerError, null, Stream.Null);
|
||||||
|
}
|
||||||
|
|
||||||
|
page.CloseAsync();
|
||||||
|
return new RequestResult(response.Status, document, stream, false, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Close()
|
||||||
|
{
|
||||||
|
this.browser.CloseAsync();
|
||||||
|
}
|
||||||
|
}
|
66
Tranga/MangaConnectors/DownloadClient.cs
Normal file
66
Tranga/MangaConnectors/DownloadClient.cs
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
using System.Net;
|
||||||
|
using HtmlAgilityPack;
|
||||||
|
|
||||||
|
namespace Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
internal abstract class DownloadClient : GlobalBase
|
||||||
|
{
|
||||||
|
private readonly Dictionary<byte, DateTime> _lastExecutedRateLimit;
|
||||||
|
private readonly Dictionary<byte, TimeSpan> _rateLimit;
|
||||||
|
|
||||||
|
protected DownloadClient(GlobalBase clone, Dictionary<byte, int> rateLimitRequestsPerMinute) : base(clone)
|
||||||
|
{
|
||||||
|
this._lastExecutedRateLimit = new();
|
||||||
|
_rateLimit = new();
|
||||||
|
foreach (KeyValuePair<byte, int> limit in rateLimitRequestsPerMinute)
|
||||||
|
_rateLimit.Add(limit.Key, TimeSpan.FromMinutes(1).Divide(limit.Value));
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
{
|
||||||
|
Log("RequestType not configured for rate-limit.");
|
||||||
|
return new RequestResult(HttpStatusCode.NotAcceptable, null, Stream.Null);
|
||||||
|
}
|
||||||
|
|
||||||
|
TimeSpan rateLimitTimeout = _rateLimit[requestType]
|
||||||
|
.Subtract(DateTime.Now.Subtract(_lastExecutedRateLimit[requestType]));
|
||||||
|
|
||||||
|
if (rateLimitTimeout > TimeSpan.Zero)
|
||||||
|
Thread.Sleep(rateLimitTimeout);
|
||||||
|
|
||||||
|
RequestResult result = MakeRequestInternal(url, referrer);
|
||||||
|
_lastExecutedRateLimit[requestType] = DateTime.Now;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract RequestResult MakeRequestInternal(string url, string? referrer = null);
|
||||||
|
public abstract void Close();
|
||||||
|
|
||||||
|
public struct RequestResult
|
||||||
|
{
|
||||||
|
public HttpStatusCode statusCode { get; }
|
||||||
|
public Stream result { get; }
|
||||||
|
public bool hasBeenRedirected { get; }
|
||||||
|
public string? redirectedToUrl { get; }
|
||||||
|
public HtmlDocument? htmlDocument { get; }
|
||||||
|
|
||||||
|
public RequestResult(HttpStatusCode statusCode, HtmlDocument? htmlDocument, Stream result)
|
||||||
|
{
|
||||||
|
this.statusCode = statusCode;
|
||||||
|
this.htmlDocument = htmlDocument;
|
||||||
|
this.result = result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public RequestResult(HttpStatusCode statusCode, HtmlDocument? htmlDocument, Stream result, bool hasBeenRedirected, string redirectedTo)
|
||||||
|
: this(statusCode, htmlDocument, result)
|
||||||
|
{
|
||||||
|
this.hasBeenRedirected = hasBeenRedirected;
|
||||||
|
redirectedToUrl = redirectedTo;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
70
Tranga/MangaConnectors/HttpDownloadClient.cs
Normal file
70
Tranga/MangaConnectors/HttpDownloadClient.cs
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
using System.Net.Http.Headers;
|
||||||
|
using HtmlAgilityPack;
|
||||||
|
|
||||||
|
namespace Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
internal class HttpDownloadClient : DownloadClient
|
||||||
|
{
|
||||||
|
private static readonly HttpClient Client = new()
|
||||||
|
{
|
||||||
|
Timeout = TimeSpan.FromSeconds(60),
|
||||||
|
DefaultRequestHeaders =
|
||||||
|
{
|
||||||
|
UserAgent =
|
||||||
|
{
|
||||||
|
new ProductInfoHeaderValue("Tranga", "0.1")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
public HttpDownloadClient(GlobalBase clone, Dictionary<byte, int> rateLimitRequestsPerMinute) : base(clone, rateLimitRequestsPerMinute)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override RequestResult MakeRequestInternal(string url, string? referrer = null)
|
||||||
|
{
|
||||||
|
HttpResponseMessage? response = null;
|
||||||
|
while (response is null)
|
||||||
|
{
|
||||||
|
HttpRequestMessage requestMessage = new(HttpMethod.Get, url);
|
||||||
|
if (referrer is not null)
|
||||||
|
requestMessage.Headers.Referrer = new Uri(referrer);
|
||||||
|
//Log($"Requesting {requestType} {url}");
|
||||||
|
response = Client.Send(requestMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
Log($"Request-Error {response.StatusCode}: {response.ReasonPhrase}");
|
||||||
|
return new RequestResult(response.StatusCode, null, Stream.Null);
|
||||||
|
}
|
||||||
|
|
||||||
|
Stream stream = response.Content.ReadAsStream();
|
||||||
|
|
||||||
|
HtmlDocument? document = null;
|
||||||
|
|
||||||
|
if (response.Content.Headers.ContentType?.MediaType == "text/html")
|
||||||
|
{
|
||||||
|
StreamReader reader = new (stream);
|
||||||
|
document = new ();
|
||||||
|
document.LoadHtml(reader.ReadToEnd());
|
||||||
|
stream.Position = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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, document, stream, true,
|
||||||
|
response.RequestMessage.RequestUri.AbsoluteUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new RequestResult(response.StatusCode, document, stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Close()
|
||||||
|
{
|
||||||
|
Log("Closing.");
|
||||||
|
}
|
||||||
|
}
|
254
Tranga/MangaConnectors/MangaConnector.cs
Normal file
254
Tranga/MangaConnectors/MangaConnector.cs
Normal file
@ -0,0 +1,254 @@
|
|||||||
|
using System.IO.Compression;
|
||||||
|
using System.Net;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Tranga.Jobs;
|
||||||
|
using static System.IO.UnixFileMode;
|
||||||
|
|
||||||
|
namespace Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Base-Class for all Connectors
|
||||||
|
/// Provides some methods to be used by all Connectors, as well as a DownloadClient
|
||||||
|
/// </summary>
|
||||||
|
public abstract class MangaConnector : GlobalBase
|
||||||
|
{
|
||||||
|
internal DownloadClient downloadClient { get; init; } = null!;
|
||||||
|
|
||||||
|
public void StopDownloadClient()
|
||||||
|
{
|
||||||
|
downloadClient.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected MangaConnector(GlobalBase clone, string name) : base(clone)
|
||||||
|
{
|
||||||
|
this.name = name;
|
||||||
|
Directory.CreateDirectory(settings.coverImageCache);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string name { get; } //Name of the Connector (e.g. Website)
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns all Publications with the given string.
|
||||||
|
/// If the string is empty or null, returns all Publication of the Connector
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="publicationTitle">Search-Query</param>
|
||||||
|
/// <returns>Publications matching the query</returns>
|
||||||
|
public abstract Manga[] GetManga(string publicationTitle = "");
|
||||||
|
|
||||||
|
public abstract Manga? GetMangaFromUrl(string url);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns all Chapters of the publication in the provided language.
|
||||||
|
/// If the language is empty or null, returns all Chapters in all Languages.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="manga">Publication to get Chapters for</param>
|
||||||
|
/// <param name="language">Language of the Chapters</param>
|
||||||
|
/// <returns>Array of Chapters matching Publication and Language</returns>
|
||||||
|
public abstract Chapter[] GetChapters(Manga manga, string language="en");
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Updates the available Chapters of a Publication
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="manga">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 Chapter[] GetNewChapters(Manga manga, string language = "en")
|
||||||
|
{
|
||||||
|
Log($"Getting new Chapters for {manga}");
|
||||||
|
Chapter[] newChapters = this.GetChapters(manga, language);
|
||||||
|
Log($"Checking for duplicates {manga}");
|
||||||
|
List<Chapter> newChaptersList = newChapters.Where(nChapter =>
|
||||||
|
float.Parse(nChapter.chapterNumber, numberFormatDecimalPoint) > manga.ignoreChaptersBelow &&
|
||||||
|
!nChapter.CheckChapterIsDownloaded(settings.downloadLocation)).ToList();
|
||||||
|
Log($"{newChaptersList.Count} new chapters. {manga}");
|
||||||
|
|
||||||
|
return newChaptersList.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Chapter[] SelectChapters(Manga manga, string searchTerm, string? language = null)
|
||||||
|
{
|
||||||
|
Chapter[] availableChapters = this.GetChapters(manga, language??"en");
|
||||||
|
Regex volumeRegex = new ("((v(ol)*(olume)*){1} *([0-9]+(-[0-9]+)?){1})", RegexOptions.IgnoreCase);
|
||||||
|
Regex chapterRegex = new ("((c(h)*(hapter)*){1} *([0-9]+(-[0-9]+)?){1})", RegexOptions.IgnoreCase);
|
||||||
|
Regex singleResultRegex = new("([0-9]+)", RegexOptions.IgnoreCase);
|
||||||
|
Regex rangeResultRegex = new("([0-9]+(-[0-9]+))", RegexOptions.IgnoreCase);
|
||||||
|
Regex allRegex = new("a(ll)?", RegexOptions.IgnoreCase);
|
||||||
|
if (volumeRegex.IsMatch(searchTerm) && chapterRegex.IsMatch(searchTerm))
|
||||||
|
{
|
||||||
|
string volume = singleResultRegex.Match(volumeRegex.Match(searchTerm).Value).Value;
|
||||||
|
string chapter = singleResultRegex.Match(chapterRegex.Match(searchTerm).Value).Value;
|
||||||
|
return availableChapters.Where(aCh => aCh.volumeNumber is not null &&
|
||||||
|
aCh.volumeNumber.Equals(volume, StringComparison.InvariantCultureIgnoreCase) &&
|
||||||
|
aCh.chapterNumber.Equals(chapter, StringComparison.InvariantCultureIgnoreCase))
|
||||||
|
.ToArray();
|
||||||
|
}
|
||||||
|
else if (volumeRegex.IsMatch(searchTerm))
|
||||||
|
{
|
||||||
|
string volume = volumeRegex.Match(searchTerm).Value;
|
||||||
|
if (rangeResultRegex.IsMatch(volume))
|
||||||
|
{
|
||||||
|
string range = rangeResultRegex.Match(volume).Value;
|
||||||
|
int start = Convert.ToInt32(range.Split('-')[0]);
|
||||||
|
int end = Convert.ToInt32(range.Split('-')[1]);
|
||||||
|
return availableChapters.Where(aCh => aCh.volumeNumber is not null &&
|
||||||
|
Convert.ToInt32(aCh.volumeNumber) >= start &&
|
||||||
|
Convert.ToInt32(aCh.volumeNumber) <= end).ToArray();
|
||||||
|
}
|
||||||
|
else if (singleResultRegex.IsMatch(volume))
|
||||||
|
{
|
||||||
|
string volumeNumber = singleResultRegex.Match(volume).Value;
|
||||||
|
return availableChapters.Where(aCh =>
|
||||||
|
aCh.volumeNumber is not null &&
|
||||||
|
aCh.volumeNumber.Equals(volumeNumber, StringComparison.InvariantCultureIgnoreCase)).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
else if (chapterRegex.IsMatch(searchTerm))
|
||||||
|
{
|
||||||
|
string chapter = chapterRegex.Match(searchTerm).Value;
|
||||||
|
if (rangeResultRegex.IsMatch(chapter))
|
||||||
|
{
|
||||||
|
string range = rangeResultRegex.Match(chapter).Value;
|
||||||
|
int start = Convert.ToInt32(range.Split('-')[0]);
|
||||||
|
int end = Convert.ToInt32(range.Split('-')[1]);
|
||||||
|
return availableChapters.Where(aCh => Convert.ToInt32(aCh.chapterNumber) >= start &&
|
||||||
|
Convert.ToInt32(aCh.chapterNumber) <= end).ToArray();
|
||||||
|
}
|
||||||
|
else if (singleResultRegex.IsMatch(chapter))
|
||||||
|
{
|
||||||
|
string chapterNumber = singleResultRegex.Match(chapter).Value;
|
||||||
|
return availableChapters.Where(aCh =>
|
||||||
|
aCh.chapterNumber.Equals(chapterNumber, StringComparison.InvariantCultureIgnoreCase)).ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (rangeResultRegex.IsMatch(searchTerm))
|
||||||
|
{
|
||||||
|
int start = Convert.ToInt32(searchTerm.Split('-')[0]);
|
||||||
|
int end = Convert.ToInt32(searchTerm.Split('-')[1]);
|
||||||
|
return availableChapters[start..(end + 1)];
|
||||||
|
}
|
||||||
|
else if(singleResultRegex.IsMatch(searchTerm))
|
||||||
|
return new [] { availableChapters[Convert.ToInt32(searchTerm)] };
|
||||||
|
else if (allRegex.IsMatch(searchTerm))
|
||||||
|
return availableChapters;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Array.Empty<Chapter>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public abstract HttpStatusCode DownloadChapter(Chapter chapter, ProgressToken? progressToken = null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Copies the already downloaded cover from cache to downloadLocation
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="manga">Publication to retrieve Cover for</param>
|
||||||
|
public void CopyCoverFromCacheToDownloadLocation(Manga manga)
|
||||||
|
{
|
||||||
|
Log($"Copy cover {manga}");
|
||||||
|
//Check if Publication already has a Folder and cover
|
||||||
|
string publicationFolder = manga.CreatePublicationFolder(settings.downloadLocation);
|
||||||
|
DirectoryInfo dirInfo = new (publicationFolder);
|
||||||
|
if (dirInfo.EnumerateFiles().Any(info => info.Name.Contains("cover", StringComparison.InvariantCultureIgnoreCase)))
|
||||||
|
{
|
||||||
|
Log($"Cover exists {manga}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string fileInCache = Path.Join(settings.coverImageCache, manga.coverFileNameInCache);
|
||||||
|
string newFilePath = Path.Join(publicationFolder, $"cover.{Path.GetFileName(fileInCache).Split('.')[^1]}" );
|
||||||
|
Log($"Cloning cover {fileInCache} -> {newFilePath}");
|
||||||
|
File.Copy(fileInCache, newFilePath, true);
|
||||||
|
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||||
|
File.SetUnixFileMode(newFilePath, GroupRead | GroupWrite | OtherRead | OtherWrite | UserRead | UserWrite);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Downloads Image from URL and saves it to the given path(incl. fileName)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="imageUrl"></param>
|
||||||
|
/// <param name="fullPath"></param>
|
||||||
|
/// <param name="requestType">RequestType for Rate-Limit</param>
|
||||||
|
/// <param name="referrer">referrer used in html request header</param>
|
||||||
|
private HttpStatusCode DownloadImage(string imageUrl, string fullPath, byte requestType, string? referrer = null)
|
||||||
|
{
|
||||||
|
DownloadClient.RequestResult requestResult = downloadClient.MakeRequest(imageUrl, requestType, referrer);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300 || requestResult.result == Stream.Null)
|
||||||
|
return requestResult.statusCode;
|
||||||
|
byte[] buffer = new byte[requestResult.result.Length];
|
||||||
|
requestResult.result.ReadExactly(buffer, 0, buffer.Length);
|
||||||
|
File.WriteAllBytes(fullPath, buffer);
|
||||||
|
return requestResult.statusCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected HttpStatusCode DownloadChapterImages(string[] imageUrls, string saveArchiveFilePath, byte requestType, string? comicInfoPath = null, string? referrer = null, ProgressToken? progressToken = null)
|
||||||
|
{
|
||||||
|
if (progressToken?.cancellationRequested ?? false)
|
||||||
|
return HttpStatusCode.RequestTimeout;
|
||||||
|
Log($"Downloading Images for {saveArchiveFilePath}");
|
||||||
|
if(progressToken is not null)
|
||||||
|
progressToken.increments = imageUrls.Length;
|
||||||
|
//Check if Publication Directory already exists
|
||||||
|
string directoryPath = Path.GetDirectoryName(saveArchiveFilePath)!;
|
||||||
|
if (!Directory.Exists(directoryPath))
|
||||||
|
Directory.CreateDirectory(directoryPath);
|
||||||
|
|
||||||
|
if (File.Exists(saveArchiveFilePath)) //Don't download twice.
|
||||||
|
return HttpStatusCode.OK;
|
||||||
|
|
||||||
|
//Create a temporary folder to store images
|
||||||
|
string tempFolder = Directory.CreateTempSubdirectory().FullName;
|
||||||
|
|
||||||
|
int chapter = 0;
|
||||||
|
//Download all Images to temporary Folder
|
||||||
|
foreach (string imageUrl in imageUrls)
|
||||||
|
{
|
||||||
|
string[] split = imageUrl.Split('.');
|
||||||
|
string extension = split[^1];
|
||||||
|
Log($"Downloading image {chapter + 1:000}/{imageUrls.Length:000}"); //TODO
|
||||||
|
HttpStatusCode status = DownloadImage(imageUrl, Path.Join(tempFolder, $"{chapter++}.{extension}"), requestType, referrer);
|
||||||
|
if ((int)status < 200 || (int)status >= 300)
|
||||||
|
{
|
||||||
|
progressToken?.Complete();
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
if (progressToken?.cancellationRequested ?? false)
|
||||||
|
{
|
||||||
|
progressToken?.Complete();
|
||||||
|
return HttpStatusCode.RequestTimeout;
|
||||||
|
}
|
||||||
|
progressToken?.Increment();
|
||||||
|
}
|
||||||
|
|
||||||
|
if(comicInfoPath is not null)
|
||||||
|
File.Copy(comicInfoPath, Path.Join(tempFolder, "ComicInfo.xml"));
|
||||||
|
|
||||||
|
Log($"Creating archive {saveArchiveFilePath}");
|
||||||
|
//ZIP-it and ship-it
|
||||||
|
ZipFile.CreateFromDirectory(tempFolder, saveArchiveFilePath);
|
||||||
|
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||||
|
File.SetUnixFileMode(saveArchiveFilePath, GroupRead | GroupWrite | OtherRead | OtherWrite | UserRead | UserWrite);
|
||||||
|
Directory.Delete(tempFolder, true); //Cleanup
|
||||||
|
|
||||||
|
progressToken?.Complete();
|
||||||
|
return HttpStatusCode.OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected string SaveCoverImageToCache(string url, byte requestType)
|
||||||
|
{
|
||||||
|
string filename = url.Split('/')[^1].Split('?')[0];
|
||||||
|
string saveImagePath = Path.Join(settings.coverImageCache, filename);
|
||||||
|
|
||||||
|
if (File.Exists(saveImagePath))
|
||||||
|
return filename;
|
||||||
|
|
||||||
|
DownloadClient.RequestResult coverResult = downloadClient.MakeRequest(url, requestType);
|
||||||
|
using MemoryStream ms = new();
|
||||||
|
coverResult.result.CopyTo(ms);
|
||||||
|
File.WriteAllBytes(saveImagePath, ms.ToArray());
|
||||||
|
Log($"Saving cover to {saveImagePath}");
|
||||||
|
return filename;
|
||||||
|
}
|
||||||
|
}
|
51
Tranga/MangaConnectors/MangaConnectorJsonConverter.cs
Normal file
51
Tranga/MangaConnectors/MangaConnectorJsonConverter.cs
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
|
||||||
|
namespace Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
public class MangaConnectorJsonConverter : JsonConverter
|
||||||
|
{
|
||||||
|
private GlobalBase _clone;
|
||||||
|
private HashSet<MangaConnector> connectors;
|
||||||
|
|
||||||
|
internal MangaConnectorJsonConverter(GlobalBase clone, HashSet<MangaConnector> connectors)
|
||||||
|
{
|
||||||
|
this._clone = clone;
|
||||||
|
this.connectors = connectors;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool CanConvert(Type objectType)
|
||||||
|
{
|
||||||
|
return (objectType == typeof(MangaConnector));
|
||||||
|
}
|
||||||
|
|
||||||
|
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
|
||||||
|
{
|
||||||
|
JObject jo = JObject.Load(reader);
|
||||||
|
switch (jo.GetValue("name")!.Value<string>()!)
|
||||||
|
{
|
||||||
|
case "MangaDex":
|
||||||
|
return this.connectors.First(c => c is MangaDex);
|
||||||
|
case "Manganato":
|
||||||
|
return this.connectors.First(c => c is Manganato);
|
||||||
|
case "MangaKatana":
|
||||||
|
return this.connectors.First(c => c is MangaKatana);
|
||||||
|
case "Mangasee":
|
||||||
|
return this.connectors.First(c => c is Mangasee);
|
||||||
|
case "Mangaworld":
|
||||||
|
return this.connectors.First(c => c is Mangaworld);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Exception();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool CanWrite => false;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Don't call this
|
||||||
|
/// </summary>
|
||||||
|
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
|
||||||
|
{
|
||||||
|
throw new Exception("Dont call this");
|
||||||
|
}
|
||||||
|
}
|
300
Tranga/MangaConnectors/MangaDex.cs
Normal file
300
Tranga/MangaConnectors/MangaDex.cs
Normal file
@ -0,0 +1,300 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
|
using System.Text.Json.Nodes;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Tranga.Jobs;
|
||||||
|
using JsonSerializer = System.Text.Json.JsonSerializer;
|
||||||
|
|
||||||
|
namespace Tranga.MangaConnectors;
|
||||||
|
public class MangaDex : MangaConnector
|
||||||
|
{
|
||||||
|
private enum RequestType : byte
|
||||||
|
{
|
||||||
|
Manga,
|
||||||
|
Feed,
|
||||||
|
AtHomeServer,
|
||||||
|
CoverUrl,
|
||||||
|
Author,
|
||||||
|
}
|
||||||
|
|
||||||
|
public MangaDex(GlobalBase clone) : base(clone, "MangaDex")
|
||||||
|
{
|
||||||
|
this.downloadClient = new HttpDownloadClient(clone, new Dictionary<byte, int>()
|
||||||
|
{
|
||||||
|
{(byte)RequestType.Manga, 250},
|
||||||
|
{(byte)RequestType.Feed, 250},
|
||||||
|
{(byte)RequestType.AtHomeServer, 40},
|
||||||
|
{(byte)RequestType.CoverUrl, 250},
|
||||||
|
{(byte)RequestType.Author, 250}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Manga[] GetManga(string publicationTitle = "")
|
||||||
|
{
|
||||||
|
Log($"Searching Publications. Term=\"{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
|
||||||
|
HashSet<Manga> retManga = new();
|
||||||
|
int loadedPublicationData = 0;
|
||||||
|
while (offset < total) //As long as we haven't requested all "Pages"
|
||||||
|
{
|
||||||
|
//Request next Page
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest(
|
||||||
|
$"https://api.mangadex.org/manga?limit={limit}&title={publicationTitle}&offset={offset}", (byte)RequestType.Manga);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
break;
|
||||||
|
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
||||||
|
|
||||||
|
offset += limit;
|
||||||
|
if (result is null)
|
||||||
|
break;
|
||||||
|
|
||||||
|
total = result["total"]!.GetValue<int>(); //Update the total number of Publications
|
||||||
|
|
||||||
|
JsonArray mangaInResult = result["data"]!.AsArray(); //Manga-data-Array
|
||||||
|
//Loop each Manga and extract information from JSON
|
||||||
|
foreach (JsonNode? mangaNode in mangaInResult)
|
||||||
|
{
|
||||||
|
Log($"Getting publication data. {++loadedPublicationData}/{total}");
|
||||||
|
Manga manga = MangaFromJsonObject((JsonObject)mangaNode);
|
||||||
|
retManga.Add(manga); //Add Publication (Manga) to result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Log($"Retrieved {retManga.Count} publications. Term=\"{publicationTitle}\"");
|
||||||
|
return retManga.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Manga? GetMangaFromUrl(string url)
|
||||||
|
{
|
||||||
|
Regex idRex = new (@"https:\/\/mangadex.org\/title\/([A-z0-9-]*)\/.*");
|
||||||
|
string id = idRex.Match(url).Groups[1].Value;
|
||||||
|
Log($"Got id {id} from {url}");
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest($"https://api.mangadex.org/manga/{id}", (byte)RequestType.Manga);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
return null;
|
||||||
|
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
||||||
|
if(result is not null)
|
||||||
|
return MangaFromJsonObject(result["data"]!.AsObject());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Manga MangaFromJsonObject(JsonObject manga)
|
||||||
|
{
|
||||||
|
JsonObject attributes = manga["attributes"]!.AsObject();
|
||||||
|
|
||||||
|
string publicationId = manga["id"]!.GetValue<string>();
|
||||||
|
|
||||||
|
string title = attributes["title"]!.AsObject().ContainsKey("en") && attributes["title"]!["en"] is not null
|
||||||
|
? attributes["title"]!["en"]!.GetValue<string>()
|
||||||
|
: attributes["title"]![((IDictionary<string, JsonNode?>)attributes["title"]!.AsObject()).Keys.First()]!.GetValue<string>();
|
||||||
|
|
||||||
|
string? description = attributes["description"]!.AsObject().ContainsKey("en") && attributes["description"]!["en"] is not null
|
||||||
|
? attributes["description"]!["en"]!.GetValue<string?>()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
JsonArray altTitlesObject = attributes["altTitles"]!.AsArray();
|
||||||
|
Dictionary<string, string> altTitlesDict = new();
|
||||||
|
foreach (JsonNode? altTitleNode in altTitlesObject)
|
||||||
|
{
|
||||||
|
JsonObject altTitleObject = (JsonObject)altTitleNode!;
|
||||||
|
string key = ((IDictionary<string, JsonNode?>)altTitleObject).Keys.ToArray()[0];
|
||||||
|
altTitlesDict.TryAdd(key, altTitleObject[key]!.GetValue<string>());
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonArray tagsObject = attributes["tags"]!.AsArray();
|
||||||
|
HashSet<string> tags = new();
|
||||||
|
foreach (JsonNode? tagNode in tagsObject)
|
||||||
|
{
|
||||||
|
JsonObject tagObject = (JsonObject)tagNode!;
|
||||||
|
if(tagObject["attributes"]!["name"]!.AsObject().ContainsKey("en"))
|
||||||
|
tags.Add(tagObject["attributes"]!["name"]!["en"]!.GetValue<string>());
|
||||||
|
}
|
||||||
|
|
||||||
|
string? posterId = null;
|
||||||
|
HashSet<string> authorIds = new();
|
||||||
|
if (manga.ContainsKey("relationships") && manga["relationships"] is not null)
|
||||||
|
{
|
||||||
|
JsonArray relationships = manga["relationships"]!.AsArray();
|
||||||
|
posterId = relationships.FirstOrDefault(relationship => relationship!["type"]!.GetValue<string>() == "cover_art")!["id"]!.GetValue<string>();
|
||||||
|
foreach (JsonNode? node in relationships.Where(relationship =>
|
||||||
|
relationship!["type"]!.GetValue<string>() == "author"))
|
||||||
|
authorIds.Add(node!["id"]!.GetValue<string>());
|
||||||
|
}
|
||||||
|
string? coverUrl = GetCoverUrl(publicationId, posterId);
|
||||||
|
string? coverCacheName = null;
|
||||||
|
if (coverUrl is not null)
|
||||||
|
coverCacheName = SaveCoverImageToCache(coverUrl, (byte)RequestType.AtHomeServer);
|
||||||
|
|
||||||
|
List<string> authors = GetAuthors(authorIds);
|
||||||
|
|
||||||
|
Dictionary<string, string> linksDict = new();
|
||||||
|
if (attributes.ContainsKey("links") && attributes["links"] is not null)
|
||||||
|
{
|
||||||
|
JsonObject linksObject = attributes["links"]!.AsObject();
|
||||||
|
foreach (string key in ((IDictionary<string, JsonNode?>)linksObject).Keys)
|
||||||
|
{
|
||||||
|
linksDict.Add(key, linksObject[key]!.GetValue<string>());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int? year = attributes.ContainsKey("year") && attributes["year"] is not null
|
||||||
|
? attributes["year"]!.GetValue<int?>()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
string? originalLanguage =
|
||||||
|
attributes.ContainsKey("originalLanguage") && attributes["originalLanguage"] is not null
|
||||||
|
? attributes["originalLanguage"]!.GetValue<string?>()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
string status = attributes["status"]!.GetValue<string>();
|
||||||
|
|
||||||
|
Manga pub = new(
|
||||||
|
title,
|
||||||
|
authors,
|
||||||
|
description,
|
||||||
|
altTitlesDict,
|
||||||
|
tags.ToArray(),
|
||||||
|
coverUrl,
|
||||||
|
coverCacheName,
|
||||||
|
linksDict,
|
||||||
|
year,
|
||||||
|
originalLanguage,
|
||||||
|
status,
|
||||||
|
publicationId
|
||||||
|
);
|
||||||
|
cachedPublications.Add(pub);
|
||||||
|
return pub;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Chapter[] GetChapters(Manga manga, string language="en")
|
||||||
|
{
|
||||||
|
Log($"Getting chapters {manga}");
|
||||||
|
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
|
||||||
|
List<Chapter> chapters = new();
|
||||||
|
//As long as we haven't requested all "Pages"
|
||||||
|
while (offset < total)
|
||||||
|
{
|
||||||
|
//Request next "Page"
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest(
|
||||||
|
$"https://api.mangadex.org/manga/{manga.publicationId}/feed?limit={limit}&offset={offset}&translatedLanguage%5B%5D={language}", (byte)RequestType.Feed);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
break;
|
||||||
|
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
||||||
|
|
||||||
|
offset += limit;
|
||||||
|
if (result is null)
|
||||||
|
break;
|
||||||
|
|
||||||
|
total = result["total"]!.GetValue<int>();
|
||||||
|
JsonArray chaptersInResult = result["data"]!.AsArray();
|
||||||
|
//Loop through all Chapters in result and extract information from JSON
|
||||||
|
foreach (JsonNode? jsonNode in chaptersInResult)
|
||||||
|
{
|
||||||
|
JsonObject chapter = (JsonObject)jsonNode!;
|
||||||
|
JsonObject attributes = chapter["attributes"]!.AsObject();
|
||||||
|
string chapterId = chapter["id"]!.GetValue<string>();
|
||||||
|
|
||||||
|
string? title = attributes.ContainsKey("title") && attributes["title"] is not null
|
||||||
|
? attributes["title"]!.GetValue<string>()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
string? volume = attributes.ContainsKey("volume") && attributes["volume"] is not null
|
||||||
|
? attributes["volume"]!.GetValue<string>()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
string chapterNum = attributes.ContainsKey("chapter") && attributes["chapter"] is not null
|
||||||
|
? attributes["chapter"]!.GetValue<string>()
|
||||||
|
: "null";
|
||||||
|
|
||||||
|
if(chapterNum is not "null")
|
||||||
|
chapters.Add(new Chapter(manga, title, volume, chapterNum, chapterId));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Return Chapters ordered by Chapter-Number
|
||||||
|
Log($"Got {chapters.Count} chapters. {manga}");
|
||||||
|
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, numberFormatDecimalPoint)).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override HttpStatusCode DownloadChapter(Chapter chapter, ProgressToken? progressToken = null)
|
||||||
|
{
|
||||||
|
if (progressToken?.cancellationRequested ?? false)
|
||||||
|
return HttpStatusCode.RequestTimeout;
|
||||||
|
Manga chapterParentManga = chapter.parentManga;
|
||||||
|
Log($"Retrieving chapter-info {chapter} {chapterParentManga}");
|
||||||
|
//Request URLs for Chapter-Images
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest($"https://api.mangadex.org/at-home/server/{chapter.url}?forcePort443=false'", (byte)RequestType.AtHomeServer);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
return requestResult.statusCode;
|
||||||
|
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
||||||
|
if (result is null)
|
||||||
|
return HttpStatusCode.NoContent;
|
||||||
|
|
||||||
|
string baseUrl = result["baseUrl"]!.GetValue<string>();
|
||||||
|
string hash = result["chapter"]!["hash"]!.GetValue<string>();
|
||||||
|
JsonArray imageFileNames = result["chapter"]!["data"]!.AsArray();
|
||||||
|
//Loop through all imageNames and construct urls (imageUrl)
|
||||||
|
HashSet<string> imageUrls = new();
|
||||||
|
foreach (JsonNode? image in imageFileNames)
|
||||||
|
imageUrls.Add($"{baseUrl}/data/{hash}/{image!.GetValue<string>()}");
|
||||||
|
|
||||||
|
string comicInfoPath = Path.GetTempFileName();
|
||||||
|
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());
|
||||||
|
|
||||||
|
//Download Chapter-Images
|
||||||
|
return DownloadChapterImages(imageUrls.ToArray(), chapter.GetArchiveFilePath(settings.downloadLocation), (byte)RequestType.AtHomeServer, comicInfoPath, progressToken:progressToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
private string? GetCoverUrl(string publicationId, string? posterId)
|
||||||
|
{
|
||||||
|
Log($"Getting CoverUrl for Publication {publicationId}");
|
||||||
|
if (posterId is null)
|
||||||
|
{
|
||||||
|
Log("No cover.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Request information where to download Cover
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest($"https://api.mangadex.org/cover/{posterId}", (byte)RequestType.CoverUrl);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
return null;
|
||||||
|
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
||||||
|
if (result is null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
string fileName = result["data"]!["attributes"]!["fileName"]!.GetValue<string>();
|
||||||
|
|
||||||
|
string coverUrl = $"https://uploads.mangadex.org/covers/{publicationId}/{fileName}";
|
||||||
|
Log($"Cover-Url {publicationId} -> {coverUrl}");
|
||||||
|
return coverUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<string> GetAuthors(IEnumerable<string> authorIds)
|
||||||
|
{
|
||||||
|
Log("Retrieving authors.");
|
||||||
|
List<string> ret = new();
|
||||||
|
foreach (string authorId in authorIds)
|
||||||
|
{
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest($"https://api.mangadex.org/author/{authorId}", (byte)RequestType.Author);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
return ret;
|
||||||
|
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(requestResult.result);
|
||||||
|
if (result is null)
|
||||||
|
return ret;
|
||||||
|
|
||||||
|
string authorName = result["data"]!["attributes"]!["name"]!.GetValue<string>();
|
||||||
|
ret.Add(authorName);
|
||||||
|
Log($"Got author {authorId} -> {authorName}");
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
}
|
225
Tranga/MangaConnectors/MangaKatana.cs
Normal file
225
Tranga/MangaConnectors/MangaKatana.cs
Normal file
@ -0,0 +1,225 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using HtmlAgilityPack;
|
||||||
|
using Tranga.Jobs;
|
||||||
|
|
||||||
|
namespace Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
public class MangaKatana : MangaConnector
|
||||||
|
{
|
||||||
|
public MangaKatana(GlobalBase clone) : base(clone, "MangaKatana")
|
||||||
|
{
|
||||||
|
this.downloadClient = new HttpDownloadClient(clone, new Dictionary<byte, int>()
|
||||||
|
{
|
||||||
|
{1, 60}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Manga[] GetManga(string publicationTitle = "")
|
||||||
|
{
|
||||||
|
Log($"Searching Publications. Term=\"{publicationTitle}\"");
|
||||||
|
string sanitizedTitle = string.Join('_', Regex.Matches(publicationTitle, "[A-z]*").Where(m => m.Value.Length > 0)).ToLower();
|
||||||
|
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<Manga>();
|
||||||
|
|
||||||
|
// 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]) };
|
||||||
|
}
|
||||||
|
|
||||||
|
Manga[] publications = ParsePublicationsFromHtml(requestResult.result);
|
||||||
|
Log($"Retrieved {publications.Length} publications. Term=\"{publicationTitle}\"");
|
||||||
|
return publications;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Manga? GetMangaFromUrl(string url)
|
||||||
|
{
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest(url, 1);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
return null;
|
||||||
|
return ParseSinglePublicationFromHtml(requestResult.result, url.Split('/')[^1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Manga[] 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");
|
||||||
|
if (searchResults is null || !searchResults.Any())
|
||||||
|
return Array.Empty<Manga>();
|
||||||
|
List<string> urls = new();
|
||||||
|
foreach (HtmlNode mangaResult in searchResults)
|
||||||
|
{
|
||||||
|
urls.Add(mangaResult.Descendants("a").First().GetAttributes()
|
||||||
|
.First(a => a.Name == "href").Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
HashSet<Manga> ret = new();
|
||||||
|
foreach (string url in urls)
|
||||||
|
{
|
||||||
|
Manga? manga = GetMangaFromUrl(url);
|
||||||
|
if (manga is not null)
|
||||||
|
ret.Add((Manga)manga);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Manga 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
Manga manga = new (sortName, authors.ToList(), description, altTitles, tags.ToArray(), posterUrl, coverFileNameInCache, links,
|
||||||
|
year, originalLanguage, status, publicationId);
|
||||||
|
cachedPublications.Add(manga);
|
||||||
|
return manga;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Chapter[] GetChapters(Manga manga, string language="en")
|
||||||
|
{
|
||||||
|
Log($"Getting chapters {manga}");
|
||||||
|
string requestUrl = $"https://mangakatana.com/manga/{manga.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
|
||||||
|
List<Chapter> chapters = ParseChaptersFromHtml(manga, requestUrl);
|
||||||
|
Log($"Got {chapters.Count} chapters. {manga}");
|
||||||
|
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, numberFormatDecimalPoint)).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Chapter> ParseChaptersFromHtml(Manga manga, 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(manga, chapterName, volumeNumber, chapterNumber, url));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override HttpStatusCode DownloadChapter(Chapter chapter, ProgressToken? progressToken = null)
|
||||||
|
{
|
||||||
|
if (progressToken?.cancellationRequested ?? false)
|
||||||
|
return HttpStatusCode.RequestTimeout;
|
||||||
|
Manga chapterParentManga = chapter.parentManga;
|
||||||
|
Log($"Retrieving chapter-info {chapter} {chapterParentManga}");
|
||||||
|
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, comicInfoPath, "https://mangakatana.com/", progressToken:progressToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
205
Tranga/MangaConnectors/Manganato.cs
Normal file
205
Tranga/MangaConnectors/Manganato.cs
Normal file
@ -0,0 +1,205 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using HtmlAgilityPack;
|
||||||
|
using Tranga.Jobs;
|
||||||
|
|
||||||
|
namespace Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
public class Manganato : MangaConnector
|
||||||
|
{
|
||||||
|
public Manganato(GlobalBase clone) : base(clone, "Manganato")
|
||||||
|
{
|
||||||
|
this.downloadClient = new HttpDownloadClient(clone, new Dictionary<byte, int>()
|
||||||
|
{
|
||||||
|
{1, 60}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Manga[] GetManga(string publicationTitle = "")
|
||||||
|
{
|
||||||
|
Log($"Searching Publications. Term=\"{publicationTitle}\"");
|
||||||
|
string sanitizedTitle = string.Join('_', Regex.Matches(publicationTitle, "[A-z]*").Where(str => str.Length > 0)).ToLower();
|
||||||
|
string requestUrl = $"https://manganato.com/search/story/{sanitizedTitle}";
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest(requestUrl, 1);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
return Array.Empty<Manga>();
|
||||||
|
|
||||||
|
if (requestResult.htmlDocument is null)
|
||||||
|
return Array.Empty<Manga>();
|
||||||
|
Manga[] publications = ParsePublicationsFromHtml(requestResult.htmlDocument);
|
||||||
|
Log($"Retrieved {publications.Length} publications. Term=\"{publicationTitle}\"");
|
||||||
|
return publications;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Manga[] ParsePublicationsFromHtml(HtmlDocument document)
|
||||||
|
{
|
||||||
|
IEnumerable<HtmlNode> searchResults = document.DocumentNode.Descendants("div").Where(n => n.HasClass("search-story-item"));
|
||||||
|
List<string> urls = new();
|
||||||
|
foreach (HtmlNode mangaResult in searchResults)
|
||||||
|
{
|
||||||
|
urls.Add(mangaResult.Descendants("a").First(n => n.HasClass("item-title")).GetAttributes()
|
||||||
|
.First(a => a.Name == "href").Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
HashSet<Manga> ret = new();
|
||||||
|
foreach (string url in urls)
|
||||||
|
{
|
||||||
|
Manga? manga = GetMangaFromUrl(url);
|
||||||
|
if (manga is not null)
|
||||||
|
ret.Add((Manga)manga);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Manga? GetMangaFromUrl(string url)
|
||||||
|
{
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest(url, 1);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (requestResult.htmlDocument is null)
|
||||||
|
return null;
|
||||||
|
return ParseSinglePublicationFromHtml(requestResult.htmlDocument, url.Split('/')[^1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Manga ParseSinglePublicationFromHtml(HtmlDocument document, string publicationId)
|
||||||
|
{
|
||||||
|
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.Descendants("div").First(d => d.HasClass("story-info-right"));
|
||||||
|
|
||||||
|
string sortName = infoNode.Descendants("h1").First().InnerText;
|
||||||
|
|
||||||
|
HtmlNode infoTable = infoNode.Descendants().First(d => d.Name == "table");
|
||||||
|
|
||||||
|
foreach (HtmlNode row in infoTable.Descendants("tr"))
|
||||||
|
{
|
||||||
|
string key = row.SelectNodes("td").First().InnerText.ToLower();
|
||||||
|
string value = row.SelectNodes("td").Last().InnerText;
|
||||||
|
string keySanitized = string.Concat(Regex.Matches(key, "[a-z]"));
|
||||||
|
|
||||||
|
switch (keySanitized)
|
||||||
|
{
|
||||||
|
case "alternative":
|
||||||
|
string[] alts = value.Split(" ; ");
|
||||||
|
for(int i = 0; i < alts.Length; i++)
|
||||||
|
altTitles.Add(i.ToString(), alts[i]);
|
||||||
|
break;
|
||||||
|
case "authors":
|
||||||
|
authors = value.Split('-');
|
||||||
|
break;
|
||||||
|
case "status":
|
||||||
|
status = value;
|
||||||
|
break;
|
||||||
|
case "genres":
|
||||||
|
string[] genres = value.Split(" - ");
|
||||||
|
tags = genres.ToHashSet();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
string posterUrl = document.DocumentNode.Descendants("span").First(s => s.HasClass("info-image")).Descendants("img").First()
|
||||||
|
.GetAttributes().First(a => a.Name == "src").Value;
|
||||||
|
|
||||||
|
string coverFileNameInCache = SaveCoverImageToCache(posterUrl, 1);
|
||||||
|
|
||||||
|
string description = document.DocumentNode.Descendants("div").First(d => d.HasClass("panel-story-info-description"))
|
||||||
|
.InnerText.Replace("Description :", "");
|
||||||
|
while (description.StartsWith('\n'))
|
||||||
|
description = description.Substring(1);
|
||||||
|
|
||||||
|
string yearString = document.DocumentNode.Descendants("li").Last(li => li.HasClass("a-h")).Descendants("span")
|
||||||
|
.First(s => s.HasClass("chapter-time")).InnerText;
|
||||||
|
int year = Convert.ToInt32(yearString.Split(',')[^1]) + 2000;
|
||||||
|
|
||||||
|
Manga manga = new (sortName, authors.ToList(), description, altTitles, tags.ToArray(), posterUrl, coverFileNameInCache, links,
|
||||||
|
year, originalLanguage, status, publicationId);
|
||||||
|
cachedPublications.Add(manga);
|
||||||
|
return manga;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Chapter[] GetChapters(Manga manga, string language="en")
|
||||||
|
{
|
||||||
|
Log($"Getting chapters {manga}");
|
||||||
|
string requestUrl = $"https://chapmanganato.com/{manga.publicationId}";
|
||||||
|
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
|
||||||
|
if (requestResult.htmlDocument is null)
|
||||||
|
return Array.Empty<Chapter>();
|
||||||
|
List<Chapter> chapters = ParseChaptersFromHtml(manga, requestResult.htmlDocument);
|
||||||
|
Log($"Got {chapters.Count} chapters. {manga}");
|
||||||
|
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, numberFormatDecimalPoint)).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Chapter> ParseChaptersFromHtml(Manga manga, HtmlDocument document)
|
||||||
|
{
|
||||||
|
List<Chapter> ret = new();
|
||||||
|
|
||||||
|
HtmlNode chapterList = document.DocumentNode.Descendants("ul").First(l => l.HasClass("row-content-chapter"));
|
||||||
|
|
||||||
|
Regex volRex = new(@"Vol\.([0-9]+).*");
|
||||||
|
Regex chapterRex = new(@"Chapter ([0-9]+(\.[0-9]+)*){1}.*");
|
||||||
|
Regex nameRex = new(@"Chapter ([0-9]+(\.[0-9]+)*){1}:? (.*)");
|
||||||
|
|
||||||
|
foreach (HtmlNode chapterInfo in chapterList.Descendants("li"))
|
||||||
|
{
|
||||||
|
string fullString = chapterInfo.Descendants("a").First(d => d.HasClass("chapter-name")).InnerText;
|
||||||
|
|
||||||
|
string? volumeNumber = volRex.IsMatch(fullString) ? volRex.Match(fullString).Groups[1].Value : null;
|
||||||
|
string chapterNumber = chapterRex.Match(fullString).Groups[1].Value;
|
||||||
|
string chapterName = nameRex.Match(fullString).Groups[3].Value;
|
||||||
|
string url = chapterInfo.Descendants("a").First(d => d.HasClass("chapter-name"))
|
||||||
|
.GetAttributeValue("href", "");
|
||||||
|
ret.Add(new Chapter(manga, chapterName, volumeNumber, chapterNumber, url));
|
||||||
|
}
|
||||||
|
ret.Reverse();
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override HttpStatusCode DownloadChapter(Chapter chapter, ProgressToken? progressToken = null)
|
||||||
|
{
|
||||||
|
if (progressToken?.cancellationRequested ?? false)
|
||||||
|
return HttpStatusCode.RequestTimeout;
|
||||||
|
Manga chapterParentManga = chapter.parentManga;
|
||||||
|
Log($"Retrieving chapter-info {chapter} {chapterParentManga}");
|
||||||
|
string requestUrl = chapter.url;
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest(requestUrl, 1);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
return requestResult.statusCode;
|
||||||
|
|
||||||
|
if (requestResult.htmlDocument is null)
|
||||||
|
return HttpStatusCode.InternalServerError;
|
||||||
|
string[] imageUrls = ParseImageUrlsFromHtml(requestResult.htmlDocument);
|
||||||
|
|
||||||
|
string comicInfoPath = Path.GetTempFileName();
|
||||||
|
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());
|
||||||
|
|
||||||
|
return DownloadChapterImages(imageUrls, chapter.GetArchiveFilePath(settings.downloadLocation), 1, comicInfoPath, "https://chapmanganato.com/", progressToken:progressToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
private string[] ParseImageUrlsFromHtml(HtmlDocument document)
|
||||||
|
{
|
||||||
|
List<string> ret = new();
|
||||||
|
|
||||||
|
HtmlNode imageContainer =
|
||||||
|
document.DocumentNode.Descendants("div").First(i => i.HasClass("container-chapter-reader"));
|
||||||
|
foreach(HtmlNode imageNode in imageContainer.Descendants("img"))
|
||||||
|
ret.Add(imageNode.GetAttributeValue("src", ""));
|
||||||
|
|
||||||
|
return ret.ToArray();
|
||||||
|
}
|
||||||
|
}
|
205
Tranga/MangaConnectors/Mangasee.cs
Normal file
205
Tranga/MangaConnectors/Mangasee.cs
Normal file
@ -0,0 +1,205 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using System.Xml.Linq;
|
||||||
|
using HtmlAgilityPack;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Tranga.Jobs;
|
||||||
|
|
||||||
|
namespace Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
public class Mangasee : MangaConnector
|
||||||
|
{
|
||||||
|
public Mangasee(GlobalBase clone) : base(clone, "Mangasee")
|
||||||
|
{
|
||||||
|
this.downloadClient = new ChromiumDownloadClient(clone, new Dictionary<byte, int>()
|
||||||
|
{
|
||||||
|
{ 1, 60 }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Manga[] GetManga(string publicationTitle = "")
|
||||||
|
{
|
||||||
|
Log($"Searching Publications. Term=\"{publicationTitle}\"");
|
||||||
|
string requestUrl = $"https://mangasee123.com/_search.php";
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest(requestUrl, 1);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
return Array.Empty<Manga>();
|
||||||
|
|
||||||
|
if (requestResult.htmlDocument is null)
|
||||||
|
return Array.Empty<Manga>();
|
||||||
|
Manga[] publications = ParsePublicationsFromHtml(requestResult.htmlDocument, publicationTitle);
|
||||||
|
Log($"Retrieved {publications.Length} publications. Term=\"{publicationTitle}\"");
|
||||||
|
return publications;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Manga? GetMangaFromUrl(string url)
|
||||||
|
{
|
||||||
|
Regex publicationIdRex = new(@"https:\/\/mangasee123.com\/manga\/(.*)(\/.*)*");
|
||||||
|
string publicationId = publicationIdRex.Match(url).Groups[1].Value;
|
||||||
|
|
||||||
|
DownloadClient.RequestResult requestResult = this.downloadClient.MakeRequest(url, 1);
|
||||||
|
if(requestResult.htmlDocument is not null)
|
||||||
|
return ParseSinglePublicationFromHtml(requestResult.htmlDocument, publicationId);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Manga[] ParsePublicationsFromHtml(HtmlDocument document, string publicationTitle)
|
||||||
|
{
|
||||||
|
string jsonString = document.DocumentNode.SelectSingleNode("//body").InnerText;
|
||||||
|
List<SearchResultItem> result = JsonConvert.DeserializeObject<List<SearchResultItem>>(jsonString)!;
|
||||||
|
Dictionary<SearchResultItem, int> queryFiltered = new();
|
||||||
|
foreach (SearchResultItem resultItem in result)
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
|
||||||
|
Log($"Retrieved {queryFiltered.Count} publications.");
|
||||||
|
|
||||||
|
HashSet<Manga> ret = new();
|
||||||
|
List<SearchResultItem> orderedFiltered =
|
||||||
|
queryFiltered.OrderBy(item => item.Value).ToDictionary(item => item.Key, item => item.Value).Keys.ToList();
|
||||||
|
|
||||||
|
foreach (SearchResultItem orderedItem in orderedFiltered)
|
||||||
|
{
|
||||||
|
Manga? manga = GetMangaFromUrl($"https://mangasee123.com/manga/{orderedItem.i}");
|
||||||
|
if (manga is not null)
|
||||||
|
ret.Add((Manga)manga);
|
||||||
|
}
|
||||||
|
return ret.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private Manga ParseSinglePublicationFromHtml(HtmlDocument document, string publicationId)
|
||||||
|
{
|
||||||
|
string originalLanguage = "", status = "";
|
||||||
|
Dictionary<string, string> altTitles = new(), links = new();
|
||||||
|
HashSet<string> tags = new();
|
||||||
|
|
||||||
|
HtmlNode posterNode = document.DocumentNode.SelectSingleNode("//div[@class='BoxBody']//div[@class='row']//img");
|
||||||
|
string posterUrl = posterNode.GetAttributeValue("src", "");
|
||||||
|
string coverFileNameInCache = SaveCoverImageToCache(posterUrl, 1);
|
||||||
|
|
||||||
|
HtmlNode titleNode = document.DocumentNode.SelectSingleNode("//div[@class='BoxBody']//div[@class='row']//h1");
|
||||||
|
string sortName = titleNode.InnerText;
|
||||||
|
|
||||||
|
HtmlNode[] authorsNodes = document.DocumentNode.SelectNodes("//div[@class='BoxBody']//div[@class='row']//span[text()='Author(s):']/..").Descendants("a").ToArray();
|
||||||
|
List<string> authors = new();
|
||||||
|
foreach(HtmlNode authorNode in authorsNodes)
|
||||||
|
authors.Add(authorNode.InnerText);
|
||||||
|
|
||||||
|
HtmlNode[] genreNodes = document.DocumentNode.SelectNodes("//div[@class='BoxBody']//div[@class='row']//span[text()='Genre(s):']/..").Descendants("a").ToArray();
|
||||||
|
foreach (HtmlNode genreNode in genreNodes)
|
||||||
|
tags.Add(genreNode.InnerText);
|
||||||
|
|
||||||
|
HtmlNode yearNode = document.DocumentNode.SelectNodes("//div[@class='BoxBody']//div[@class='row']//span[text()='Released:']/..").Descendants("a").First();
|
||||||
|
int year = Convert.ToInt32(yearNode.InnerText);
|
||||||
|
|
||||||
|
HtmlNode[] statusNodes = document.DocumentNode.SelectNodes("//div[@class='BoxBody']//div[@class='row']//span[text()='Status:']/..").Descendants("a").ToArray();
|
||||||
|
foreach(HtmlNode statusNode in statusNodes)
|
||||||
|
if (statusNode.InnerText.Contains("publish", StringComparison.CurrentCultureIgnoreCase))
|
||||||
|
status = statusNode.InnerText.Split(' ')[0];
|
||||||
|
|
||||||
|
HtmlNode descriptionNode = document.DocumentNode.SelectNodes("//div[@class='BoxBody']//div[@class='row']//span[text()='Description:']/..").Descendants("div").First();
|
||||||
|
string description = descriptionNode.InnerText;
|
||||||
|
|
||||||
|
Manga manga = new (sortName, authors.ToList(), description, altTitles, tags.ToArray(), posterUrl, coverFileNameInCache, links,
|
||||||
|
year, originalLanguage, status, publicationId);
|
||||||
|
cachedPublications.Add(manga);
|
||||||
|
return manga;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReSharper disable once ClassNeverInstantiated.Local Will be instantiated during deserialization
|
||||||
|
private class SearchResultItem
|
||||||
|
{
|
||||||
|
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(Manga manga, string language="en")
|
||||||
|
{
|
||||||
|
Log($"Getting chapters {manga}");
|
||||||
|
XDocument doc = XDocument.Load($"https://mangasee123.com/rss/{manga.publicationId}.xml");
|
||||||
|
XElement[] chapterItems = doc.Descendants("item").ToArray();
|
||||||
|
List<Chapter> chapters = new();
|
||||||
|
foreach (XElement chapter in chapterItems)
|
||||||
|
{
|
||||||
|
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(),"");
|
||||||
|
chapters.Add(new Chapter(manga, "", volumeNumber, chapterNumber, url));
|
||||||
|
}
|
||||||
|
|
||||||
|
//Return Chapters ordered by Chapter-Number
|
||||||
|
Log($"Got {chapters.Count} chapters. {manga}");
|
||||||
|
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, numberFormatDecimalPoint)).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override HttpStatusCode DownloadChapter(Chapter chapter, ProgressToken? progressToken = null)
|
||||||
|
{
|
||||||
|
if (progressToken?.cancellationRequested ?? false)
|
||||||
|
return HttpStatusCode.RequestTimeout;
|
||||||
|
Manga chapterParentManga = chapter.parentManga;
|
||||||
|
if (progressToken?.cancellationRequested??false)
|
||||||
|
return HttpStatusCode.RequestTimeout;
|
||||||
|
|
||||||
|
Log($"Retrieving chapter-info {chapter} {chapterParentManga}");
|
||||||
|
|
||||||
|
DownloadClient.RequestResult requestResult = this.downloadClient.MakeRequest(chapter.url, 1);
|
||||||
|
if(requestResult.htmlDocument is null)
|
||||||
|
return HttpStatusCode.RequestTimeout;
|
||||||
|
HtmlDocument document = requestResult.htmlDocument;
|
||||||
|
|
||||||
|
HtmlNode gallery = document.DocumentNode.Descendants("div").First(div => div.HasClass("ImageGallery"));
|
||||||
|
HtmlNode[] images = gallery.Descendants("img").Where(img => img.HasClass("img-fluid")).ToArray();
|
||||||
|
List<string> urls = new();
|
||||||
|
foreach(HtmlNode galleryImage in images)
|
||||||
|
urls.Add(galleryImage.GetAttributeValue("src", ""));
|
||||||
|
|
||||||
|
string comicInfoPath = Path.GetTempFileName();
|
||||||
|
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());
|
||||||
|
|
||||||
|
return DownloadChapterImages(urls.ToArray(), chapter.GetArchiveFilePath(settings.downloadLocation), 1, comicInfoPath, progressToken:progressToken);
|
||||||
|
}
|
||||||
|
}
|
183
Tranga/MangaConnectors/Mangaworld.cs
Normal file
183
Tranga/MangaConnectors/Mangaworld.cs
Normal file
@ -0,0 +1,183 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using HtmlAgilityPack;
|
||||||
|
using Tranga.Jobs;
|
||||||
|
|
||||||
|
namespace Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
public class Mangaworld: MangaConnector
|
||||||
|
{
|
||||||
|
public Mangaworld(GlobalBase clone) : base(clone, "Mangaworld")
|
||||||
|
{
|
||||||
|
this.downloadClient = new HttpDownloadClient(clone, new Dictionary<byte, int>()
|
||||||
|
{
|
||||||
|
{1, 60}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Manga[] GetManga(string publicationTitle = "")
|
||||||
|
{
|
||||||
|
Log($"Searching Publications. Term=\"{publicationTitle}\"");
|
||||||
|
string sanitizedTitle = string.Join('_', Regex.Matches(publicationTitle, "[A-z]*").Where(str => str.Length > 0)).ToLower();
|
||||||
|
string requestUrl = $"https://www.mangaworld.bz/archive?keyword={sanitizedTitle}";
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest(requestUrl, 1);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
return Array.Empty<Manga>();
|
||||||
|
|
||||||
|
if (requestResult.htmlDocument is null)
|
||||||
|
return Array.Empty<Manga>();
|
||||||
|
Manga[] publications = ParsePublicationsFromHtml(requestResult.htmlDocument);
|
||||||
|
Log($"Retrieved {publications.Length} publications. Term=\"{publicationTitle}\"");
|
||||||
|
return publications;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Manga[] ParsePublicationsFromHtml(HtmlDocument document)
|
||||||
|
{
|
||||||
|
|
||||||
|
List<string> urls = document.DocumentNode
|
||||||
|
.SelectNodes(
|
||||||
|
"//div[@class='comics-grid']//div[@class='entry']//a[contains(concat(' ',normalize-space(@class),' '),'thumb')]")
|
||||||
|
.Select(thumb => thumb.GetAttributeValue("href", "")).ToList();
|
||||||
|
|
||||||
|
HashSet<Manga> ret = new();
|
||||||
|
foreach (string url in urls)
|
||||||
|
{
|
||||||
|
Manga? manga = GetMangaFromUrl(url);
|
||||||
|
if (manga is not null)
|
||||||
|
ret.Add((Manga)manga);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Manga? GetMangaFromUrl(string url)
|
||||||
|
{
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest(url, 1);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
if (requestResult.htmlDocument is null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
return ParseSinglePublicationFromHtml(requestResult.htmlDocument, url.Split('/')[^2]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Manga ParseSinglePublicationFromHtml(HtmlDocument document, string publicationId)
|
||||||
|
{
|
||||||
|
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.Descendants("div").First(d => d.HasClass("info"));
|
||||||
|
|
||||||
|
string sortName = infoNode.Descendants("h1").First().InnerText;
|
||||||
|
|
||||||
|
HtmlNode metadata = infoNode.Descendants().First(d => d.HasClass("meta-data"));
|
||||||
|
|
||||||
|
HtmlNode altTitlesNode = metadata.SelectSingleNode("//span[text()='Titoli alternativi: ']/..").ChildNodes[1];
|
||||||
|
|
||||||
|
string[] alts = altTitlesNode.InnerText.Split(", ");
|
||||||
|
for(int i = 0; i < alts.Length; i++)
|
||||||
|
altTitles.Add(i.ToString(), alts[i]);
|
||||||
|
|
||||||
|
HtmlNode genresNode =
|
||||||
|
metadata.SelectSingleNode("//span[text()='Generi: ']/..");
|
||||||
|
tags = genresNode.SelectNodes("a").Select(node => node.InnerText).ToHashSet();
|
||||||
|
|
||||||
|
HtmlNode authorsNode =
|
||||||
|
metadata.SelectSingleNode("//span[text()='Autore: ']/..");
|
||||||
|
authors = new[] { authorsNode.SelectNodes("a").First().InnerText };
|
||||||
|
|
||||||
|
status = metadata.SelectSingleNode("//span[text()='Stato: ']/..").SelectNodes("a").First().InnerText;
|
||||||
|
|
||||||
|
string posterUrl = document.DocumentNode.SelectSingleNode("//img[@class='rounded']").GetAttributeValue("src", "");
|
||||||
|
|
||||||
|
string coverFileNameInCache = SaveCoverImageToCache(posterUrl, 1);
|
||||||
|
|
||||||
|
string description = document.DocumentNode.SelectSingleNode("//div[@id='noidungm']").InnerText;
|
||||||
|
|
||||||
|
string yearString = metadata.SelectSingleNode("//span[text()='Anno di uscita: ']/..").SelectNodes("a").First().InnerText;
|
||||||
|
int year = Convert.ToInt32(yearString);
|
||||||
|
|
||||||
|
Manga manga = new (sortName, authors.ToList(), description, altTitles, tags.ToArray(), posterUrl, coverFileNameInCache, links,
|
||||||
|
year, originalLanguage, status, publicationId);
|
||||||
|
cachedPublications.Add(manga);
|
||||||
|
return manga;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Chapter[] GetChapters(Manga manga, string language="en")
|
||||||
|
{
|
||||||
|
Log($"Getting chapters {manga}");
|
||||||
|
string requestUrl = $"https://www.mangaworld.bz/manga/{manga.publicationId}";
|
||||||
|
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
|
||||||
|
if (requestResult.htmlDocument is null)
|
||||||
|
return Array.Empty<Chapter>();
|
||||||
|
List<Chapter> chapters = ParseChaptersFromHtml(manga, requestResult.htmlDocument);
|
||||||
|
Log($"Got {chapters.Count} chapters. {manga}");
|
||||||
|
return chapters.OrderBy(chapter => Convert.ToSingle(chapter.chapterNumber, numberFormatDecimalPoint)).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Chapter> ParseChaptersFromHtml(Manga manga, HtmlDocument document)
|
||||||
|
{
|
||||||
|
List<Chapter> ret = new();
|
||||||
|
|
||||||
|
foreach (HtmlNode volNode in document.DocumentNode.SelectNodes(
|
||||||
|
"//div[contains(concat(' ',normalize-space(@class),' '),'chapters-wrapper')]//div[contains(concat(' ',normalize-space(@class),' '),'volume-element')]"))
|
||||||
|
{
|
||||||
|
string volume = volNode.SelectSingleNode("//p[contains(concat(' ',normalize-space(@class),' '),'volume-name')]").InnerText.Split(' ')[^1];
|
||||||
|
foreach (HtmlNode chNode in volNode.SelectNodes("//div[contains(concat(' ',normalize-space(@class),' '),'volume-chapters')]/div[@class='chapter']"))
|
||||||
|
{
|
||||||
|
string number = chNode.SelectSingleNode("a").SelectSingleNode("span").InnerText.Split(" ")[^1];
|
||||||
|
string url = chNode.SelectSingleNode("a").GetAttributeValue("href", "");
|
||||||
|
ret.Add(new Chapter(manga, null, volume, number, url));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ret.Reverse();
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override HttpStatusCode DownloadChapter(Chapter chapter, ProgressToken? progressToken = null)
|
||||||
|
{
|
||||||
|
if (progressToken?.cancellationRequested ?? false)
|
||||||
|
return HttpStatusCode.RequestTimeout;
|
||||||
|
Manga chapterParentManga = chapter.parentManga;
|
||||||
|
Log($"Retrieving chapter-info {chapter} {chapterParentManga}");
|
||||||
|
string requestUrl = $"{chapter.url}?style=list";
|
||||||
|
DownloadClient.RequestResult requestResult =
|
||||||
|
downloadClient.MakeRequest(requestUrl, 1);
|
||||||
|
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||||
|
return requestResult.statusCode;
|
||||||
|
|
||||||
|
if (requestResult.htmlDocument is null)
|
||||||
|
return HttpStatusCode.InternalServerError;
|
||||||
|
string[] imageUrls = ParseImageUrlsFromHtml(requestResult.htmlDocument);
|
||||||
|
|
||||||
|
string comicInfoPath = Path.GetTempFileName();
|
||||||
|
File.WriteAllText(comicInfoPath, chapter.GetComicInfoXmlString());
|
||||||
|
|
||||||
|
return DownloadChapterImages(imageUrls, chapter.GetArchiveFilePath(settings.downloadLocation), 1, comicInfoPath, "https://www.mangaworld.bz/", progressToken:progressToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
private string[] ParseImageUrlsFromHtml(HtmlDocument document)
|
||||||
|
{
|
||||||
|
List<string> ret = new();
|
||||||
|
|
||||||
|
HtmlNode imageContainer =
|
||||||
|
document.DocumentNode.SelectSingleNode("//div[@id='page']");
|
||||||
|
foreach(HtmlNode imageNode in imageContainer.Descendants("img"))
|
||||||
|
ret.Add(imageNode.GetAttributeValue("src", ""));
|
||||||
|
|
||||||
|
return ret.ToArray();
|
||||||
|
}
|
||||||
|
}
|
56
Tranga/NotificationConnectors/Gotify.cs
Normal file
56
Tranga/NotificationConnectors/Gotify.cs
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
using System.Text;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
|
||||||
|
namespace Tranga.NotificationConnectors;
|
||||||
|
|
||||||
|
public class Gotify : NotificationConnector
|
||||||
|
{
|
||||||
|
public string endpoint { get; }
|
||||||
|
// ReSharper disable once MemberCanBePrivate.Global
|
||||||
|
public string appToken { get; }
|
||||||
|
private readonly HttpClient _client = new();
|
||||||
|
|
||||||
|
[JsonConstructor]
|
||||||
|
public Gotify(GlobalBase clone, string endpoint, string appToken) : base(clone, NotificationConnectorType.Gotify)
|
||||||
|
{
|
||||||
|
this.endpoint = endpoint;
|
||||||
|
this.appToken = appToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString()
|
||||||
|
{
|
||||||
|
return $"Gotify {endpoint}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void SendNotification(string title, string notificationText)
|
||||||
|
{
|
||||||
|
Log($"Sending notification: {title} - {notificationText}");
|
||||||
|
MessageData message = new(title, notificationText);
|
||||||
|
HttpRequestMessage request = new(HttpMethod.Post, $"{endpoint}/message");
|
||||||
|
request.Headers.Add("X-Gotify-Key", this.appToken);
|
||||||
|
request.Content = new StringContent(JsonConvert.SerializeObject(message, Formatting.None), Encoding.UTF8, "application/json");
|
||||||
|
HttpResponseMessage response = _client.Send(request);
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
StreamReader sr = new (response.Content.ReadAsStream());
|
||||||
|
Log($"{response.StatusCode}: {sr.ReadToEnd()}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class MessageData
|
||||||
|
{
|
||||||
|
// ReSharper disable four times UnusedAutoPropertyAccessor.Local
|
||||||
|
public string message { get; }
|
||||||
|
public long priority { get; }
|
||||||
|
public string title { get; }
|
||||||
|
public Dictionary<string, object> extras { get; }
|
||||||
|
|
||||||
|
public MessageData(string title, string message)
|
||||||
|
{
|
||||||
|
this.title = title;
|
||||||
|
this.message = message;
|
||||||
|
this.extras = new();
|
||||||
|
this.priority = 4;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
49
Tranga/NotificationConnectors/LunaSea.cs
Normal file
49
Tranga/NotificationConnectors/LunaSea.cs
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
using System.Text;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
|
||||||
|
namespace Tranga.NotificationConnectors;
|
||||||
|
|
||||||
|
public class LunaSea : NotificationConnector
|
||||||
|
{
|
||||||
|
// ReSharper disable once MemberCanBePrivate.Global
|
||||||
|
public string id { get; init; }
|
||||||
|
private readonly HttpClient _client = new();
|
||||||
|
|
||||||
|
[JsonConstructor]
|
||||||
|
public LunaSea(GlobalBase clone, string id) : base(clone, NotificationConnectorType.LunaSea)
|
||||||
|
{
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString()
|
||||||
|
{
|
||||||
|
return $"LunaSea {id}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void SendNotification(string title, string notificationText)
|
||||||
|
{
|
||||||
|
Log($"Sending notification: {title} - {notificationText}");
|
||||||
|
MessageData message = new(title, notificationText);
|
||||||
|
HttpRequestMessage request = new(HttpMethod.Post, $"https://notify.lunasea.app/v1/custom/{id}");
|
||||||
|
request.Content = new StringContent(JsonConvert.SerializeObject(message, Formatting.None), Encoding.UTF8, "application/json");
|
||||||
|
HttpResponseMessage response = _client.Send(request);
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
StreamReader sr = new (response.Content.ReadAsStream());
|
||||||
|
Log($"{response.StatusCode}: {sr.ReadToEnd()}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class MessageData
|
||||||
|
{
|
||||||
|
// ReSharper disable twice UnusedAutoPropertyAccessor.Local
|
||||||
|
public string title { get; }
|
||||||
|
public string body { get; }
|
||||||
|
|
||||||
|
public MessageData(string title, string body)
|
||||||
|
{
|
||||||
|
this.title = title;
|
||||||
|
this.body = body;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
15
Tranga/NotificationConnectors/NotificationConnector.cs
Normal file
15
Tranga/NotificationConnectors/NotificationConnector.cs
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
namespace Tranga.NotificationConnectors;
|
||||||
|
|
||||||
|
public abstract class NotificationConnector : GlobalBase
|
||||||
|
{
|
||||||
|
public readonly NotificationConnectorType notificationConnectorType;
|
||||||
|
|
||||||
|
protected NotificationConnector(GlobalBase clone, NotificationConnectorType notificationConnectorType) : base(clone)
|
||||||
|
{
|
||||||
|
this.notificationConnectorType = notificationConnectorType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum NotificationConnectorType : byte { Gotify = 0, LunaSea = 1 }
|
||||||
|
|
||||||
|
public abstract void SendNotification(string title, string notificationText);
|
||||||
|
}
|
@ -0,0 +1,42 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
|
||||||
|
namespace Tranga.NotificationConnectors;
|
||||||
|
|
||||||
|
public class NotificationManagerJsonConverter : JsonConverter
|
||||||
|
{
|
||||||
|
private GlobalBase _clone;
|
||||||
|
|
||||||
|
public NotificationManagerJsonConverter(GlobalBase clone)
|
||||||
|
{
|
||||||
|
this._clone = clone;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool CanConvert(Type objectType)
|
||||||
|
{
|
||||||
|
return (objectType == typeof(NotificationConnector));
|
||||||
|
}
|
||||||
|
|
||||||
|
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue,
|
||||||
|
JsonSerializer serializer)
|
||||||
|
{
|
||||||
|
JObject jo = JObject.Load(reader);
|
||||||
|
if (jo["notificationConnectorType"]!.Value<byte>() == (byte)NotificationConnector.NotificationConnectorType.Gotify)
|
||||||
|
return new Gotify(this._clone, jo.GetValue("endpoint")!.Value<string>()!, jo.GetValue("appToken")!.Value<string>()!);
|
||||||
|
else if (jo["notificationConnectorType"]!.Value<byte>() ==
|
||||||
|
(byte)NotificationConnector.NotificationConnectorType.LunaSea)
|
||||||
|
return new LunaSea(this._clone, jo.GetValue("id")!.Value<string>()!);
|
||||||
|
|
||||||
|
throw new Exception();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool CanWrite => false;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Don't call this
|
||||||
|
/// </summary>
|
||||||
|
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
|
||||||
|
{
|
||||||
|
throw new Exception("Dont call this");
|
||||||
|
}
|
||||||
|
}
|
@ -1,94 +0,0 @@
|
|||||||
using Newtonsoft.Json;
|
|
||||||
|
|
||||||
namespace Tranga;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Contains information on a Publication (Manga)
|
|
||||||
/// </summary>
|
|
||||||
public readonly struct Publication
|
|
||||||
{
|
|
||||||
public string sortName { get; }
|
|
||||||
// ReSharper disable UnusedAutoPropertyAccessor.Global we need it, trust
|
|
||||||
[JsonIgnore]public string[,] altTitles { get; }
|
|
||||||
// ReSharper disable trice MemberCanBePrivate.Global, trust
|
|
||||||
public string? description { get; }
|
|
||||||
public string[] tags { get; }
|
|
||||||
public string? posterUrl { get; }
|
|
||||||
[JsonIgnore]public string[,]? links { get; }
|
|
||||||
public int? year { get; }
|
|
||||||
public string? originalLanguage { get; }
|
|
||||||
public string status { get; }
|
|
||||||
public string folderName { get; }
|
|
||||||
public string downloadUrl { get; }
|
|
||||||
|
|
||||||
public Publication(string sortName, string? description, string[,] altTitles, string[] tags, string? posterUrl, string[,]? links, int? year, string? originalLanguage, string status, string downloadUrl)
|
|
||||||
{
|
|
||||||
this.sortName = sortName;
|
|
||||||
this.description = description;
|
|
||||||
this.altTitles = altTitles;
|
|
||||||
this.tags = tags;
|
|
||||||
this.posterUrl = posterUrl;
|
|
||||||
this.links = links;
|
|
||||||
this.year = year;
|
|
||||||
this.originalLanguage = originalLanguage;
|
|
||||||
this.status = status;
|
|
||||||
this.downloadUrl = downloadUrl;
|
|
||||||
this.folderName = string.Concat(sortName.Split(Path.GetInvalidPathChars().Concat(Path.GetInvalidFileNameChars()).ToArray()));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <returns>Serialized JSON String for series.json</returns>
|
|
||||||
public 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);
|
|
||||||
}
|
|
||||||
|
|
||||||
//Only for series.json
|
|
||||||
private struct SeriesInfo
|
|
||||||
{
|
|
||||||
// ReSharper disable once UnusedAutoPropertyAccessor.Local we need it, trust
|
|
||||||
[JsonRequired]public Metadata metadata { get; }
|
|
||||||
public SeriesInfo(Metadata metadata) => this.metadata = metadata;
|
|
||||||
}
|
|
||||||
|
|
||||||
//Only for series.json what an abomination, why are all the fields not-null????
|
|
||||||
private struct Metadata
|
|
||||||
{
|
|
||||||
// ReSharper disable UnusedAutoPropertyAccessor.Local we need them all, trust me
|
|
||||||
[JsonRequired] public string type { get; }
|
|
||||||
[JsonRequired] public string publisher { get; }
|
|
||||||
// ReSharper disable twice IdentifierTypo
|
|
||||||
[JsonRequired] public int comicid { get; }
|
|
||||||
[JsonRequired] public string booktype { get; }
|
|
||||||
// ReSharper disable InconsistentNaming This one property is capitalized. Why?
|
|
||||||
[JsonRequired] public string ComicImage { get; }
|
|
||||||
[JsonRequired] public int total_issues { get; }
|
|
||||||
[JsonRequired] public string publication_run { get; }
|
|
||||||
[JsonRequired]public string name { get; }
|
|
||||||
[JsonRequired]public string year { get; }
|
|
||||||
[JsonRequired]public string status { get; }
|
|
||||||
[JsonRequired]public string description_text { get; }
|
|
||||||
|
|
||||||
public Metadata(string name, string year, string status, string description_text)
|
|
||||||
{
|
|
||||||
this.name = name;
|
|
||||||
this.year = year;
|
|
||||||
if(status == "ongoing" || status == "hiatus")
|
|
||||||
this.status = "Continuing";
|
|
||||||
else if (status == "completed" || status == "cancelled")
|
|
||||||
this.status = "Ended";
|
|
||||||
else
|
|
||||||
this.status = status;
|
|
||||||
this.description_text = description_text;
|
|
||||||
|
|
||||||
//kill it with fire, but otherwise Komga will not parse
|
|
||||||
type = "Manga";
|
|
||||||
publisher = "";
|
|
||||||
comicid = 0;
|
|
||||||
booktype = "";
|
|
||||||
ComicImage = "";
|
|
||||||
total_issues = 0;
|
|
||||||
publication_run = "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
547
Tranga/Server.cs
Normal file
547
Tranga/Server.cs
Normal file
@ -0,0 +1,547 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Tranga.Jobs;
|
||||||
|
using Tranga.LibraryConnectors;
|
||||||
|
using Tranga.MangaConnectors;
|
||||||
|
using Tranga.NotificationConnectors;
|
||||||
|
|
||||||
|
namespace Tranga;
|
||||||
|
|
||||||
|
public class Server : GlobalBase
|
||||||
|
{
|
||||||
|
private readonly HttpListener _listener = new ();
|
||||||
|
private readonly Tranga _parent;
|
||||||
|
|
||||||
|
public Server(Tranga parent) : base(parent)
|
||||||
|
{
|
||||||
|
this._parent = parent;
|
||||||
|
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||||
|
this._listener.Prefixes.Add($"http://*:{settings.apiPortNumber}/");
|
||||||
|
else
|
||||||
|
this._listener.Prefixes.Add($"http://localhost:{settings.apiPortNumber}/");
|
||||||
|
Thread listenThread = new (Listen);
|
||||||
|
listenThread.Start();
|
||||||
|
Thread watchThread = new(WatchRunning);
|
||||||
|
watchThread.Start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void WatchRunning()
|
||||||
|
{
|
||||||
|
while(_parent.keepRunning)
|
||||||
|
Thread.Sleep(1000);
|
||||||
|
this._listener.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Listen()
|
||||||
|
{
|
||||||
|
this._listener.Start();
|
||||||
|
foreach(string prefix in this._listener.Prefixes)
|
||||||
|
Log($"Listening on {prefix}");
|
||||||
|
while (this._listener.IsListening && _parent.keepRunning)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
HttpListenerContext context = this._listener.GetContext();
|
||||||
|
//Log($"{context.Request.HttpMethod} {context.Request.Url} {context.Request.UserAgent}");
|
||||||
|
Task t = new(() =>
|
||||||
|
{
|
||||||
|
HandleRequest(context);
|
||||||
|
});
|
||||||
|
t.Start();
|
||||||
|
}
|
||||||
|
catch (HttpListenerException e)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void HandleRequest(HttpListenerContext context)
|
||||||
|
{
|
||||||
|
HttpListenerRequest request = context.Request;
|
||||||
|
HttpListenerResponse response = context.Response;
|
||||||
|
if(request.HttpMethod == "OPTIONS")
|
||||||
|
SendResponse(HttpStatusCode.OK, context.Response);
|
||||||
|
if(request.Url!.LocalPath.Contains("favicon"))
|
||||||
|
SendResponse(HttpStatusCode.NoContent, response);
|
||||||
|
|
||||||
|
switch (request.HttpMethod)
|
||||||
|
{
|
||||||
|
case "GET":
|
||||||
|
HandleGet(request, response);
|
||||||
|
break;
|
||||||
|
case "POST":
|
||||||
|
HandlePost(request, response);
|
||||||
|
break;
|
||||||
|
case "DELETE":
|
||||||
|
HandleDelete(request, response);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Dictionary<string, string> GetRequestVariables(string query)
|
||||||
|
{
|
||||||
|
Dictionary<string, string> ret = new();
|
||||||
|
Regex queryRex = new (@"\?{1}&?([A-z0-9-=]+=[A-z0-9-=]+)+(&[A-z0-9-=]+=[A-z0-9-=]+)*");
|
||||||
|
if (!queryRex.IsMatch(query))
|
||||||
|
return ret;
|
||||||
|
query = query.Substring(1);
|
||||||
|
foreach (string keyValuePair in query.Split('&').Where(str => str.Length >= 3))
|
||||||
|
{
|
||||||
|
string var = keyValuePair.Split('=')[0];
|
||||||
|
string val = Regex.Replace(keyValuePair.Substring(var.Length + 1), "%20", " ");
|
||||||
|
val = Regex.Replace(val, "%[0-9]{2}", "");
|
||||||
|
ret.Add(var, val);
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void HandleGet(HttpListenerRequest request, HttpListenerResponse response)
|
||||||
|
{
|
||||||
|
Dictionary<string, string> requestVariables = GetRequestVariables(request.Url!.Query);
|
||||||
|
string? connectorName, jobId, internalId;
|
||||||
|
MangaConnector? connector;
|
||||||
|
Manga? manga;
|
||||||
|
string path = Regex.Match(request.Url!.LocalPath, @"[A-z0-9]+(\/[A-z0-9]+)*").Value;
|
||||||
|
switch (path)
|
||||||
|
{
|
||||||
|
case "Connectors":
|
||||||
|
SendResponse(HttpStatusCode.OK, response, _parent.GetConnectors().Select(con => con.name).ToArray());
|
||||||
|
break;
|
||||||
|
case "Manga/Cover":
|
||||||
|
if (!requestVariables.TryGetValue("internalId", out internalId) ||
|
||||||
|
!_parent.TryGetPublicationById(internalId, out manga))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
string filePath = settings.GetFullCoverPath((Manga)manga!);
|
||||||
|
if (File.Exists(filePath))
|
||||||
|
{
|
||||||
|
FileStream coverStream = new(filePath, FileMode.Open);
|
||||||
|
SendResponse(HttpStatusCode.OK, response, coverStream);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.NotFound, response);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "Manga/FromConnector":
|
||||||
|
requestVariables.TryGetValue("title", out string? title);
|
||||||
|
requestVariables.TryGetValue("url", out string? url);
|
||||||
|
if (!requestVariables.TryGetValue("connector", out connectorName) ||
|
||||||
|
!_parent.TryGetConnector(connectorName, out connector) ||
|
||||||
|
(title is null && url is null))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url is not null)
|
||||||
|
{
|
||||||
|
HashSet<Manga> ret = new();
|
||||||
|
manga = connector!.GetMangaFromUrl(url);
|
||||||
|
if (manga is not null)
|
||||||
|
ret.Add((Manga)manga);
|
||||||
|
SendResponse(HttpStatusCode.OK, response, ret);
|
||||||
|
}else
|
||||||
|
SendResponse(HttpStatusCode.OK, response, connector!.GetManga(title!));
|
||||||
|
break;
|
||||||
|
case "Manga/Chapters":
|
||||||
|
if(!requestVariables.TryGetValue("connector", out connectorName) ||
|
||||||
|
!requestVariables.TryGetValue("internalId", out internalId) ||
|
||||||
|
!_parent.TryGetConnector(connectorName, out connector) ||
|
||||||
|
!_parent.TryGetPublicationById(internalId, out manga))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
requestVariables.TryGetValue("translatedLanguage", out string? translatedLanguage);
|
||||||
|
SendResponse(HttpStatusCode.OK, response, connector!.GetChapters((Manga)manga!, translatedLanguage??"en"));
|
||||||
|
break;
|
||||||
|
case "Jobs":
|
||||||
|
if (!requestVariables.TryGetValue("jobId", out jobId))
|
||||||
|
{
|
||||||
|
if(!_parent.jobBoss.jobs.Any(jjob => jjob.id == jobId))
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
else
|
||||||
|
SendResponse(HttpStatusCode.OK, response, _parent.jobBoss.jobs.First(jjob => jjob.id == jobId));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
SendResponse(HttpStatusCode.OK, response, _parent.jobBoss.jobs);
|
||||||
|
break;
|
||||||
|
case "Jobs/Progress":
|
||||||
|
if (requestVariables.TryGetValue("jobId", out jobId))
|
||||||
|
{
|
||||||
|
if(!_parent.jobBoss.jobs.Any(jjob => jjob.id == jobId))
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
else
|
||||||
|
SendResponse(HttpStatusCode.OK, response, _parent.jobBoss.jobs.First(jjob => jjob.id == jobId).progressToken);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
SendResponse(HttpStatusCode.OK, response, _parent.jobBoss.jobs.Select(jjob => jjob.progressToken));
|
||||||
|
break;
|
||||||
|
case "Jobs/Running":
|
||||||
|
SendResponse(HttpStatusCode.OK, response, _parent.jobBoss.jobs.Where(jjob => jjob.progressToken.state is ProgressToken.State.Running));
|
||||||
|
break;
|
||||||
|
case "Jobs/Waiting":
|
||||||
|
SendResponse(HttpStatusCode.OK, response, _parent.jobBoss.jobs.Where(jjob => jjob.progressToken.state is ProgressToken.State.Standby));
|
||||||
|
break;
|
||||||
|
case "Jobs/MonitorJobs":
|
||||||
|
SendResponse(HttpStatusCode.OK, response, _parent.jobBoss.jobs.Where(jjob => jjob is DownloadNewChapters));
|
||||||
|
break;
|
||||||
|
case "Settings":
|
||||||
|
SendResponse(HttpStatusCode.OK, response, settings);
|
||||||
|
break;
|
||||||
|
case "NotificationConnectors":
|
||||||
|
SendResponse(HttpStatusCode.OK, response, notificationConnectors);
|
||||||
|
break;
|
||||||
|
case "NotificationConnectors/Types":
|
||||||
|
SendResponse(HttpStatusCode.OK, response,
|
||||||
|
Enum.GetValues<NotificationConnector.NotificationConnectorType>().Select(nc => new KeyValuePair<byte, string?>((byte)nc, Enum.GetName(nc))));
|
||||||
|
break;
|
||||||
|
case "LibraryConnectors":
|
||||||
|
SendResponse(HttpStatusCode.OK, response, libraryConnectors);
|
||||||
|
break;
|
||||||
|
case "LibraryConnectors/Types":
|
||||||
|
SendResponse(HttpStatusCode.OK, response,
|
||||||
|
Enum.GetValues<LibraryConnector.LibraryType>().Select(lc => new KeyValuePair<byte, string?>((byte)lc, Enum.GetName(lc))));
|
||||||
|
break;
|
||||||
|
case "Ping":
|
||||||
|
SendResponse(HttpStatusCode.OK, response, "Pong");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void HandlePost(HttpListenerRequest request, HttpListenerResponse response)
|
||||||
|
{
|
||||||
|
Dictionary<string, string> requestVariables = GetRequestVariables(request.Url!.Query);
|
||||||
|
string? connectorName, internalId, jobId, chapterNumStr, customFolderName, translatedLanguage;
|
||||||
|
MangaConnector? connector;
|
||||||
|
Manga? tmpManga;
|
||||||
|
Manga manga;
|
||||||
|
Job? job;
|
||||||
|
string path = Regex.Match(request.Url!.LocalPath, @"[A-z0-9]+(\/[A-z0-9]+)*").Value;
|
||||||
|
switch (path)
|
||||||
|
{
|
||||||
|
case "Manga":
|
||||||
|
if(!requestVariables.TryGetValue("internalId", out internalId) ||
|
||||||
|
!_parent.TryGetPublicationById(internalId, out tmpManga))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
manga = (Manga)tmpManga!;
|
||||||
|
SendResponse(HttpStatusCode.OK, response, manga);
|
||||||
|
break;
|
||||||
|
case "Jobs/MonitorManga":
|
||||||
|
if(!requestVariables.TryGetValue("connector", out connectorName) ||
|
||||||
|
!requestVariables.TryGetValue("internalId", out internalId) ||
|
||||||
|
!requestVariables.TryGetValue("interval", out string? intervalStr) ||
|
||||||
|
!_parent.TryGetConnector(connectorName, out connector)||
|
||||||
|
!_parent.TryGetPublicationById(internalId, out tmpManga) ||
|
||||||
|
!TimeSpan.TryParse(intervalStr, out TimeSpan interval))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
manga = (Manga)tmpManga!;
|
||||||
|
|
||||||
|
if (requestVariables.TryGetValue("ignoreBelowChapterNum", out chapterNumStr))
|
||||||
|
{
|
||||||
|
if (!float.TryParse(chapterNumStr, numberFormatDecimalPoint, out float chapterNum))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
manga.ignoreChaptersBelow = chapterNum;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requestVariables.TryGetValue("customFolderName", out customFolderName))
|
||||||
|
manga.MovePublicationFolder(settings.downloadLocation, customFolderName);
|
||||||
|
requestVariables.TryGetValue("translatedLanguage", out translatedLanguage);
|
||||||
|
|
||||||
|
_parent.jobBoss.AddJob(new DownloadNewChapters(this, connector!, manga, true, interval, translatedLanguage: translatedLanguage??"en"));
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;
|
||||||
|
case "Jobs/DownloadNewChapters":
|
||||||
|
if(!requestVariables.TryGetValue("connector", out connectorName) ||
|
||||||
|
!requestVariables.TryGetValue("internalId", out internalId) ||
|
||||||
|
!_parent.TryGetConnector(connectorName, out connector)||
|
||||||
|
!_parent.TryGetPublicationById(internalId, out tmpManga))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
manga = (Manga)tmpManga!;
|
||||||
|
|
||||||
|
if (requestVariables.TryGetValue("ignoreBelowChapterNum", out chapterNumStr))
|
||||||
|
{
|
||||||
|
if (!float.TryParse(chapterNumStr, numberFormatDecimalPoint, out float chapterNum))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
manga.ignoreChaptersBelow = chapterNum;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requestVariables.TryGetValue("customFolderName", out customFolderName))
|
||||||
|
manga.MovePublicationFolder(settings.downloadLocation, customFolderName);
|
||||||
|
requestVariables.TryGetValue("translatedLanguage", out translatedLanguage);
|
||||||
|
|
||||||
|
_parent.jobBoss.AddJob(new DownloadNewChapters(this, connector!, manga, false, translatedLanguage: translatedLanguage??"en"));
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;
|
||||||
|
case "Jobs/StartNow":
|
||||||
|
if (!requestVariables.TryGetValue("jobId", out jobId) ||
|
||||||
|
!_parent.jobBoss.TryGetJobById(jobId, out job))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_parent.jobBoss.AddJobToQueue(job!);
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;
|
||||||
|
case "Jobs/Cancel":
|
||||||
|
if (!requestVariables.TryGetValue("jobId", out jobId) ||
|
||||||
|
!_parent.jobBoss.TryGetJobById(jobId, out job))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
job!.Cancel();
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;
|
||||||
|
case "Settings/UpdateDownloadLocation":
|
||||||
|
if (!requestVariables.TryGetValue("downloadLocation", out string? downloadLocation) ||
|
||||||
|
!requestVariables.TryGetValue("moveFiles", out string? moveFilesStr) ||
|
||||||
|
!Boolean.TryParse(moveFilesStr, out bool moveFiles))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
settings.UpdateDownloadLocation(downloadLocation, moveFiles);
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;
|
||||||
|
/*case "Settings/UpdateWorkingDirectory":
|
||||||
|
if (!requestVariables.TryGetValue("workingDirectory", out string? workingDirectory))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
settings.UpdateWorkingDirectory(workingDirectory);
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;*/
|
||||||
|
case "NotificationConnectors/Update":
|
||||||
|
if (!requestVariables.TryGetValue("notificationConnector", out string? notificationConnectorStr) ||
|
||||||
|
!Enum.TryParse(notificationConnectorStr, out NotificationConnector.NotificationConnectorType notificationConnectorType))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (notificationConnectorType is NotificationConnector.NotificationConnectorType.Gotify)
|
||||||
|
{
|
||||||
|
if (!requestVariables.TryGetValue("gotifyUrl", out string? gotifyUrl) ||
|
||||||
|
!requestVariables.TryGetValue("gotifyAppToken", out string? gotifyAppToken))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
AddNotificationConnector(new Gotify(this, gotifyUrl, gotifyAppToken));
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (notificationConnectorType is NotificationConnector.NotificationConnectorType.LunaSea)
|
||||||
|
{
|
||||||
|
if (!requestVariables.TryGetValue("lunaseaWebhook", out string? lunaseaWebhook))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
AddNotificationConnector(new LunaSea(this, lunaseaWebhook));
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "LibraryConnectors/Update":
|
||||||
|
if (!requestVariables.TryGetValue("libraryConnector", out string? libraryConnectorStr) ||
|
||||||
|
!Enum.TryParse(libraryConnectorStr,
|
||||||
|
out LibraryConnector.LibraryType libraryConnectorType))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (libraryConnectorType is LibraryConnector.LibraryType.Kavita)
|
||||||
|
{
|
||||||
|
if (!requestVariables.TryGetValue("kavitaUrl", out string? kavitaUrl) ||
|
||||||
|
!requestVariables.TryGetValue("kavitaUsername", out string? kavitaUsername) ||
|
||||||
|
!requestVariables.TryGetValue("kavitaPassword", out string? kavitaPassword))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
AddLibraryConnector(new Kavita(this, kavitaUrl, kavitaUsername, kavitaPassword));
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (libraryConnectorType is LibraryConnector.LibraryType.Komga)
|
||||||
|
{
|
||||||
|
if (!requestVariables.TryGetValue("komgaUrl", out string? komgaUrl) ||
|
||||||
|
!requestVariables.TryGetValue("komgaAuth", out string? komgaAuth))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
AddLibraryConnector(new Komga(this, komgaUrl, komgaAuth));
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "LogMessages":
|
||||||
|
if (logger is null || !File.Exists(logger?.logFilePath))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.NotFound, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requestVariables.TryGetValue("count", out string? count))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
uint messageCount = uint.Parse(count);
|
||||||
|
SendResponse(HttpStatusCode.OK, response, logger.Tail(messageCount));
|
||||||
|
}
|
||||||
|
catch (FormatException f)
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.InternalServerError, response, f);
|
||||||
|
}
|
||||||
|
}else
|
||||||
|
SendResponse(HttpStatusCode.OK, response, logger.GetLog());
|
||||||
|
break;
|
||||||
|
case "LogFile":
|
||||||
|
if (logger is null || !File.Exists(logger?.logFilePath))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.NotFound, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
string logDir = new FileInfo(logger.logFilePath).DirectoryName!;
|
||||||
|
string tmpFilePath = Path.Join(logDir, "Tranga.log");
|
||||||
|
File.Copy(logger.logFilePath, tmpFilePath);
|
||||||
|
SendResponse(HttpStatusCode.OK, response, new FileStream(tmpFilePath, FileMode.Open));
|
||||||
|
File.Delete(tmpFilePath);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void HandleDelete(HttpListenerRequest request, HttpListenerResponse response)
|
||||||
|
{
|
||||||
|
Dictionary<string, string> requestVariables = GetRequestVariables(request.Url!.Query);
|
||||||
|
string? connectorName, internalId;
|
||||||
|
MangaConnector connector;
|
||||||
|
Manga manga;
|
||||||
|
string path = Regex.Match(request.Url!.LocalPath, @"[A-z0-9]+(\/[A-z0-9]+)*").Value;
|
||||||
|
switch (path)
|
||||||
|
{
|
||||||
|
case "Jobs":
|
||||||
|
if (!requestVariables.TryGetValue("jobId", out string? jobId) ||
|
||||||
|
!_parent.jobBoss.TryGetJobById(jobId, out Job? job))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_parent.jobBoss.RemoveJob(job!);
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;
|
||||||
|
case "Jobs/DownloadNewChapters":
|
||||||
|
if(!requestVariables.TryGetValue("connector", out connectorName) ||
|
||||||
|
!requestVariables.TryGetValue("internalId", out internalId) ||
|
||||||
|
_parent.GetConnector(connectorName) is null ||
|
||||||
|
_parent.GetPublicationById(internalId) is null)
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
connector = _parent.GetConnector(connectorName)!;
|
||||||
|
manga = (Manga)_parent.GetPublicationById(internalId)!;
|
||||||
|
_parent.jobBoss.RemoveJobs(_parent.jobBoss.GetJobsLike(connector, manga));
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;
|
||||||
|
case "NotificationConnectors":
|
||||||
|
if (!requestVariables.TryGetValue("notificationConnector", out string? notificationConnectorStr) ||
|
||||||
|
!Enum.TryParse(notificationConnectorStr, out NotificationConnector.NotificationConnectorType notificationConnectorType))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
DeleteNotificationConnector(notificationConnectorType);
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;
|
||||||
|
case "LibraryConnectors":
|
||||||
|
if (!requestVariables.TryGetValue("libraryConnectors", out string? libraryConnectorStr) ||
|
||||||
|
!Enum.TryParse(libraryConnectorStr,
|
||||||
|
out LibraryConnector.LibraryType libraryConnectoryType))
|
||||||
|
{
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
DeleteLibraryConnector(libraryConnectoryType);
|
||||||
|
SendResponse(HttpStatusCode.Accepted, response);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
SendResponse(HttpStatusCode.BadRequest, response);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SendResponse(HttpStatusCode statusCode, HttpListenerResponse response, object? content = null)
|
||||||
|
{
|
||||||
|
//Log($"Response: {statusCode} {content}");
|
||||||
|
response.StatusCode = (int)statusCode;
|
||||||
|
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
|
||||||
|
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, DELETE");
|
||||||
|
response.AddHeader("Access-Control-Max-Age", "1728000");
|
||||||
|
response.AppendHeader("Access-Control-Allow-Origin", "*");
|
||||||
|
|
||||||
|
if (content is not FileStream stream)
|
||||||
|
{
|
||||||
|
response.ContentType = "application/json";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
response.OutputStream.Write(content is not null
|
||||||
|
? Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(content))
|
||||||
|
: Array.Empty<byte>());
|
||||||
|
response.OutputStream.Close();
|
||||||
|
}
|
||||||
|
catch (HttpListenerException e)
|
||||||
|
{
|
||||||
|
Log(e.ToString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
stream.CopyTo(response.OutputStream);
|
||||||
|
response.OutputStream.Close();
|
||||||
|
stream.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,129 +0,0 @@
|
|||||||
using Logging;
|
|
||||||
|
|
||||||
namespace Tranga;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Executes TrangaTasks
|
|
||||||
/// Based on the TrangaTask.Task a method is called.
|
|
||||||
/// The chapterCollection is updated with new Publications/Chapters.
|
|
||||||
/// </summary>
|
|
||||||
public static class TaskExecutor
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Executes TrangaTask.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="taskManager">Parent</param>
|
|
||||||
/// <param name="trangaTask">Task to execute</param>
|
|
||||||
/// <param name="chapterCollection">Current chapterCollection to update</param>
|
|
||||||
/// <param name="logger"></param>
|
|
||||||
/// <exception cref="ArgumentException">Is thrown when there is no Connector available with the name of the TrangaTask.connectorName</exception>
|
|
||||||
public static void Execute(TaskManager taskManager, TrangaTask trangaTask, Dictionary<Publication, List<Chapter>> chapterCollection, Logger? logger)
|
|
||||||
{
|
|
||||||
//Only execute task if it is not already being executed.
|
|
||||||
if (trangaTask.state == TrangaTask.ExecutionState.Running)
|
|
||||||
{
|
|
||||||
logger?.WriteLine("TaskExecutor", $"Task already running {trangaTask}");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
trangaTask.state = TrangaTask.ExecutionState.Running;
|
|
||||||
logger?.WriteLine("TaskExecutor", $"Starting Task {trangaTask}");
|
|
||||||
|
|
||||||
//Connector is not needed for all tasks
|
|
||||||
Connector? connector = null;
|
|
||||||
if (trangaTask.task != TrangaTask.Task.UpdateKomgaLibrary)
|
|
||||||
connector = taskManager.GetConnector(trangaTask.connectorName!);
|
|
||||||
|
|
||||||
//Call appropriate Method based on TrangaTask.Task
|
|
||||||
switch (trangaTask.task)
|
|
||||||
{
|
|
||||||
case TrangaTask.Task.DownloadNewChapters:
|
|
||||||
DownloadNewChapters(connector!, (Publication)trangaTask.publication!, trangaTask.language, chapterCollection);
|
|
||||||
break;
|
|
||||||
case TrangaTask.Task.UpdateChapters:
|
|
||||||
UpdateChapters(connector!, (Publication)trangaTask.publication!, trangaTask.language, chapterCollection);
|
|
||||||
break;
|
|
||||||
case TrangaTask.Task.UpdatePublications:
|
|
||||||
UpdatePublications(connector!, chapterCollection);
|
|
||||||
break;
|
|
||||||
case TrangaTask.Task.UpdateKomgaLibrary:
|
|
||||||
UpdateKomgaLibrary(taskManager);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
logger?.WriteLine("TaskExecutor", $"Task finished! {trangaTask}");
|
|
||||||
trangaTask.lastExecuted = DateTime.Now;
|
|
||||||
trangaTask.state = TrangaTask.ExecutionState.Waiting;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Updates all Komga-Libraries
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="taskManager">Parent</param>
|
|
||||||
private static void UpdateKomgaLibrary(TaskManager taskManager)
|
|
||||||
{
|
|
||||||
if (taskManager.komga is null)
|
|
||||||
return;
|
|
||||||
Komga komga = taskManager.komga;
|
|
||||||
|
|
||||||
Komga.KomgaLibrary[] allLibraries = komga.GetLibraries();
|
|
||||||
foreach (Komga.KomgaLibrary lib in allLibraries)
|
|
||||||
komga.UpdateLibrary(lib.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Updates the available Publications from a Connector (all of them)
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="connector">Connector to receive Publications from</param>
|
|
||||||
/// <param name="chapterCollection"></param>
|
|
||||||
private static void UpdatePublications(Connector connector, Dictionary<Publication, List<Chapter>> chapterCollection)
|
|
||||||
{
|
|
||||||
Publication[] publications = connector.GetPublications();
|
|
||||||
foreach (Publication publication in publications)
|
|
||||||
chapterCollection.TryAdd(publication, new List<Chapter>());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Checks for new Chapters and Downloads new ones.
|
|
||||||
/// If no Chapters had been downloaded previously, download also cover and create series.json
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="connector">Connector to use</param>
|
|
||||||
/// <param name="publication">Publication to check</param>
|
|
||||||
/// <param name="language">Language to receive chapters for</param>
|
|
||||||
/// <param name="chapterCollection"></param>
|
|
||||||
private static void DownloadNewChapters(Connector connector, Publication publication, string language, Dictionary<Publication, List<Chapter>> chapterCollection)
|
|
||||||
{
|
|
||||||
List<Chapter> newChapters = UpdateChapters(connector, publication, language, chapterCollection);
|
|
||||||
connector.DownloadCover(publication);
|
|
||||||
|
|
||||||
//Check if Publication already has a Folder and a series.json
|
|
||||||
string publicationFolder = Path.Join(connector.downloadLocation, publication.folderName);
|
|
||||||
if(!Directory.Exists(publicationFolder))
|
|
||||||
Directory.CreateDirectory(publicationFolder);
|
|
||||||
|
|
||||||
string seriesInfoPath = Path.Join(publicationFolder, "series.json");
|
|
||||||
if(!File.Exists(seriesInfoPath))
|
|
||||||
File.WriteAllText(seriesInfoPath,publication.GetSeriesInfoJson());
|
|
||||||
|
|
||||||
foreach(Chapter newChapter in newChapters)
|
|
||||||
connector.DownloadChapter(publication, newChapter);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Updates the available Chapters of a Publication
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="connector">Connector to use</param>
|
|
||||||
/// <param name="publication">Publication to check</param>
|
|
||||||
/// <param name="language">Language to receive chapters for</param>
|
|
||||||
/// <param name="chapterCollection"></param>
|
|
||||||
/// <returns>List of Chapters that were previously not in collection</returns>
|
|
||||||
private static List<Chapter> UpdateChapters(Connector connector, Publication publication, string language, Dictionary<Publication, List<Chapter>> chapterCollection)
|
|
||||||
{
|
|
||||||
List<Chapter> newChaptersList = new();
|
|
||||||
chapterCollection.TryAdd(publication, newChaptersList); //To ensure publication is actually in collection
|
|
||||||
|
|
||||||
Chapter[] newChapters = connector.GetChapters(publication, language);
|
|
||||||
newChaptersList = newChapters.Where(nChapter => !connector.ChapterIsDownloaded(publication, nChapter)).ToList();
|
|
||||||
|
|
||||||
return newChaptersList;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,289 +0,0 @@
|
|||||||
using Logging;
|
|
||||||
using Newtonsoft.Json;
|
|
||||||
using Tranga.Connectors;
|
|
||||||
|
|
||||||
namespace Tranga;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Manages all TrangaTasks.
|
|
||||||
/// Provides a Threaded environment to execute Tasks, and still manage the Task-Collection
|
|
||||||
/// </summary>
|
|
||||||
public class TaskManager
|
|
||||||
{
|
|
||||||
private readonly Dictionary<Publication, List<Chapter>> _chapterCollection = new();
|
|
||||||
private readonly HashSet<TrangaTask> _allTasks;
|
|
||||||
private bool _continueRunning = true;
|
|
||||||
private readonly Connector[] _connectors;
|
|
||||||
private Dictionary<Connector, List<TrangaTask>> tasksToExecute = new();
|
|
||||||
private string downloadLocation { get; }
|
|
||||||
private Logger? logger { get; }
|
|
||||||
|
|
||||||
public Komga? komga { get; }
|
|
||||||
|
|
||||||
/// <param name="folderPath">Local path to save data (Manga) to</param>
|
|
||||||
/// <param name="komgaBaseUrl">The Url of the Komga-instance that you want to update</param>
|
|
||||||
/// <param name="komgaUsername">The Komga username</param>
|
|
||||||
/// <param name="komgaPassword">The Komga password</param>
|
|
||||||
/// <param name="logger"></param>
|
|
||||||
public TaskManager(string folderPath, string? komgaBaseUrl = null, string? komgaUsername = null, string? komgaPassword = null, Logger? logger = null)
|
|
||||||
{
|
|
||||||
this.logger = logger;
|
|
||||||
this.downloadLocation = folderPath;
|
|
||||||
|
|
||||||
if (komgaBaseUrl != null && komgaUsername != null && komgaPassword != null)
|
|
||||||
this.komga = new Komga(komgaBaseUrl, komgaUsername, komgaPassword, logger);
|
|
||||||
this._connectors = new Connector[]{ new MangaDex(folderPath, logger) };
|
|
||||||
foreach(Connector cConnector in this._connectors)
|
|
||||||
tasksToExecute.Add(cConnector, new List<TrangaTask>());
|
|
||||||
_allTasks = new HashSet<TrangaTask>();
|
|
||||||
|
|
||||||
Thread taskChecker = new(TaskCheckerThread);
|
|
||||||
taskChecker.Start();
|
|
||||||
}
|
|
||||||
|
|
||||||
public TaskManager(SettingsData settings, Logger? logger = null)
|
|
||||||
{
|
|
||||||
this.logger = logger;
|
|
||||||
this._connectors = new Connector[]{ new MangaDex(settings.downloadLocation, logger) };
|
|
||||||
foreach(Connector cConnector in this._connectors)
|
|
||||||
tasksToExecute.Add(cConnector, new List<TrangaTask>());
|
|
||||||
this.downloadLocation = settings.downloadLocation;
|
|
||||||
this.komga = settings.komga;
|
|
||||||
_allTasks = settings.allTasks;
|
|
||||||
Thread taskChecker = new(TaskCheckerThread);
|
|
||||||
taskChecker.Start();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Runs continuously until shutdown.
|
|
||||||
/// Checks if tasks have to be executed (time elapsed)
|
|
||||||
/// </summary>
|
|
||||||
private void TaskCheckerThread()
|
|
||||||
{
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), "Starting TaskCheckerThread.");
|
|
||||||
while (_continueRunning)
|
|
||||||
{
|
|
||||||
//Check if previous tasks have finished and execute new tasks
|
|
||||||
foreach (KeyValuePair<Connector, List<TrangaTask>> connectorTaskQueue in tasksToExecute)
|
|
||||||
{
|
|
||||||
if(connectorTaskQueue.Value.RemoveAll(task => task.state == TrangaTask.ExecutionState.Waiting) > 0)
|
|
||||||
ExportData(Directory.GetCurrentDirectory());
|
|
||||||
|
|
||||||
if (connectorTaskQueue.Value.Count > 0 && connectorTaskQueue.Value.All(task => task.state is TrangaTask.ExecutionState.Enqueued))
|
|
||||||
ExecuteTaskNow(connectorTaskQueue.Value.First());
|
|
||||||
}
|
|
||||||
|
|
||||||
//Check if task should be executed
|
|
||||||
//Depending on type execute immediately or enqueue
|
|
||||||
foreach (TrangaTask task in _allTasks.Where(aTask => aTask.ShouldExecute()))
|
|
||||||
{
|
|
||||||
task.state = TrangaTask.ExecutionState.Enqueued;
|
|
||||||
if(task.connectorName is null)
|
|
||||||
ExecuteTaskNow(task);
|
|
||||||
else
|
|
||||||
{
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Task due: {task}");
|
|
||||||
tasksToExecute[GetConnector(task.connectorName!)].Add(task);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Thread.Sleep(1000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Forces the execution of a given task
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="task">Task to execute</param>
|
|
||||||
public void ExecuteTaskNow(TrangaTask task)
|
|
||||||
{
|
|
||||||
if (!this._allTasks.Contains(task))
|
|
||||||
return;
|
|
||||||
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Forcing Execution: {task}");
|
|
||||||
Task t = new Task(() =>
|
|
||||||
{
|
|
||||||
TaskExecutor.Execute(this, task, this._chapterCollection, logger);
|
|
||||||
});
|
|
||||||
t.Start();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Creates and adds a new Task to the task-Collection
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="task">TrangaTask.Task to later execute</param>
|
|
||||||
/// <param name="connectorName">Name of the connector to use</param>
|
|
||||||
/// <param name="publication">Publication to execute Task on, can be null in case of unrelated Task</param>
|
|
||||||
/// <param name="reoccurrence">Time-Interval between Executions</param>
|
|
||||||
/// <param name="language">language, should Task require parameter. Can be empty</param>
|
|
||||||
/// <exception cref="ArgumentException">Is thrown when connectorName is not a available Connector</exception>
|
|
||||||
public TrangaTask AddTask(TrangaTask.Task task, string? connectorName, Publication? publication, TimeSpan reoccurrence,
|
|
||||||
string language = "")
|
|
||||||
{
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Adding new Task {task} {connectorName} {publication?.sortName}");
|
|
||||||
if (task != TrangaTask.Task.UpdateKomgaLibrary && connectorName is null)
|
|
||||||
throw new ArgumentException($"connectorName can not be null for task {task}");
|
|
||||||
|
|
||||||
TrangaTask newTask;
|
|
||||||
if (task == TrangaTask.Task.UpdateKomgaLibrary)
|
|
||||||
{
|
|
||||||
newTask = new TrangaTask(task, null, null, reoccurrence, language);
|
|
||||||
|
|
||||||
//Check if same task already exists
|
|
||||||
// ReSharper disable once SimplifyLinqExpressionUseAll readabilty
|
|
||||||
if (!_allTasks.Any(trangaTask => trangaTask.task == task))
|
|
||||||
{
|
|
||||||
_allTasks.Add(newTask);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
//Get appropriate Connector from available Connectors for TrangaTask
|
|
||||||
Connector? connector = _connectors.FirstOrDefault(c => c.name == connectorName);
|
|
||||||
if (connector is null)
|
|
||||||
throw new ArgumentException($"Connector {connectorName} is not a known connector.");
|
|
||||||
|
|
||||||
newTask = new TrangaTask(task, connector.name, publication, reoccurrence, language);
|
|
||||||
|
|
||||||
//Check if same task already exists
|
|
||||||
if (!_allTasks.Any(trangaTask => trangaTask.task == task && trangaTask.connectorName == connector.name &&
|
|
||||||
trangaTask.publication?.downloadUrl == publication?.downloadUrl))
|
|
||||||
{
|
|
||||||
if(task != TrangaTask.Task.UpdatePublications)
|
|
||||||
_chapterCollection.Add((Publication)publication!, new List<Chapter>());
|
|
||||||
_allTasks.Add(newTask);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Added new Task {newTask.ToString()}");
|
|
||||||
ExportData(Directory.GetCurrentDirectory());
|
|
||||||
|
|
||||||
return newTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Removes Task from task-collection
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="task">TrangaTask.Task type</param>
|
|
||||||
/// <param name="connectorName">Name of Connector that was used</param>
|
|
||||||
/// <param name="publication">Publication that was used</param>
|
|
||||||
public void RemoveTask(TrangaTask.Task task, string? connectorName, Publication? publication)
|
|
||||||
{
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Removing Task {task} {publication?.sortName}");
|
|
||||||
if (task == TrangaTask.Task.UpdateKomgaLibrary)
|
|
||||||
{
|
|
||||||
_allTasks.RemoveWhere(uTask => uTask.task == TrangaTask.Task.UpdateKomgaLibrary);
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Removed Task {task}");
|
|
||||||
}
|
|
||||||
else if (connectorName is null)
|
|
||||||
throw new ArgumentException($"connectorName can not be null for Task {task}");
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if(_allTasks.RemoveWhere(trangaTask =>
|
|
||||||
trangaTask.task == task && trangaTask.connectorName == connectorName &&
|
|
||||||
trangaTask.publication?.downloadUrl == publication?.downloadUrl) > 0)
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Removed Task {task} {publication?.sortName} {publication?.downloadUrl}.");
|
|
||||||
else
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"No Task {task} {publication?.sortName} {publication?.downloadUrl} could be found.");
|
|
||||||
}
|
|
||||||
ExportData(Directory.GetCurrentDirectory());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <returns>All available Connectors</returns>
|
|
||||||
public Dictionary<string, Connector> GetAvailableConnectors()
|
|
||||||
{
|
|
||||||
return this._connectors.ToDictionary(connector => connector.name, connector => connector);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <returns>All TrangaTasks in task-collection</returns>
|
|
||||||
public TrangaTask[] GetAllTasks()
|
|
||||||
{
|
|
||||||
TrangaTask[] ret = new TrangaTask[_allTasks.Count];
|
|
||||||
_allTasks.CopyTo(ret);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <returns>All added Publications</returns>
|
|
||||||
public Publication[] GetAllPublications()
|
|
||||||
{
|
|
||||||
return this._chapterCollection.Keys.ToArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Return Connector with given Name
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="connectorName">Connector-name (exact)</param>
|
|
||||||
/// <exception cref="Exception">If Connector is not available</exception>
|
|
||||||
public Connector GetConnector(string? connectorName)
|
|
||||||
{
|
|
||||||
if(connectorName is null)
|
|
||||||
throw new Exception($"connectorName can not be null");
|
|
||||||
Connector? ret = this._connectors.FirstOrDefault(connector => connector.name == connectorName);
|
|
||||||
if (ret is null)
|
|
||||||
throw new Exception($"Connector {connectorName} is not an available Connector.");
|
|
||||||
return (Connector)ret!;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Shuts down the taskManager.
|
|
||||||
/// </summary>
|
|
||||||
/// <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})");
|
|
||||||
_continueRunning = false;
|
|
||||||
ExportData(Directory.GetCurrentDirectory());
|
|
||||||
|
|
||||||
if(force)
|
|
||||||
Environment.Exit(_allTasks.Count(task => task.state is TrangaTask.ExecutionState.Enqueued or TrangaTask.ExecutionState.Running));
|
|
||||||
|
|
||||||
//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!");
|
|
||||||
Environment.Exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Loads stored data (settings, tasks) from file
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="importFolderPath">working directory, filename has to be data.json</param>
|
|
||||||
public static SettingsData LoadData(string importFolderPath)
|
|
||||||
{
|
|
||||||
string importPath = Path.Join(importFolderPath, "data.json");
|
|
||||||
if (!File.Exists(importPath))
|
|
||||||
return new SettingsData("", null, new HashSet<TrangaTask>());
|
|
||||||
|
|
||||||
string toRead = File.ReadAllText(importPath);
|
|
||||||
SettingsData data = JsonConvert.DeserializeObject<SettingsData>(toRead)!;
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Exports data (settings, tasks) to file
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="exportFolderPath">Folder path, filename will be data.json</param>
|
|
||||||
private void ExportData(string exportFolderPath)
|
|
||||||
{
|
|
||||||
logger?.WriteLine(this.GetType().ToString(), $"Exporting data to data.json");
|
|
||||||
SettingsData data = new SettingsData(this.downloadLocation, this.komga, this._allTasks);
|
|
||||||
|
|
||||||
string exportPath = Path.Join(exportFolderPath, "data.json");
|
|
||||||
string serializedData = JsonConvert.SerializeObject(data);
|
|
||||||
File.Delete(exportPath);
|
|
||||||
File.WriteAllText(exportPath, serializedData);
|
|
||||||
}
|
|
||||||
|
|
||||||
public class SettingsData
|
|
||||||
{
|
|
||||||
public string downloadLocation { get; set; }
|
|
||||||
public Komga? komga { get; set; }
|
|
||||||
public HashSet<TrangaTask> allTasks { get; }
|
|
||||||
|
|
||||||
public SettingsData(string downloadLocation, Komga? komga, HashSet<TrangaTask> allTasks)
|
|
||||||
{
|
|
||||||
this.downloadLocation = downloadLocation;
|
|
||||||
this.komga = komga;
|
|
||||||
this.allTasks = allTasks;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
79
Tranga/Tranga.cs
Normal file
79
Tranga/Tranga.cs
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
using Logging;
|
||||||
|
using Tranga.Jobs;
|
||||||
|
using Tranga.MangaConnectors;
|
||||||
|
|
||||||
|
namespace Tranga;
|
||||||
|
|
||||||
|
public partial class Tranga : GlobalBase
|
||||||
|
{
|
||||||
|
public bool keepRunning;
|
||||||
|
public JobBoss jobBoss;
|
||||||
|
private Server _server;
|
||||||
|
private HashSet<MangaConnector> _connectors;
|
||||||
|
|
||||||
|
public Tranga(Logger? logger, TrangaSettings settings) : base(logger, settings)
|
||||||
|
{
|
||||||
|
keepRunning = true;
|
||||||
|
_connectors = new HashSet<MangaConnector>()
|
||||||
|
{
|
||||||
|
new Manganato(this),
|
||||||
|
new Mangasee(this),
|
||||||
|
new MangaDex(this),
|
||||||
|
new MangaKatana(this),
|
||||||
|
new Mangaworld(this)
|
||||||
|
};
|
||||||
|
jobBoss = new(this, this._connectors);
|
||||||
|
StartJobBoss();
|
||||||
|
this._server = new Server(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public MangaConnector? GetConnector(string name)
|
||||||
|
{
|
||||||
|
foreach(MangaConnector mc in _connectors)
|
||||||
|
if (mc.name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
|
||||||
|
return mc;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryGetConnector(string name, out MangaConnector? connector)
|
||||||
|
{
|
||||||
|
connector = GetConnector(name);
|
||||||
|
return connector is not null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IEnumerable<MangaConnector> GetConnectors()
|
||||||
|
{
|
||||||
|
return _connectors;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Manga? GetPublicationById(string internalId)
|
||||||
|
{
|
||||||
|
if (cachedPublications.Exists(publication => publication.internalId == internalId))
|
||||||
|
return cachedPublications.First(publication => publication.internalId == internalId);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryGetPublicationById(string internalId, out Manga? manga)
|
||||||
|
{
|
||||||
|
manga = GetPublicationById(internalId);
|
||||||
|
return manga is not null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void StartJobBoss()
|
||||||
|
{
|
||||||
|
Thread t = new (() =>
|
||||||
|
{
|
||||||
|
while (keepRunning)
|
||||||
|
{
|
||||||
|
jobBoss.CheckJobs();
|
||||||
|
Thread.Sleep(100);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (MangaConnector connector in _connectors)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
});
|
||||||
|
t.Start();
|
||||||
|
}
|
||||||
|
}
|
@ -4,14 +4,24 @@
|
|||||||
<TargetFramework>net7.0</TargetFramework>
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="HtmlAgilityPack" Version="1.11.46" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
|
<PackageReference Include="PuppeteerSharp" Version="10.0.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Logging\Logging.csproj" />
|
<ProjectReference Include="..\Logging\Logging.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Content Include="..\.dockerignore">
|
||||||
|
<Link>.dockerignore</Link>
|
||||||
|
<DependentUpon>Dockerfile</DependentUpon>
|
||||||
|
</Content>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
136
Tranga/TrangaArgs.cs
Normal file
136
Tranga/TrangaArgs.cs
Normal file
@ -0,0 +1,136 @@
|
|||||||
|
using Logging;
|
||||||
|
|
||||||
|
namespace Tranga;
|
||||||
|
|
||||||
|
public partial class Tranga : GlobalBase
|
||||||
|
{
|
||||||
|
|
||||||
|
public static void Main(string[] args)
|
||||||
|
{
|
||||||
|
string[]? help = GetArg(args, ArgEnum.Help);
|
||||||
|
if (help is not null)
|
||||||
|
{
|
||||||
|
PrintHelp();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string[]? consoleLogger = GetArg(args, ArgEnum.ConsoleLogger);
|
||||||
|
string[]? fileLogger = GetArg(args, ArgEnum.FileLogger);
|
||||||
|
string? filePath = fileLogger?[0];//TODO validate path
|
||||||
|
|
||||||
|
List<Logger.LoggerType> enabledLoggers = new();
|
||||||
|
if(consoleLogger is not null)
|
||||||
|
enabledLoggers.Add(Logger.LoggerType.ConsoleLogger);
|
||||||
|
if (fileLogger is not null)
|
||||||
|
enabledLoggers.Add(Logger.LoggerType.FileLogger);
|
||||||
|
Logger logger = new(enabledLoggers.ToArray(), Console.Out, Console.OutputEncoding, filePath);
|
||||||
|
|
||||||
|
TrangaSettings? settings = null;
|
||||||
|
string[]? downloadLocationPath = GetArg(args, ArgEnum.DownloadLocation);
|
||||||
|
string[]? workingDirectory = GetArg(args, ArgEnum.WorkingDirectory);
|
||||||
|
|
||||||
|
if (downloadLocationPath is not null && workingDirectory is not null)
|
||||||
|
{
|
||||||
|
settings = new TrangaSettings(downloadLocationPath[0], workingDirectory[0]);
|
||||||
|
}else if (downloadLocationPath is not null)
|
||||||
|
{
|
||||||
|
if (settings is null)
|
||||||
|
settings = new TrangaSettings(downloadLocation: downloadLocationPath[0]);
|
||||||
|
else
|
||||||
|
settings = new TrangaSettings(downloadLocation: downloadLocationPath[0], settings.workingDirectory);
|
||||||
|
}else if (workingDirectory is not null)
|
||||||
|
{
|
||||||
|
if (settings is null)
|
||||||
|
settings = new TrangaSettings(downloadLocation: workingDirectory[0]);
|
||||||
|
else
|
||||||
|
settings = new TrangaSettings(settings.downloadLocation, workingDirectory[0]);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
settings = new TrangaSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
Directory.CreateDirectory(settings.downloadLocation);//TODO validate path
|
||||||
|
Directory.CreateDirectory(settings.workingDirectory);//TODO validate path
|
||||||
|
|
||||||
|
Tranga _ = new (logger, settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void PrintHelp()
|
||||||
|
{
|
||||||
|
Console.WriteLine("Tranga-Help:");
|
||||||
|
foreach (Argument argument in arguments.Values)
|
||||||
|
{
|
||||||
|
foreach(string name in argument.names)
|
||||||
|
Console.Write("{0} ", name);
|
||||||
|
if(argument.parameterCount > 0)
|
||||||
|
Console.Write($"<{argument.parameterCount}>");
|
||||||
|
Console.Write("\r\n {0}\r\n", argument.helpText);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns an array containing the parameters for the argument.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="args">List of argument-strings</param>
|
||||||
|
/// <param name="arg">Requested parameter</param>
|
||||||
|
/// <returns>
|
||||||
|
/// If there are no parameters for an argument, returns an empty array.
|
||||||
|
/// If the argument is not found returns null.
|
||||||
|
/// </returns>
|
||||||
|
private static string[]? GetArg(string[] args, ArgEnum arg)
|
||||||
|
{
|
||||||
|
List<string> argsList = args.ToList();
|
||||||
|
List<string> ret = new();
|
||||||
|
foreach (string name in arguments[arg].names)
|
||||||
|
{
|
||||||
|
int argIndex = argsList.IndexOf(name);
|
||||||
|
if (argIndex != -1)
|
||||||
|
{
|
||||||
|
if (arguments[arg].parameterCount == 0)
|
||||||
|
return ret.ToArray();
|
||||||
|
for (int parameterIndex = 1; parameterIndex <= arguments[arg].parameterCount; parameterIndex++)
|
||||||
|
{
|
||||||
|
if(argIndex + parameterIndex >= argsList.Count || args[argIndex + parameterIndex].Contains('-'))//End of arguments, or no parameter provided, when one is required
|
||||||
|
Console.WriteLine($"No parameter provided for argument {name}. -h for help.");
|
||||||
|
ret.Add(args[argIndex + parameterIndex]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ret.Any() ? ret.ToArray() : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Dictionary<ArgEnum, Argument> arguments = new()
|
||||||
|
{
|
||||||
|
{ ArgEnum.DownloadLocation, new(new []{"-d", "--downloadLocation"}, 1, "Directory to which downloaded Manga are saved") },
|
||||||
|
{ ArgEnum.WorkingDirectory, new(new []{"-w", "--workingDirectory"}, 1, "Directory in which application-data is saved") },
|
||||||
|
{ ArgEnum.ConsoleLogger, new(new []{"-c", "--consoleLogger"}, 0, "Enables the consoleLogger") },
|
||||||
|
{ ArgEnum.FileLogger, new(new []{"-f", "--fileLogger"}, 1, "Enables the fileLogger, Directory where logfiles are saved") },
|
||||||
|
{ ArgEnum.Help, new(new []{"-h", "--help"}, 0, "Print this") }
|
||||||
|
//{ ArgEnum., new(new []{""}, 1, "") }
|
||||||
|
};
|
||||||
|
|
||||||
|
internal enum ArgEnum
|
||||||
|
{
|
||||||
|
TrangaSettings,
|
||||||
|
DownloadLocation,
|
||||||
|
WorkingDirectory,
|
||||||
|
ConsoleLogger,
|
||||||
|
FileLogger,
|
||||||
|
Help
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct Argument
|
||||||
|
{
|
||||||
|
public string[] names { get; }
|
||||||
|
public byte parameterCount { get; }
|
||||||
|
public string helpText { get; }
|
||||||
|
|
||||||
|
public Argument(string[] names, byte parameterCount, string helpText)
|
||||||
|
{
|
||||||
|
this.names = names;
|
||||||
|
this.parameterCount = parameterCount;
|
||||||
|
this.helpText = helpText;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
135
Tranga/TrangaSettings.cs
Normal file
135
Tranga/TrangaSettings.cs
Normal file
@ -0,0 +1,135 @@
|
|||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Tranga.LibraryConnectors;
|
||||||
|
using Tranga.NotificationConnectors;
|
||||||
|
using static System.IO.UnixFileMode;
|
||||||
|
|
||||||
|
namespace Tranga;
|
||||||
|
|
||||||
|
public class TrangaSettings
|
||||||
|
{
|
||||||
|
public string downloadLocation { get; private set; }
|
||||||
|
public string workingDirectory { get; private set; }
|
||||||
|
public int apiPortNumber { get; init; }
|
||||||
|
[JsonIgnore] public string settingsFilePath => Path.Join(workingDirectory, "settings.json");
|
||||||
|
[JsonIgnore] public string libraryConnectorsFilePath => Path.Join(workingDirectory, "libraryConnectors.json");
|
||||||
|
[JsonIgnore] public string notificationConnectorsFilePath => Path.Join(workingDirectory, "notificationConnectors.json");
|
||||||
|
[JsonIgnore] public string jobsFolderPath => Path.Join(workingDirectory, "jobs");
|
||||||
|
[JsonIgnore] public string coverImageCache => Path.Join(workingDirectory, "imageCache");
|
||||||
|
public ushort? version { get; set; }
|
||||||
|
|
||||||
|
public TrangaSettings(string? downloadLocation = null, string? workingDirectory = null, int? apiPortNumber = null)
|
||||||
|
{
|
||||||
|
string lockFilePath = $"{settingsFilePath}.lock";
|
||||||
|
if (File.Exists(settingsFilePath) && !File.Exists(lockFilePath))
|
||||||
|
{//Load from settings file
|
||||||
|
FileStream lockFile = File.Create(lockFilePath,0, FileOptions.DeleteOnClose);
|
||||||
|
string settingsStr = File.ReadAllText(settingsFilePath);
|
||||||
|
TrangaSettings settings = JsonConvert.DeserializeObject<TrangaSettings>(settingsStr)!;
|
||||||
|
this.downloadLocation = downloadLocation ?? settings.downloadLocation;
|
||||||
|
this.workingDirectory = workingDirectory ?? settings.workingDirectory;
|
||||||
|
this.apiPortNumber = apiPortNumber ?? settings.apiPortNumber;
|
||||||
|
lockFile.Close();
|
||||||
|
}
|
||||||
|
else if(!File.Exists(settingsFilePath))
|
||||||
|
{//No settings file exists
|
||||||
|
if (downloadLocation?.Length < 1 || workingDirectory?.Length < 1)
|
||||||
|
throw new ArgumentException("Download-location and working-directory paths can not be empty!");
|
||||||
|
this.apiPortNumber = apiPortNumber ?? 6531;
|
||||||
|
this.downloadLocation = downloadLocation ?? (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "/Manga" : Path.Join(Directory.GetCurrentDirectory(), "Downloads"));
|
||||||
|
this.workingDirectory = workingDirectory ?? Path.Join(RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "/var/lib" : Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "tranga-api");
|
||||||
|
ExportSettings();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{//Settingsfile is locked
|
||||||
|
this.apiPortNumber = apiPortNumber!.Value;
|
||||||
|
this.downloadLocation = downloadLocation!;
|
||||||
|
this.workingDirectory = workingDirectory!;
|
||||||
|
}
|
||||||
|
UpdateDownloadLocation(this.downloadLocation!, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public HashSet<LibraryConnector> LoadLibraryConnectors(GlobalBase clone)
|
||||||
|
{
|
||||||
|
if (!File.Exists(libraryConnectorsFilePath))
|
||||||
|
return new HashSet<LibraryConnector>();
|
||||||
|
return JsonConvert.DeserializeObject<HashSet<LibraryConnector>>(File.ReadAllText(libraryConnectorsFilePath),
|
||||||
|
new JsonSerializerSettings()
|
||||||
|
{
|
||||||
|
Converters =
|
||||||
|
{
|
||||||
|
new LibraryManagerJsonConverter(clone)
|
||||||
|
}
|
||||||
|
})!;
|
||||||
|
}
|
||||||
|
|
||||||
|
public HashSet<NotificationConnector> LoadNotificationConnectors(GlobalBase clone)
|
||||||
|
{
|
||||||
|
if (!File.Exists(notificationConnectorsFilePath))
|
||||||
|
return new HashSet<NotificationConnector>();
|
||||||
|
return JsonConvert.DeserializeObject<HashSet<NotificationConnector>>(File.ReadAllText(notificationConnectorsFilePath),
|
||||||
|
new JsonSerializerSettings()
|
||||||
|
{
|
||||||
|
Converters =
|
||||||
|
{
|
||||||
|
new NotificationManagerJsonConverter(clone)
|
||||||
|
}
|
||||||
|
})!;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void UpdateDownloadLocation(string newPath, bool moveFiles = true)
|
||||||
|
{
|
||||||
|
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||||
|
Directory.CreateDirectory(newPath,
|
||||||
|
GroupRead | GroupWrite | None | OtherRead | OtherWrite | UserRead | UserWrite);
|
||||||
|
else
|
||||||
|
Directory.CreateDirectory(newPath);
|
||||||
|
|
||||||
|
if (moveFiles && Directory.Exists(this.downloadLocation))
|
||||||
|
Directory.Move(this.downloadLocation, newPath);
|
||||||
|
|
||||||
|
this.downloadLocation = newPath;
|
||||||
|
ExportSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void UpdateWorkingDirectory(string newPath)
|
||||||
|
{
|
||||||
|
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||||
|
Directory.CreateDirectory(newPath,
|
||||||
|
GroupRead | GroupWrite | None | OtherRead | OtherWrite | UserRead | UserWrite);
|
||||||
|
else
|
||||||
|
Directory.CreateDirectory(newPath);
|
||||||
|
Directory.Move(this.workingDirectory, newPath);
|
||||||
|
this.workingDirectory = newPath;
|
||||||
|
ExportSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
Thread.Sleep(100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
Directory.CreateDirectory(new FileInfo(settingsFilePath).DirectoryName!);
|
||||||
|
File.WriteAllText(settingsFilePath, JsonConvert.SerializeObject(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
public string GetFullCoverPath(Manga manga)
|
||||||
|
{
|
||||||
|
return Path.Join(this.coverImageCache, manga.coverFileNameInCache);
|
||||||
|
}
|
||||||
|
}
|
@ -1,61 +0,0 @@
|
|||||||
using Newtonsoft.Json;
|
|
||||||
|
|
||||||
namespace Tranga;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Stores information on Task
|
|
||||||
/// </summary>
|
|
||||||
public class TrangaTask
|
|
||||||
{
|
|
||||||
// ReSharper disable once CommentTypo ...Tell me why!
|
|
||||||
// ReSharper disable once MemberCanBePrivate.Global I want it thaaat way
|
|
||||||
public TimeSpan reoccurrence { get; }
|
|
||||||
public DateTime lastExecuted { get; set; }
|
|
||||||
public string? connectorName { get; }
|
|
||||||
public Task task { get; }
|
|
||||||
public Publication? publication { get; }
|
|
||||||
public string language { get; }
|
|
||||||
[JsonIgnore]public ExecutionState state { get; set; }
|
|
||||||
|
|
||||||
public enum ExecutionState
|
|
||||||
{
|
|
||||||
Waiting,
|
|
||||||
Enqueued,
|
|
||||||
Running
|
|
||||||
};
|
|
||||||
|
|
||||||
public TrangaTask(Task task, string? connectorName, Publication? publication, TimeSpan reoccurrence, string language = "")
|
|
||||||
{
|
|
||||||
if(task != Task.UpdateKomgaLibrary && connectorName is null)
|
|
||||||
throw new ArgumentException($"connectorName can not be null for task {task}");
|
|
||||||
|
|
||||||
if (publication is null && task != Task.UpdatePublications && task != Task.UpdateKomgaLibrary)
|
|
||||||
throw new ArgumentException($"Publication can not be null for task {task}");
|
|
||||||
|
|
||||||
this.publication = publication;
|
|
||||||
this.reoccurrence = reoccurrence;
|
|
||||||
this.lastExecuted = DateTime.Now.Subtract(reoccurrence);
|
|
||||||
this.connectorName = connectorName;
|
|
||||||
this.task = task;
|
|
||||||
this.language = language;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <returns>True if elapsed time since last execution is greater than set interval</returns>
|
|
||||||
public bool ShouldExecute()
|
|
||||||
{
|
|
||||||
return DateTime.Now.Subtract(this.lastExecuted) > reoccurrence && state is ExecutionState.Waiting;
|
|
||||||
}
|
|
||||||
|
|
||||||
public enum Task
|
|
||||||
{
|
|
||||||
UpdatePublications,
|
|
||||||
UpdateChapters,
|
|
||||||
DownloadNewChapters,
|
|
||||||
UpdateKomgaLibrary
|
|
||||||
}
|
|
||||||
|
|
||||||
public override string ToString()
|
|
||||||
{
|
|
||||||
return $"{task,-20} | {lastExecuted,-20} | {reoccurrence,-12} | {state,-10} | {connectorName,-15} | {publication?.sortName}";
|
|
||||||
}
|
|
||||||
}
|
|
18
docker-compose.yaml
Normal file
18
docker-compose.yaml
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
version: '3'
|
||||||
|
services:
|
||||||
|
tranga-api:
|
||||||
|
image: glax/tranga-api:cuttingedge
|
||||||
|
container_name: tranga-api
|
||||||
|
volumes:
|
||||||
|
- ./Manga:/Manga
|
||||||
|
ports:
|
||||||
|
- "6531:6531"
|
||||||
|
restart: unless-stopped
|
||||||
|
tranga-website:
|
||||||
|
image: glax/tranga-website:cuttingedge
|
||||||
|
container_name: tranga-website
|
||||||
|
ports:
|
||||||
|
- "9555:80"
|
||||||
|
depends_on:
|
||||||
|
- tranga-api
|
||||||
|
restart: unless-stopped
|
Reference in New Issue
Block a user