mirror of
https://github.com/C9Glax/tranga.git
synced 2025-09-10 20:08:19 +02:00
Compare commits
582 Commits
oldstable
...
1360b7afc5
Author | SHA1 | Date | |
---|---|---|---|
1360b7afc5 | |||
3a8a2d2c86 | |||
af01e4a6a4 | |||
d4ea40a875 | |||
09e6b07186 | |||
26987c983f | |||
b3df3bf144 | |||
757d7a8ab0 | |||
ddcab0c6ed | |||
f1a61a7b90 | |||
78e7e8fc06 | |||
d1b2f0ab19 | |||
8439b8b2ab | |||
62090d1677 | |||
e0735eea0f | |||
65418c0495 | |||
35e36a557c | |||
ee3789fdfd | |||
aae5c88ec9 | |||
0cb239a4e6 | |||
b24308021b | |||
2d662c269b | |||
c8be88d645 | |||
48914985d2 | |||
f94513a4ae | |||
b76f460778 | |||
f9e017ec11 | |||
ec54cad58c | |||
a5c82b2505 | |||
35bbbc521e | |||
2cb898d8eb | |||
c23d29436f | |||
cb14a7c31f | |||
55f04710a7 | |||
6fa166363a | |||
1b0aa7d543 | |||
0c94e6e5fe | |||
ffe1f4fd2c | |||
e96b2585e0 | |||
3b8570cf57 | |||
6c61869e66 | |||
1c6398414d | |||
29d21f06e5 | |||
b4a0ce68c3 | |||
94a8dfc90a | |||
81463de409 | |||
e31ecbd66b | |||
c81a3633de | |||
5883ed6426 | |||
7e70288662 | |||
24299a955a | |||
49856657ca | |||
16ef2fc9f1 | |||
32f7a6642a | |||
4d5c95b119 | |||
6da116acb3 | |||
34b7d0c2a3 | |||
cb06cbbb61 | |||
a0eb2be4bd | |||
ce9195272d | |||
d6bb9fca21 | |||
4f6053172d | |||
bbaf3c46b3 | |||
ccaed156bb | |||
dcf8ada486 | |||
9d560692dc | |||
9d2dd2eabb | |||
16c0cde526 | |||
7189dccd89 | |||
044553abcb | |||
f2bc48bc52 | |||
93d3878b07 | |||
cae8cde53f | |||
394944e11a | |||
fb004657eb | |||
9d84716278 | |||
461272d02a | |||
7a8ae9e175 | |||
31a22416ee | |||
f08e77102f | |||
6604c1b412 | |||
2ab1ae04c1 | |||
902ebc48ff | |||
54efc5fd5b | |||
6f3ccda0ed | |||
04da402847 | |||
d8c8310a48 | |||
fd508b7e6c | |||
3c4f1c16db | |||
fa29c21dfb | |||
15f38f009f | |||
b34aa5e73a | |||
d63733bb5a | |||
d9144e3708 | |||
072a5c3210 | |||
ed2dc72c75 | |||
56397dd0d2 | |||
9deac27f11 | |||
637ad2e215 | |||
650cbffc8a | |||
c8fcde656e | |||
10d0a65637 | |||
35053bbc85 | |||
d7cbafba50 | |||
e9052de0e6 | |||
e9231691fd | |||
191d805afa | |||
826b0e4b98 | |||
1abee5149c | |||
ed148ce3d6 | |||
ddf009293a | |||
c6bb949224 | |||
2ff163067a | |||
29cdaa382e | |||
![]() |
1ff3673adb | ||
e063cf1fd9 | |||
8170e1d762 | |||
254383b006 | |||
df431e533a | |||
9a4cc0cbaf | |||
861cf7e166 | |||
7e34b3b91e | |||
29d36484f9 | |||
2c6e8e4d16 | |||
fab2886684 | |||
d9ccf71b21 | |||
f36f34f212 | |||
ff10432c79 | |||
776e1e4890 | |||
db0643fa19 | |||
3eeb563ca1 | |||
7a88b1f7ee | |||
b5411e9c6c | |||
07b260dea6 | |||
71ad32de31 | |||
ecd2c2722f | |||
ff1e467ada | |||
24f68b4a8e | |||
e51e90aabc | |||
dc2c27f4bd | |||
![]() |
406d8eef51 | ||
1fba599c79 | |||
a668a16035 | |||
f89b8e1977 | |||
11290062c0 | |||
f46910fac6 | |||
f974c5ddd1 | |||
a01963a125 | |||
8a877ee465 | |||
c370e656f1 | |||
58ed976737 | |||
1b6af73a0c | |||
70fe23857b | |||
0027af2d36 | |||
1a8f70f501 | |||
aa67c11050 | |||
7b38d0aa2b | |||
64e31fad54 | |||
49a70e2341 | |||
9659f2a68a | |||
d474868116 | |||
b1312c4164 | |||
33856f9927 | |||
02ab3d8cae | |||
7974c58fd5 | |||
503d9dfb5f | |||
62b035f6c5 | |||
40c70fbf19 | |||
49bd66ccab | |||
9b251169a5 | |||
aa29c45094 | |||
bd60fda05a | |||
8ecbdb91b2 | |||
cb1c68f295 | |||
421a25ec31 | |||
2d122a918f | |||
100cb06ba0 | |||
6125b036bf | |||
3fe3fc09b0 | |||
96d5b09391 | |||
84aecda916 | |||
0803a92a66 | |||
7f55aaf85d | |||
3853e2daa2 | |||
852fbf5ae8 | |||
4e7a725fee | |||
698d138642 | |||
8efb60652b | |||
fe60b98cb8 | |||
63442e9af6 | |||
703e32a30e | |||
4ddfe4a54c | |||
fb2b4d6920 | |||
496b49ccb3 | |||
b3efcf19d9 | |||
0903ec606b | |||
6cfa29e3dd | |||
0519ed26de | |||
aacdb72d6a | |||
3283dd7290 | |||
937c5cb7a7 | |||
225b7f02ad | |||
6258e07f20 | |||
622198a09e | |||
49b382fe1f | |||
5a6dc5a5b2 | |||
4bc70eca68 | |||
63fee081e6 | |||
e45b72dcf9 | |||
021ad5e804 | |||
8e0c964883 | |||
d6e945741a | |||
3a3306240f | |||
110dd36166 | |||
065cac62af | |||
563afa1e6f | |||
be2adff57d | |||
adc7ee606e | |||
a764f381c9 | |||
590ccdd09a | |||
0f0a49f74f | |||
a1a5028858 | |||
1792952039 | |||
9e62eb53cb | |||
f3c4b012b0 | |||
7e1c65b470 | |||
4247ae7740 | |||
a5954ed5c8 | |||
d08544b892 | |||
f6f86deb7f | |||
16f5817a31 | |||
d5d9f44a5f | |||
83bc3b418b | |||
205f0a1629 | |||
a1c2942208 | |||
4b4e24c6a0 | |||
475a29b10d | |||
694b88d200 | |||
0f6c060026 | |||
b49b11828c | |||
2d69b30e83 | |||
53d9be5656 | |||
7d4a6be569 | |||
7477f4d04d | |||
30a8162777 | |||
57baad3d2c | |||
3c5f51e495 | |||
397d3c93df | |||
1b49b171f4 | |||
ec5d048df5 | |||
a490e233d7 | |||
f085c5cf8e | |||
31beeeffae | |||
99a3f2614d | |||
15ced9aed8 | |||
64b17aea7a | |||
c696c38983 | |||
dbbac1ad59 | |||
b955d41530 | |||
91e033a2ec | |||
4dd31dfe18 | |||
66fcdca7e7 | |||
9350de0ae9 | |||
c94c55300c | |||
721f932fac | |||
f691529591 | |||
d75262a8f3 | |||
9521f66bac | |||
3981a41303 | |||
f2961711cf | |||
93ad691971 | |||
cef3b24efd | |||
f10c478cab | |||
01ba927491 | |||
90ce1395b8 | |||
892ef6c9d6 | |||
31c039d71e | |||
5b03befbf1 | |||
5012bbb2eb | |||
45a8f7a038 | |||
9b4baa1334 | |||
657ab571f9 | |||
1480aa0a03 | |||
232fe6406a | |||
a2bc14d54a | |||
d278a25f16 | |||
5f42a2d5ae | |||
60d84d1186 | |||
7ee4d32c07 | |||
0e68d64f75 | |||
434e30dc47 | |||
19ff3f578a | |||
cc03b6fa9c | |||
1f59ef66cd | |||
d7f21550cd | |||
d93c8fdb94 | |||
80320fd44d | |||
6449132dbf | |||
0df3381c8c | |||
2ca43e6f5d | |||
3ba1261f31 | |||
be72d4ba97 | |||
f237d82cac | |||
a43901564b | |||
34ec185125 | |||
cd08d9d78b | |||
339f40b61b | |||
8ee8f33f33 | |||
6721bd863f | |||
ee820cfa27 | |||
24361d5a43 | |||
6687ab4b3b | |||
290324f9d9 | |||
ef87e02d0b | |||
0af83f2fd0 | |||
f3854ab594 | |||
207604a437 | |||
832ddf1442 | |||
313225a1a1 | |||
ffc0e7555a | |||
ecfc8f349b | |||
94678e744f | |||
73eb02e7cb | |||
c3ebd6acac | |||
a694b9f5ab | |||
b24d2e12fc | |||
6909c367e5 | |||
4cb48dd1b4 | |||
d43ae881b5 | |||
3583e45071 | |||
c4adba6357 | |||
ed74975312 | |||
043f0b9593 | |||
022ebe2bcc | |||
3a8b400851 | |||
6c5bc3685e | |||
c679d7c677 | |||
4075adfe6b | |||
72abc90af3 | |||
894f105786 | |||
d314559361 | |||
5ab0bd0b78 | |||
5c0ace291b | |||
0d931bc835 | |||
e1e5a45960 | |||
3ecbc1a805 | |||
3305519307 | |||
9fca2d81ab | |||
949c0cc16d | |||
5921e524a9 | |||
bf332717a5 | |||
bb31a94eea | |||
1d2ca4d76a | |||
e2ff2c76ed | |||
8a0829ef69 | |||
d257095885 | |||
68cc23e158 | |||
235183cd7f | |||
dccc9fdbef | |||
9928abb674 | |||
ebb034e0c7 | |||
1dca7ec569 | |||
7229fad6c5 | |||
663e2e2ca0 | |||
![]() |
6315940cd6 | ||
![]() |
ef7ebf022d | ||
![]() |
725813c2f3 | ||
![]() |
a69e12179b | ||
![]() |
45ca2695eb | ||
![]() |
bd9e79d026 | ||
![]() |
6bbd09072b | ||
![]() |
d6018b60ae | ||
![]() |
a713a006dd | ||
![]() |
ebe7e145aa | ||
be6b3da1be | |||
b818f63f2a | |||
110a0bf481 | |||
fdbe585aa0 | |||
6a8df2f5f8 | |||
524596ad85 | |||
94adefa8e6 | |||
7cf7eb85d2 | |||
55c0e2c4e7 | |||
5494f2b754 | |||
80190e1286 | |||
16dd1ffa97 | |||
9cb5f636dd | |||
df319e9afb | |||
84388a469a | |||
d322445550 | |||
81d22bc022 | |||
6b0cefbc7c | |||
519030861d | |||
6940e6c64d | |||
e66ab49e7d | |||
67a15cec7f | |||
ae11c31b9d | |||
60b128fc30 | |||
729f018712 | |||
03e89913e3 | |||
c4fc2f436b | |||
ebc30c85bf | |||
d6b0e3a366 | |||
e1bfdd675b | |||
e6f8853b49 | |||
99ddb06d6d | |||
62876498d0 | |||
1044821147 | |||
7f946da1c3 | |||
79e7941dda | |||
faa235783c | |||
87c5ad001d | |||
3b58e0498b | |||
87274aca19 | |||
77c5903cf1 | |||
0d32f15ee9 | |||
a0774841bc | |||
3ee3a07565 | |||
b9eecd3afd | |||
6534341fd5 | |||
6737be4a20 | |||
84833acdeb | |||
538e6fa60b | |||
8c5bcd2665 | |||
50dfd92c91 | |||
bf9fe517b0 | |||
1008da7ee8 | |||
ec884f888f | |||
57df419d65 | |||
395619acd3 | |||
502821c246 | |||
9d6a8ed686 | |||
afcc2cacaf | |||
4040b5845c | |||
7daebcb1c4 | |||
44ff158c66 | |||
b5b45d0801 | |||
29f3f1a16e | |||
1bd914571c | |||
483dcc41df | |||
bc44a5333b | |||
5018800d09 | |||
c7dc5e75f2 | |||
3f37eefe72 | |||
b7bc04a045 | |||
f7daacf0d4 | |||
1cb8899195 | |||
3e581e2ddb | |||
07c6081c03 | |||
585d7e3380 | |||
febce6b92a | |||
fb7ed21d82 | |||
2db85e5070 | |||
96b5921ed6 | |||
9d47445339 | |||
93696fbac1 | |||
582b3af89c | |||
f57667bc8f | |||
f9a30f2587 | |||
240af81fa9 | |||
26b2910000 | |||
a88b85e599 | |||
27f823cfeb | |||
70993a692a | |||
1a631362c9 | |||
00c4f0533f | |||
8670863810 | |||
2c9bd2532e | |||
575fb739cc | |||
d4af068f0e | |||
6a4d454a08 | |||
225db8beda | |||
d80fcd9039 | |||
4871bc801d | |||
1c5f105a4d | |||
26a07f4a2f | |||
48ab44c28d | |||
32ecdcda76 | |||
a92eba2d14 | |||
7b6724ad38 | |||
be68ddc9b7 | |||
96e2845a5b | |||
c36204c7a8 | |||
18edcef1c3 | |||
73ad881600 | |||
c6cfd9eb6c | |||
99df9a9dfd | |||
77bb309dfa | |||
3b9d4a6735 | |||
190fa8cba7 | |||
217700d08d | |||
75eea8c761 | |||
06cdbbd283 | |||
054c88712e | |||
e95eb0497c | |||
3c3f7bb95a | |||
032ee95716 | |||
fc884adc9f | |||
960d3f7c62 | |||
6520aebcdf | |||
1ee9b644aa | |||
2f36701fef | |||
b18f8e4059 | |||
8145abb744 | |||
9dd52178b9 | |||
cf242f81e1 | |||
6b9ddca711 | |||
d73bf70868 | |||
d221532e0d | |||
5bc2a8909d | |||
f3e0959be8 | |||
8607bd2c89 | |||
fab30dc5a7 | |||
fd20b9febf | |||
ee6de661c8 | |||
790e77b00c | |||
4f14903538 | |||
6ae3918679 | |||
8ccb6c0cb5 | |||
beb455308f | |||
5c309131ad | |||
27a559834f | |||
2cfc7ac2c5 | |||
017f31ca83 | |||
4021237888 | |||
7ed3846c5f | |||
7f95ab9439 | |||
49a9b7ccb0 | |||
0735e2c588 | |||
5b22246c41 | |||
2e1f633f40 | |||
8887cea718 | |||
061da1b4bf | |||
80dc8fbe65 | |||
28a0efe488 | |||
3d08b1f9f2 | |||
2651a0c53b | |||
0ced3a7dd9 | |||
a56555eee4 | |||
cee7870aad | |||
bce77180bc | |||
8c66bbc89f | |||
e360037fda | |||
ea866e0136 | |||
c3231327f9 | |||
03e90eccd3 | |||
64482931a3 | |||
cce4901a5d | |||
3adb103fc4 | |||
b6ffb97a04 | |||
49cfff8a2f | |||
6d48a100ca | |||
4104169c19 | |||
4cb7c941a2 | |||
b3fb53f6d8 | |||
8b9769b816 | |||
9a02859f6b | |||
e96dd07521 | |||
a610eff8f0 | |||
c41f04d92d | |||
5e647099cd | |||
011af9c7a8 | |||
630e507564 | |||
fa2598084f | |||
f79743ee93 | |||
2828fec316 | |||
bd14722791 | |||
d22b49cfa8 | |||
595051b0fe | |||
238395a3da | |||
0313d81204 | |||
f5cecb9e30 | |||
7e5fa6ce41 | |||
![]() |
a8aa7d3370 | ||
![]() |
01bab62190 | ||
![]() |
2768ab38e6 | ||
![]() |
33b8ede492 | ||
![]() |
dbc1b94124 | ||
![]() |
6f5fb7e0bb | ||
![]() |
7628510b87 | ||
![]() |
dd965d886a | ||
![]() |
7e54577c54 |
@@ -1,27 +0,0 @@
|
||||
**/.dockerignore
|
||||
**/.env
|
||||
**/.git
|
||||
**/.gitignore
|
||||
**/.project
|
||||
**/.settings
|
||||
**/.toolstarget
|
||||
**/.vs
|
||||
**/.vscode
|
||||
**/.idea
|
||||
**/*.*proj.user
|
||||
**/*.dbmdl
|
||||
**/*.jfm
|
||||
**/azds.yaml
|
||||
**/bin
|
||||
**/charts
|
||||
**/docker-compose*
|
||||
**/Dockerfile*
|
||||
**/node_modules
|
||||
**/npm-debug.log
|
||||
**/obj
|
||||
**/secrets.dev.yaml
|
||||
**/values.dev.yaml
|
||||
LICENSE
|
||||
README.md
|
||||
Manga
|
||||
settings
|
@@ -37,8 +37,8 @@ jobs:
|
||||
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,linux/arm64
|
||||
#platforms: linux/amd64,linux/amd64/v2,linux/amd64/v3,linux/arm64,linux/arm/v7
|
||||
platforms: linux/amd64,linux/amd64/v2,linux/amd64/v3,linux/arm64,linux/arm/v7
|
||||
pull: true
|
||||
push: true
|
||||
tags: |
|
||||
|
45
.github/workflows/docker-image-oldstable.yml
vendored
45
.github/workflows/docker-image-oldstable.yml
vendored
@@ -1,45 +0,0 @@
|
||||
name: Docker Image CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "oldstable" ]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
|
||||
# https://github.com/docker/setup-qemu-action#usage
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3.6.0
|
||||
|
||||
# https://github.com/marketplace/actions/docker-setup-buildx
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@v3.11.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@v6.18.0
|
||||
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,linux/arm64
|
||||
pull: true
|
||||
push: true
|
||||
tags: |
|
||||
glax/tranga-api:oldstable
|
45
.github/workflows/docker-image-serverv2.yml
vendored
45
.github/workflows/docker-image-serverv2.yml
vendored
@@ -1,45 +0,0 @@
|
||||
name: Docker Image CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "postgres-Server-V2" ]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
|
||||
# https://github.com/docker/setup-qemu-action#usage
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3.6.0
|
||||
|
||||
# https://github.com/marketplace/actions/docker-setup-buildx
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@v3.11.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@v6.18.0
|
||||
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,linux/arm64
|
||||
pull: true
|
||||
push: true
|
||||
tags: |
|
||||
glax/tranga-api:Server-V2
|
4
.github/workflows/docker-image-testing.yml
vendored
4
.github/workflows/docker-image-testing.yml
vendored
@@ -37,8 +37,8 @@ jobs:
|
||||
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 #,linux/arm64
|
||||
#platforms: linux/amd64,linux/amd64/v2,linux/amd64/v3,linux/arm64,linux/arm/v7
|
||||
platforms: linux/amd64,linux/amd64/v2,linux/amd64/v3,linux/arm64,linux/arm/v7
|
||||
pull: true
|
||||
push: true
|
||||
tags: |
|
||||
|
2
.gitignore
vendored
2
.gitignore
vendored
@@ -20,6 +20,8 @@ riderModule.iml
|
||||
cover.jpg
|
||||
cover.png
|
||||
/.vscode
|
||||
/.vs/
|
||||
Tranga/Properties/launchSettings.json
|
||||
/Manga
|
||||
/settings
|
||||
*.DotSettings.user
|
42
API/API.csproj
Normal file
42
API/API.csproj
Normal file
@@ -0,0 +1,42 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<NoWarn>$(NoWarn);1591</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.1.0" />
|
||||
<PackageReference Include="HtmlAgilityPack" Version="1.12.2" />
|
||||
<PackageReference Include="JikanDotNet" Version="2.9.1" />
|
||||
<PackageReference Include="log4net" Version="3.2.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="9.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.8">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Npgsql" Version="9.0.3" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.Design" Version="1.1.0" />
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.11" />
|
||||
<PackageReference Include="Soenneker.Utils.String.NeedlemanWunsch" Version="3.0.978" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.4" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="9.0.4" />
|
||||
<PackageReference Include="System.Drawing.Common" Version="9.0.8" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Migrations\Manga\" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="Log4Net.config.xml" CopyToOutputDirectory="Always" CopyToPublishDirectory="Always" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
6
API/API.http
Normal file
6
API/API.http
Normal file
@@ -0,0 +1,6 @@
|
||||
@API_HostAddress = http://localhost:5105
|
||||
|
||||
GET {{API_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
18
API/Constants.cs
Normal file
18
API/Constants.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using SixLabors.ImageSharp;
|
||||
|
||||
namespace API;
|
||||
|
||||
public struct Constants
|
||||
{
|
||||
public const string TRANGA =
|
||||
"\n\n" +
|
||||
" _______ v2\n" +
|
||||
"|_ _|.----..---.-..-----..-----..---.-.\n" +
|
||||
" | | | _|| _ || || _ || _ |\n" +
|
||||
" |___| |__| |___._||__|__||___ ||___._|\n" +
|
||||
" |_____| \n\n";
|
||||
|
||||
public static readonly Size ImageSmSize = new (225, 320);
|
||||
public static readonly Size ImageMdSize = new (450, 640);
|
||||
public static readonly Size ImageLgSize = new (900, 1280);
|
||||
}
|
24
API/Controllers/DTOs/AltTitle.cs
Normal file
24
API/Controllers/DTOs/AltTitle.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="API.Schema.MangaContext.AltTitle"/> DTO
|
||||
/// </summary>
|
||||
public sealed record AltTitle(string Language, string Title)
|
||||
{
|
||||
/// <summary>
|
||||
/// Language of the Title
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Language of the Title")]
|
||||
public string Language { get; init; } = Language;
|
||||
|
||||
/// <summary>
|
||||
/// Title
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Title")]
|
||||
public string Title { get; init; } = Title;
|
||||
}
|
17
API/Controllers/DTOs/Author.cs
Normal file
17
API/Controllers/DTOs/Author.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="API.Schema.MangaContext.Author"/> DTO
|
||||
/// </summary>
|
||||
public sealed record Author(string Key, string Name) : Identifiable(Key)
|
||||
{
|
||||
/// <summary>
|
||||
/// Name of the Author.
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Name of the Author.")]
|
||||
public string Name { get; init; } = Name;
|
||||
}
|
52
API/Controllers/DTOs/Chapter.cs
Normal file
52
API/Controllers/DTOs/Chapter.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="API.Schema.MangaContext.Chapter"/> DTO
|
||||
/// </summary>
|
||||
public sealed record Chapter(string Key, string MangaId, int? Volume, string ChapterNumber, string? Title, IEnumerable<MangaConnectorId> MangaConnectorIds, bool Downloaded) : Identifiable(Key)
|
||||
{
|
||||
/// <summary>
|
||||
/// Identifier of the Manga this Chapter belongs to
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Identifier of the Manga this Chapter belongs to")]
|
||||
public string MangaId { get; init; } = MangaId;
|
||||
|
||||
/// <summary>
|
||||
/// Volume number
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Volume number")]
|
||||
public int? Volume { get; init; } = Volume;
|
||||
|
||||
/// <summary>
|
||||
/// Chapter number
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Chapter number")]
|
||||
public string ChapterNumber { get; init; } = ChapterNumber;
|
||||
|
||||
/// <summary>
|
||||
/// Title of the Chapter
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Title of the Chapter")]
|
||||
public string? Title { get; init; } = Title;
|
||||
|
||||
/// <summary>
|
||||
/// Whether Chapter is Downloaded (on disk)
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Whether Chapter is Downloaded (on disk)")]
|
||||
public bool Downloaded { get; init; } = Downloaded;
|
||||
|
||||
/// <summary>
|
||||
/// Ids of the Manga on MangaConnectors
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Ids of the Manga on MangaConnectors")]
|
||||
public IEnumerable<MangaConnectorId> MangaConnectorIds { get; init; } = MangaConnectorIds;
|
||||
}
|
21
API/Controllers/DTOs/FileLibrary.cs
Normal file
21
API/Controllers/DTOs/FileLibrary.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
public sealed record FileLibrary(string Key, string BasePath, string LibraryName) : Identifiable(Key)
|
||||
{
|
||||
/// <summary>
|
||||
/// The directory Path of the library
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The directory Path of the library")]
|
||||
public string BasePath { get; internal set; } = BasePath;
|
||||
|
||||
/// <summary>
|
||||
/// The Name of the library
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Name of the library")]
|
||||
public string LibraryName { get; internal set; } = LibraryName;
|
||||
}
|
18
API/Controllers/DTOs/Identifiable.cs
Normal file
18
API/Controllers/DTOs/Identifiable.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="API.Schema.Identifiable"/>
|
||||
/// </summary>
|
||||
public record Identifiable(string Key)
|
||||
{
|
||||
/// <summary>
|
||||
/// Unique Identifier of the DTO
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Unique Identifier of the DTO")]
|
||||
[StringLength(TokenGen.MaximumLength, MinimumLength = TokenGen.MinimumLength)]
|
||||
public string Key { get; init; } = Key;
|
||||
}
|
23
API/Controllers/DTOs/LibraryConnector.cs
Normal file
23
API/Controllers/DTOs/LibraryConnector.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using API.Schema.LibraryContext.LibraryConnectors;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
public record LibraryConnector(string Key, string BaseUrl, LibraryType Type) : Identifiable(Key)
|
||||
{
|
||||
/// <summary>
|
||||
/// The Url of the Library instance
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Url]
|
||||
[Description("The Url of the Library instance")]
|
||||
public string BaseUrl { get; init;} = BaseUrl;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="LibraryType"/>
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Library Type")]
|
||||
public LibraryType Type { get; init; } = Type;
|
||||
}
|
25
API/Controllers/DTOs/Link.cs
Normal file
25
API/Controllers/DTOs/Link.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="API.Schema.MangaContext.Link"/> DTO
|
||||
/// </summary>
|
||||
public sealed record Link(string Key, string Provider, string Url) : Identifiable(Key)
|
||||
{
|
||||
/// <summary>
|
||||
/// Name of the Provider
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Name of the Provider")]
|
||||
public string Provider { get; init; } = Provider;
|
||||
|
||||
/// <summary>
|
||||
/// Url
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Url")]
|
||||
public string Url { get; init; } = Url;
|
||||
}
|
73
API/Controllers/DTOs/Manga.cs
Normal file
73
API/Controllers/DTOs/Manga.cs
Normal file
@@ -0,0 +1,73 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using API.Schema.MangaContext;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Schema.MangaContext.Manga"/> DTO
|
||||
/// </summary>
|
||||
public sealed record Manga(string Key, string Name, string Description, MangaReleaseStatus ReleaseStatus, IEnumerable<MangaConnectorId> MangaConnectorIds, float IgnoreChaptersBefore, uint? Year, string? OriginalLanguage, IEnumerable<string> ChapterIds, IEnumerable<Author> Authors, IEnumerable<string> Tags, IEnumerable<Link> Links, IEnumerable<AltTitle> AltTitles, string? FileLibraryId)
|
||||
: MinimalManga(Key, Name, Description, ReleaseStatus, MangaConnectorIds)
|
||||
{
|
||||
/// <summary>
|
||||
/// Chapter cutoff for Downloads (Chapters before this will not be downloaded)
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Chapter cutoff for Downloads (Chapters before this will not be downloaded)")]
|
||||
public float IgnoreChaptersBefore { get; init; } = IgnoreChaptersBefore;
|
||||
|
||||
/// <summary>
|
||||
/// Release Year
|
||||
/// </summary>
|
||||
[Description("Release Year")]
|
||||
public uint? Year { get; init; } = Year;
|
||||
|
||||
/// <summary>
|
||||
/// Release Language
|
||||
/// </summary>
|
||||
[Description("Release Language")]
|
||||
public string? OriginalLanguage { get; init; } = OriginalLanguage;
|
||||
|
||||
/// <summary>
|
||||
/// Keys of ChapterDTOs
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Keys of ChapterDTOs")]
|
||||
public IEnumerable<string> ChapterIds { get; init; } = ChapterIds;
|
||||
|
||||
/// <summary>
|
||||
/// Author-names
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Author-names")]
|
||||
public IEnumerable<Author> Authors { get; init; } = Authors;
|
||||
|
||||
/// <summary>
|
||||
/// Manga Tags
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Manga Tags")]
|
||||
public IEnumerable<string> Tags { get; init; } = Tags;
|
||||
|
||||
/// <summary>
|
||||
/// Links for more Metadata
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Links for more Metadata")]
|
||||
public IEnumerable<Link> Links { get; init; } = Links;
|
||||
|
||||
/// <summary>
|
||||
/// Alt Titles of Manga
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Alt Titles of Manga")]
|
||||
public IEnumerable<AltTitle> AltTitles { get; init; } = AltTitles;
|
||||
|
||||
/// <summary>
|
||||
/// Id of the Library the Manga gets downloaded to
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Id of the Library the Manga gets downloaded to")]
|
||||
public string? FileLibraryId { get; init; } = FileLibraryId;
|
||||
}
|
28
API/Controllers/DTOs/MangaConnector.cs
Normal file
28
API/Controllers/DTOs/MangaConnector.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
public sealed record MangaConnector(string Name, bool Enabled, string IconUrl, string[] SupportedLanguages) : Identifiable(Name)
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether Connector is used for Searches and Downloads
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Whether Connector is used for Searches and Downloads")]
|
||||
public bool Enabled { get; init; } = Enabled;
|
||||
|
||||
/// <summary>
|
||||
/// Languages supported by the Connector
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Languages supported by the Connector")]
|
||||
public string[] SupportedLanguages { get; init; } = SupportedLanguages;
|
||||
|
||||
/// <summary>
|
||||
/// Url of the Website Icon
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Url of the Website Icon")]
|
||||
public string IconUrl { get; init; } = IconUrl;
|
||||
}
|
38
API/Controllers/DTOs/MangaConnectorId.cs
Normal file
38
API/Controllers/DTOs/MangaConnectorId.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using API.Schema.MangaContext;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="MangaConnectorId{T}"/> DTO
|
||||
/// </summary>
|
||||
public sealed record MangaConnectorId(string Key, string MangaConnectorName, string ForeignKey, string? WebsiteUrl, bool UseForDownload) : Identifiable(Key)
|
||||
{
|
||||
/// <summary>
|
||||
/// Name of the Connector
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Name of the Connector")]
|
||||
public string MangaConnectorName { get; init; } = MangaConnectorName;
|
||||
|
||||
/// <summary>
|
||||
/// Key of the referenced DTO
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Key of the referenced DTO")]
|
||||
public string ForeignKey { get; init; } = ForeignKey;
|
||||
|
||||
/// <summary>
|
||||
/// Website Link for reference, if any
|
||||
/// </summary>
|
||||
[Description("Website Link for reference, if any")]
|
||||
public string? WebsiteUrl { get; init; } = WebsiteUrl;
|
||||
|
||||
/// <summary>
|
||||
/// Whether this Link is used for downloads
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Whether this Link is used for downloads")]
|
||||
public bool UseForDownload { get; init; } = UseForDownload;
|
||||
}
|
39
API/Controllers/DTOs/MinimalManga.cs
Normal file
39
API/Controllers/DTOs/MinimalManga.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using API.Schema.MangaContext;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
/// <summary>
|
||||
/// Shortened Version of <see cref="Manga"/>
|
||||
/// </summary>
|
||||
public record MinimalManga(string Key, string Name, string Description, MangaReleaseStatus ReleaseStatus, IEnumerable<MangaConnectorId> MangaConnectorIds) : Identifiable(Key)
|
||||
{
|
||||
/// <summary>
|
||||
/// Name of the Manga
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Name of the Manga")]
|
||||
public string Name { get; init; } = Name;
|
||||
|
||||
/// <summary>
|
||||
/// Description of the Manga
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Description of the Manga")]
|
||||
public string Description { get; init; } = Description;
|
||||
|
||||
/// <summary>
|
||||
/// ReleaseStatus of the Manga
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("ReleaseStatus of the Manga")]
|
||||
public MangaReleaseStatus ReleaseStatus { get; init; } = ReleaseStatus;
|
||||
|
||||
/// <summary>
|
||||
/// Ids of the Manga on MangaConnectors
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Ids of the Manga on MangaConnectors")]
|
||||
public IEnumerable<MangaConnectorId> MangaConnectorIds { get; init; } = MangaConnectorIds;
|
||||
}
|
46
API/Controllers/DTOs/NotificationConnector.cs
Normal file
46
API/Controllers/DTOs/NotificationConnector.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
public record NotificationConnector(string Name, string Url, string HttpMethod, string Body, Dictionary<string, string> Headers) : Identifiable(Name)
|
||||
{
|
||||
/// <summary>
|
||||
/// The Name of the Notification Connector
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Name of the Notification Connector")]
|
||||
public string Name { get; init; } = Name;
|
||||
|
||||
/// <summary>
|
||||
/// The Url of the Instance
|
||||
/// </summary>
|
||||
/// <remarks>Formatting placeholders: "%title" and "%text" will be replaced when notifications are sent</remarks>
|
||||
[Required]
|
||||
[Url]
|
||||
[Description("The Url of the Instance")]
|
||||
public string Url { get; internal set; } = Url;
|
||||
|
||||
/// <summary>
|
||||
/// The HTTP Request Method to use for notifications
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The HTTP Request Method to use for notifications")]
|
||||
public string HttpMethod { get; internal set; } = HttpMethod;
|
||||
|
||||
/// <summary>
|
||||
/// The Request Body to use to send notifications
|
||||
/// </summary>
|
||||
/// <remarks>Formatting placeholders: "%title" and "%text" will be replaced when notifications are sent</remarks>
|
||||
[Required]
|
||||
[Description("The Request Body to use to send notifications")]
|
||||
public string Body { get; internal set; } = Body;
|
||||
|
||||
/// <summary>
|
||||
/// The Request Headers to use to send notifications
|
||||
/// </summary>
|
||||
/// <remarks>Formatting placeholders: "%title" and "%text" will be replaced when notifications are sent</remarks>
|
||||
[Required]
|
||||
[Description("The Request Headers to use to send notifications")]
|
||||
public Dictionary<string, string> Headers { get; internal set; } = Headers;
|
||||
}
|
33
API/Controllers/DTOs/PeriodicWorker.cs
Normal file
33
API/Controllers/DTOs/PeriodicWorker.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using API.Workers;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IPeriodic"/> DTO (<seealso cref="Worker"/> <seealso cref="BaseWorker"/>)
|
||||
/// </summary>
|
||||
public sealed record PeriodicWorker(string Key, IEnumerable<string> Dependencies, IEnumerable<string> MissingDependencies, bool DependenciesFulfilled, WorkerExecutionState State, DateTime LastExecution, TimeSpan Interval, DateTime NextExecution)
|
||||
: Worker(Key, Dependencies, MissingDependencies, DependenciesFulfilled, State)
|
||||
{
|
||||
/// <summary>
|
||||
/// Timestamp when Worker executed last.
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Timestamp when Worker executed last.")]
|
||||
public DateTime LastExecution { get; init; } = LastExecution;
|
||||
|
||||
/// <summary>
|
||||
/// Interval at which Worker runs.
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Interval at which Worker runs.")]
|
||||
public TimeSpan Interval { get; init; } = Interval;
|
||||
|
||||
/// <summary>
|
||||
/// Timestamp when Worker is scheduled to execute next.
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Timestamp when Worker is scheduled to execute next.")]
|
||||
public DateTime NextExecution { get; init; } = LastExecution;
|
||||
}
|
39
API/Controllers/DTOs/Worker.cs
Normal file
39
API/Controllers/DTOs/Worker.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using API.Workers;
|
||||
|
||||
namespace API.Controllers.DTOs;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="BaseWorker"/> DTO
|
||||
/// </summary>
|
||||
public record Worker(string Key, IEnumerable<string> Dependencies, IEnumerable<string> MissingDependencies, bool DependenciesFulfilled, WorkerExecutionState State) : Identifiable(Key)
|
||||
{
|
||||
/// <summary>
|
||||
/// Workers this worker depends on having ran.
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Workers this worker depends on having ran.")]
|
||||
public IEnumerable<string> Dependencies { get; init; } = Dependencies;
|
||||
|
||||
/// <summary>
|
||||
/// Workers that have not yet ran, that need to run for this Worker to run.
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Workers that have not yet ran, that need to run for this Worker to run.")]
|
||||
public IEnumerable<string> MissingDependencies { get; init; } = MissingDependencies;
|
||||
|
||||
/// <summary>
|
||||
/// Worker can run.
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Worker can run.")]
|
||||
public bool DependenciesFulfilled { get; init; } = DependenciesFulfilled;
|
||||
|
||||
/// <summary>
|
||||
/// Execution state of the Worker.
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("Execution state of the Worker.")]
|
||||
public WorkerExecutionState State { get; init; } = State;
|
||||
}
|
147
API/Controllers/FileLibraryController.cs
Normal file
147
API/Controllers/FileLibraryController.cs
Normal file
@@ -0,0 +1,147 @@
|
||||
using API.Controllers.Requests;
|
||||
using API.Schema.MangaContext;
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using static Microsoft.AspNetCore.Http.StatusCodes;
|
||||
using FileLibrary = API.Controllers.DTOs.FileLibrary;
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace API.Controllers;
|
||||
|
||||
[ApiVersion(2)]
|
||||
[ApiController]
|
||||
[Route("v{v:apiVersion}/[controller]")]
|
||||
public class FileLibraryController(MangaContext context) : Controller
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns all <see cref="DTOs.FileLibrary"/>
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpGet]
|
||||
[ProducesResponseType<List<FileLibrary>>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status500InternalServerError)]
|
||||
public async Task<Results<Ok<List<FileLibrary>>, InternalServerError>> GetFileLibraries ()
|
||||
{
|
||||
if (await context.FileLibraries.ToListAsync(HttpContext.RequestAborted) is not { } result)
|
||||
return TypedResults.InternalServerError();
|
||||
|
||||
List<FileLibrary> fileLibraries = result.Select(f => new FileLibrary(f.Key, f.BasePath, f.LibraryName)).ToList();
|
||||
|
||||
return TypedResults.Ok(fileLibraries);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns <see cref="FileLibrary"/> with <paramref name="FileLibraryId"/>
|
||||
/// </summary>
|
||||
/// <param name="FileLibraryId"><see cref="FileLibrary"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="FileLibrary"/> with <paramref name="FileLibraryId"/> not found.</response>
|
||||
[HttpGet("{FileLibraryId}")]
|
||||
[ProducesResponseType<FileLibrary>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok<FileLibrary>, NotFound<string>>> GetFileLibrary (string FileLibraryId)
|
||||
{
|
||||
if(await context.FileLibraries.FirstOrDefaultAsync(l => l.Key == FileLibraryId, HttpContext.RequestAborted) is not { } library)
|
||||
return TypedResults.NotFound(nameof(FileLibraryId));
|
||||
|
||||
return TypedResults.Ok(new FileLibrary(library.Key, library.BasePath, library.LibraryName));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Changes the <see cref="FileLibraryId"/>.BasePath with <paramref name="FileLibraryId"/>
|
||||
/// </summary>
|
||||
/// <param name="FileLibraryId"><see cref="FileLibrary"/>.Key</param>
|
||||
/// <param name="newBasePath">New <see cref="FileLibraryId"/>.BasePath</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="FileLibrary"/> with <paramref name="FileLibraryId"/> not found.</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPatch("{FileLibraryId}/ChangeBasePath")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Ok, NotFound<string>, InternalServerError<string>>> ChangeLibraryBasePath (string FileLibraryId, [FromBody]string newBasePath)
|
||||
{
|
||||
if(await context.FileLibraries.FirstOrDefaultAsync(l => l.Key == FileLibraryId, HttpContext.RequestAborted) is not { } library)
|
||||
return TypedResults.NotFound(nameof(FileLibraryId));
|
||||
|
||||
//TODO Path check
|
||||
library.BasePath = newBasePath;
|
||||
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Changes the <see cref="FileLibraryId"/>.LibraryName with <paramref name="FileLibraryId"/>
|
||||
/// </summary>
|
||||
/// <param name="FileLibraryId"><see cref="FileLibrary"/>.Key</param>
|
||||
/// <param name="newName">New <see cref="FileLibraryId"/>.LibraryName</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="FileLibrary"/> with <paramref name="FileLibraryId"/> not found.</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPatch("{FileLibraryId}/ChangeName")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Ok, NotFound<string>, InternalServerError<string>>> ChangeLibraryName (string FileLibraryId, [FromBody] string newName)
|
||||
{
|
||||
if(await context.FileLibraries.FirstOrDefaultAsync(l => l.Key == FileLibraryId, HttpContext.RequestAborted) is not { } library)
|
||||
return TypedResults.NotFound(nameof(FileLibraryId));
|
||||
|
||||
//TODO Name check
|
||||
library.LibraryName = newName;
|
||||
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates new <see cref="FileLibrary"/>
|
||||
/// </summary>
|
||||
/// <param name="requestData">New <see cref="FileLibrary"/> to add</param>
|
||||
/// <response code="200">Key of new Library</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPut]
|
||||
[ProducesResponseType<string>(Status201Created, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Created<string>, InternalServerError<string>>> CreateNewLibrary ([FromBody]CreateLibraryRecord requestData)
|
||||
{
|
||||
//TODO Parameter check
|
||||
Schema.MangaContext.FileLibrary library = new Schema.MangaContext.FileLibrary(requestData.BasePath, requestData.LibraryName);
|
||||
context.FileLibraries.Add(library);
|
||||
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
|
||||
return TypedResults.Created(string.Empty, library.Key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the <see cref="FileLibraryId"/>.LibraryName with <paramref name="FileLibraryId"/>
|
||||
/// </summary>
|
||||
/// <param name="FileLibraryId"><see cref="FileLibrary"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="FileLibrary"/> with <paramref name="FileLibraryId"/> not found.</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpDelete("{FileLibraryId}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Ok, NotFound<string>, InternalServerError<string>>> DeleteLocalLibrary (string FileLibraryId)
|
||||
{
|
||||
if(await context.FileLibraries.FirstOrDefaultAsync(l => l.Key == FileLibraryId, HttpContext.RequestAborted) is not { } library)
|
||||
return TypedResults.NotFound(nameof(FileLibraryId));
|
||||
|
||||
context.FileLibraries.Remove(library);
|
||||
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
}
|
102
API/Controllers/LibraryConnectorController.cs
Normal file
102
API/Controllers/LibraryConnectorController.cs
Normal file
@@ -0,0 +1,102 @@
|
||||
using API.Controllers.Requests;
|
||||
using API.Schema.LibraryContext;
|
||||
using API.Schema.LibraryContext.LibraryConnectors;
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using static Microsoft.AspNetCore.Http.StatusCodes;
|
||||
using LibraryConnector = API.Controllers.DTOs.LibraryConnector;
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace API.Controllers;
|
||||
|
||||
[ApiVersion(2)]
|
||||
[ApiController]
|
||||
[Route("v{v:apiVersion}/[controller]")]
|
||||
public class LibraryConnectorController(LibraryContext context) : Controller
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets all configured <see cref="DTOs.LibraryConnector"/>
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpGet]
|
||||
[ProducesResponseType<List<LibraryConnector>>(Status200OK, "application/json")]
|
||||
public async Task<Results<Ok<List<LibraryConnector>>, InternalServerError>> GetAllConnectors ()
|
||||
{
|
||||
if (await context.LibraryConnectors.ToListAsync(HttpContext.RequestAborted) is not { } connectors)
|
||||
return TypedResults.InternalServerError();
|
||||
|
||||
List<LibraryConnector> libraryConnectors = connectors.Select(c => new LibraryConnector(c.Key, c.BaseUrl, c.LibraryType)).ToList();
|
||||
|
||||
return TypedResults.Ok(libraryConnectors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns <see cref="LibraryConnector"/> with <paramref name="LibraryConnectorId"/>
|
||||
/// </summary>
|
||||
/// <param name="LibraryConnectorId"><see cref="LibraryConnector"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="LibraryConnector"/> with <paramref name="LibraryConnectorId"/> not found.</response>
|
||||
[HttpGet("{LibraryConnectorId}")]
|
||||
[ProducesResponseType<LibraryConnector>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok<LibraryConnector>, NotFound<string>>> GetConnector (string LibraryConnectorId)
|
||||
{
|
||||
if (await context.LibraryConnectors.FirstOrDefaultAsync(l => l.Key == LibraryConnectorId) is not { } connector)
|
||||
return TypedResults.NotFound(nameof(LibraryConnectorId));
|
||||
|
||||
return TypedResults.Ok(new LibraryConnector(connector.Key, connector.BaseUrl, connector.LibraryType));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="LibraryConnector"/>
|
||||
/// </summary>
|
||||
/// <param name="requestData"></param>
|
||||
/// <response code="201"></response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPut]
|
||||
[ProducesResponseType<string>(Status201Created, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Created<string>, InternalServerError<string>>> CreateConnector ([FromBody]CreateLibraryConnectorRecord requestData)
|
||||
{
|
||||
//TODO verify data
|
||||
API.Schema.LibraryContext.LibraryConnectors.LibraryConnector connector = requestData.LibraryType switch
|
||||
{
|
||||
LibraryType.Kavita => new Kavita(requestData.Url, requestData.Username, requestData.Password),
|
||||
LibraryType.Komga => new Komga(requestData.Url, requestData.Username, requestData.Password),
|
||||
_ => throw new NotImplementedException()
|
||||
};
|
||||
|
||||
context.LibraryConnectors.Add(connector);
|
||||
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
return TypedResults.Created(string.Empty, connector.Key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes <see cref="LibraryConnector"/> with <paramref name="LibraryConnectorId"/>
|
||||
/// </summary>
|
||||
/// <param name="LibraryConnectorId">ToFileLibrary-Connector-ID</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="LibraryConnector"/> with <paramref name="LibraryConnectorId"/> not found.</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpDelete("{LibraryConnectorId}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Ok, NotFound<string>, InternalServerError<string>>> DeleteConnector (string LibraryConnectorId)
|
||||
{
|
||||
if (await context.LibraryConnectors.FirstOrDefaultAsync(l => l.Key == LibraryConnectorId) is not { } connector)
|
||||
return TypedResults.NotFound(nameof(LibraryConnectorId));
|
||||
|
||||
context.LibraryConnectors.Remove(connector);
|
||||
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
}
|
39
API/Controllers/MaintenanceController.cs
Normal file
39
API/Controllers/MaintenanceController.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using API.MangaConnectors;
|
||||
using API.Schema.MangaContext;
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using static Microsoft.AspNetCore.Http.StatusCodes;
|
||||
|
||||
namespace API.Controllers;
|
||||
|
||||
[ApiVersion(2)]
|
||||
[ApiController]
|
||||
[Route("v{v:apiVersion}/[controller]")]
|
||||
public class MaintenanceController(MangaContext mangaContext) : Controller
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Removes all <see cref="Manga"/> not marked for Download on any <see cref="MangaConnector"/>
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPost("CleanupNoDownloadManga")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Ok, InternalServerError<string>>> CleanupNoDownloadManga()
|
||||
{
|
||||
if (await mangaContext.Mangas
|
||||
.Include(m => m.MangaConnectorIds)
|
||||
.Where(m => !m.MangaConnectorIds.Any(id => id.UseForDownload))
|
||||
.ToArrayAsync(HttpContext.RequestAborted) is not { } noDownloads)
|
||||
return TypedResults.InternalServerError("Could not fetch Manga");
|
||||
|
||||
mangaContext.Mangas.RemoveRange(noDownloads);
|
||||
|
||||
if(await mangaContext.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
}
|
98
API/Controllers/MangaConnectorController.cs
Normal file
98
API/Controllers/MangaConnectorController.cs
Normal file
@@ -0,0 +1,98 @@
|
||||
using API.Controllers.DTOs;
|
||||
using API.Schema.MangaContext;
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using static Microsoft.AspNetCore.Http.StatusCodes;
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace API.Controllers;
|
||||
|
||||
[ApiVersion(2)]
|
||||
[ApiController]
|
||||
[Route("v{v:apiVersion}/[controller]")]
|
||||
public class MangaConnectorController(MangaContext context) : Controller
|
||||
{
|
||||
/// <summary>
|
||||
/// Get all <see cref="API.MangaConnectors.MangaConnector"/> (Scanlation-Sites)
|
||||
/// </summary>
|
||||
/// <response code="200">Names of <see cref="API.MangaConnectors.MangaConnector"/> (Scanlation-Sites)</response>
|
||||
[HttpGet]
|
||||
[ProducesResponseType<List<MangaConnector>>(Status200OK, "application/json")]
|
||||
public Ok<List<MangaConnector>> GetConnectors()
|
||||
{
|
||||
return TypedResults.Ok(Tranga.MangaConnectors
|
||||
.Select(c => new MangaConnector(c.Name, c.Enabled, c.IconUrl, c.SupportedLanguages))
|
||||
.ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the <see cref="API.MangaConnectors.MangaConnector"/> (Scanlation-Sites) with the requested Name
|
||||
/// </summary>
|
||||
/// <param name="MangaConnectorName"><see cref="API.MangaConnectors.MangaConnector"/>.Name</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="MangaConnector"/> (Scanlation-Sites) with Name not found.</response>
|
||||
[HttpGet("{MangaConnectorName}")]
|
||||
[ProducesResponseType<MangaConnector>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public Results<Ok<MangaConnector>, NotFound<string>> GetConnector(string MangaConnectorName)
|
||||
{
|
||||
if(Tranga.MangaConnectors.FirstOrDefault(c => c.Name.Equals(MangaConnectorName, StringComparison.InvariantCultureIgnoreCase)) is not { } connector)
|
||||
return TypedResults.NotFound(nameof(MangaConnectorName));
|
||||
|
||||
return TypedResults.Ok(new MangaConnector(connector.Name, connector.Enabled, connector.IconUrl, connector.SupportedLanguages));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get all enabled <see cref="API.MangaConnectors.MangaConnector"/> (Scanlation-Sites)
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
[HttpGet("Enabled")]
|
||||
[ProducesResponseType<List<MangaConnector>>(Status200OK, "application/json")]
|
||||
public Ok<List<MangaConnector>> GetEnabledConnectors()
|
||||
{
|
||||
return TypedResults.Ok(Tranga.MangaConnectors
|
||||
.Where(c => c.Enabled)
|
||||
.Select(c => new MangaConnector(c.Name, c.Enabled, c.IconUrl, c.SupportedLanguages))
|
||||
.ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get all disabled <see cref="API.MangaConnectors.MangaConnector"/> (Scanlation-Sites)
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
[HttpGet("Disabled")]
|
||||
[ProducesResponseType<List<MangaConnector>>(Status200OK, "application/json")]
|
||||
public Ok<List<MangaConnector>> GetDisabledConnectors()
|
||||
{
|
||||
|
||||
return TypedResults.Ok(Tranga.MangaConnectors
|
||||
.Where(c => c.Enabled == false)
|
||||
.Select(c => new MangaConnector(c.Name, c.Enabled, c.IconUrl, c.SupportedLanguages))
|
||||
.ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enabled or disables <see cref="API.MangaConnectors.MangaConnector"/> (Scanlation-Sites) with Name
|
||||
/// </summary>
|
||||
/// <param name="MangaConnectorName"><see cref="API.MangaConnectors.MangaConnector"/>.Name</param>
|
||||
/// <param name="Enabled">Set true to enable, false to disable</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="API.MangaConnectors.MangaConnector"/> (Scanlation-Sites) with Name not found.</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPatch("{MangaConnectorName}/SetEnabled/{Enabled}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Ok, NotFound<string>, InternalServerError<string>>> SetEnabled(string MangaConnectorName, bool Enabled)
|
||||
{
|
||||
if(Tranga.MangaConnectors.FirstOrDefault(c => c.Name.Equals(MangaConnectorName, StringComparison.InvariantCultureIgnoreCase)) is not { } connector)
|
||||
return TypedResults.NotFound(nameof(MangaConnectorName));
|
||||
|
||||
connector.Enabled = Enabled;
|
||||
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
}
|
579
API/Controllers/MangaController.cs
Normal file
579
API/Controllers/MangaController.cs
Normal file
@@ -0,0 +1,579 @@
|
||||
using API.Controllers.DTOs;
|
||||
using API.Schema.MangaContext;
|
||||
using API.Workers;
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
using static Microsoft.AspNetCore.Http.StatusCodes;
|
||||
using AltTitle = API.Controllers.DTOs.AltTitle;
|
||||
using Author = API.Controllers.DTOs.Author;
|
||||
using Chapter = API.Controllers.DTOs.Chapter;
|
||||
using Link = API.Controllers.DTOs.Link;
|
||||
using Manga = API.Controllers.DTOs.Manga;
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace API.Controllers;
|
||||
|
||||
[ApiVersion(2)]
|
||||
[ApiController]
|
||||
[Route("v{v:apiVersion}/[controller]")]
|
||||
public class MangaController(MangaContext context) : Controller
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Returns all cached <see cref="DTOs.Manga"/>
|
||||
/// </summary>
|
||||
/// <response code="200"><see cref="MinimalManga"/> exert of <see cref="Schema.MangaContext.Manga"/>. Use <see cref="GetManga"/> for more information</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpGet]
|
||||
[ProducesResponseType<List<MinimalManga>>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status500InternalServerError)]
|
||||
public async Task<Results<Ok<List<MinimalManga>>, InternalServerError>> GetAllManga ()
|
||||
{
|
||||
if (await context.Mangas.Include(m => m.MangaConnectorIds).ToArrayAsync(HttpContext.RequestAborted) is not
|
||||
{ } result)
|
||||
return TypedResults.InternalServerError();
|
||||
|
||||
return TypedResults.Ok(result.Select(m =>
|
||||
{
|
||||
IEnumerable<MangaConnectorId> ids = m.MangaConnectorIds.Select(id => new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
return new MinimalManga(m.Key, m.Name, m.Description, m.ReleaseStatus, ids);
|
||||
}).ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all cached <see cref="Schema.MangaContext.Manga"/>.Keys
|
||||
/// </summary>
|
||||
/// <response code="200"><see cref="Schema.MangaContext.Manga"/> Keys/IDs</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpGet("Keys")]
|
||||
[ProducesResponseType<string[]>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status500InternalServerError)]
|
||||
public async Task<Results<Ok<string[]>, InternalServerError>> GetAllMangaKeys ()
|
||||
{
|
||||
if (await context.Mangas.Select(m => m.Key).ToArrayAsync(HttpContext.RequestAborted) is not { } result)
|
||||
return TypedResults.InternalServerError();
|
||||
|
||||
return TypedResults.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all <see cref="Schema.MangaContext.Manga"/> that are being downloaded from at least one <see cref="API.MangaConnectors.MangaConnector"/>
|
||||
/// </summary>
|
||||
/// <response code="200"><see cref="MinimalManga"/> exert of <see cref="Schema.MangaContext.Manga"/>. Use <see cref="GetManga"/> for more information</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpGet("Downloading")]
|
||||
[ProducesResponseType<MinimalManga[]>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status500InternalServerError)]
|
||||
public async Task<Results<Ok<List<MinimalManga>>, InternalServerError>> GetMangaDownloading()
|
||||
{
|
||||
if (await context.Mangas
|
||||
.Include(m => m.MangaConnectorIds)
|
||||
.Where(m => m.MangaConnectorIds.Any(id => id.UseForDownload))
|
||||
.ToArrayAsync(HttpContext.RequestAborted) is not { } result)
|
||||
return TypedResults.InternalServerError();
|
||||
|
||||
return TypedResults.Ok(result.Select(m =>
|
||||
{
|
||||
IEnumerable<MangaConnectorId> ids = m.MangaConnectorIds.Select(id => new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
return new MinimalManga(m.Key, m.Name, m.Description, m.ReleaseStatus, ids);
|
||||
}).ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all cached <see cref="Schema.MangaContext.Manga"/> with <paramref name="MangaIds"/>
|
||||
/// </summary>
|
||||
/// <param name="MangaIds">Array of <see cref="Schema.MangaContext.Manga"/>.Key</param>
|
||||
/// <response code="200"><see cref="DTOs.Manga"/></response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPost("WithIDs")]
|
||||
[ProducesResponseType<List<Manga>>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status500InternalServerError)]
|
||||
public async Task<Results<Ok<List<Manga>>, InternalServerError>> GetMangaWithIds ([FromBody]string[] MangaIds)
|
||||
{
|
||||
if (await context.MangaIncludeAll()
|
||||
.Where(m => MangaIds.Contains(m.Key))
|
||||
.ToArrayAsync(HttpContext.RequestAborted) is not { } result)
|
||||
return TypedResults.InternalServerError();
|
||||
|
||||
return TypedResults.Ok(result.Select(m =>
|
||||
{
|
||||
IEnumerable<MangaConnectorId> ids = m.MangaConnectorIds.Select(id => new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
IEnumerable<Author> authors = m.Authors.Select(a => new Author(a.Key, a.AuthorName));
|
||||
IEnumerable<string> tags = m.MangaTags.Select(t => t.Tag);
|
||||
IEnumerable<Link> links = m.Links.Select(l => new Link(l.Key, l.LinkProvider, l.LinkUrl));
|
||||
IEnumerable<AltTitle> altTitles = m.AltTitles.Select(a => new AltTitle(a.Language, a.Title));
|
||||
return new Manga(m.Key, m.Name, m.Description, m.ReleaseStatus, ids, m.IgnoreChaptersBefore, m.Year, m.OriginalLanguage, m.ChapterIds, authors, tags, links, altTitles, m.LibraryId);
|
||||
}).ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return <see cref="Schema.MangaContext.Manga"/> with <paramref name="MangaId"/>
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="Schema.MangaContext.Manga"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="Manga"/> with <paramref name="MangaId"/> not found</response>
|
||||
[HttpGet("{MangaId}")]
|
||||
[ProducesResponseType<Manga>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok<Manga>, NotFound<string>>> GetManga (string MangaId)
|
||||
{
|
||||
if (await context.MangaIncludeAll().FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
|
||||
IEnumerable<MangaConnectorId> ids = manga.MangaConnectorIds.Select(id => new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
IEnumerable<Author> authors = manga.Authors.Select(a => new Author(a.Key, a.AuthorName));
|
||||
IEnumerable<string> tags = manga.MangaTags.Select(t => t.Tag);
|
||||
IEnumerable<Link> links = manga.Links.Select(l => new Link(l.Key, l.LinkProvider, l.LinkUrl));
|
||||
IEnumerable<AltTitle> altTitles = manga.AltTitles.Select(a => new AltTitle(a.Language, a.Title));
|
||||
Manga result = new (manga.Key, manga.Name, manga.Description, manga.ReleaseStatus, ids, manga.IgnoreChaptersBefore, manga.Year, manga.OriginalLanguage, manga.ChapterIds, authors, tags, links, altTitles, manga.LibraryId);
|
||||
|
||||
return TypedResults.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete <see cref="Manga"/> with <paramref name="MangaId"/>
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="Manga"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="Manga"/> with <paramref name="MangaId"/> not found</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpDelete("{MangaId}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Ok, NotFound<string>, InternalServerError<string>>> DeleteManga (string MangaId)
|
||||
{
|
||||
if (await context.Mangas.FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
|
||||
context.Mangas.Remove(manga);
|
||||
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Merge two <see cref="Manga"/> into one. THIS IS NOT REVERSIBLE!
|
||||
/// </summary>
|
||||
/// <param name="MangaIdFrom"><see cref="Manga"/>.Key of <see cref="Manga"/> merging data from (getting deleted)</param>
|
||||
/// <param name="MangaIdInto"><see cref="Manga"/>.Key of <see cref="Manga"/> merging data into</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="Manga"/> with <paramref name="MangaIdFrom"/> or <paramref name="MangaIdInto"/> not found</response>
|
||||
[HttpPatch("{MangaIdFrom}/MergeInto/{MangaIdInto}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok, NotFound<string>>> MergeIntoManga (string MangaIdFrom, string MangaIdInto)
|
||||
{
|
||||
if (await context.MangaIncludeAll().FirstOrDefaultAsync(m => m.Key == MangaIdFrom, HttpContext.RequestAborted) is not { } from)
|
||||
return TypedResults.NotFound(nameof(MangaIdFrom));
|
||||
if (await context.MangaIncludeAll().FirstOrDefaultAsync(m => m.Key == MangaIdInto, HttpContext.RequestAborted) is not { } into)
|
||||
return TypedResults.NotFound(nameof(MangaIdInto));
|
||||
|
||||
BaseWorker[] newJobs = into.MergeFrom(from, context);
|
||||
Tranga.AddWorkers(newJobs);
|
||||
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns Cover of <see cref="Manga"/> with <paramref name="MangaId"/>
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="Manga"/>.Key</param>
|
||||
/// <param name="CoverSize">Size of the cover returned
|
||||
/// <br /> - <see cref="CoverSize.Small"/> <see cref="Constants.ImageSmSize"/>
|
||||
/// <br /> - <see cref="CoverSize.Medium"/> <see cref="Constants.ImageMdSize"/>
|
||||
/// <br /> - <see cref="CoverSize.Large"/> <see cref="Constants.ImageLgSize"/>
|
||||
/// </param>
|
||||
/// <response code="200">JPEG Image</response>
|
||||
/// <response code="204">Cover not loaded</response>
|
||||
/// <response code="404"><see cref="Manga"/> with <paramref name="MangaId"/> not found</response>
|
||||
/// <response code="503">Retry later, downloading cover</response>
|
||||
[HttpGet("{MangaId}/Cover/{CoverSize?}")]
|
||||
[ProducesResponseType<FileContentResult>(Status200OK,"image/jpeg")]
|
||||
[ProducesResponseType(Status204NoContent)]
|
||||
[ProducesResponseType(Status400BadRequest)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType(Status503ServiceUnavailable)]
|
||||
public async Task<Results<FileContentHttpResult, NoContent, BadRequest, NotFound<string>, StatusCodeHttpResult>> GetCover (string MangaId, CoverSize? CoverSize = null)
|
||||
{
|
||||
if (await context.Mangas.FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
|
||||
string cache = CoverSize switch
|
||||
{
|
||||
MangaController.CoverSize.Small => TrangaSettings.coverImageCacheSmall,
|
||||
MangaController.CoverSize.Medium => TrangaSettings.coverImageCacheMedium,
|
||||
MangaController.CoverSize.Large => TrangaSettings.coverImageCacheLarge,
|
||||
_ => TrangaSettings.coverImageCacheOriginal
|
||||
};
|
||||
|
||||
if (await manga.GetCoverImage(cache, HttpContext.RequestAborted) is not { } data)
|
||||
{
|
||||
if (Tranga.GetRunningWorkers().Any(worker => worker is DownloadCoverFromMangaconnectorWorker w && context.MangaConnectorToManga.Find(w.MangaConnectorIdId)?.ObjId == MangaId))
|
||||
{
|
||||
Response.Headers.Append("Retry-After", $"{Tranga.Settings.WorkCycleTimeoutMs * 2 / 1000:D}");
|
||||
return TypedResults.StatusCode(Status503ServiceUnavailable);
|
||||
}
|
||||
return TypedResults.NoContent();
|
||||
}
|
||||
|
||||
DateTime lastModified = data.fileInfo.LastWriteTime;
|
||||
EntityTagHeaderValue entityTagHeaderValue = EntityTagHeaderValue.Parse($"\"{lastModified.Ticks}\"");
|
||||
if(HttpContext.Request.Headers.ETag.Equals(entityTagHeaderValue.Tag.Value))
|
||||
return TypedResults.StatusCode(Status304NotModified);
|
||||
HttpContext.Response.Headers.CacheControl = "public";
|
||||
return TypedResults.Bytes(data.stream.ToArray(), "image/jpeg", lastModified: new DateTimeOffset(lastModified), entityTag: entityTagHeaderValue);
|
||||
}
|
||||
public enum CoverSize { Original, Large, Medium, Small }
|
||||
|
||||
/// <summary>
|
||||
/// Returns all <see cref="Chapter"/> of <see cref="Manga"/> with <paramref name="MangaId"/>
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="Manga"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="Manga"/> with <paramref name="MangaId"/> not found</response>
|
||||
[HttpGet("{MangaId}/Chapters")]
|
||||
[ProducesResponseType<List<Chapter>>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status404NotFound)]
|
||||
public async Task<Results<Ok<List<Chapter>>, NotFound<string>>> GetChapters(string MangaId)
|
||||
{
|
||||
if (await context.Mangas.Include(m => m.Chapters).ThenInclude(c => c.MangaConnectorIds).FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
|
||||
List<Chapter> chapters = manga.Chapters.Select(c =>
|
||||
{
|
||||
IEnumerable<MangaConnectorId> ids = c.MangaConnectorIds.Select(id =>
|
||||
new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
return new Chapter(c.Key, c.ParentMangaId, c.VolumeNumber, c.ChapterNumber, c.Title, ids, c.Downloaded);
|
||||
}).ToList();
|
||||
return TypedResults.Ok(chapters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all downloaded <see cref="Chapter"/> for <see cref="Manga"/> with <paramref name="MangaId"/>
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="Manga"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="204">No available chapters</response>
|
||||
/// <response code="404"><see cref="Manga"/> with <paramref name="MangaId"/> not found.</response>
|
||||
[HttpGet("{MangaId}/Chapters/Downloaded")]
|
||||
[ProducesResponseType<Chapter[]>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status204NoContent)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok<List<Chapter>>, NoContent, NotFound<string>>> GetChaptersDownloaded(string MangaId)
|
||||
{
|
||||
if (await context.Mangas.Include(m => m.Chapters).FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
|
||||
List<Chapter> chapters = manga.Chapters.Where(c => c.Downloaded).Select(c =>
|
||||
{
|
||||
IEnumerable<MangaConnectorId> ids = c.MangaConnectorIds.Select(id =>
|
||||
new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
return new Chapter(c.Key, c.ParentMangaId, c.VolumeNumber, c.ChapterNumber, c.Title, ids, c.Downloaded);
|
||||
}).ToList();
|
||||
if (chapters.Count == 0)
|
||||
return TypedResults.NoContent();
|
||||
|
||||
return TypedResults.Ok(chapters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all <see cref="Chapter"/> not downloaded for <see cref="Manga"/> with <paramref name="MangaId"/>
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="Manga"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="204">No available chapters</response>
|
||||
/// <response code="404"><see cref="Manga"/> with <paramref name="MangaId"/> not found.</response>
|
||||
[HttpGet("{MangaId}/Chapters/NotDownloaded")]
|
||||
[ProducesResponseType<List<Chapter>>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status204NoContent)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok<List<Chapter>>, NoContent, NotFound<string>>> GetChaptersNotDownloaded(string MangaId)
|
||||
{
|
||||
if (await context.Mangas.Include(m => m.Chapters).FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
|
||||
List<Chapter> chapters = manga.Chapters.Where(c => c.Downloaded == false).Select(c =>
|
||||
{
|
||||
IEnumerable<MangaConnectorId> ids = c.MangaConnectorIds.Select(id =>
|
||||
new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
return new Chapter(c.Key, c.ParentMangaId, c.VolumeNumber, c.ChapterNumber, c.Title, ids, c.Downloaded);
|
||||
}).ToList();
|
||||
if (chapters.Count == 0)
|
||||
return TypedResults.NoContent();
|
||||
|
||||
return TypedResults.Ok(chapters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the latest <see cref="Chapter"/> of requested <see cref="Manga"/> available on <see cref="API.MangaConnectors.MangaConnector"/>
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="Manga"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="204">No available chapters</response>
|
||||
/// <response code="404"><see cref="Manga"/> with <paramref name="MangaId"/> not found.</response>
|
||||
/// <response code="412">Could not retrieve the maximum chapter-number</response>
|
||||
/// <response code="503">Retry after timeout, updating value</response>
|
||||
[HttpGet("{MangaId}/Chapter/LatestAvailable")]
|
||||
[ProducesResponseType<int>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status204NoContent)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType(Status500InternalServerError)]
|
||||
[ProducesResponseType(Status503ServiceUnavailable)]
|
||||
public async Task<Results<Ok<Chapter>, NoContent, InternalServerError, NotFound<string>, StatusCodeHttpResult>> GetLatestChapter(string MangaId)
|
||||
{
|
||||
if (await context.Mangas.Include(m => m.Chapters).FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
|
||||
List<API.Schema.MangaContext.Chapter> chapters = manga.Chapters.ToList();
|
||||
if (chapters.Count == 0)
|
||||
{
|
||||
if (Tranga.GetRunningWorkers().Any(worker =>
|
||||
worker is RetrieveMangaChaptersFromMangaconnectorWorker w &&
|
||||
context.MangaConnectorToManga.Find(w.MangaConnectorIdId)?.ObjId == MangaId &&
|
||||
w.State < WorkerExecutionState.Completed))
|
||||
{
|
||||
Response.Headers.Append("Retry-After", $"{Tranga.Settings.WorkCycleTimeoutMs * 2 / 1000:D}");
|
||||
return TypedResults.StatusCode(Status503ServiceUnavailable);
|
||||
}
|
||||
else
|
||||
return TypedResults.NoContent();
|
||||
}
|
||||
|
||||
API.Schema.MangaContext.Chapter? max = chapters.Max();
|
||||
if (max is null)
|
||||
return TypedResults.InternalServerError();
|
||||
|
||||
foreach (CollectionEntry collectionEntry in context.Entry(max).Collections)
|
||||
await collectionEntry.LoadAsync(HttpContext.RequestAborted);
|
||||
|
||||
IEnumerable<MangaConnectorId> ids = max.MangaConnectorIds.Select(id =>
|
||||
new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
return TypedResults.Ok(new Chapter(max.Key, max.ParentMangaId, max.VolumeNumber, max.ChapterNumber, max.Title,ids, max.Downloaded));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the latest <see cref="Chapter"/> of requested <see cref="Manga"/> that is downloaded
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="Manga"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="204">No available chapters</response>
|
||||
/// <response code="404"><see cref="Manga"/> with <paramref name="MangaId"/> not found.</response>
|
||||
/// <response code="412">Could not retrieve the maximum chapter-number</response>
|
||||
/// <response code="503">Retry after timeout, updating value</response>
|
||||
[HttpGet("{MangaId}/Chapter/LatestDownloaded")]
|
||||
[ProducesResponseType<Chapter>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status204NoContent)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType(Status412PreconditionFailed)]
|
||||
[ProducesResponseType(Status503ServiceUnavailable)]
|
||||
public async Task<Results<Ok<Chapter>, NoContent, NotFound<string>, StatusCodeHttpResult>> GetLatestChapterDownloaded(string MangaId)
|
||||
{
|
||||
if (await context.Mangas.FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
|
||||
await context.Entry(manga).Collection(m => m.Chapters).LoadAsync(HttpContext.RequestAborted);
|
||||
|
||||
List<API.Schema.MangaContext.Chapter> chapters = manga.Chapters.ToList();
|
||||
if (chapters.Count == 0)
|
||||
{
|
||||
if (Tranga.GetRunningWorkers().Any(worker => worker is RetrieveMangaChaptersFromMangaconnectorWorker w && context.MangaConnectorToManga.Find(w.MangaConnectorIdId)?.ObjId == MangaId && w.State < WorkerExecutionState.Completed))
|
||||
{
|
||||
Response.Headers.Append("Retry-After", $"{Tranga.Settings.WorkCycleTimeoutMs * 2 / 1000:D}");
|
||||
return TypedResults.StatusCode(Status503ServiceUnavailable);
|
||||
}else
|
||||
return TypedResults.NoContent();
|
||||
}
|
||||
|
||||
API.Schema.MangaContext.Chapter? max = chapters.Max();
|
||||
if (max is null)
|
||||
return TypedResults.StatusCode(Status412PreconditionFailed);
|
||||
|
||||
IEnumerable<MangaConnectorId> ids = max.MangaConnectorIds.Select(id =>
|
||||
new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
return TypedResults.Ok(new Chapter(max.Key, max.ParentMangaId, max.VolumeNumber, max.ChapterNumber, max.Title,ids, max.Downloaded));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configure the <see cref="Chapter"/> cut-off for <see cref="Manga"/>
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="Manga"/>.Key</param>
|
||||
/// <param name="chapterThreshold">Threshold (<see cref="Chapter"/> ChapterNumber)</param>
|
||||
/// <response code="202"></response>
|
||||
/// <response code="404"><see cref="Manga"/> with <paramref name="MangaId"/> not found.</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPatch("{MangaId}/IgnoreChaptersBefore")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Ok, NotFound<string>, InternalServerError<string>>> IgnoreChaptersBefore(string MangaId, [FromBody]float chapterThreshold)
|
||||
{
|
||||
if (await context.Mangas.FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
|
||||
manga.IgnoreChaptersBefore = chapterThreshold;
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Move <see cref="Manga"/> to different <see cref="FileLibrary"/>
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="Manga"/>.Key</param>
|
||||
/// <param name="LibraryId"><see cref="FileLibrary"/>.Key</param>
|
||||
/// <response code="202">Folder is going to be moved</response>
|
||||
/// <response code="404"><paramref name="MangaId"/> or <paramref name="LibraryId"/> not found</response>
|
||||
[HttpPost("{MangaId}/ChangeLibrary/{LibraryId}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok, NotFound<string>>> ChangeLibrary(string MangaId, string LibraryId)
|
||||
{
|
||||
if (await context.Mangas.FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
if (await context.FileLibraries.FirstOrDefaultAsync(l => l.Key == LibraryId, HttpContext.RequestAborted) is not { } library)
|
||||
return TypedResults.NotFound(nameof(LibraryId));
|
||||
|
||||
if(manga.LibraryId == library.Key)
|
||||
return TypedResults.Ok();
|
||||
|
||||
MoveMangaLibraryWorker moveLibrary = new(manga, library);
|
||||
|
||||
Tranga.AddWorkers([moveLibrary]);
|
||||
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// (Un-)Marks <see cref="Manga"/> as requested for Download from <see cref="API.MangaConnectors.MangaConnector"/>
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="Manga"/> with <paramref name="MangaId"/></param>
|
||||
/// <param name="MangaConnectorName"><see cref="API.MangaConnectors.MangaConnector"/> with <paramref name="MangaConnectorName"/></param>
|
||||
/// <param name="IsRequested">true to mark as requested, false to mark as not-requested</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><paramref name="MangaId"/> or <paramref name="MangaConnectorName"/> not found</response>
|
||||
/// <response code="412"><see cref="Manga"/> was not linked to <see cref="API.MangaConnectors.MangaConnector"/>, so nothing changed</response>
|
||||
/// <response code="428"><see cref="Manga"/> is not linked to <see cref="API.MangaConnectors.MangaConnector"/> yet. Search for <see cref="Manga"/> on <see cref="API.MangaConnectors.MangaConnector"/> first (to create a <see cref="MangaConnectorId{T}"/>).</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPost("{MangaId}/SetAsDownloadFrom/{MangaConnectorName}/{IsRequested}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType<string>(Status412PreconditionFailed, "text/plain")]
|
||||
[ProducesResponseType<string>(Status428PreconditionRequired, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Ok, NotFound<string>, StatusCodeHttpResult, InternalServerError<string>>> MarkAsRequested(string MangaId, string MangaConnectorName, bool IsRequested)
|
||||
{
|
||||
if (await context.Mangas.FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } _)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
if(!Tranga.TryGetMangaConnector(MangaConnectorName, out API.MangaConnectors.MangaConnector? _))
|
||||
return TypedResults.NotFound(nameof(MangaConnectorName));
|
||||
|
||||
if (context.MangaConnectorToManga
|
||||
.FirstOrDefault(id => id.MangaConnectorName == MangaConnectorName && id.ObjId == MangaId)
|
||||
is not { } mcId)
|
||||
{
|
||||
if(IsRequested)
|
||||
return TypedResults.StatusCode(Status428PreconditionRequired);
|
||||
else
|
||||
return TypedResults.StatusCode(Status412PreconditionFailed);
|
||||
}
|
||||
|
||||
mcId.UseForDownload = IsRequested;
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
|
||||
DownloadCoverFromMangaconnectorWorker downloadCover = new(mcId);
|
||||
RetrieveMangaChaptersFromMangaconnectorWorker retrieveChapters = new(mcId, Tranga.Settings.DownloadLanguage);
|
||||
Tranga.AddWorkers([downloadCover, retrieveChapters]);
|
||||
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initiate a search for <see cref="API.Schema.MangaContext.Manga"/> on a different <see cref="API.MangaConnectors.MangaConnector"/>
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="API.Schema.MangaContext.Manga"/> with <paramref name="MangaId"/></param>
|
||||
/// <param name="MangaConnectorName"><see cref="API.MangaConnectors.MangaConnector"/>.Name</param>
|
||||
/// <response code="200"><see cref="MinimalManga"/> exert of <see cref="Schema.MangaContext.Manga"/></response>
|
||||
/// <response code="404"><see cref="API.MangaConnectors.MangaConnector"/> with Name not found</response>
|
||||
/// <response code="412"><see cref="API.MangaConnectors.MangaConnector"/> with Name is disabled</response>
|
||||
[HttpPost("{MangaId}/SearchOn/{MangaConnectorName}")]
|
||||
[ProducesResponseType<List<MinimalManga>>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType(Status406NotAcceptable)]
|
||||
public async Task<Results<Ok<List<MinimalManga>>, NotFound<string>, StatusCodeHttpResult>> SearchOnDifferentConnector (string MangaId, string MangaConnectorName)
|
||||
{
|
||||
if (await context.Mangas.FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
|
||||
return new SearchController(context).SearchManga(MangaConnectorName, manga.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all <see cref="Manga"/> which where Authored by <see cref="Author"/> with <paramref name="AuthorId"/>
|
||||
/// </summary>
|
||||
/// <param name="AuthorId"><see cref="Author"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="Author"/> with <paramref name="AuthorId"/></response>
|
||||
/// /// <response code="500">Error during Database Operation</response>
|
||||
[HttpGet("WithAuthorId/{AuthorId}")]
|
||||
[ProducesResponseType<List<Manga>>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok<List<Manga>>, NotFound<string>, InternalServerError>> GetMangaWithAuthorIds (string AuthorId)
|
||||
{
|
||||
if (await context.Authors.FirstOrDefaultAsync(a => a.Key == AuthorId, HttpContext.RequestAborted) is not { } _)
|
||||
return TypedResults.NotFound(nameof(AuthorId));
|
||||
|
||||
if (await context.MangaIncludeAll().Where(m => m.Authors.Any(a => a.Key == AuthorId)).ToListAsync(HttpContext.RequestAborted) is not { } result)
|
||||
return TypedResults.InternalServerError();
|
||||
|
||||
return TypedResults.Ok(result.Select(m =>
|
||||
{
|
||||
IEnumerable<MangaConnectorId> ids = m.MangaConnectorIds.Select(id => new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
IEnumerable<Author> authors = m.Authors.Select(a => new Author(a.Key, a.AuthorName));
|
||||
IEnumerable<string> tags = m.MangaTags.Select(t => t.Tag);
|
||||
IEnumerable<Link> links = m.Links.Select(l => new Link(l.Key, l.LinkProvider, l.LinkUrl));
|
||||
IEnumerable<AltTitle> altTitles = m.AltTitles.Select(a => new AltTitle(a.Language, a.Title));
|
||||
return new Manga(m.Key, m.Name, m.Description, m.ReleaseStatus, ids, m.IgnoreChaptersBefore, m.Year, m.OriginalLanguage, m.ChapterIds, authors, tags, links, altTitles, m.LibraryId);
|
||||
}).ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all <see cref="Manga"/> with <see cref="Tag"/>
|
||||
/// </summary>
|
||||
/// <param name="Tag"><see cref="Tag"/>.Tag</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="Tag"/> not found</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpGet("WithTag/{Tag}")]
|
||||
[ProducesResponseType<Manga[]>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType(Status500InternalServerError)]
|
||||
public async Task<Results<Ok<List<Manga>>, NotFound<string>, InternalServerError>> GetMangasWithTag (string Tag)
|
||||
{
|
||||
if (await context.Tags.FirstOrDefaultAsync(t => t.Tag == Tag, HttpContext.RequestAborted) is not { } tag)
|
||||
return TypedResults.NotFound(nameof(Tag));
|
||||
|
||||
|
||||
if (await context.MangaIncludeAll().Where(m => m.MangaTags.Any(t => t.Tag.Equals(tag))) .ToListAsync(HttpContext.RequestAborted) is not { } result)
|
||||
return TypedResults.InternalServerError();
|
||||
|
||||
return TypedResults.Ok(result.Select(m =>
|
||||
{
|
||||
IEnumerable<MangaConnectorId> ids = m.MangaConnectorIds.Select(id => new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
IEnumerable<Author> authors = m.Authors.Select(a => new Author(a.Key, a.AuthorName));
|
||||
IEnumerable<string> tags = m.MangaTags.Select(t => t.Tag);
|
||||
IEnumerable<Link> links = m.Links.Select(l => new Link(l.Key, l.LinkProvider, l.LinkUrl));
|
||||
IEnumerable<AltTitle> altTitles = m.AltTitles.Select(a => new AltTitle(a.Language, a.Title));
|
||||
return new Manga(m.Key, m.Name, m.Description, m.ReleaseStatus, ids, m.IgnoreChaptersBefore, m.Year, m.OriginalLanguage, m.ChapterIds, authors, tags, links, altTitles, m.LibraryId);
|
||||
}).ToList());
|
||||
}
|
||||
}
|
129
API/Controllers/MetadataFetcherController.cs
Normal file
129
API/Controllers/MetadataFetcherController.cs
Normal file
@@ -0,0 +1,129 @@
|
||||
using API.Schema.MangaContext;
|
||||
using API.Schema.MangaContext.MetadataFetchers;
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using static Microsoft.AspNetCore.Http.StatusCodes;
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace API.Controllers;
|
||||
|
||||
[ApiVersion(2)]
|
||||
[ApiController]
|
||||
[Route("v{v:apiVersion}/[controller]")]
|
||||
public class MetadataFetcherController(MangaContext context) : Controller
|
||||
{
|
||||
/// <summary>
|
||||
/// Get all <see cref="MetadataFetcher"/> (Metadata-Sites)
|
||||
/// </summary>
|
||||
/// <response code="200">Names of <see cref="MetadataFetcher"/> (Metadata-Sites)</response>
|
||||
[HttpGet]
|
||||
[ProducesResponseType<List<string>>(Status200OK, "application/json")]
|
||||
public Ok<List<string>> GetConnectors ()
|
||||
{
|
||||
return TypedResults.Ok(Tranga.MetadataFetchers.Select(m => m.Name).ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all <see cref="MetadataEntry"/>
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpGet("Links")]
|
||||
[ProducesResponseType<List<MetadataEntry>>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status500InternalServerError)]
|
||||
public async Task<Results<Ok<List<MetadataEntry>>, InternalServerError>> GetLinkedEntries ()
|
||||
{
|
||||
if (await context.MetadataEntries.ToListAsync() is not { } result)
|
||||
return TypedResults.InternalServerError();
|
||||
|
||||
return TypedResults.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Searches <see cref="MetadataFetcher"/> (Metadata-Sites) for Manga-Metadata
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="Manga"/>.Key</param>
|
||||
/// <param name="MetadataFetcherName"><see cref="MetadataFetcher"/>.Name</param>
|
||||
/// <param name="searchTerm">Instead of using the <paramref name="MangaId"/> for search on Website, use a specific term</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="400"><see cref="MetadataFetcher"/> (Metadata-Sites) with <paramref name="MetadataFetcherName"/> does not exist</response>
|
||||
/// <response code="404"><see cref="Manga"/> with <paramref name="MangaId"/> not found</response>
|
||||
[HttpPost("{MetadataFetcherName}/SearchManga/{MangaId}")]
|
||||
[ProducesResponseType<MetadataSearchResult[]>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status400BadRequest)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok<List<MetadataSearchResult>>, BadRequest, NotFound<string>>> SearchMangaMetadata(string MangaId, string MetadataFetcherName, [FromBody (EmptyBodyBehavior = EmptyBodyBehavior.Allow)]string? searchTerm = null)
|
||||
{
|
||||
if (await context.Mangas.FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
if(Tranga.MetadataFetchers.FirstOrDefault(f => f.Name == MetadataFetcherName) is not { } fetcher)
|
||||
return TypedResults.BadRequest();
|
||||
|
||||
MetadataSearchResult[] searchResults = searchTerm is null ? fetcher.SearchMetadataEntry(manga) : fetcher.SearchMetadataEntry(searchTerm);
|
||||
return TypedResults.Ok(searchResults.ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Links <see cref="MetadataFetcher"/> (Metadata-Sites) using Provider-Specific Identifier to <see cref="Manga"/>
|
||||
/// </summary>
|
||||
/// <param name="MangaId"><see cref="Manga"/>.Key</param>
|
||||
/// <param name="MetadataFetcherName"><see cref="MetadataFetcher"/>.Name</param>
|
||||
/// <param name="Identifier"><see cref="MetadataFetcherName"/>-Specific ID</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="400"><see cref="MetadataFetcher"/> (Metadata-Sites) with <paramref name="MetadataFetcherName"/> does not exist</response>
|
||||
/// <response code="404"><see cref="Manga"/> with <paramref name="MangaId"/> not found</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPost("{MetadataFetcherName}/Link/{MangaId}")]
|
||||
[ProducesResponseType<MetadataEntry>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status400BadRequest)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Ok<MetadataEntry>, BadRequest, NotFound<string>, InternalServerError<string>>> LinkMangaMetadata (string MangaId, string MetadataFetcherName, [FromBody]string Identifier)
|
||||
{
|
||||
if (await context.Mangas.FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
if(Tranga.MetadataFetchers.FirstOrDefault(f => f.Name == MetadataFetcherName) is not { } fetcher)
|
||||
return TypedResults.BadRequest();
|
||||
|
||||
MetadataEntry entry = fetcher.CreateMetadataEntry(manga, Identifier);
|
||||
context.MetadataEntries.Add(entry);
|
||||
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
return TypedResults.Ok(entry);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Un-Links <see cref="MetadataFetcher"/> (Metadata-Sites) from <see cref="Manga"/>
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="400"><see cref="MetadataFetcher"/> (Metadata-Sites) with <paramref name="MetadataFetcherName"/> does not exist</response>
|
||||
/// <response code="404"><see cref="Manga"/> with <paramref name="MangaId"/> not found</response>
|
||||
/// <response code="412">No <see cref="MetadataEntry"/> linking <see cref="Manga"/> and <see cref="MetadataFetcher"/> found</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPost("{MetadataFetcherName}/Unlink/{MangaId}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType(Status400BadRequest)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType(Status412PreconditionFailed)]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Ok, BadRequest, NotFound<string>, InternalServerError<string>, StatusCodeHttpResult>> UnlinkMangaMetadata (string MangaId, string MetadataFetcherName)
|
||||
{
|
||||
if (await context.Mangas.FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } _)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
if(Tranga.MetadataFetchers.FirstOrDefault(f => f.Name == MetadataFetcherName) is null)
|
||||
return TypedResults.BadRequest();
|
||||
if (context.MetadataEntries.FirstOrDefault(e =>
|
||||
e.MangaId == MangaId && e.MetadataFetcherName == MetadataFetcherName) is not { } entry)
|
||||
return TypedResults.StatusCode(Status412PreconditionFailed);
|
||||
|
||||
context.Remove(entry);
|
||||
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
}
|
165
API/Controllers/NotificationConnectorController.cs
Normal file
165
API/Controllers/NotificationConnectorController.cs
Normal file
@@ -0,0 +1,165 @@
|
||||
using System.Text;
|
||||
using API.Controllers.DTOs;
|
||||
using API.Controllers.Requests;
|
||||
using API.Schema.NotificationsContext;
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using static Microsoft.AspNetCore.Http.StatusCodes;
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace API.Controllers;
|
||||
|
||||
[ApiVersion(2)]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
[Route("v{v:apiVersion}/[controller]")]
|
||||
public class NotificationConnectorController(NotificationsContext context) : Controller
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets all configured <see cref="NotificationConnector"/>
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpGet]
|
||||
[ProducesResponseType<List<NotificationConnector>>(Status200OK, "application/json")]
|
||||
[ProducesResponseType(Status500InternalServerError)]
|
||||
public async Task<Results<Ok<List<NotificationConnector>>, InternalServerError>> GetAllConnectors ()
|
||||
{
|
||||
if(await context.NotificationConnectors.ToListAsync(HttpContext.RequestAborted) is not { } result)
|
||||
return TypedResults.InternalServerError();
|
||||
|
||||
List<NotificationConnector> notificationConnectors = result.Select(n => new NotificationConnector(n.Name, n.Url, n.HttpMethod, n.Body, n.Headers)).ToList();
|
||||
|
||||
return TypedResults.Ok(notificationConnectors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns <see cref="NotificationConnector"/> with requested Name
|
||||
/// </summary>
|
||||
/// <param name="Name"><see cref="NotificationConnector"/>.Name</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="NotificationConnector"/> with <paramref name="Name"/> not found</response>
|
||||
[HttpGet("{Name}")]
|
||||
[ProducesResponseType<NotificationConnector>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok<NotificationConnector>, NotFound<string>>> GetConnector (string Name)
|
||||
{
|
||||
if (await context.NotificationConnectors.FirstOrDefaultAsync(c => c.Name == Name, HttpContext.RequestAborted) is not { } connector)
|
||||
return TypedResults.NotFound(nameof(Name));
|
||||
|
||||
NotificationConnector notificationConnector = new NotificationConnector(connector.Name, connector.Url, connector.HttpMethod, connector.Body, connector.Headers);
|
||||
|
||||
return TypedResults.Ok(notificationConnector);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="NotificationConnector"/>
|
||||
/// </summary>
|
||||
/// <remarks>Formatting placeholders: "%title" and "%text" can be placed in url, header-values and body and will be replaced when notifications are sent</remarks>
|
||||
/// <response code="200">ID of the new <see cref="NotificationConnector"/></response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPut]
|
||||
[ProducesResponseType<string>(Status201Created, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Created<string>, InternalServerError<string>>> CreateConnector ([FromBody]CreateNotificationConnectorRecord requestData)
|
||||
{
|
||||
// TODO validate data
|
||||
API.Schema.NotificationsContext.NotificationConnectors.NotificationConnector newConnector =
|
||||
new(requestData.Name, requestData.Url, requestData.Headers, requestData.HttpMethod, requestData.Body);
|
||||
|
||||
context.NotificationConnectors.Add(newConnector);
|
||||
context.Notifications.Add(new ("Added new Notification Connector!", newConnector.Name, NotificationUrgency.High));
|
||||
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
return TypedResults.Created(string.Empty, newConnector.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new Gotify-<see cref="NotificationConnector"/>
|
||||
/// </summary>
|
||||
/// <remarks>Priority needs to be between 0 and 10</remarks>
|
||||
/// <response code="200">ID of the new <see cref="NotificationConnector"/></response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPut("Gotify")]
|
||||
[ProducesResponseType<string>(Status201Created, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Created<string>, InternalServerError<string>>> CreateGotifyConnector ([FromBody]CreateGotifyConnectorRecord createGotifyConnectorData)
|
||||
{
|
||||
//TODO Validate Data
|
||||
CreateNotificationConnectorRecord gotifyConnector = new (createGotifyConnectorData.Name,
|
||||
createGotifyConnectorData.Url,
|
||||
"POST",
|
||||
$"{{\"message\": \"%text\", \"title\": \"%title\", \"Priority\": {createGotifyConnectorData.Priority}}}",
|
||||
new () { { "X-Gotify-Key", createGotifyConnectorData.AppToken } });
|
||||
return await CreateConnector(gotifyConnector);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new Ntfy-<see cref="NotificationConnector"/>
|
||||
/// </summary>
|
||||
/// <remarks>Priority needs to be between 1 and 5</remarks>
|
||||
/// <response code="200">ID of the new <see cref="NotificationConnector"/></response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPut("Ntfy")]
|
||||
[ProducesResponseType<string>(Status201Created, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Created<string>, InternalServerError<string>>> CreateNtfyConnector ([FromBody]CreateNtfyConnectorRecord createNtfyConnectorRecord)
|
||||
{
|
||||
//TODO Validate Data
|
||||
string authHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{createNtfyConnectorRecord.Username}:{createNtfyConnectorRecord.Password}"));
|
||||
string auth = Convert.ToBase64String(Encoding.UTF8.GetBytes(authHeader)).Replace("=","");
|
||||
|
||||
CreateNotificationConnectorRecord ntfyConnector = new (createNtfyConnectorRecord.Name,
|
||||
$"{createNtfyConnectorRecord.Url}?auth={auth}",
|
||||
"POST",
|
||||
$"{{\"message\": \"%text\", \"title\": \"%title\", \"Priority\": {createNtfyConnectorRecord.Priority} \"Topic\": \"{createNtfyConnectorRecord.Topic}\"}}",
|
||||
new () {{"Authorization", auth}});
|
||||
return await CreateConnector(ntfyConnector);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new Pushover-<see cref="NotificationConnector"/>
|
||||
/// </summary>
|
||||
/// <remarks>https://pushover.net/api</remarks>
|
||||
/// <response code="200">ID of the new <see cref="NotificationConnector"/></response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPut("Pushover")]
|
||||
[ProducesResponseType<string>(Status201Created, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Created<string>, InternalServerError<string>>> CreatePushoverConnector ([FromBody]CreatePushoverConnectorRecord createPushoverConnectorRecord)
|
||||
{
|
||||
//TODO Validate Data
|
||||
CreateNotificationConnectorRecord pushoverConnector = new (createPushoverConnectorRecord.Name,
|
||||
$"https://api.pushover.net/1/messages.json",
|
||||
"POST",
|
||||
$"{{\"token\": \"{createPushoverConnectorRecord.AppToken}\", \"user\": \"{createPushoverConnectorRecord.Username}\", \"message:\":\"%text\", \"%title\" }}",
|
||||
new ());
|
||||
return await CreateConnector(pushoverConnector);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the <see cref="NotificationConnector"/> with the requested Name
|
||||
/// </summary>
|
||||
/// <param name="Name"><see cref="NotificationConnector"/>.Name</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="NotificationConnector"/> with Name not found</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpDelete("{Name}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Ok, NotFound<string>, InternalServerError<string>>> DeleteConnector (string Name)
|
||||
{
|
||||
if (await context.NotificationConnectors.FirstOrDefaultAsync(c => c.Name == Name, HttpContext.RequestAborted) is not { } connector)
|
||||
return TypedResults.NotFound(nameof(Name));
|
||||
|
||||
context.NotificationConnectors.Remove(connector);
|
||||
|
||||
if(await context.Sync(HttpContext.RequestAborted) is { success: false } result)
|
||||
return TypedResults.InternalServerError(result.exceptionMessage);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
}
|
124
API/Controllers/QueryController.cs
Normal file
124
API/Controllers/QueryController.cs
Normal file
@@ -0,0 +1,124 @@
|
||||
using API.Controllers.DTOs;
|
||||
using API.Schema.MangaContext;
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Soenneker.Utils.String.NeedlemanWunsch;
|
||||
using static Microsoft.AspNetCore.Http.StatusCodes;
|
||||
using Author = API.Controllers.DTOs.Author;
|
||||
using Chapter = API.Controllers.DTOs.Chapter;
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace API.Controllers;
|
||||
|
||||
[ApiVersion(2)]
|
||||
[ApiController]
|
||||
[Route("v{v:apiVersion}/[controller]")]
|
||||
public class QueryController(MangaContext context) : Controller
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the <see cref="Author"/> with <paramref name="AuthorId"/>
|
||||
/// </summary>
|
||||
/// <param name="AuthorId"><see cref="Author"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="Author"/> with <paramref name="AuthorId"/> not found</response>
|
||||
[HttpGet("Author/{AuthorId}")]
|
||||
[ProducesResponseType<Author>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok<Author>, NotFound<string>>> GetAuthor (string AuthorId)
|
||||
{
|
||||
if (await context.Authors.FirstOrDefaultAsync(a => a.Key == AuthorId, HttpContext.RequestAborted) is not { } author)
|
||||
return TypedResults.NotFound(nameof(AuthorId));
|
||||
|
||||
return TypedResults.Ok(new Author(author.Key, author.AuthorName));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns <see cref="Chapter"/> with <paramref name="ChapterId"/>
|
||||
/// </summary>
|
||||
/// <param name="ChapterId"><see cref="Chapter"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="Chapter"/> with <paramref name="ChapterId"/> not found</response>
|
||||
[HttpGet("Chapter/{ChapterId}")]
|
||||
[ProducesResponseType<Chapter>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok<Chapter>, NotFound<string>>> GetChapter (string ChapterId)
|
||||
{
|
||||
if (await context.Chapters.FirstOrDefaultAsync(c => c.Key == ChapterId, HttpContext.RequestAborted) is not { } chapter)
|
||||
return TypedResults.NotFound(nameof(ChapterId));
|
||||
|
||||
IEnumerable<MangaConnectorId> ids = chapter.MangaConnectorIds.Select(id =>
|
||||
new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
return TypedResults.Ok(new Chapter(chapter.Key, chapter.ParentMangaId, chapter.VolumeNumber, chapter.ChapterNumber, chapter.Title,ids, chapter.Downloaded));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the <see cref="MangaConnectorId{Manga}"/> with <see cref="MangaConnectorId{Manga}"/>.Key
|
||||
/// </summary>
|
||||
/// <param name="MangaConnectorIdId">Key of <see cref="MangaConnectorId{Manga}"/></param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="MangaConnectorId{Manga}"/> with <paramref name="MangaConnectorIdId"/> not found</response>
|
||||
[HttpGet("Manga/MangaConnectorId/{MangaConnectorIdId}")]
|
||||
[ProducesResponseType<MangaConnectorId>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok<MangaConnectorId>, NotFound<string>>> GetMangaMangaConnectorId (string MangaConnectorIdId)
|
||||
{
|
||||
if (await context.MangaConnectorToManga.FirstOrDefaultAsync(c => c.Key == MangaConnectorIdId, HttpContext.RequestAborted) is not { } mcIdManga)
|
||||
return TypedResults.NotFound(nameof(MangaConnectorIdId));
|
||||
|
||||
MangaConnectorId result = new (mcIdManga.Key, mcIdManga.MangaConnectorName, mcIdManga.ObjId, mcIdManga.WebsiteUrl, mcIdManga.UseForDownload);
|
||||
|
||||
return TypedResults.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns <see cref="Schema.MangaContext.Manga"/> with names similar to <see cref="Schema.MangaContext.Manga"/> (identified by <paramref name="MangaId"/>)
|
||||
/// </summary>
|
||||
/// <param name="MangaId">Key of <see cref="Schema.MangaContext.Manga"/></param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="Schema.MangaContext.Manga"/> with <paramref name="MangaId"/> not found</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpGet("Manga/{MangaId}/SimilarName")]
|
||||
[ProducesResponseType<List<string>>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType(Status500InternalServerError)]
|
||||
public async Task<Results<Ok<List<string>>, NotFound<string>, InternalServerError>> GetSimilarManga (string MangaId)
|
||||
{
|
||||
if (await context.Mangas.FirstOrDefaultAsync(m => m.Key == MangaId, HttpContext.RequestAborted) is not { } manga)
|
||||
return TypedResults.NotFound(nameof(MangaId));
|
||||
|
||||
string name = manga.Name;
|
||||
|
||||
if (await context.Mangas.Where(m => m.Key != MangaId)
|
||||
.ToDictionaryAsync(m => m.Key, m => m.Name, HttpContext.RequestAborted) is not { } mangaNames)
|
||||
return TypedResults.InternalServerError();
|
||||
|
||||
List<string> similarIds = mangaNames
|
||||
.Where(kv => NeedlemanWunschStringUtil.CalculateSimilarityPercentage(name, kv.Value) > 0.8)
|
||||
.Select(kv => kv.Key)
|
||||
.ToList();
|
||||
|
||||
return TypedResults.Ok(similarIds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the <see cref="MangaConnectorId{Chapter}"/> with <see cref="MangaConnectorId{Chapter}"/>.Key
|
||||
/// </summary>
|
||||
/// <param name="MangaConnectorIdId">Key of <see cref="MangaConnectorId{Manga}"/></param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="MangaConnectorId{Chapter}"/> with <paramref name="MangaConnectorIdId"/> not found</response>
|
||||
[HttpGet("Chapter/MangaConnectorId/{MangaConnectorIdId}")]
|
||||
[ProducesResponseType<MangaConnectorId>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public async Task<Results<Ok<MangaConnectorId>, NotFound<string>>> GetChapterMangaConnectorId (string MangaConnectorIdId)
|
||||
{
|
||||
if (await context.MangaConnectorToManga.FirstOrDefaultAsync(c => c.Key == MangaConnectorIdId, HttpContext.RequestAborted) is not { } mcIdChapter)
|
||||
return TypedResults.NotFound(nameof(MangaConnectorIdId));
|
||||
|
||||
MangaConnectorId result = new(mcIdChapter.Key, mcIdChapter.MangaConnectorName, mcIdChapter.ObjId, mcIdChapter.WebsiteUrl, mcIdChapter.UseForDownload);
|
||||
|
||||
return TypedResults.Ok(result);
|
||||
}
|
||||
}
|
37
API/Controllers/Requests/CreateGotifyConnectorRecord.cs
Normal file
37
API/Controllers/Requests/CreateGotifyConnectorRecord.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace API.Controllers.Requests;
|
||||
|
||||
public record CreateGotifyConnectorRecord(string Name, string Url, string AppToken, int Priority)
|
||||
{
|
||||
/// <summary>
|
||||
/// The Name of the Notification Connector
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Name of the Notification Connector")]
|
||||
public string Name { get; init; } = Name;
|
||||
|
||||
/// <summary>
|
||||
/// The Url of the Instance
|
||||
/// </summary>
|
||||
/// <remarks>Formatting placeholders: "%title" and "%text" will be replaced when notifications are sent</remarks>
|
||||
[Required]
|
||||
[Url]
|
||||
[Description("The Url of the Instance")]
|
||||
public string Url { get; internal set; } = Url;
|
||||
|
||||
/// <summary>
|
||||
/// The Apptoken used for authentication
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Apptoken used for authentication")]
|
||||
public string AppToken { get; init; } = AppToken;
|
||||
|
||||
/// <summary>
|
||||
/// The Priority of Notifications
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Priority of Notifications")]
|
||||
public int Priority { get; init; } = Priority;
|
||||
}
|
37
API/Controllers/Requests/CreateLibraryConnectorRecord.cs
Normal file
37
API/Controllers/Requests/CreateLibraryConnectorRecord.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using API.Schema.LibraryContext.LibraryConnectors;
|
||||
|
||||
namespace API.Controllers.Requests;
|
||||
|
||||
public sealed record CreateLibraryConnectorRecord(LibraryType LibraryType, string Url, string Username, string Password)
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="LibraryType"/>
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Library Type")]
|
||||
public LibraryType LibraryType { get; init; } = LibraryType;
|
||||
|
||||
/// <summary>
|
||||
/// The Url of the Library instance
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Url]
|
||||
[Description("The Url of the Library instance")]
|
||||
public string Url { get; init; } = Url;
|
||||
|
||||
/// <summary>
|
||||
/// The Username to authenticate to the Library instance
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Username to authenticate to the Library instance")]
|
||||
public string Username { get; init; } = Username;
|
||||
|
||||
/// <summary>
|
||||
/// The Password to authenticate to the Library instance
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Password to authenticate to the Library instance")]
|
||||
public string Password { get; init; } = Password;
|
||||
}
|
21
API/Controllers/Requests/CreateLibraryRecord.cs
Normal file
21
API/Controllers/Requests/CreateLibraryRecord.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace API.Controllers.Requests;
|
||||
|
||||
public sealed record CreateLibraryRecord(string BasePath, string LibraryName)
|
||||
{
|
||||
/// <summary>
|
||||
/// The directory Path of the library
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The directory Path of the library")]
|
||||
public string BasePath { get; init; } = BasePath;
|
||||
|
||||
/// <summary>
|
||||
/// The Name of the library
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Name of the library")]
|
||||
public string LibraryName { get; init; } = LibraryName;
|
||||
}
|
@@ -0,0 +1,46 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace API.Controllers.Requests;
|
||||
|
||||
public record CreateNotificationConnectorRecord(string Name, string Url, string HttpMethod, string Body, Dictionary<string, string> Headers)
|
||||
{
|
||||
/// <summary>
|
||||
/// The Name of the Notification Connector
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Name of the Notification Connector")]
|
||||
public string Name { get; init; } = Name;
|
||||
|
||||
/// <summary>
|
||||
/// The Url of the Instance
|
||||
/// </summary>
|
||||
/// <remarks>Formatting placeholders: "%title" and "%text" will be replaced when notifications are sent</remarks>
|
||||
[Required]
|
||||
[Url]
|
||||
[Description("The Url of the Instance")]
|
||||
public string Url { get; internal set; } = Url;
|
||||
|
||||
/// <summary>
|
||||
/// The HTTP Request Method to use for notifications
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The HTTP Request Method to use for notifications")]
|
||||
public string HttpMethod { get; internal set; } = HttpMethod;
|
||||
|
||||
/// <summary>
|
||||
/// The Request Body to use to send notifications
|
||||
/// </summary>
|
||||
/// <remarks>Formatting placeholders: "%title" and "%text" will be replaced when notifications are sent</remarks>
|
||||
[Required]
|
||||
[Description("The Request Body to use to send notifications")]
|
||||
public string Body { get; internal set; } = Body;
|
||||
|
||||
/// <summary>
|
||||
/// The Request Headers to use to send notifications
|
||||
/// </summary>
|
||||
/// <remarks>Formatting placeholders: "%title" and "%text" will be replaced when notifications are sent</remarks>
|
||||
[Required]
|
||||
[Description("The Request Headers to use to send notifications")]
|
||||
public Dictionary<string, string> Headers { get; internal set; } = Headers;
|
||||
}
|
51
API/Controllers/Requests/CreateNtfyConnectorRecord.cs
Normal file
51
API/Controllers/Requests/CreateNtfyConnectorRecord.cs
Normal file
@@ -0,0 +1,51 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace API.Controllers.Requests;
|
||||
|
||||
public record CreateNtfyConnectorRecord(string Name, string Url, string Username, string Password, string Topic, int Priority)
|
||||
{
|
||||
/// <summary>
|
||||
/// The Name of the Notification Connector
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Name of the Notification Connector")]
|
||||
public string Name { get; init; } = Name;
|
||||
|
||||
/// <summary>
|
||||
/// The Url of the Instance
|
||||
/// </summary>
|
||||
/// <remarks>Formatting placeholders: "%title" and "%text" will be replaced when notifications are sent</remarks>
|
||||
[Required]
|
||||
[Url]
|
||||
[Description("The Url of the Instance")]
|
||||
public string Url { get; internal set; } = Url;
|
||||
|
||||
/// <summary>
|
||||
/// The Priority of Notifications
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Priority of Notifications")]
|
||||
public int Priority { get; init; } = Priority;
|
||||
|
||||
/// <summary>
|
||||
/// The Username used for authentication
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Username used for authentication")]
|
||||
public string Username { get; init; } = Username;
|
||||
|
||||
/// <summary>
|
||||
/// The Password used for authentication
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Password used for authentication")]
|
||||
public string Password { get; init; } = Password;
|
||||
|
||||
/// <summary>
|
||||
/// The Topic of Notifications
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Topic of Notifications")]
|
||||
public string Topic { get; init; } = Topic;
|
||||
}
|
28
API/Controllers/Requests/CreatePushoverConnectorRecord.cs
Normal file
28
API/Controllers/Requests/CreatePushoverConnectorRecord.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace API.Controllers.Requests;
|
||||
|
||||
public record CreatePushoverConnectorRecord(string Name, string AppToken, string Username)
|
||||
{
|
||||
/// <summary>
|
||||
/// The Name of the Notification Connector
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Name of the Notification Connector")]
|
||||
public string Name { get; init; } = Name;
|
||||
|
||||
/// <summary>
|
||||
/// The Apptoken used for authentication
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Apptoken used for authentication")]
|
||||
public string AppToken { get; init; } = AppToken;
|
||||
|
||||
/// <summary>
|
||||
/// The Username used for authentication
|
||||
/// </summary>
|
||||
[Required]
|
||||
[Description("The Username used for authentication")]
|
||||
public string Username { get; init; } = Username;
|
||||
}
|
79
API/Controllers/SearchController.cs
Normal file
79
API/Controllers/SearchController.cs
Normal file
@@ -0,0 +1,79 @@
|
||||
using API.Controllers.DTOs;
|
||||
using API.Schema.MangaContext;
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using static Microsoft.AspNetCore.Http.StatusCodes;
|
||||
using Manga = API.Schema.MangaContext.Manga;
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace API.Controllers;
|
||||
|
||||
[ApiVersion(2)]
|
||||
[ApiController]
|
||||
[Route("v{v:apiVersion}/[controller]")]
|
||||
public class SearchController(MangaContext context) : Controller
|
||||
{
|
||||
/// <summary>
|
||||
/// Initiate a search for a <see cref="Schema.MangaContext.Manga"/> on <see cref="MangaConnector"/> with searchTerm
|
||||
/// </summary>
|
||||
/// <param name="MangaConnectorName"><see cref="MangaConnector"/>.Name</param>
|
||||
/// <param name="Query">searchTerm</param>
|
||||
/// <response code="200"><see cref="MinimalManga"/> exert of <see cref="Schema.MangaContext.Manga"/></response>
|
||||
/// <response code="404"><see cref="MangaConnector"/> with Name not found</response>
|
||||
/// <response code="412"><see cref="MangaConnector"/> with Name is disabled</response>
|
||||
[HttpGet("{MangaConnectorName}/{Query}")]
|
||||
[ProducesResponseType<List<MinimalManga>>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType(Status406NotAcceptable)]
|
||||
public Results<Ok<List<MinimalManga>>, NotFound<string>, StatusCodeHttpResult> SearchManga (string MangaConnectorName, string Query)
|
||||
{
|
||||
if(Tranga.MangaConnectors.FirstOrDefault(c => c.Name.Equals(MangaConnectorName, StringComparison.InvariantCultureIgnoreCase)) is not { } connector)
|
||||
return TypedResults.NotFound(nameof(MangaConnectorName));
|
||||
if (connector.Enabled is false)
|
||||
return TypedResults.StatusCode(Status412PreconditionFailed);
|
||||
|
||||
(Manga manga, MangaConnectorId<Manga> id)[] mangas = connector.SearchManga(Query);
|
||||
|
||||
IEnumerable<(Manga manga, MangaConnectorId<Manga> id)> addedManga = mangas.Where(kv => context.AddMangaToContext(kv, HttpContext.RequestAborted).GetAwaiter().GetResult());
|
||||
|
||||
IEnumerable<MinimalManga> result = addedManga.Select(manga => manga.manga).Select(m =>
|
||||
{
|
||||
IEnumerable<MangaConnectorId> ids = m.MangaConnectorIds.Select(id =>
|
||||
new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
return new MinimalManga(m.Key, m.Name, m.Description, m.ReleaseStatus, ids);
|
||||
});
|
||||
|
||||
return TypedResults.Ok(result.ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns <see cref="Schema.MangaContext.Manga"/> from the <see cref="MangaConnector"/> associated with <paramref name="url"/>
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <response code="200"><see cref="MinimalManga"/> exert of <see cref="Schema.MangaContext.Manga"/>.</response>
|
||||
/// <response code="404"><see cref="Manga"/> not found</response>
|
||||
/// <response code="500">Error during Database Operation</response>
|
||||
[HttpPost("Url")]
|
||||
[ProducesResponseType<MinimalManga>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType<string>(Status500InternalServerError, "text/plain")]
|
||||
public async Task<Results<Ok<MinimalManga>, NotFound<string>, InternalServerError<string>>> GetMangaFromUrl ([FromBody]string url)
|
||||
{
|
||||
if(Tranga.MangaConnectors.FirstOrDefault(c => c.Name.Equals("Global", StringComparison.InvariantCultureIgnoreCase)) is not { } connector)
|
||||
return TypedResults.InternalServerError("Could not find Global Connector.");
|
||||
|
||||
if(connector.GetMangaFromUrl(url) is not ({ } m, not null) manga)
|
||||
return TypedResults.NotFound("Could not retrieve Manga");
|
||||
|
||||
if(await context.AddMangaToContext(manga, HttpContext.RequestAborted) == false)
|
||||
return TypedResults.InternalServerError("Could not add Manga to context");
|
||||
|
||||
IEnumerable<MangaConnectorId> ids = m.MangaConnectorIds.Select(id =>
|
||||
new MangaConnectorId(id.Key, id.MangaConnectorName, id.ObjId, id.WebsiteUrl, id.UseForDownload));
|
||||
MinimalManga result = new (m.Key, m.Name, m.Description, m.ReleaseStatus, ids);
|
||||
|
||||
return TypedResults.Ok(result);
|
||||
}
|
||||
}
|
293
API/Controllers/SettingsController.cs
Normal file
293
API/Controllers/SettingsController.cs
Normal file
@@ -0,0 +1,293 @@
|
||||
using API.MangaDownloadClients;
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using static Microsoft.AspNetCore.Http.StatusCodes;
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace API.Controllers;
|
||||
|
||||
[ApiVersion(2)]
|
||||
[ApiController]
|
||||
[Route("v{v:apiVersion}/[controller]")]
|
||||
public class SettingsController() : Controller
|
||||
{
|
||||
/// <summary>
|
||||
/// Get all <see cref="Tranga.Settings"/>
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
[HttpGet]
|
||||
[ProducesResponseType<TrangaSettings>(Status200OK, "application/json")]
|
||||
public Ok<TrangaSettings> GetSettings()
|
||||
{
|
||||
return TypedResults.Ok(Tranga.Settings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the current UserAgent used by Tranga
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
[HttpGet("UserAgent")]
|
||||
[ProducesResponseType<string>(Status200OK, "text/plain")]
|
||||
public Ok<string> GetUserAgent()
|
||||
{
|
||||
return TypedResults.Ok(Tranga.Settings.UserAgent);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set a new UserAgent
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
[HttpPatch("UserAgent")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
public Ok SetUserAgent([FromBody]string userAgent)
|
||||
{
|
||||
//TODO Validate
|
||||
Tranga.Settings.SetUserAgent(userAgent);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reset the UserAgent to default
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
[HttpDelete("UserAgent")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
public Ok ResetUserAgent()
|
||||
{
|
||||
Tranga.Settings.SetUserAgent(TrangaSettings.DefaultUserAgent);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get all Request-Limits
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
[HttpGet("RequestLimits")]
|
||||
[ProducesResponseType<Dictionary<RequestType,int>>(Status200OK, "application/json")]
|
||||
public Ok<Dictionary<RequestType,int>> GetRequestLimits()
|
||||
{
|
||||
return TypedResults.Ok(Tranga.Settings.RequestLimits);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Update all Request-Limits to new values
|
||||
/// </summary>
|
||||
/// <remarks><h1>NOT IMPLEMENTED</h1></remarks>
|
||||
[HttpPatch("RequestLimits")]
|
||||
[ProducesResponseType(Status501NotImplemented)]
|
||||
public StatusCodeHttpResult SetRequestLimits()
|
||||
{
|
||||
return TypedResults.StatusCode(Status501NotImplemented);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates a Request-Limit value
|
||||
/// </summary>
|
||||
/// <param name="RequestType">Type of Request</param>
|
||||
/// <param name="requestLimit">New limit in Requests/Minute</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="400">Limit needs to be greater than 0</response>
|
||||
[HttpPatch("RequestLimits/{RequestType}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType(Status400BadRequest)]
|
||||
public Results<Ok, BadRequest> SetRequestLimit(RequestType RequestType, [FromBody]int requestLimit)
|
||||
{
|
||||
if (requestLimit <= 0)
|
||||
return TypedResults.BadRequest();
|
||||
Tranga.Settings.SetRequestLimit(RequestType, requestLimit);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reset Request-Limit
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
[HttpDelete("RequestLimits/{RequestType}")]
|
||||
[ProducesResponseType<string>(Status200OK)]
|
||||
public Ok ResetRequestLimits(RequestType RequestType)
|
||||
{
|
||||
Tranga.Settings.SetRequestLimit(RequestType, TrangaSettings.DefaultRequestLimits[RequestType]);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reset Request-Limit
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
[HttpDelete("RequestLimits")]
|
||||
[ProducesResponseType<string>(Status200OK)]
|
||||
public Ok ResetRequestLimits()
|
||||
{
|
||||
Tranga.Settings.ResetRequestLimits();
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns Level of Image-Compression for Images
|
||||
/// </summary>
|
||||
/// <response code="200">JPEG ImageCompression-level as Integer</response>
|
||||
[HttpGet("ImageCompressionLevel")]
|
||||
[ProducesResponseType<int>(Status200OK, "text/plain")]
|
||||
public Ok<int> GetImageCompression()
|
||||
{
|
||||
return TypedResults.Ok(Tranga.Settings.ImageCompression);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set the Image-Compression-Level for Images
|
||||
/// </summary>
|
||||
/// <param name="level">100 to disable, 0-99 for JPEG ImageCompression-Level</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="400">Level outside permitted range</response>
|
||||
[HttpPatch("ImageCompressionLevel/{level}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType(Status400BadRequest)]
|
||||
public Results<Ok, BadRequest> SetImageCompression(int level)
|
||||
{
|
||||
if (level < 1 || level > 100)
|
||||
return TypedResults.BadRequest();
|
||||
Tranga.Settings.UpdateImageCompression(level);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get state of Black/White-Image setting
|
||||
/// </summary>
|
||||
/// <response code="200">True if enabled</response>
|
||||
[HttpGet("BWImages")]
|
||||
[ProducesResponseType<bool>(Status200OK, "text/plain")]
|
||||
public Ok<bool> GetBwImagesToggle()
|
||||
{
|
||||
return TypedResults.Ok(Tranga.Settings.BlackWhiteImages);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enable/Disable conversion of Images to Black and White
|
||||
/// </summary>
|
||||
/// <param name="enabled">true to enable</param>
|
||||
/// <response code="200"></response>
|
||||
[HttpPatch("BWImages/{enabled}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
public Ok SetBwImagesToggle(bool enabled)
|
||||
{
|
||||
Tranga.Settings.SetBlackWhiteImageEnabled(enabled);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Chapter Naming Scheme
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Placeholders:
|
||||
/// %M Obj Name
|
||||
/// %V Volume
|
||||
/// %C Chapter
|
||||
/// %T Title
|
||||
/// %A Author (first in list)
|
||||
/// %I Chapter Internal ID
|
||||
/// %i Obj Internal ID
|
||||
/// %Y Year (Obj)
|
||||
///
|
||||
/// ?_(...) replace _ with a value from above:
|
||||
/// Everything inside the braces will only be added if the value of %_ is not null
|
||||
/// </remarks>
|
||||
/// <response code="200"></response>
|
||||
[HttpGet("ChapterNamingScheme")]
|
||||
[ProducesResponseType<string>(Status200OK, "text/plain")]
|
||||
public Ok<string> GetCustomNamingScheme()
|
||||
{
|
||||
return TypedResults.Ok(Tranga.Settings.ChapterNamingScheme);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the Chapter Naming Scheme
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Placeholders:
|
||||
/// %M Obj Name
|
||||
/// %V Volume
|
||||
/// %C Chapter
|
||||
/// %T Title
|
||||
/// %A Author (first in list)
|
||||
/// %Y Year (Obj)
|
||||
///
|
||||
/// ?_(...) replace _ with a value from above:
|
||||
/// Everything inside the braces will only be added if the value of %_ is not null
|
||||
/// </remarks>
|
||||
/// <response code="200"></response>
|
||||
[HttpPatch("ChapterNamingScheme")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
public Ok SetCustomNamingScheme([FromBody]string namingScheme)
|
||||
{
|
||||
//TODO Move old Chapters
|
||||
Tranga.Settings.SetChapterNamingScheme(namingScheme);
|
||||
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the FlareSolverr-URL
|
||||
/// </summary>
|
||||
/// <param name="flareSolverrUrl">URL of FlareSolverr-Instance</param>
|
||||
/// <response code="200"></response>
|
||||
[HttpPost("FlareSolverr/Url")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
public Ok SetFlareSolverrUrl([FromBody]string flareSolverrUrl)
|
||||
{
|
||||
Tranga.Settings.SetFlareSolverrUrl(flareSolverrUrl);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the FlareSolverr-URL (HttpClient does not use FlareSolverr anymore)
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
[HttpDelete("FlareSolverr/Url")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
public Ok ClearFlareSolverrUrl()
|
||||
{
|
||||
Tranga.Settings.SetFlareSolverrUrl(string.Empty);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test FlareSolverr
|
||||
/// </summary>
|
||||
/// <response code="200">FlareSolverr is working!</response>
|
||||
/// <response code="500">FlareSolverr is not working</response>
|
||||
[HttpPost("FlareSolverr/Test")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType(Status500InternalServerError)]
|
||||
public Results<Ok, InternalServerError> TestFlareSolverrReachable()
|
||||
{
|
||||
const string knownProtectedUrl = "https://prowlarr.servarr.com/v1/ping";
|
||||
FlareSolverrDownloadClient client = new();
|
||||
RequestResult result = client.MakeRequestInternal(knownProtectedUrl);
|
||||
return (int)result.statusCode >= 200 && (int)result.statusCode < 300 ? TypedResults.Ok() : TypedResults.InternalServerError();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the language in which Manga are downloaded
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
[HttpGet("DownloadLanguage")]
|
||||
[ProducesResponseType<string>(Status200OK, "text/plain")]
|
||||
public Ok<string> GetDownloadLanguage()
|
||||
{
|
||||
return TypedResults.Ok(Tranga.Settings.DownloadLanguage);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the language in which Manga are downloaded
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
[HttpPatch("DownloadLanguage/{Language}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
public Ok SetDownloadLanguage(string Language)
|
||||
{
|
||||
//TODO Validation
|
||||
Tranga.Settings.SetDownloadLanguage(Language);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
}
|
135
API/Controllers/WorkerController.cs
Normal file
135
API/Controllers/WorkerController.cs
Normal file
@@ -0,0 +1,135 @@
|
||||
using API.Controllers.DTOs;
|
||||
using API.Workers;
|
||||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using static Microsoft.AspNetCore.Http.StatusCodes;
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
namespace API.Controllers;
|
||||
|
||||
[ApiVersion(2)]
|
||||
[ApiController]
|
||||
[Route("v{version:apiVersion}/[controller]")]
|
||||
public class WorkerController : Controller
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns all <see cref="BaseWorker"/>
|
||||
/// </summary>
|
||||
/// <response code="200"><see cref="Worker"/></response>
|
||||
[HttpGet]
|
||||
[ProducesResponseType<List<Worker>>(Status200OK, "application/json")]
|
||||
public Ok<List<Worker>> GetWorkers()
|
||||
{
|
||||
IEnumerable<Worker> result = Tranga.GetRunningWorkers().Select(w =>
|
||||
new Worker(w.Key, w.AllDependencies.Select(d => d.Key), w.MissingDependencies.Select(d => d.Key), w.AllDependenciesFulfilled, w.State));
|
||||
return TypedResults.Ok(result.ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all <see cref="BaseWorker"/>.Keys
|
||||
/// </summary>
|
||||
/// <response code="200"></response>
|
||||
[HttpGet("Keys")]
|
||||
[ProducesResponseType<string[]>(Status200OK, "application/json")]
|
||||
public Ok<List<string>> GetWorkerIds()
|
||||
{
|
||||
return TypedResults.Ok(Tranga.GetRunningWorkers().Select(w => w.Key).ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get all <see cref="BaseWorker"/> in requested <see cref="WorkerExecutionState"/>
|
||||
/// </summary>
|
||||
/// <param name="State">Requested <see cref="WorkerExecutionState"/></param>
|
||||
/// <response code="200"></response>
|
||||
[HttpGet("State/{State}")]
|
||||
[ProducesResponseType<List<Worker>>(Status200OK, "application/json")]
|
||||
public Ok<List<Worker>> GetWorkersInState(WorkerExecutionState State)
|
||||
{
|
||||
IEnumerable<Worker> result = Tranga.GetRunningWorkers().Where(worker => worker.State == State).Select(w =>
|
||||
new Worker(w.Key, w.AllDependencies.Select(d => d.Key), w.MissingDependencies.Select(d => d.Key), w.AllDependenciesFulfilled, w.State));
|
||||
return TypedResults.Ok(result.ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return <see cref="BaseWorker"/> with <paramref name="WorkerId"/>
|
||||
/// </summary>
|
||||
/// <param name="WorkerId"><see cref="BaseWorker"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="BaseWorker"/> with <paramref name="WorkerId"/> could not be found</response>
|
||||
[HttpGet("{WorkerId}")]
|
||||
[ProducesResponseType<Worker>(Status200OK, "application/json")]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public Results<Ok<Worker>, NotFound<string>> GetWorker(string WorkerId)
|
||||
{
|
||||
if(Tranga.GetRunningWorkers().FirstOrDefault(w => w.Key == WorkerId) is not { } w)
|
||||
return TypedResults.NotFound(nameof(WorkerId));
|
||||
|
||||
Worker result = new (w.Key, w.AllDependencies.Select(d => d.Key), w.MissingDependencies.Select(d => d.Key), w.AllDependenciesFulfilled, w.State);
|
||||
|
||||
return TypedResults.Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete <see cref="BaseWorker"/> with <paramref name="WorkerId"/> and all child-<see cref="BaseWorker"/>s
|
||||
/// </summary>
|
||||
/// <param name="WorkerId"><see cref="BaseWorker"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="BaseWorker"/> with <paramref name="WorkerId"/> could not be found</response>
|
||||
[HttpDelete("{WorkerId}")]
|
||||
[ProducesResponseType(Status200OK)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
public Results<Ok, NotFound<string>> DeleteWorker(string WorkerId)
|
||||
{
|
||||
if(Tranga.GetRunningWorkers().FirstOrDefault(w => w.Key == WorkerId) is not { } worker)
|
||||
return TypedResults.NotFound(nameof(WorkerId));
|
||||
Tranga.StopWorker(worker);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts <see cref="BaseWorker"/> with <paramref name="WorkerId"/>
|
||||
/// </summary>
|
||||
/// <param name="WorkerId"><see cref="BaseWorker"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="BaseWorker"/> with <paramref name="WorkerId"/> could not be found</response>
|
||||
/// <response code="412"><see cref="BaseWorker"/> was already running</response>
|
||||
[HttpPost("{WorkerId}/Start")]
|
||||
[ProducesResponseType(Status202Accepted)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType(Status412PreconditionFailed)]
|
||||
public Results<Ok, NotFound<string>, StatusCodeHttpResult> StartWorker(string WorkerId)
|
||||
{
|
||||
if(Tranga.GetRunningWorkers().FirstOrDefault(w => w.Key == WorkerId) is not { } worker)
|
||||
return TypedResults.NotFound(nameof(WorkerId));
|
||||
|
||||
if (worker.State >= WorkerExecutionState.Waiting)
|
||||
return TypedResults.StatusCode(Status412PreconditionFailed);
|
||||
|
||||
Tranga.StartWorker(worker);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops <see cref="BaseWorker"/> with <paramref name="WorkerId"/>
|
||||
/// </summary>
|
||||
/// <param name="WorkerId"><see cref="BaseWorker"/>.Key</param>
|
||||
/// <response code="200"></response>
|
||||
/// <response code="404"><see cref="BaseWorker"/> with <paramref name="WorkerId"/> could not be found</response>
|
||||
/// <response code="412"><see cref="BaseWorker"/> was already not running</response>
|
||||
[HttpPost("{WorkerId}/Stop")]
|
||||
[ProducesResponseType(Status202Accepted)]
|
||||
[ProducesResponseType<string>(Status404NotFound, "text/plain")]
|
||||
[ProducesResponseType(Status412PreconditionFailed)]
|
||||
public Results<Ok, NotFound<string>, StatusCodeHttpResult> StopWorker(string WorkerId)
|
||||
{
|
||||
if(Tranga.GetRunningWorkers().FirstOrDefault(w => w.Key == WorkerId) is not { } worker)
|
||||
return TypedResults.NotFound(nameof(WorkerId));
|
||||
|
||||
if(worker.State is < WorkerExecutionState.Running or >= WorkerExecutionState.Completed)
|
||||
return TypedResults.StatusCode(Status412PreconditionFailed);
|
||||
|
||||
Tranga.StopWorker(worker);
|
||||
return TypedResults.Ok();
|
||||
}
|
||||
}
|
35
API/HttpRequestTimeFeature.cs
Normal file
35
API/HttpRequestTimeFeature.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
namespace API;
|
||||
|
||||
public interface IHttpRequestTimeFeature
|
||||
{
|
||||
DateTime RequestTime { get; }
|
||||
}
|
||||
|
||||
public class HttpRequestTimeFeature : IHttpRequestTimeFeature
|
||||
{
|
||||
public DateTime RequestTime { get; }
|
||||
|
||||
public HttpRequestTimeFeature()
|
||||
{
|
||||
RequestTime = DateTime.Now;
|
||||
}
|
||||
}
|
||||
|
||||
public class RequestTimeMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
|
||||
public RequestTimeMiddleware(RequestDelegate next)
|
||||
{
|
||||
_next = next;
|
||||
}
|
||||
|
||||
public Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
var httpRequestTimeFeature = new HttpRequestTimeFeature();
|
||||
context.Features.Set<IHttpRequestTimeFeature>(httpRequestTimeFeature);
|
||||
|
||||
// Call the next delegate/middleware in the pipeline
|
||||
return this._next(context);
|
||||
}
|
||||
}
|
23
API/Log4Net.config.xml
Normal file
23
API/Log4Net.config.xml
Normal file
@@ -0,0 +1,23 @@
|
||||
<log4net>
|
||||
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
|
||||
<layout type="log4net.Layout.PatternLayout">
|
||||
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
|
||||
</layout>
|
||||
</appender>
|
||||
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
|
||||
<file value="/usr/share/tranga-api/log/Tranga.log" />
|
||||
<appendToFile value="true" />
|
||||
<rollingStyle value="Composite" />
|
||||
<datePattern value="yyyyMMdd" />
|
||||
<maxSizeRollBackups value="4" />
|
||||
<maximumFileSize value="256MB" />
|
||||
<layout type="log4net.Layout.PatternLayout">
|
||||
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
|
||||
</layout>
|
||||
</appender>
|
||||
<root>
|
||||
<level value="DEBUG" />
|
||||
<appender-ref ref="ConsoleAppender" />
|
||||
<appender-ref ref="RollingLogFileAppender" />
|
||||
</root>
|
||||
</log4net>
|
262
API/MangaConnectors/ComickIo.cs
Normal file
262
API/MangaConnectors/ComickIo.cs
Normal file
@@ -0,0 +1,262 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using API.MangaDownloadClients;
|
||||
using API.Schema.MangaContext;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace API.MangaConnectors;
|
||||
|
||||
public class ComickIo : MangaConnector
|
||||
{
|
||||
//https://api.comick.io/docs/
|
||||
//https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes
|
||||
|
||||
public ComickIo() : base("ComickIo",
|
||||
["en","pt","pt-br","it","de","ru","aa","ab","ae","af","ak","am","an","ar-ae","ar-bh","ar-dz","ar-eg","ar-iq","ar-jo","ar-kw","ar-lb","ar-ly","ar-ma","ar-om","ar-qa","ar-sa","ar-sy","ar-tn","ar-ye","ar","as","av","ay","az","ba","be","bg","bh","bi","bm","bn","bo","br","bs","ca","ce","ch","co","cr","cs","cu","cv","cy","da","de-at","de-ch","de-de","de-li","de-lu","div","dv","dz","ee","el","en-au","en-bz","en-ca","en-cb","en-gb","en-ie","en-jm","en-nz","en-ph","en-tt","en-us","en-za","en-zw","eo","es-ar","es-bo","es-cl","es-co","es-cr","es-do","es-ec","es-es","es-gt","es-hn","es-la","es-mx","es-ni","es-pa","es-pe","es-pr","es-py","es-sv","es-us","es-uy","es-ve","es","et","eu","fa","ff","fi","fj","fo","fr-be","fr-ca","fr-ch","fr-fr","fr-lu","fr-mc","fr","fy","ga","gd","gl","gn","gu","gv","ha","he","hi","ho","hr-ba","hr-hr","hr","ht","hu","hy","hz","ia","id","ie","ig","ii","ik","in","io","is","it-ch","it-it","iu","iw","ja","ja-ro","ji","jv","jw","ka","kg","ki","kj","kk","kl","km","kn","ko","ko-ro","kr","ks","ku","kv","kw","ky","kz","la","lb","lg","li","ln","lo","ls","lt","lu","lv","mg","mh","mi","mk","ml","mn","mo","mr","ms-bn","ms-my","ms","mt","my","na","nb","nd","ne","ng","nl-be","nl-nl","nl","nn","no","nr","ns","nv","ny","oc","oj","om","or","os","pa","pi","pl","ps","pt-pt","qu-bo","qu-ec","qu-pe","qu","rm","rn","ro","rw","sa","sb","sc","sd","se-fi","se-no","se-se","se","sg","sh","si","sk","sl","sm","sn","so","sq","sr-ba","sr-sp","sr","ss","st","su","sv-fi","sv-se","sv","sw","sx","syr","ta","te","tg","th","ti","tk","tl","tn","to","tr","ts","tt","tw","ty","ug","uk","ur","us","uz","ve","vi","vo","wa","wo","xh","yi","yo","za","zh-cn","zh-hk","zh-mo","zh-ro","zh-sg","zh-tw","zh","zu"],
|
||||
["comick.io"],
|
||||
"https://comick.io/static/icons/unicorn-64.png")
|
||||
{
|
||||
this.downloadClient = new HttpDownloadClient();
|
||||
}
|
||||
|
||||
public override (Manga, MangaConnectorId<Manga>)[] SearchManga(string mangaSearchName)
|
||||
{
|
||||
Log.Info($"Searching Obj: {mangaSearchName}");
|
||||
|
||||
List<string> slugs = new();
|
||||
int page = 1;
|
||||
while(page < 50)
|
||||
{
|
||||
string requestUrl = $"https://api.comick.fun/v1.0/search/?type=comic&t=false&limit=100&showall=true&" +
|
||||
$"page={page}&q={mangaSearchName}";
|
||||
|
||||
RequestResult result = downloadClient.MakeRequest(requestUrl, RequestType.Default);
|
||||
if ((int)result.statusCode < 200 || (int)result.statusCode >= 300)
|
||||
{
|
||||
Log.Error("Request failed");
|
||||
return [];
|
||||
}
|
||||
|
||||
using StreamReader sr = new (result.result);
|
||||
JArray data = JArray.Parse(sr.ReadToEnd());
|
||||
|
||||
if (data.Count < 1)
|
||||
break;
|
||||
|
||||
slugs.AddRange(data.Select(token => token.Value<string>("slug")!));
|
||||
page++;
|
||||
}
|
||||
Log.Debug($"Search {mangaSearchName} yielded {slugs.Count} slugs. Requesting mangas now...");
|
||||
|
||||
|
||||
List<(Manga, MangaConnectorId<Manga>)> mangas = new ();
|
||||
foreach (string slug in slugs)
|
||||
{
|
||||
if(GetMangaFromId(slug) is { } entry)
|
||||
mangas.Add(entry);
|
||||
}
|
||||
|
||||
Log.Info($"Search {mangaSearchName} yielded {mangas.Count} results.");
|
||||
return mangas.ToArray();
|
||||
}
|
||||
|
||||
private readonly Regex _getSlugFromTitleRex = new(@"https?:\/\/comick\.io\/comic\/(.+)(?:\/.*)*");
|
||||
public override (Manga, MangaConnectorId<Manga>)? GetMangaFromUrl(string url)
|
||||
{
|
||||
Match m = _getSlugFromTitleRex.Match(url);
|
||||
return m.Groups[1].Success ? GetMangaFromId(m.Groups[1].Value) : null;
|
||||
}
|
||||
|
||||
public override (Manga, MangaConnectorId<Manga>)? GetMangaFromId(string mangaIdOnSite)
|
||||
{
|
||||
string requestUrl = $"https://api.comick.fun/comic/{mangaIdOnSite}";
|
||||
|
||||
RequestResult result = downloadClient.MakeRequest(requestUrl, RequestType.MangaInfo);
|
||||
if ((int)result.statusCode < 200 || (int)result.statusCode >= 300)
|
||||
{
|
||||
Log.Error("Request failed");
|
||||
return null;
|
||||
}
|
||||
using StreamReader sr = new (result.result);
|
||||
JToken data = JToken.Parse(sr.ReadToEnd());
|
||||
|
||||
return ParseMangaFromJToken(data);
|
||||
}
|
||||
|
||||
public override (Chapter, MangaConnectorId<Chapter>)[] GetChapters(MangaConnectorId<Manga> mangaConnectorId,
|
||||
string? language = null)
|
||||
{
|
||||
Log.Info($"Getting Chapters: {mangaConnectorId.IdOnConnectorSite}");
|
||||
List<(Chapter, MangaConnectorId<Chapter>)> chapters = new();
|
||||
int page = 1;
|
||||
while(page < 50)
|
||||
{
|
||||
string requestUrl = $"https://api.comick.fun/comic/{mangaConnectorId.IdOnConnectorSite}/chapters?limit=100&page={page}&lang={language}";
|
||||
|
||||
RequestResult result = downloadClient.MakeRequest(requestUrl, RequestType.MangaInfo);
|
||||
if ((int)result.statusCode < 200 || (int)result.statusCode >= 300)
|
||||
{
|
||||
Log.Error("Request failed");
|
||||
return [];
|
||||
}
|
||||
|
||||
using StreamReader sr = new (result.result);
|
||||
JToken data = JToken.Parse(sr.ReadToEnd());
|
||||
JArray? chaptersArray = data["chapters"] as JArray;
|
||||
|
||||
if (chaptersArray is null || chaptersArray.Count < 1)
|
||||
break;
|
||||
|
||||
chapters.AddRange(ParseChapters(mangaConnectorId, chaptersArray));
|
||||
|
||||
page++;
|
||||
}
|
||||
|
||||
return chapters.ToArray();
|
||||
}
|
||||
|
||||
private readonly Regex _hidFromUrl = new(@"https?:\/\/comick\.io\/comic\/.+\/([^-]+).*");
|
||||
internal override string[] GetChapterImageUrls(MangaConnectorId<Chapter> chapterId)
|
||||
{
|
||||
|
||||
Log.Info($"Getting Chapter Image-Urls: {chapterId.Obj}");
|
||||
if (chapterId.WebsiteUrl is null || !UrlMatchesConnector(chapterId.WebsiteUrl))
|
||||
{
|
||||
Log.Debug($"Url is not for Connector. {chapterId.WebsiteUrl}");
|
||||
return [];
|
||||
}
|
||||
|
||||
Match m = _hidFromUrl.Match(chapterId.WebsiteUrl);
|
||||
if (!m.Groups[1].Success)
|
||||
{
|
||||
Log.Debug($"Could not parse hid from url. {chapterId.WebsiteUrl}");
|
||||
return [];
|
||||
}
|
||||
|
||||
string hid = m.Groups[1].Value;
|
||||
|
||||
string requestUrl = $"https://api.comick.fun/chapter/{hid}/get_images";
|
||||
RequestResult result = downloadClient.MakeRequest(requestUrl, RequestType.MangaInfo);
|
||||
if ((int)result.statusCode < 200 || (int)result.statusCode >= 300)
|
||||
{
|
||||
Log.Error("Request failed");
|
||||
return [];
|
||||
}
|
||||
|
||||
using StreamReader sr = new (result.result);
|
||||
JArray data = JArray.Parse(sr.ReadToEnd());
|
||||
|
||||
return data.Select(token =>
|
||||
{
|
||||
string url = $"https://meo.comick.pictures/{token.Value<string>("b2key")}";
|
||||
return url;
|
||||
}).ToArray();
|
||||
}
|
||||
|
||||
private (Manga manga, MangaConnectorId<Manga> id) ParseMangaFromJToken(JToken json)
|
||||
{
|
||||
string? hid = json["comic"]?.Value<string>("hid");
|
||||
string? slug = json["comic"]?.Value<string>("slug");
|
||||
string? name = json["comic"]?.Value<string>("title");
|
||||
string? description = json["comic"]?.Value<string>("desc");
|
||||
string? originalLanguage = json["comic"]?.Value<string>("country");
|
||||
string url = $"https://comick.io/comic/{slug}";
|
||||
string? coverName = json["comic"]?["md_covers"]?.First?.Value<string>("b2key");
|
||||
string coverUrl = $"https://meo.comick.pictures/{coverName}";
|
||||
int? releaseStatusStr = json["comic"]?.Value<int>("status");
|
||||
MangaReleaseStatus status = releaseStatusStr switch
|
||||
{
|
||||
1 => MangaReleaseStatus.Continuing,
|
||||
2 => MangaReleaseStatus.Completed,
|
||||
3 => MangaReleaseStatus.Cancelled,
|
||||
4 => MangaReleaseStatus.OnHiatus,
|
||||
_ => MangaReleaseStatus.Unreleased
|
||||
};
|
||||
uint? year = json["comic"]?.Value<uint?>("year");
|
||||
JArray? altTitlesArray = json["comic"]?["md_titles"] as JArray;
|
||||
//Cant let language be null, so fill with whatever.
|
||||
byte whatever = 0;
|
||||
List<AltTitle> altTitles = altTitlesArray?
|
||||
.Select(token => new AltTitle(token.Value<string>("lang")??whatever++.ToString(), token.Value<string>("title")!))
|
||||
.ToList()??[];
|
||||
|
||||
JArray? authorsArray = json["authors"] as JArray;
|
||||
JArray? artistsArray = json["artists"] as JArray;
|
||||
List<Author> authors = authorsArray?.Concat(artistsArray!)
|
||||
.Select(token => new Author(token.Value<string>("name")!))
|
||||
.DistinctBy(a => a.Key)
|
||||
.ToList()??[];
|
||||
|
||||
JArray? genreArray = json["comic"]?["md_comic_md_genres"] as JArray;
|
||||
List<MangaTag> tags = genreArray?
|
||||
.Select(token => new MangaTag(token["md_genres"]?.Value<string>("name")!))
|
||||
.ToList()??[];
|
||||
|
||||
JArray? linksArray = json["comic"]?["links"] as JArray;
|
||||
List<Link> links = linksArray?
|
||||
.ToObject<Dictionary<string,string>>()?
|
||||
.Select(kv =>
|
||||
{
|
||||
string fullUrl = kv.Key switch
|
||||
{
|
||||
"al" => $"https://anilist.co/manga/{kv.Value}",
|
||||
"ap" => $"https://www.anime-planet.com/manga/{kv.Value}",
|
||||
"bw" => $"https://bookwalker.jp/{kv.Value}",
|
||||
"mu" => $"https://www.mangaupdates.com/series.html?id={kv.Value}",
|
||||
"nu" => $"https://www.novelupdates.com/series/{kv.Value}",
|
||||
"mal" => $"https://myanimelist.net/manga/{kv.Value}",
|
||||
_ => kv.Value
|
||||
};
|
||||
string key = kv.Key switch
|
||||
{
|
||||
"al" => "AniList",
|
||||
"ap" => "Anime Planet",
|
||||
"bw" => "BookWalker",
|
||||
"mu" => "Obj Updates",
|
||||
"nu" => "Novel Updates",
|
||||
"kt" => "Kitsu.io",
|
||||
"amz" => "Amazon",
|
||||
"ebj" => "eBookJapan",
|
||||
"mal" => "MyAnimeList",
|
||||
"cdj" => "CDJapan",
|
||||
_ => kv.Key
|
||||
};
|
||||
return new Link(key, fullUrl);
|
||||
}).ToList()??[];
|
||||
|
||||
if(hid is null)
|
||||
throw new Exception("hid is null");
|
||||
if(slug is null)
|
||||
throw new Exception("slug is null");
|
||||
if(name is null)
|
||||
throw new Exception("name is null");
|
||||
|
||||
Manga manga = new (name, description??"", coverUrl, status, authors, tags, links, altTitles,
|
||||
year: year, originalLanguage: originalLanguage);
|
||||
MangaConnectorId<Manga> mcId = new (manga, this, hid, url);
|
||||
manga.MangaConnectorIds.Add(mcId);
|
||||
return (manga, mcId);
|
||||
}
|
||||
|
||||
private List<(Chapter, MangaConnectorId<Chapter>)> ParseChapters(MangaConnectorId<Manga> mcIdManga, JArray chaptersArray)
|
||||
{
|
||||
List<(Chapter, MangaConnectorId<Chapter>)> chapters = new ();
|
||||
foreach (JToken chapter in chaptersArray)
|
||||
{
|
||||
string? chapterNum = chapter.Value<string>("chap");
|
||||
string? volumeNumStr = chapter.Value<string>("vol");
|
||||
int? volumeNum = volumeNumStr is null ? null : int.Parse(volumeNumStr);
|
||||
string? title = chapter.Value<string>("title");
|
||||
string? hid = chapter.Value<string>("hid");
|
||||
string url = $"https://comick.io/comic/{mcIdManga.IdOnConnectorSite}/{hid}";
|
||||
|
||||
if(chapterNum is null || hid is null)
|
||||
continue;
|
||||
|
||||
Chapter ch = new (mcIdManga.Obj, chapterNum, volumeNum, title);
|
||||
MangaConnectorId<Chapter> mcId = new(ch, this, hid, url);
|
||||
ch.MangaConnectorIds.Add(mcId);
|
||||
chapters.Add((ch, mcId));
|
||||
}
|
||||
return chapters;
|
||||
}
|
||||
}
|
58
API/MangaConnectors/Global.cs
Normal file
58
API/MangaConnectors/Global.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
using API.Schema.MangaContext;
|
||||
|
||||
namespace API.MangaConnectors;
|
||||
|
||||
public class Global : MangaConnector
|
||||
{
|
||||
public Global() : base("Global", ["all"], [""], "https://avatars.githubusercontent.com/u/13404778")
|
||||
{
|
||||
}
|
||||
|
||||
public override (Manga, MangaConnectorId<Manga>)[] SearchManga(string mangaSearchName)
|
||||
{
|
||||
//Get all enabled Connectors
|
||||
MangaConnector[] enabledConnectors = Tranga.MangaConnectors.Where(c => c.Enabled && c.Name != "Global").ToArray();
|
||||
|
||||
//Create Task for each MangaConnector to search simultaneously
|
||||
Task<(Manga, MangaConnectorId<Manga>)[]>[] tasks =
|
||||
enabledConnectors.Select(c => new Task<(Manga, MangaConnectorId<Manga>)[]>(() => c.SearchManga(mangaSearchName))).ToArray();
|
||||
foreach (var task in tasks)
|
||||
task.Start();
|
||||
|
||||
//Wait for all tasks to finish
|
||||
do
|
||||
{
|
||||
Thread.Sleep(50);
|
||||
}while(tasks.Any(t => t.Status < TaskStatus.RanToCompletion));
|
||||
|
||||
//Concatenate all results into one
|
||||
(Manga, MangaConnectorId<Manga>)[] ret = tasks.Select(t => t.IsCompletedSuccessfully ? t.Result : []).ToArray().SelectMany(i => i).ToArray();
|
||||
return ret;
|
||||
}
|
||||
|
||||
public override (Manga, MangaConnectorId<Manga>)? GetMangaFromUrl(string url)
|
||||
{
|
||||
MangaConnector? mc = Tranga.MangaConnectors.FirstOrDefault(c => c.UrlMatchesConnector(url));
|
||||
return mc?.GetMangaFromUrl(url) ?? null;
|
||||
}
|
||||
|
||||
public override (Manga, MangaConnectorId<Manga>)? GetMangaFromId(string mangaIdOnSite)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public override (Chapter, MangaConnectorId<Chapter>)[] GetChapters(MangaConnectorId<Manga> manga,
|
||||
string? language = null)
|
||||
{
|
||||
if (!Tranga.TryGetMangaConnector(manga.MangaConnectorName, out MangaConnector? mangaConnector))
|
||||
return [];
|
||||
return mangaConnector.GetChapters(manga, language);
|
||||
}
|
||||
|
||||
internal override string[] GetChapterImageUrls(MangaConnectorId<Chapter> chapterId)
|
||||
{
|
||||
if (!Tranga.TryGetMangaConnector(chapterId.MangaConnectorName, out MangaConnector? mangaConnector))
|
||||
return [];
|
||||
return mangaConnector.GetChapterImageUrls(chapterId);
|
||||
}
|
||||
}
|
91
API/MangaConnectors/MangaConnector.cs
Normal file
91
API/MangaConnectors/MangaConnector.cs
Normal file
@@ -0,0 +1,91 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Text.RegularExpressions;
|
||||
using API.MangaDownloadClients;
|
||||
using API.Schema.MangaContext;
|
||||
using log4net;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.Formats.Jpeg;
|
||||
using SixLabors.ImageSharp.Processing;
|
||||
|
||||
namespace API.MangaConnectors;
|
||||
|
||||
[PrimaryKey("Name")]
|
||||
public abstract class MangaConnector(string name, string[] supportedLanguages, string[] baseUris, string iconUrl)
|
||||
{
|
||||
[NotMapped] internal DownloadClient downloadClient { get; init; } = null!;
|
||||
|
||||
[NotMapped] protected ILog Log { get; init; } = LogManager.GetLogger(name);
|
||||
|
||||
[StringLength(32)] public string Name { get; init; } = name;
|
||||
[StringLength(8)] public string[] SupportedLanguages { get; init; } = supportedLanguages;
|
||||
[StringLength(2048)] public string IconUrl { get; init; } = iconUrl;
|
||||
[StringLength(256)] public string[] BaseUris { get; init; } = baseUris;
|
||||
public bool Enabled { get; internal set; } = true;
|
||||
|
||||
public abstract (Manga, MangaConnectorId<Manga>)[] SearchManga(string mangaSearchName);
|
||||
|
||||
public abstract (Manga, MangaConnectorId<Manga>)? GetMangaFromUrl(string url);
|
||||
|
||||
public abstract (Manga, MangaConnectorId<Manga>)? GetMangaFromId(string mangaIdOnSite);
|
||||
|
||||
public abstract (Chapter, MangaConnectorId<Chapter>)[] GetChapters(MangaConnectorId<Manga> mangaId,
|
||||
string? language = null);
|
||||
|
||||
internal abstract string[] GetChapterImageUrls(MangaConnectorId<Chapter> chapterId);
|
||||
|
||||
public bool UrlMatchesConnector(string url) => BaseUris.Any(baseUri => Regex.IsMatch(url, "https?://" + baseUri + "/.*"));
|
||||
|
||||
internal string? SaveCoverImageToCache(MangaConnectorId<Manga> mangaId, int retries = 3)
|
||||
{
|
||||
if(retries < 0)
|
||||
return null;
|
||||
|
||||
Regex urlRex = new (@"https?:\/\/((?:[a-zA-Z0-9-]+\.)+[a-zA-Z0-9]+)\/(?:.+\/)*(.+\.([a-zA-Z]+))");
|
||||
//https?:\/\/[a-zA-Z0-9-]+\.([a-zA-Z0-9-]+\.[a-zA-Z0-9]+)\/(?:.+\/)*(.+\.([a-zA-Z]+)) for only second level domains
|
||||
Match match = urlRex.Match(mangaId.Obj.CoverUrl);
|
||||
string filename = $"{match.Groups[1].Value}-{mangaId.ObjId}.{mangaId.MangaConnectorName}.{match.Groups[3].Value}";
|
||||
string saveImagePath = Path.Join(TrangaSettings.coverImageCacheOriginal, filename);
|
||||
|
||||
if (File.Exists(saveImagePath))
|
||||
return filename;
|
||||
|
||||
RequestResult coverResult = downloadClient.MakeRequest(mangaId.Obj.CoverUrl, RequestType.MangaCover, $"https://{match.Groups[1].Value}");
|
||||
if ((int)coverResult.statusCode < 200 || (int)coverResult.statusCode >= 300)
|
||||
return SaveCoverImageToCache(mangaId, --retries);
|
||||
|
||||
try
|
||||
{
|
||||
using MemoryStream ms = new();
|
||||
coverResult.result.CopyTo(ms);
|
||||
byte[] imageBytes = ms.ToArray();
|
||||
Directory.CreateDirectory(TrangaSettings.coverImageCacheOriginal);
|
||||
File.WriteAllBytes(saveImagePath, imageBytes);
|
||||
|
||||
using Image image = Image.Load(imageBytes);
|
||||
Directory.CreateDirectory(TrangaSettings.coverImageCacheLarge);
|
||||
using Image large = image.Clone(x => x.Resize(new ResizeOptions
|
||||
{ Size = Constants.ImageLgSize, Mode = ResizeMode.Max }));
|
||||
large.SaveAsJpeg(Path.Join(TrangaSettings.coverImageCacheLarge, filename), new (){ Quality = 40 });
|
||||
|
||||
Directory.CreateDirectory(TrangaSettings.coverImageCacheMedium);
|
||||
using Image medium = image.Clone(x => x.Resize(new ResizeOptions
|
||||
{ Size = Constants.ImageMdSize, Mode = ResizeMode.Max }));
|
||||
medium.SaveAsJpeg(Path.Join(TrangaSettings.coverImageCacheMedium, filename), new (){ Quality = 40 });
|
||||
|
||||
Directory.CreateDirectory(TrangaSettings.coverImageCacheSmall);
|
||||
using Image small = image.Clone(x => x.Resize(new ResizeOptions
|
||||
{ Size = Constants.ImageSmSize, Mode = ResizeMode.Max }));
|
||||
small.SaveAsJpeg(Path.Join(TrangaSettings.coverImageCacheSmall, filename), new (){ Quality = 40 });
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Error(e);
|
||||
}
|
||||
|
||||
|
||||
return filename;
|
||||
}
|
||||
}
|
343
API/MangaConnectors/MangaDex.cs
Normal file
343
API/MangaConnectors/MangaDex.cs
Normal file
@@ -0,0 +1,343 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using API.MangaDownloadClients;
|
||||
using API.Schema.MangaContext;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace API.MangaConnectors;
|
||||
|
||||
public class MangaDex : MangaConnector
|
||||
{
|
||||
//https://api.mangadex.org/docs/3-enumerations/#language-codes--localization
|
||||
//https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes
|
||||
//https://gist.github.com/Josantonius/b455e315bc7f790d14b136d61d9ae469
|
||||
public MangaDex() : base("MangaDex",
|
||||
["en","pt","pt-br","it","de","ru","aa","ab","ae","af","ak","am","an","ar-ae","ar-bh","ar-dz","ar-eg","ar-iq","ar-jo","ar-kw","ar-lb","ar-ly","ar-ma","ar-om","ar-qa","ar-sa","ar-sy","ar-tn","ar-ye","ar","as","av","ay","az","ba","be","bg","bh","bi","bm","bn","bo","br","bs","ca","ce","ch","co","cr","cs","cu","cv","cy","da","de-at","de-ch","de-de","de-li","de-lu","div","dv","dz","ee","el","en-au","en-bz","en-ca","en-cb","en-gb","en-ie","en-jm","en-nz","en-ph","en-tt","en-us","en-za","en-zw","eo","es-ar","es-bo","es-cl","es-co","es-cr","es-do","es-ec","es-es","es-gt","es-hn","es-la","es-mx","es-ni","es-pa","es-pe","es-pr","es-py","es-sv","es-us","es-uy","es-ve","es","et","eu","fa","ff","fi","fj","fo","fr-be","fr-ca","fr-ch","fr-fr","fr-lu","fr-mc","fr","fy","ga","gd","gl","gn","gu","gv","ha","he","hi","ho","hr-ba","hr-hr","hr","ht","hu","hy","hz","ia","id","ie","ig","ii","ik","in","io","is","it-ch","it-it","iu","iw","ja","ja-ro","ji","jv","jw","ka","kg","ki","kj","kk","kl","km","kn","ko","ko-ro","kr","ks","ku","kv","kw","ky","kz","la","lb","lg","li","ln","lo","ls","lt","lu","lv","mg","mh","mi","mk","ml","mn","mo","mr","ms-bn","ms-my","ms","mt","my","na","nb","nd","ne","ng","nl-be","nl-nl","nl","nn","no","nr","ns","nv","ny","oc","oj","om","or","os","pa","pi","pl","ps","pt-pt","qu-bo","qu-ec","qu-pe","qu","rm","rn","ro","rw","sa","sb","sc","sd","se-fi","se-no","se-se","se","sg","sh","si","sk","sl","sm","sn","so","sq","sr-ba","sr-sp","sr","ss","st","su","sv-fi","sv-se","sv","sw","sx","syr","ta","te","tg","th","ti","tk","tl","tn","to","tr","ts","tt","tw","ty","ug","uk","ur","us","uz","ve","vi","vo","wa","wo","xh","yi","yo","za","zh-cn","zh-hk","zh-mo","zh-ro","zh-sg","zh-tw","zh","zu"],
|
||||
["mangadex.org"],
|
||||
"https://mangadex.org/favicon.ico")
|
||||
{
|
||||
this.downloadClient = new HttpDownloadClient();
|
||||
}
|
||||
|
||||
private const int Limit = 100;
|
||||
public override (Manga, MangaConnectorId<Manga>)[] SearchManga(string mangaSearchName)
|
||||
{
|
||||
Log.Info($"Searching Obj: {mangaSearchName}");
|
||||
List<(Manga, MangaConnectorId<Manga>)> mangas = new ();
|
||||
|
||||
int offset = 0;
|
||||
int total = int.MaxValue;
|
||||
while(offset < total)
|
||||
{
|
||||
string requestUrl =
|
||||
$"https://api.mangadex.org/manga?limit={Limit}&offset={offset}&title={mangaSearchName}" +
|
||||
$"&contentRating%5B%5D=safe&contentRating%5B%5D=suggestive&contentRating%5B%5D=erotica" +
|
||||
$"&includes%5B%5D=manga&includes%5B%5D=cover_art&includes%5B%5D=author&includes%5B%5D=artist&includes%5B%5D=tag'";
|
||||
offset += Limit;
|
||||
|
||||
RequestResult result = downloadClient.MakeRequest(requestUrl, RequestType.MangaDexFeed);
|
||||
if ((int)result.statusCode < 200 || (int)result.statusCode >= 300)
|
||||
{
|
||||
Log.Error("Request failed");
|
||||
return [];
|
||||
}
|
||||
|
||||
using StreamReader sr = new (result.result);
|
||||
JObject jObject = JObject.Parse(sr.ReadToEnd());
|
||||
|
||||
if (jObject.Value<string>("result") != "ok")
|
||||
{
|
||||
JArray? errors = jObject["errors"] as JArray;
|
||||
Log.Error($"Request failed: {string.Join(',', errors?.Select(e => e.Value<string>("title")) ?? [])}");
|
||||
return [];
|
||||
}
|
||||
|
||||
total = jObject.Value<int>("total");
|
||||
|
||||
JArray? data = jObject.Value<JArray>("data");
|
||||
if (data is null)
|
||||
{
|
||||
Log.Error("Data was null");
|
||||
return [];
|
||||
}
|
||||
|
||||
mangas.AddRange(data.Select(ParseMangaFromJToken));
|
||||
}
|
||||
|
||||
Log.Info($"Search {mangaSearchName} yielded {mangas.Count} results.");
|
||||
return mangas.ToArray();
|
||||
}
|
||||
|
||||
private static readonly Regex GetMangaIdFromUrl = new(@"https?:\/\/mangadex\.org\/title\/([a-z0-9-]+)\/?.*");
|
||||
public override (Manga, MangaConnectorId<Manga>)? GetMangaFromUrl(string url)
|
||||
{
|
||||
Log.Info($"Getting Obj: {url}");
|
||||
if (!UrlMatchesConnector(url))
|
||||
{
|
||||
Log.Debug($"Url is not for Connector. {url}");
|
||||
return null;
|
||||
}
|
||||
|
||||
Match match = GetMangaIdFromUrl.Match(url);
|
||||
if (!match.Success || !match.Groups[1].Success)
|
||||
{
|
||||
Log.Debug($"Url is not for Connector (Could not retrieve id). {url}");
|
||||
return null;
|
||||
}
|
||||
string id = match.Groups[1].Value;
|
||||
|
||||
return GetMangaFromId(id);
|
||||
}
|
||||
|
||||
public override (Manga, MangaConnectorId<Manga>)? GetMangaFromId(string mangaIdOnSite)
|
||||
{
|
||||
Log.Info($"Getting Obj: {mangaIdOnSite}");
|
||||
string requestUrl =
|
||||
$"https://api.mangadex.org/manga/{mangaIdOnSite}" +
|
||||
$"?includes%5B%5D=manga&includes%5B%5D=cover_art&includes%5B%5D=author&includes%5B%5D=artist&includes%5B%5D=tag'";
|
||||
|
||||
RequestResult result = downloadClient.MakeRequest(requestUrl, RequestType.MangaDexFeed);
|
||||
if ((int)result.statusCode < 200 || (int)result.statusCode >= 300)
|
||||
{
|
||||
Log.Error("Request failed");
|
||||
return null;
|
||||
}
|
||||
|
||||
using StreamReader sr = new (result.result);
|
||||
JObject jObject = JObject.Parse(sr.ReadToEnd());
|
||||
|
||||
if (jObject.Value<string>("result") != "ok")
|
||||
{
|
||||
JArray? errors = jObject["errors"] as JArray;
|
||||
Log.Error($"Request failed: {string.Join(',', errors?.Select(e => e.Value<string>("title")) ?? [])}");
|
||||
return null;
|
||||
}
|
||||
|
||||
JObject? data = jObject["data"] as JObject;
|
||||
if (data is null)
|
||||
{
|
||||
Log.Error("Data was null");
|
||||
return null;
|
||||
}
|
||||
|
||||
return ParseMangaFromJToken(data);
|
||||
}
|
||||
|
||||
public override (Chapter, MangaConnectorId<Chapter>)[] GetChapters(MangaConnectorId<Manga> manga, string? language = null)
|
||||
{
|
||||
Log.Info($"Getting Chapters: {manga.IdOnConnectorSite}");
|
||||
List<(Chapter, MangaConnectorId<Chapter>)> chapters = new ();
|
||||
|
||||
int offset = 0;
|
||||
int total = int.MaxValue;
|
||||
while(offset < total)
|
||||
{
|
||||
string requestUrl =
|
||||
$"https://api.mangadex.org/manga/{manga.IdOnConnectorSite}/feed?limit={Limit}&offset={offset}&" +
|
||||
$"translatedLanguage%5B%5D={language}&" +
|
||||
$"contentRating%5B%5D=safe&contentRating%5B%5D=suggestive&contentRating%5B%5D=erotica&includeFutureUpdates=0&includes%5B%5D=";
|
||||
offset += Limit;
|
||||
|
||||
RequestResult result = downloadClient.MakeRequest(requestUrl, RequestType.MangaDexFeed);
|
||||
if ((int)result.statusCode < 200 || (int)result.statusCode >= 300)
|
||||
{
|
||||
Log.Error("Request failed");
|
||||
return [];
|
||||
}
|
||||
|
||||
using StreamReader sr = new (result.result);
|
||||
JObject jObject = JObject.Parse(sr.ReadToEnd());
|
||||
|
||||
if (jObject.Value<string>("result") != "ok")
|
||||
{
|
||||
JArray? errors = jObject["errors"] as JArray;
|
||||
Log.Error($"Request failed: {string.Join(',', errors?.Select(e => e.Value<string>("title")) ?? [])}");
|
||||
return [];
|
||||
}
|
||||
|
||||
total = jObject.Value<int>("total");
|
||||
|
||||
JArray? data = jObject.Value<JArray>("data");
|
||||
if (data is null)
|
||||
{
|
||||
Log.Error("Data was null");
|
||||
return [];
|
||||
}
|
||||
|
||||
chapters.AddRange(data.Select(d => ParseChapterFromJToken(manga, d)));
|
||||
}
|
||||
|
||||
Log.Info($"Request for chapters for {manga.Obj.Name} yielded {chapters.Count} results.");
|
||||
return chapters.ToArray();
|
||||
}
|
||||
|
||||
private static readonly Regex GetChapterIdFromUrl = new(@"https?:\/\/mangadex\.org\/chapter\/([a-z0-9-]+)\/?.*");
|
||||
internal override string[] GetChapterImageUrls(MangaConnectorId<Chapter> chapterId)
|
||||
{
|
||||
Log.Info($"Getting Chapter Image-Urls: {chapterId.Obj}");
|
||||
if (chapterId.WebsiteUrl is null || !UrlMatchesConnector(chapterId.WebsiteUrl))
|
||||
{
|
||||
Log.Debug($"Url is not for Connector. {chapterId.WebsiteUrl}");
|
||||
return [];
|
||||
}
|
||||
|
||||
Match match = GetChapterIdFromUrl.Match(chapterId.WebsiteUrl);
|
||||
if (!match.Success || !match.Groups[1].Success)
|
||||
{
|
||||
Log.Debug($"Url is not for Connector (Could not retrieve id). {chapterId.WebsiteUrl}");
|
||||
return [];
|
||||
}
|
||||
|
||||
string id = match.Groups[1].Value;
|
||||
string requestUrl = $"https://api.mangadex.org/at-home/server/{id}";
|
||||
|
||||
RequestResult result = downloadClient.MakeRequest(requestUrl, RequestType.Default);
|
||||
if ((int)result.statusCode < 200 || (int)result.statusCode >= 300)
|
||||
{
|
||||
Log.Error("Request failed");
|
||||
return [];
|
||||
}
|
||||
|
||||
using StreamReader sr = new (result.result);
|
||||
JObject jObject = JObject.Parse(sr.ReadToEnd());
|
||||
|
||||
if (jObject.Value<string>("result") != "ok")
|
||||
{
|
||||
JArray? errors = jObject["errors"] as JArray;
|
||||
Log.Error($"Request failed: {string.Join(',', errors?.Select(e => e.Value<string>("title")) ?? [])}");
|
||||
return [];
|
||||
}
|
||||
|
||||
string? baseUrl = jObject.Value<string>("baseUrl");
|
||||
JToken? chapterToken = jObject["chapter"];
|
||||
string? hash = chapterToken?.Value<string>("hash");
|
||||
JArray? data = chapterToken?["data"] as JArray;
|
||||
|
||||
if (baseUrl is null || hash is null || data is null)
|
||||
{
|
||||
Log.Error("Data was null");
|
||||
return [];
|
||||
}
|
||||
|
||||
IEnumerable<string> urls = data.Select(t => $"{baseUrl}/data/{hash}/{t.Value<string>()}");
|
||||
|
||||
return urls.ToArray();
|
||||
}
|
||||
|
||||
private (Manga manga, MangaConnectorId<Manga> id) ParseMangaFromJToken(JToken jToken)
|
||||
{
|
||||
string? id = jToken.Value<string>("id");
|
||||
if(id is null)
|
||||
throw new Exception("jToken was not in expected format");
|
||||
|
||||
JObject? attributes = jToken["attributes"] as JObject;
|
||||
if(attributes is null)
|
||||
throw new Exception("jToken was not in expected format");
|
||||
string? name = attributes["title"]?.Value<string>("en") ?? attributes["title"]?.First?.First?.Value<string>();
|
||||
string description = attributes["description"]?.Value<string>("en")??attributes["description"]?.First?.First?.Value<string>()??"";
|
||||
string? status = attributes["status"]?.Value<string>();
|
||||
uint? year = attributes["year"]?.Value<uint?>();
|
||||
string? originalLanguage = attributes["originalLanguage"]?.Value<string>();
|
||||
JArray? altTitlesJArray = attributes.TryGetValue("altTitles", out JToken? altTitlesArray) ? altTitlesArray as JArray : null;
|
||||
JArray? tagsJArray = attributes.TryGetValue("tags", out JToken? tagsArray) ? tagsArray as JArray : null;
|
||||
JArray? relationships = jToken["relationships"] as JArray;
|
||||
if (name is null || status is null || relationships is null)
|
||||
throw new Exception("jToken was not in expected format");
|
||||
|
||||
string? coverFileName = relationships.FirstOrDefault(r => r["type"]?.Value<string>() == "cover_art")?["attributes"]?.Value<string>("fileName");
|
||||
if(coverFileName is null)
|
||||
throw new Exception("jToken was not in expected format");
|
||||
|
||||
List<Link> links = attributes["links"]?
|
||||
.ToObject<Dictionary<string,string>>()?
|
||||
.Select(kv =>
|
||||
{
|
||||
//https://api.mangadex.org/docs/3-enumerations/#manga-links-data
|
||||
string url = kv.Key switch
|
||||
{
|
||||
"al" => $"https://anilist.co/manga/{kv.Value}",
|
||||
"ap" => $"https://www.anime-planet.com/manga/{kv.Value}",
|
||||
"bw" => $"https://bookwalker.jp/{kv.Value}",
|
||||
"mu" => $"https://www.mangaupdates.com/series.html?id={kv.Value}",
|
||||
"nu" => $"https://www.novelupdates.com/series/{kv.Value}",
|
||||
"mal" => $"https://myanimelist.net/manga/{kv.Value}",
|
||||
_ => kv.Value
|
||||
};
|
||||
string key = kv.Key switch
|
||||
{
|
||||
"al" => "AniList",
|
||||
"ap" => "Anime Planet",
|
||||
"bw" => "BookWalker",
|
||||
"mu" => "Obj Updates",
|
||||
"nu" => "Novel Updates",
|
||||
"kt" => "Kitsu.io",
|
||||
"amz" => "Amazon",
|
||||
"ebj" => "eBookJapan",
|
||||
"mal" => "MyAnimeList",
|
||||
"cdj" => "CDJapan",
|
||||
_ => kv.Key
|
||||
};
|
||||
return new Link(key, url);
|
||||
}).ToList()??[];
|
||||
|
||||
List<AltTitle> altTitles = altTitlesJArray?
|
||||
.Select(t =>
|
||||
{
|
||||
JObject? j = t as JObject;
|
||||
JProperty? p = j?.Properties().First();
|
||||
if (p is null)
|
||||
return null;
|
||||
return new AltTitle(p.Name, p.Value.ToString());
|
||||
}).Where(x => x is not null).Cast<AltTitle>().ToList()??[];
|
||||
|
||||
List<MangaTag> tags = tagsJArray?
|
||||
.Where(t => t.Value<string>("type") == "tag")
|
||||
.Select(t => t["attributes"]?["name"]?.Value<string>("en")??t["attributes"]?["name"]?.First?.First?.Value<string>())
|
||||
.Select(str => str is not null ? new MangaTag(str) : null)
|
||||
.Where(x => x is not null).Cast<MangaTag>().ToList()??[];
|
||||
|
||||
List<Author> authors = relationships
|
||||
.Where(r => r["type"]?.Value<string>() == "author")
|
||||
.Select(t => t["attributes"]?.Value<string>("name"))
|
||||
.Select(str => str is not null ? new Author(str) : null)
|
||||
.Where(x => x is not null).Cast<Author>().ToList();
|
||||
|
||||
|
||||
MangaReleaseStatus releaseStatus = status switch
|
||||
{
|
||||
"completed" => MangaReleaseStatus.Completed,
|
||||
"ongoing" => MangaReleaseStatus.Continuing,
|
||||
"cancelled" => MangaReleaseStatus.Cancelled,
|
||||
"hiatus" => MangaReleaseStatus.OnHiatus,
|
||||
_ => MangaReleaseStatus.Unreleased
|
||||
};
|
||||
string websiteUrl = $"https://mangadex.org/title/{id}";
|
||||
string coverUrl = $"https://uploads.mangadex.org/covers/{id}/{coverFileName}";
|
||||
|
||||
Manga manga = new (name, description, coverUrl, releaseStatus, authors, tags, links,altTitles,
|
||||
null, 0f, year, originalLanguage);
|
||||
MangaConnectorId<Manga> mcId = new (manga, this, id, websiteUrl);
|
||||
manga.MangaConnectorIds.Add(mcId);
|
||||
return (manga, mcId);
|
||||
}
|
||||
|
||||
private (Chapter chapter, MangaConnectorId<Chapter> id) ParseChapterFromJToken(MangaConnectorId<Manga> mcIdManga, JToken jToken)
|
||||
{
|
||||
string? id = jToken.Value<string>("id");
|
||||
JToken? attributes = jToken["attributes"];
|
||||
string? chapterStr = attributes?.Value<string>("chapter");
|
||||
string? volumeStr = attributes?.Value<string>("volume");
|
||||
int? volumeNumber = null;
|
||||
string? title = attributes?.Value<string>("title");
|
||||
|
||||
if(id is null || chapterStr is null)
|
||||
throw new Exception("jToken was not in expected format");
|
||||
if(volumeStr is not null)
|
||||
volumeNumber = int.Parse(volumeStr);
|
||||
|
||||
string websiteUrl = $"https://mangadex.org/chapter/{id}";
|
||||
Chapter chapter = new (mcIdManga.Obj, chapterStr, volumeNumber, title);
|
||||
MangaConnectorId<Chapter> mcId = new(chapter, this, id, websiteUrl);
|
||||
chapter.MangaConnectorIds.Add(mcId);
|
||||
return (chapter, mcId);
|
||||
}
|
||||
}
|
53
API/MangaDownloadClients/DownloadClient.cs
Normal file
53
API/MangaDownloadClients/DownloadClient.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using log4net;
|
||||
|
||||
namespace API.MangaDownloadClients;
|
||||
|
||||
public abstract class DownloadClient
|
||||
{
|
||||
private static readonly ConcurrentDictionary<RequestType, DateTime> LastExecutedRateLimit = new();
|
||||
protected ILog Log { get; init; }
|
||||
|
||||
protected DownloadClient()
|
||||
{
|
||||
this.Log = LogManager.GetLogger(GetType());
|
||||
}
|
||||
|
||||
// TODO Requests still go too fast across threads!
|
||||
public RequestResult MakeRequest(string url, RequestType requestType, string? referrer = null, string? clickButton = null)
|
||||
{
|
||||
Log.Debug($"Requesting {requestType} {url}");
|
||||
|
||||
// If we don't have a RequestLimit set for a Type, use the default one
|
||||
if (!Tranga.Settings.RequestLimits.ContainsKey(requestType))
|
||||
requestType = RequestType.Default;
|
||||
|
||||
int rateLimit = Tranga.Settings.RequestLimits[requestType];
|
||||
// TODO this probably needs a better check whether the useragent matches...
|
||||
// If the UserAgent is the default one, do not exceed the default request-limits.
|
||||
if (Tranga.Settings.UserAgent == TrangaSettings.DefaultUserAgent && rateLimit > TrangaSettings.DefaultRequestLimits[requestType])
|
||||
rateLimit = TrangaSettings.DefaultRequestLimits[requestType];
|
||||
|
||||
// Apply the delay
|
||||
TimeSpan timeBetweenRequests = TimeSpan.FromMinutes(1).Divide(rateLimit);
|
||||
DateTime now = DateTime.Now;
|
||||
LastExecutedRateLimit.TryAdd(requestType, now.Subtract(timeBetweenRequests));
|
||||
|
||||
TimeSpan rateLimitTimeout = timeBetweenRequests.Subtract(now.Subtract(LastExecutedRateLimit[requestType]));
|
||||
Log.Debug($"Request limit {requestType} {rateLimit}/Minute timeBetweenRequests: {timeBetweenRequests:ss'.'fffff} Timeout: {rateLimitTimeout:ss'.'fffff}");
|
||||
|
||||
if (rateLimitTimeout > TimeSpan.Zero)
|
||||
Thread.Sleep(rateLimitTimeout);
|
||||
|
||||
// Make the request
|
||||
RequestResult result = MakeRequestInternal(url, referrer, clickButton);
|
||||
|
||||
// Update the time the last request was made
|
||||
LastExecutedRateLimit[requestType] = DateTime.UtcNow;
|
||||
Log.Debug($"Result {url}: {result}");
|
||||
return result;
|
||||
}
|
||||
|
||||
internal abstract RequestResult MakeRequestInternal(string url, string? referrer = null, string? clickButton = null);
|
||||
}
|
178
API/MangaDownloadClients/FlareSolverrDownloadClient.cs
Normal file
178
API/MangaDownloadClients/FlareSolverrDownloadClient.cs
Normal file
@@ -0,0 +1,178 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using HtmlAgilityPack;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace API.MangaDownloadClients;
|
||||
|
||||
public class FlareSolverrDownloadClient : DownloadClient
|
||||
{
|
||||
internal override RequestResult MakeRequestInternal(string url, string? referrer = null, string? clickButton = null)
|
||||
{
|
||||
if (clickButton is not null)
|
||||
Log.Warn("Client can not click button");
|
||||
if(referrer is not null)
|
||||
Log.Warn("Client can not set referrer");
|
||||
if (Tranga.Settings.FlareSolverrUrl == string.Empty)
|
||||
{
|
||||
Log.Error("FlareSolverr URL is empty");
|
||||
return new(HttpStatusCode.InternalServerError, null, Stream.Null);
|
||||
}
|
||||
|
||||
Uri flareSolverrUri = new (Tranga.Settings.FlareSolverrUrl);
|
||||
if (flareSolverrUri.Segments.Last() != "v1")
|
||||
flareSolverrUri = new UriBuilder(flareSolverrUri)
|
||||
{
|
||||
Path = "v1"
|
||||
}.Uri;
|
||||
|
||||
HttpClient client = new()
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(10),
|
||||
DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher,
|
||||
DefaultRequestHeaders = { { "User-Agent", Tranga.Settings.UserAgent } }
|
||||
};
|
||||
|
||||
JObject requestObj = new()
|
||||
{
|
||||
["cmd"] = "request.get",
|
||||
["url"] = url
|
||||
};
|
||||
|
||||
HttpRequestMessage requestMessage = new(HttpMethod.Post, flareSolverrUri)
|
||||
{
|
||||
Content = new StringContent(JsonConvert.SerializeObject(requestObj)),
|
||||
};
|
||||
requestMessage.Content.Headers.ContentType = new ("application/json");
|
||||
Log.Debug($"Requesting {url}");
|
||||
|
||||
HttpResponseMessage? response;
|
||||
try
|
||||
{
|
||||
response = client.Send(requestMessage);
|
||||
}
|
||||
catch (HttpRequestException e)
|
||||
{
|
||||
Log.Error(e);
|
||||
return new (HttpStatusCode.Unused, null, Stream.Null);
|
||||
}
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
Log.Debug($"Request returned status code {(int)response.StatusCode} {response.StatusCode}:\n" +
|
||||
$"=====\n" +
|
||||
$"Request:\n" +
|
||||
$"{requestMessage.Method} {requestMessage.RequestUri}\n" +
|
||||
$"{requestMessage.Version} {requestMessage.VersionPolicy}\n" +
|
||||
$"Headers:\n\t{string.Join("\n\t", requestMessage.Headers.Select(h => $"{h.Key}: <{string.Join(">, <", h.Value)}"))}>\n" +
|
||||
$"{requestMessage.Content?.ReadAsStringAsync().Result}" +
|
||||
$"=====\n" +
|
||||
$"Response:\n" +
|
||||
$"{response.Version}\n" +
|
||||
$"Headers:\n\t{string.Join("\n\t", response.Headers.Select(h => $"{h.Key}: <{string.Join(">, <", h.Value)}"))}>\n" +
|
||||
$"{response.Content.ReadAsStringAsync().Result}");
|
||||
return new (response.StatusCode, null, Stream.Null);
|
||||
}
|
||||
|
||||
string responseString = response.Content.ReadAsStringAsync().Result;
|
||||
JObject responseObj = JObject.Parse(responseString);
|
||||
if (!IsInCorrectFormat(responseObj, out string? reason))
|
||||
{
|
||||
Log.Error($"Wrong format: {reason}");
|
||||
return new(HttpStatusCode.Unused, null, Stream.Null);
|
||||
}
|
||||
|
||||
string statusResponse = responseObj["status"]!.Value<string>()!;
|
||||
if (statusResponse != "ok")
|
||||
{
|
||||
Log.Debug($"Status is not ok: {statusResponse}");
|
||||
return new(HttpStatusCode.Unused, null, Stream.Null);
|
||||
}
|
||||
JObject solution = (responseObj["solution"] as JObject)!;
|
||||
|
||||
if (!Enum.TryParse(solution["status"]!.Value<int>().ToString(), out HttpStatusCode statusCode))
|
||||
{
|
||||
Log.Error($"Wrong format: Cant parse status code: {solution["status"]!.Value<int>()}");
|
||||
return new(HttpStatusCode.Unused, null, Stream.Null);
|
||||
}
|
||||
if (statusCode < HttpStatusCode.OK || statusCode >= HttpStatusCode.MultipleChoices)
|
||||
{
|
||||
Log.Debug($"Status is: {statusCode}");
|
||||
return new(statusCode, null, Stream.Null);
|
||||
}
|
||||
|
||||
if (solution["response"]!.Value<string>() is not { } htmlString)
|
||||
{
|
||||
Log.Error("Wrong format: Cant find response in solution");
|
||||
return new(HttpStatusCode.Unused, null, Stream.Null);
|
||||
}
|
||||
|
||||
if (IsJson(htmlString, out HtmlDocument document, out string? json))
|
||||
{
|
||||
MemoryStream ms = new();
|
||||
ms.Write(Encoding.UTF8.GetBytes(json));
|
||||
ms.Position = 0;
|
||||
return new(statusCode, document, ms);
|
||||
}
|
||||
else
|
||||
{
|
||||
MemoryStream ms = new();
|
||||
ms.Write(Encoding.UTF8.GetBytes(htmlString));
|
||||
ms.Position = 0;
|
||||
return new(statusCode, document, ms);
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsInCorrectFormat(JObject responseObj, [NotNullWhen(false)]out string? reason)
|
||||
{
|
||||
reason = null;
|
||||
if (!responseObj.ContainsKey("status"))
|
||||
{
|
||||
reason = "Cant find status on response";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (responseObj["solution"] is not JObject solution)
|
||||
{
|
||||
reason = "Cant find solution";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!solution.ContainsKey("status"))
|
||||
{
|
||||
reason = "Wrong format: Cant find status in solution";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!solution.ContainsKey("response"))
|
||||
{
|
||||
|
||||
reason = "Wrong format: Cant find response in solution";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool IsJson(string htmlString, out HtmlDocument document, [NotNullWhen(true)]out string? jsonString)
|
||||
{
|
||||
jsonString = null;
|
||||
document = new();
|
||||
document.LoadHtml(htmlString);
|
||||
|
||||
HtmlNode pre = document.DocumentNode.SelectSingleNode("//pre");
|
||||
try
|
||||
{
|
||||
using JsonDocument _ = JsonDocument.Parse(pre.InnerText);
|
||||
jsonString = pre.InnerText;
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
88
API/MangaDownloadClients/HttpDownloadClient.cs
Normal file
88
API/MangaDownloadClients/HttpDownloadClient.cs
Normal file
@@ -0,0 +1,88 @@
|
||||
using System.Net;
|
||||
using HtmlAgilityPack;
|
||||
|
||||
namespace API.MangaDownloadClients;
|
||||
|
||||
internal class HttpDownloadClient : DownloadClient
|
||||
{
|
||||
private static readonly FlareSolverrDownloadClient FlareSolverrDownloadClient = new();
|
||||
internal override RequestResult MakeRequestInternal(string url, string? referrer = null, string? clickButton = null)
|
||||
{
|
||||
if (clickButton is not null)
|
||||
Log.Warn("Client can not click button");
|
||||
HttpClient client = new();
|
||||
client.Timeout = TimeSpan.FromSeconds(10);
|
||||
client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher;
|
||||
client.DefaultRequestHeaders.Add("User-Agent", Tranga.Settings.UserAgent);
|
||||
HttpResponseMessage? response;
|
||||
Uri uri = new(url);
|
||||
HttpRequestMessage requestMessage = new(HttpMethod.Get, uri);
|
||||
if (referrer is not null)
|
||||
requestMessage.Headers.Referrer = new (referrer);
|
||||
Log.Debug($"Requesting {url}");
|
||||
try
|
||||
{
|
||||
response = client.Send(requestMessage);
|
||||
}
|
||||
catch (HttpRequestException e)
|
||||
{
|
||||
Log.Error(e);
|
||||
return new (HttpStatusCode.Unused, null, Stream.Null);
|
||||
}
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
Log.Debug($"Request returned status code {(int)response.StatusCode} {response.StatusCode}");
|
||||
if (response.Headers.Server.Any(s =>
|
||||
(s.Product?.Name ?? "").Contains("cloudflare", StringComparison.InvariantCultureIgnoreCase)))
|
||||
{
|
||||
Log.Debug("Retrying with FlareSolverr!");
|
||||
return FlareSolverrDownloadClient.MakeRequestInternal(url, referrer, clickButton);
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.Debug($"Request returned status code {(int)response.StatusCode} {response.StatusCode}:\n" +
|
||||
$"=====\n" +
|
||||
$"Request:\n" +
|
||||
$"{requestMessage.Method} {requestMessage.RequestUri}\n" +
|
||||
$"{requestMessage.Version} {requestMessage.VersionPolicy}\n" +
|
||||
$"Headers:\n\t{string.Join("\n\t", requestMessage.Headers.Select(h => $"{h.Key}: <{string.Join(">, <", h.Value)}"))}>\n" +
|
||||
$"{requestMessage.Content?.ReadAsStringAsync().Result}" +
|
||||
$"=====\n" +
|
||||
$"Response:\n" +
|
||||
$"{response.Version}\n" +
|
||||
$"Headers:\n\t{string.Join("\n\t", response.Headers.Select(h => $"{h.Key}: <{string.Join(">, <", h.Value)}"))}>\n" +
|
||||
$"{response.Content.ReadAsStringAsync().Result}");
|
||||
}
|
||||
}
|
||||
|
||||
Stream stream;
|
||||
try
|
||||
{
|
||||
stream = response.Content.ReadAsStream();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Error(e);
|
||||
return new (HttpStatusCode.Unused, null, Stream.Null);
|
||||
}
|
||||
|
||||
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 && response.RequestMessage.RequestUri != uri)
|
||||
{
|
||||
return new (response.StatusCode, document, stream, true, response.RequestMessage.RequestUri.AbsoluteUri);
|
||||
}
|
||||
|
||||
return new (response.StatusCode, document, stream);
|
||||
}
|
||||
}
|
@@ -1,7 +1,7 @@
|
||||
using System.Net;
|
||||
using HtmlAgilityPack;
|
||||
|
||||
namespace Tranga.MangaConnectors;
|
||||
namespace API.MangaDownloadClients;
|
||||
|
||||
public struct RequestResult
|
||||
{
|
||||
@@ -24,4 +24,10 @@ public struct RequestResult
|
||||
this.hasBeenRedirected = hasBeenRedirected;
|
||||
redirectedToUrl = redirectedTo;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return
|
||||
$"{(int)statusCode} {statusCode.ToString()} {(hasBeenRedirected ? "Redirected: " : "")} {redirectedToUrl}";
|
||||
}
|
||||
}
|
@@ -1,4 +1,4 @@
|
||||
namespace Tranga.MangaConnectors;
|
||||
namespace API.MangaDownloadClients;
|
||||
|
||||
public enum RequestType : byte
|
||||
{
|
70
API/Migrations/Library/20250703191925_Initial.Designer.cs
generated
Normal file
70
API/Migrations/Library/20250703191925_Initial.Designer.cs
generated
Normal file
@@ -0,0 +1,70 @@
|
||||
// <auto-generated />
|
||||
using API.Schema.LibraryContext;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Library
|
||||
{
|
||||
[DbContext(typeof(LibraryContext))]
|
||||
[Migration("20250703191925_Initial")]
|
||||
partial class Initial
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.5")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("API.Schema.LibraryContext.LibraryConnectors.LibraryConnector", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Auth")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("BaseUrl")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<byte>("LibraryType")
|
||||
.HasColumnType("smallint");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("LibraryConnectors");
|
||||
|
||||
b.HasDiscriminator<byte>("LibraryType");
|
||||
|
||||
b.UseTphMappingStrategy();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.LibraryContext.LibraryConnectors.Kavita", b =>
|
||||
{
|
||||
b.HasBaseType("API.Schema.LibraryContext.LibraryConnectors.LibraryConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue((byte)1);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.LibraryContext.LibraryConnectors.Komga", b =>
|
||||
{
|
||||
b.HasBaseType("API.Schema.LibraryContext.LibraryConnectors.LibraryConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue((byte)0);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
35
API/Migrations/Library/20250703191925_Initial.cs
Normal file
35
API/Migrations/Library/20250703191925_Initial.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Library
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class Initial : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "LibraryConnectors",
|
||||
columns: table => new
|
||||
{
|
||||
Key = table.Column<string>(type: "text", nullable: false),
|
||||
LibraryType = table.Column<byte>(type: "smallint", nullable: false),
|
||||
BaseUrl = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
|
||||
Auth = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_LibraryConnectors", x => x.Key);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "LibraryConnectors");
|
||||
}
|
||||
}
|
||||
}
|
71
API/Migrations/Library/20250901194308_KeyLengthChange.Designer.cs
generated
Normal file
71
API/Migrations/Library/20250901194308_KeyLengthChange.Designer.cs
generated
Normal file
@@ -0,0 +1,71 @@
|
||||
// <auto-generated />
|
||||
using API.Schema.LibraryContext;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Library
|
||||
{
|
||||
[DbContext(typeof(LibraryContext))]
|
||||
[Migration("20250901194308_KeyLengthChange")]
|
||||
partial class KeyLengthChange
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("API.Schema.LibraryContext.LibraryConnectors.LibraryConnector", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("Auth")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("BaseUrl")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<byte>("LibraryType")
|
||||
.HasColumnType("smallint");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("LibraryConnectors");
|
||||
|
||||
b.HasDiscriminator<byte>("LibraryType");
|
||||
|
||||
b.UseTphMappingStrategy();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.LibraryContext.LibraryConnectors.Kavita", b =>
|
||||
{
|
||||
b.HasBaseType("API.Schema.LibraryContext.LibraryConnectors.LibraryConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue((byte)1);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.LibraryContext.LibraryConnectors.Komga", b =>
|
||||
{
|
||||
b.HasBaseType("API.Schema.LibraryContext.LibraryConnectors.LibraryConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue((byte)0);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
36
API/Migrations/Library/20250901194308_KeyLengthChange.cs
Normal file
36
API/Migrations/Library/20250901194308_KeyLengthChange.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Library
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class KeyLengthChange : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "LibraryConnectors",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "LibraryConnectors",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)",
|
||||
oldMaxLength: 64);
|
||||
}
|
||||
}
|
||||
}
|
68
API/Migrations/Library/LibraryContextModelSnapshot.cs
Normal file
68
API/Migrations/Library/LibraryContextModelSnapshot.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
// <auto-generated />
|
||||
using API.Schema.LibraryContext;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Library
|
||||
{
|
||||
[DbContext(typeof(LibraryContext))]
|
||||
partial class LibraryContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("API.Schema.LibraryContext.LibraryConnectors.LibraryConnector", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("Auth")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("BaseUrl")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<byte>("LibraryType")
|
||||
.HasColumnType("smallint");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("LibraryConnectors");
|
||||
|
||||
b.HasDiscriminator<byte>("LibraryType");
|
||||
|
||||
b.UseTphMappingStrategy();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.LibraryContext.LibraryConnectors.Kavita", b =>
|
||||
{
|
||||
b.HasBaseType("API.Schema.LibraryContext.LibraryConnectors.LibraryConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue((byte)1);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.LibraryContext.LibraryConnectors.Komga", b =>
|
||||
{
|
||||
b.HasBaseType("API.Schema.LibraryContext.LibraryConnectors.LibraryConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue((byte)0);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
527
API/Migrations/Manga/20250722203315_Initial.Designer.cs
generated
Normal file
527
API/Migrations/Manga/20250722203315_Initial.Designer.cs
generated
Normal file
@@ -0,0 +1,527 @@
|
||||
// <auto-generated />
|
||||
using API.Schema.MangaContext;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Manga
|
||||
{
|
||||
[DbContext(typeof(MangaContext))]
|
||||
[Migration("20250722203315_Initial")]
|
||||
partial class Initial
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.5")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("API.MangaConnectors.MangaConnector", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.PrimitiveCollection<string[]>("BaseUris")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("text[]");
|
||||
|
||||
b.Property<bool>("Enabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("IconUrl")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("character varying(2048)");
|
||||
|
||||
b.PrimitiveCollection<string[]>("SupportedLanguages")
|
||||
.IsRequired()
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("text[]");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("MangaConnector");
|
||||
|
||||
b.HasDiscriminator<string>("Name").HasValue("MangaConnector");
|
||||
|
||||
b.UseTphMappingStrategy();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Author", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("AuthorName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("Authors");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Chapter", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("ChapterNumber")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)");
|
||||
|
||||
b.Property<bool>("Downloaded")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("FileName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("ParentMangaId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<int?>("VolumeNumber")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.HasIndex("ParentMangaId");
|
||||
|
||||
b.ToTable("Chapters");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.FileLibrary", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("BasePath")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("LibraryName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("FileLibraries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Manga", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("CoverFileNameInCache")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("CoverUrl")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("DirectoryName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(1024)
|
||||
.HasColumnType("character varying(1024)");
|
||||
|
||||
b.Property<float>("IgnoreChaptersBefore")
|
||||
.HasColumnType("real");
|
||||
|
||||
b.Property<string>("LibraryId")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("OriginalLanguage")
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b.Property<byte>("ReleaseStatus")
|
||||
.HasColumnType("smallint");
|
||||
|
||||
b.Property<long?>("Year")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.HasIndex("LibraryId");
|
||||
|
||||
b.ToTable("Mangas");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaConnectorId<API.Schema.MangaContext.Chapter>", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("IdOnConnectorSite")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("MangaConnectorName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.Property<string>("ObjId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<bool>("UseForDownload")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("WebsiteUrl")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.HasIndex("ObjId");
|
||||
|
||||
b.ToTable("MangaConnectorToChapter");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaConnectorId<API.Schema.MangaContext.Manga>", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("IdOnConnectorSite")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("MangaConnectorName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.Property<string>("ObjId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<bool>("UseForDownload")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("WebsiteUrl")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.HasIndex("ObjId");
|
||||
|
||||
b.ToTable("MangaConnectorToManga");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaTag", b =>
|
||||
{
|
||||
b.Property<string>("Tag")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.HasKey("Tag");
|
||||
|
||||
b.ToTable("Tags");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MetadataFetchers.MetadataEntry", b =>
|
||||
{
|
||||
b.Property<string>("MetadataFetcherName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Identifier")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("MangaId")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("MetadataFetcherName", "Identifier");
|
||||
|
||||
b.HasIndex("MangaId");
|
||||
|
||||
b.ToTable("MetadataEntries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MetadataFetchers.MetadataFetcher", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("MetadataEntry")
|
||||
.IsRequired()
|
||||
.HasMaxLength(21)
|
||||
.HasColumnType("character varying(21)");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("MetadataFetcher");
|
||||
|
||||
b.HasDiscriminator<string>("MetadataEntry").HasValue("MetadataFetcher");
|
||||
|
||||
b.UseTphMappingStrategy();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("AuthorToManga", b =>
|
||||
{
|
||||
b.Property<string>("AuthorIds")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("MangaIds")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("AuthorIds", "MangaIds");
|
||||
|
||||
b.HasIndex("MangaIds");
|
||||
|
||||
b.ToTable("AuthorToManga");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MangaTagToManga", b =>
|
||||
{
|
||||
b.Property<string>("MangaTagIds")
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("MangaIds")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.HasKey("MangaTagIds", "MangaIds");
|
||||
|
||||
b.HasIndex("MangaIds");
|
||||
|
||||
b.ToTable("MangaTagToManga");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.MangaConnectors.ComickIo", b =>
|
||||
{
|
||||
b.HasBaseType("API.MangaConnectors.MangaConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue("ComickIo");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.MangaConnectors.Global", b =>
|
||||
{
|
||||
b.HasBaseType("API.MangaConnectors.MangaConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue("Global");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.MangaConnectors.MangaDex", b =>
|
||||
{
|
||||
b.HasBaseType("API.MangaConnectors.MangaConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue("MangaDex");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MetadataFetchers.MyAnimeList", b =>
|
||||
{
|
||||
b.HasBaseType("API.Schema.MangaContext.MetadataFetchers.MetadataFetcher");
|
||||
|
||||
b.HasDiscriminator().HasValue("MyAnimeList");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Chapter", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Manga", "ParentManga")
|
||||
.WithMany("Chapters")
|
||||
.HasForeignKey("ParentMangaId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("ParentManga");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Manga", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.FileLibrary", "Library")
|
||||
.WithMany()
|
||||
.HasForeignKey("LibraryId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.OwnsMany("API.Schema.MangaContext.AltTitle", "AltTitles", b1 =>
|
||||
{
|
||||
b1.Property<string>("Key")
|
||||
.HasColumnType("text");
|
||||
|
||||
b1.Property<string>("Language")
|
||||
.IsRequired()
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b1.Property<string>("MangaKey")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b1.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b1.HasKey("Key");
|
||||
|
||||
b1.HasIndex("MangaKey");
|
||||
|
||||
b1.ToTable("AltTitle");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("MangaKey");
|
||||
});
|
||||
|
||||
b.OwnsMany("API.Schema.MangaContext.Link", "Links", b1 =>
|
||||
{
|
||||
b1.Property<string>("Key")
|
||||
.HasColumnType("text");
|
||||
|
||||
b1.Property<string>("LinkProvider")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b1.Property<string>("LinkUrl")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("character varying(2048)");
|
||||
|
||||
b1.Property<string>("MangaKey")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b1.HasKey("Key");
|
||||
|
||||
b1.HasIndex("MangaKey");
|
||||
|
||||
b1.ToTable("Link");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("MangaKey");
|
||||
});
|
||||
|
||||
b.Navigation("AltTitles");
|
||||
|
||||
b.Navigation("Library");
|
||||
|
||||
b.Navigation("Links");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaConnectorId<API.Schema.MangaContext.Chapter>", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Chapter", "Obj")
|
||||
.WithMany("MangaConnectorIds")
|
||||
.HasForeignKey("ObjId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Obj");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaConnectorId<API.Schema.MangaContext.Manga>", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Manga", "Obj")
|
||||
.WithMany("MangaConnectorIds")
|
||||
.HasForeignKey("ObjId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Obj");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MetadataFetchers.MetadataEntry", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Manga", "Manga")
|
||||
.WithMany()
|
||||
.HasForeignKey("MangaId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("API.Schema.MangaContext.MetadataFetchers.MetadataFetcher", "MetadataFetcher")
|
||||
.WithMany()
|
||||
.HasForeignKey("MetadataFetcherName")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Manga");
|
||||
|
||||
b.Navigation("MetadataFetcher");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("AuthorToManga", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Author", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("AuthorIds")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("API.Schema.MangaContext.Manga", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("MangaIds")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MangaTagToManga", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Manga", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("MangaIds")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("API.Schema.MangaContext.MangaTag", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("MangaTagIds")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Chapter", b =>
|
||||
{
|
||||
b.Navigation("MangaConnectorIds");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Manga", b =>
|
||||
{
|
||||
b.Navigation("Chapters");
|
||||
|
||||
b.Navigation("MangaConnectorIds");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
375
API/Migrations/Manga/20250722203315_Initial.cs
Normal file
375
API/Migrations/Manga/20250722203315_Initial.cs
Normal file
@@ -0,0 +1,375 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Manga
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class Initial : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Authors",
|
||||
columns: table => new
|
||||
{
|
||||
Key = table.Column<string>(type: "text", nullable: false),
|
||||
AuthorName = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Authors", x => x.Key);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "FileLibraries",
|
||||
columns: table => new
|
||||
{
|
||||
Key = table.Column<string>(type: "text", nullable: false),
|
||||
BasePath = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
|
||||
LibraryName = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_FileLibraries", x => x.Key);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "MangaConnector",
|
||||
columns: table => new
|
||||
{
|
||||
Name = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
|
||||
SupportedLanguages = table.Column<string[]>(type: "text[]", maxLength: 8, nullable: false),
|
||||
IconUrl = table.Column<string>(type: "character varying(2048)", maxLength: 2048, nullable: false),
|
||||
BaseUris = table.Column<string[]>(type: "text[]", maxLength: 256, nullable: false),
|
||||
Enabled = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_MangaConnector", x => x.Name);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "MetadataFetcher",
|
||||
columns: table => new
|
||||
{
|
||||
Name = table.Column<string>(type: "text", nullable: false),
|
||||
MetadataEntry = table.Column<string>(type: "character varying(21)", maxLength: 21, nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_MetadataFetcher", x => x.Name);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Tags",
|
||||
columns: table => new
|
||||
{
|
||||
Tag = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Tags", x => x.Tag);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Mangas",
|
||||
columns: table => new
|
||||
{
|
||||
Key = table.Column<string>(type: "text", nullable: false),
|
||||
Name = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: false),
|
||||
Description = table.Column<string>(type: "text", nullable: false),
|
||||
CoverUrl = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: false),
|
||||
ReleaseStatus = table.Column<byte>(type: "smallint", nullable: false),
|
||||
LibraryId = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
|
||||
IgnoreChaptersBefore = table.Column<float>(type: "real", nullable: false),
|
||||
DirectoryName = table.Column<string>(type: "character varying(1024)", maxLength: 1024, nullable: false),
|
||||
CoverFileNameInCache = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: true),
|
||||
Year = table.Column<long>(type: "bigint", nullable: true),
|
||||
OriginalLanguage = table.Column<string>(type: "character varying(8)", maxLength: 8, nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Mangas", x => x.Key);
|
||||
table.ForeignKey(
|
||||
name: "FK_Mangas_FileLibraries_LibraryId",
|
||||
column: x => x.LibraryId,
|
||||
principalTable: "FileLibraries",
|
||||
principalColumn: "Key",
|
||||
onDelete: ReferentialAction.SetNull);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "AltTitle",
|
||||
columns: table => new
|
||||
{
|
||||
Key = table.Column<string>(type: "text", nullable: false),
|
||||
Language = table.Column<string>(type: "character varying(8)", maxLength: 8, nullable: false),
|
||||
Title = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
|
||||
MangaKey = table.Column<string>(type: "text", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_AltTitle", x => x.Key);
|
||||
table.ForeignKey(
|
||||
name: "FK_AltTitle_Mangas_MangaKey",
|
||||
column: x => x.MangaKey,
|
||||
principalTable: "Mangas",
|
||||
principalColumn: "Key",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "AuthorToManga",
|
||||
columns: table => new
|
||||
{
|
||||
AuthorIds = table.Column<string>(type: "text", nullable: false),
|
||||
MangaIds = table.Column<string>(type: "text", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_AuthorToManga", x => new { x.AuthorIds, x.MangaIds });
|
||||
table.ForeignKey(
|
||||
name: "FK_AuthorToManga_Authors_AuthorIds",
|
||||
column: x => x.AuthorIds,
|
||||
principalTable: "Authors",
|
||||
principalColumn: "Key",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_AuthorToManga_Mangas_MangaIds",
|
||||
column: x => x.MangaIds,
|
||||
principalTable: "Mangas",
|
||||
principalColumn: "Key",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Chapters",
|
||||
columns: table => new
|
||||
{
|
||||
Key = table.Column<string>(type: "text", nullable: false),
|
||||
ParentMangaId = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
|
||||
VolumeNumber = table.Column<int>(type: "integer", nullable: true),
|
||||
ChapterNumber = table.Column<string>(type: "character varying(10)", maxLength: 10, nullable: false),
|
||||
Title = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
|
||||
FileName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
|
||||
Downloaded = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Chapters", x => x.Key);
|
||||
table.ForeignKey(
|
||||
name: "FK_Chapters_Mangas_ParentMangaId",
|
||||
column: x => x.ParentMangaId,
|
||||
principalTable: "Mangas",
|
||||
principalColumn: "Key",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Link",
|
||||
columns: table => new
|
||||
{
|
||||
Key = table.Column<string>(type: "text", nullable: false),
|
||||
LinkProvider = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
|
||||
LinkUrl = table.Column<string>(type: "character varying(2048)", maxLength: 2048, nullable: false),
|
||||
MangaKey = table.Column<string>(type: "text", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Link", x => x.Key);
|
||||
table.ForeignKey(
|
||||
name: "FK_Link_Mangas_MangaKey",
|
||||
column: x => x.MangaKey,
|
||||
principalTable: "Mangas",
|
||||
principalColumn: "Key",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "MangaConnectorToManga",
|
||||
columns: table => new
|
||||
{
|
||||
Key = table.Column<string>(type: "text", nullable: false),
|
||||
ObjId = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
|
||||
MangaConnectorName = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
|
||||
IdOnConnectorSite = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
|
||||
WebsiteUrl = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: true),
|
||||
UseForDownload = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_MangaConnectorToManga", x => x.Key);
|
||||
table.ForeignKey(
|
||||
name: "FK_MangaConnectorToManga_Mangas_ObjId",
|
||||
column: x => x.ObjId,
|
||||
principalTable: "Mangas",
|
||||
principalColumn: "Key",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "MangaTagToManga",
|
||||
columns: table => new
|
||||
{
|
||||
MangaTagIds = table.Column<string>(type: "character varying(64)", nullable: false),
|
||||
MangaIds = table.Column<string>(type: "text", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_MangaTagToManga", x => new { x.MangaTagIds, x.MangaIds });
|
||||
table.ForeignKey(
|
||||
name: "FK_MangaTagToManga_Mangas_MangaIds",
|
||||
column: x => x.MangaIds,
|
||||
principalTable: "Mangas",
|
||||
principalColumn: "Key",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_MangaTagToManga_Tags_MangaTagIds",
|
||||
column: x => x.MangaTagIds,
|
||||
principalTable: "Tags",
|
||||
principalColumn: "Tag",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "MetadataEntries",
|
||||
columns: table => new
|
||||
{
|
||||
MetadataFetcherName = table.Column<string>(type: "text", nullable: false),
|
||||
Identifier = table.Column<string>(type: "text", nullable: false),
|
||||
MangaId = table.Column<string>(type: "text", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_MetadataEntries", x => new { x.MetadataFetcherName, x.Identifier });
|
||||
table.ForeignKey(
|
||||
name: "FK_MetadataEntries_Mangas_MangaId",
|
||||
column: x => x.MangaId,
|
||||
principalTable: "Mangas",
|
||||
principalColumn: "Key",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_MetadataEntries_MetadataFetcher_MetadataFetcherName",
|
||||
column: x => x.MetadataFetcherName,
|
||||
principalTable: "MetadataFetcher",
|
||||
principalColumn: "Name",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "MangaConnectorToChapter",
|
||||
columns: table => new
|
||||
{
|
||||
Key = table.Column<string>(type: "text", nullable: false),
|
||||
ObjId = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
|
||||
MangaConnectorName = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
|
||||
IdOnConnectorSite = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
|
||||
WebsiteUrl = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: true),
|
||||
UseForDownload = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_MangaConnectorToChapter", x => x.Key);
|
||||
table.ForeignKey(
|
||||
name: "FK_MangaConnectorToChapter_Chapters_ObjId",
|
||||
column: x => x.ObjId,
|
||||
principalTable: "Chapters",
|
||||
principalColumn: "Key",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_AltTitle_MangaKey",
|
||||
table: "AltTitle",
|
||||
column: "MangaKey");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_AuthorToManga_MangaIds",
|
||||
table: "AuthorToManga",
|
||||
column: "MangaIds");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Chapters_ParentMangaId",
|
||||
table: "Chapters",
|
||||
column: "ParentMangaId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Link_MangaKey",
|
||||
table: "Link",
|
||||
column: "MangaKey");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_MangaConnectorToChapter_ObjId",
|
||||
table: "MangaConnectorToChapter",
|
||||
column: "ObjId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_MangaConnectorToManga_ObjId",
|
||||
table: "MangaConnectorToManga",
|
||||
column: "ObjId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Mangas_LibraryId",
|
||||
table: "Mangas",
|
||||
column: "LibraryId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_MangaTagToManga_MangaIds",
|
||||
table: "MangaTagToManga",
|
||||
column: "MangaIds");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_MetadataEntries_MangaId",
|
||||
table: "MetadataEntries",
|
||||
column: "MangaId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "AltTitle");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "AuthorToManga");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Link");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "MangaConnector");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "MangaConnectorToChapter");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "MangaConnectorToManga");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "MangaTagToManga");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "MetadataEntries");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Authors");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Chapters");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Tags");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "MetadataFetcher");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Mangas");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "FileLibraries");
|
||||
}
|
||||
}
|
||||
}
|
535
API/Migrations/Manga/20250901194144_KeyLengthChange.Designer.cs
generated
Normal file
535
API/Migrations/Manga/20250901194144_KeyLengthChange.Designer.cs
generated
Normal file
@@ -0,0 +1,535 @@
|
||||
// <auto-generated />
|
||||
using API.Schema.MangaContext;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Manga
|
||||
{
|
||||
[DbContext(typeof(MangaContext))]
|
||||
[Migration("20250901194144_KeyLengthChange")]
|
||||
partial class KeyLengthChange
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("API.MangaConnectors.MangaConnector", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.PrimitiveCollection<string[]>("BaseUris")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("text[]");
|
||||
|
||||
b.Property<bool>("Enabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("IconUrl")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("character varying(2048)");
|
||||
|
||||
b.PrimitiveCollection<string[]>("SupportedLanguages")
|
||||
.IsRequired()
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("text[]");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("MangaConnector");
|
||||
|
||||
b.HasDiscriminator<string>("Name").HasValue("MangaConnector");
|
||||
|
||||
b.UseTphMappingStrategy();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Author", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("AuthorName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("Authors");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Chapter", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("ChapterNumber")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)");
|
||||
|
||||
b.Property<bool>("Downloaded")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("FileName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("ParentMangaId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<int?>("VolumeNumber")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.HasIndex("ParentMangaId");
|
||||
|
||||
b.ToTable("Chapters");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.FileLibrary", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("BasePath")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("LibraryName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("FileLibraries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Manga", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("CoverFileNameInCache")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("CoverUrl")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("DirectoryName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(1024)
|
||||
.HasColumnType("character varying(1024)");
|
||||
|
||||
b.Property<float>("IgnoreChaptersBefore")
|
||||
.HasColumnType("real");
|
||||
|
||||
b.Property<string>("LibraryId")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("OriginalLanguage")
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b.Property<byte>("ReleaseStatus")
|
||||
.HasColumnType("smallint");
|
||||
|
||||
b.Property<long?>("Year")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.HasIndex("LibraryId");
|
||||
|
||||
b.ToTable("Mangas");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaConnectorId<API.Schema.MangaContext.Chapter>", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("IdOnConnectorSite")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("MangaConnectorName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.Property<string>("ObjId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<bool>("UseForDownload")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("WebsiteUrl")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.HasIndex("ObjId");
|
||||
|
||||
b.ToTable("MangaConnectorToChapter");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaConnectorId<API.Schema.MangaContext.Manga>", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("IdOnConnectorSite")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("MangaConnectorName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.Property<string>("ObjId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<bool>("UseForDownload")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("WebsiteUrl")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.HasIndex("ObjId");
|
||||
|
||||
b.ToTable("MangaConnectorToManga");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaTag", b =>
|
||||
{
|
||||
b.Property<string>("Tag")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.HasKey("Tag");
|
||||
|
||||
b.ToTable("Tags");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MetadataFetchers.MetadataEntry", b =>
|
||||
{
|
||||
b.Property<string>("MetadataFetcherName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Identifier")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("MangaId")
|
||||
.IsRequired()
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.HasKey("MetadataFetcherName", "Identifier");
|
||||
|
||||
b.HasIndex("MangaId");
|
||||
|
||||
b.ToTable("MetadataEntries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MetadataFetchers.MetadataFetcher", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("MetadataEntry")
|
||||
.IsRequired()
|
||||
.HasMaxLength(21)
|
||||
.HasColumnType("character varying(21)");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("MetadataFetcher");
|
||||
|
||||
b.HasDiscriminator<string>("MetadataEntry").HasValue("MetadataFetcher");
|
||||
|
||||
b.UseTphMappingStrategy();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("AuthorToManga", b =>
|
||||
{
|
||||
b.Property<string>("AuthorIds")
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("MangaIds")
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.HasKey("AuthorIds", "MangaIds");
|
||||
|
||||
b.HasIndex("MangaIds");
|
||||
|
||||
b.ToTable("AuthorToManga");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MangaTagToManga", b =>
|
||||
{
|
||||
b.Property<string>("MangaTagIds")
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("MangaIds")
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.HasKey("MangaTagIds", "MangaIds");
|
||||
|
||||
b.HasIndex("MangaIds");
|
||||
|
||||
b.ToTable("MangaTagToManga");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.MangaConnectors.ComickIo", b =>
|
||||
{
|
||||
b.HasBaseType("API.MangaConnectors.MangaConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue("ComickIo");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.MangaConnectors.Global", b =>
|
||||
{
|
||||
b.HasBaseType("API.MangaConnectors.MangaConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue("Global");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.MangaConnectors.MangaDex", b =>
|
||||
{
|
||||
b.HasBaseType("API.MangaConnectors.MangaConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue("MangaDex");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MetadataFetchers.MyAnimeList", b =>
|
||||
{
|
||||
b.HasBaseType("API.Schema.MangaContext.MetadataFetchers.MetadataFetcher");
|
||||
|
||||
b.HasDiscriminator().HasValue("MyAnimeList");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Chapter", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Manga", "ParentManga")
|
||||
.WithMany("Chapters")
|
||||
.HasForeignKey("ParentMangaId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("ParentManga");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Manga", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.FileLibrary", "Library")
|
||||
.WithMany()
|
||||
.HasForeignKey("LibraryId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.OwnsMany("API.Schema.MangaContext.AltTitle", "AltTitles", b1 =>
|
||||
{
|
||||
b1.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b1.Property<string>("Language")
|
||||
.IsRequired()
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b1.Property<string>("MangaKey")
|
||||
.IsRequired()
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b1.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b1.HasKey("Key");
|
||||
|
||||
b1.HasIndex("MangaKey");
|
||||
|
||||
b1.ToTable("AltTitle");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("MangaKey");
|
||||
});
|
||||
|
||||
b.OwnsMany("API.Schema.MangaContext.Link", "Links", b1 =>
|
||||
{
|
||||
b1.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b1.Property<string>("LinkProvider")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b1.Property<string>("LinkUrl")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("character varying(2048)");
|
||||
|
||||
b1.Property<string>("MangaKey")
|
||||
.IsRequired()
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b1.HasKey("Key");
|
||||
|
||||
b1.HasIndex("MangaKey");
|
||||
|
||||
b1.ToTable("Link");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("MangaKey");
|
||||
});
|
||||
|
||||
b.Navigation("AltTitles");
|
||||
|
||||
b.Navigation("Library");
|
||||
|
||||
b.Navigation("Links");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaConnectorId<API.Schema.MangaContext.Chapter>", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Chapter", "Obj")
|
||||
.WithMany("MangaConnectorIds")
|
||||
.HasForeignKey("ObjId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Obj");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaConnectorId<API.Schema.MangaContext.Manga>", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Manga", "Obj")
|
||||
.WithMany("MangaConnectorIds")
|
||||
.HasForeignKey("ObjId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Obj");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MetadataFetchers.MetadataEntry", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Manga", "Manga")
|
||||
.WithMany()
|
||||
.HasForeignKey("MangaId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("API.Schema.MangaContext.MetadataFetchers.MetadataFetcher", "MetadataFetcher")
|
||||
.WithMany()
|
||||
.HasForeignKey("MetadataFetcherName")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Manga");
|
||||
|
||||
b.Navigation("MetadataFetcher");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("AuthorToManga", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Author", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("AuthorIds")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("API.Schema.MangaContext.Manga", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("MangaIds")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MangaTagToManga", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Manga", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("MangaIds")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("API.Schema.MangaContext.MangaTag", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("MangaTagIds")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Chapter", b =>
|
||||
{
|
||||
b.Navigation("MangaConnectorIds");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Manga", b =>
|
||||
{
|
||||
b.Navigation("Chapters");
|
||||
|
||||
b.Navigation("MangaConnectorIds");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
258
API/Migrations/Manga/20250901194144_KeyLengthChange.cs
Normal file
258
API/Migrations/Manga/20250901194144_KeyLengthChange.cs
Normal file
@@ -0,0 +1,258 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Manga
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class KeyLengthChange : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "MangaId",
|
||||
table: "MetadataEntries",
|
||||
type: "character varying(64)",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "MangaIds",
|
||||
table: "MangaTagToManga",
|
||||
type: "character varying(64)",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "Mangas",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "MangaConnectorToManga",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "MangaConnectorToChapter",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "MangaKey",
|
||||
table: "Link",
|
||||
type: "character varying(64)",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "Link",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "FileLibraries",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "Chapters",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "MangaIds",
|
||||
table: "AuthorToManga",
|
||||
type: "character varying(64)",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "AuthorIds",
|
||||
table: "AuthorToManga",
|
||||
type: "character varying(64)",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "Authors",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "MangaKey",
|
||||
table: "AltTitle",
|
||||
type: "character varying(64)",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "AltTitle",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "MangaId",
|
||||
table: "MetadataEntries",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "MangaIds",
|
||||
table: "MangaTagToManga",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "Mangas",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)",
|
||||
oldMaxLength: 64);
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "MangaConnectorToManga",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)",
|
||||
oldMaxLength: 64);
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "MangaConnectorToChapter",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)",
|
||||
oldMaxLength: 64);
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "MangaKey",
|
||||
table: "Link",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "Link",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)",
|
||||
oldMaxLength: 64);
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "FileLibraries",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)",
|
||||
oldMaxLength: 64);
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "Chapters",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)",
|
||||
oldMaxLength: 64);
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "MangaIds",
|
||||
table: "AuthorToManga",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "AuthorIds",
|
||||
table: "AuthorToManga",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "Authors",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)",
|
||||
oldMaxLength: 64);
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "MangaKey",
|
||||
table: "AltTitle",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "AltTitle",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)",
|
||||
oldMaxLength: 64);
|
||||
}
|
||||
}
|
||||
}
|
532
API/Migrations/Manga/MangaContextModelSnapshot.cs
Normal file
532
API/Migrations/Manga/MangaContextModelSnapshot.cs
Normal file
@@ -0,0 +1,532 @@
|
||||
// <auto-generated />
|
||||
using API.Schema.MangaContext;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Manga
|
||||
{
|
||||
[DbContext(typeof(MangaContext))]
|
||||
partial class MangaContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("API.MangaConnectors.MangaConnector", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.PrimitiveCollection<string[]>("BaseUris")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("text[]");
|
||||
|
||||
b.Property<bool>("Enabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("IconUrl")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("character varying(2048)");
|
||||
|
||||
b.PrimitiveCollection<string[]>("SupportedLanguages")
|
||||
.IsRequired()
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("text[]");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("MangaConnector");
|
||||
|
||||
b.HasDiscriminator<string>("Name").HasValue("MangaConnector");
|
||||
|
||||
b.UseTphMappingStrategy();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Author", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("AuthorName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("Authors");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Chapter", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("ChapterNumber")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)");
|
||||
|
||||
b.Property<bool>("Downloaded")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("FileName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("ParentMangaId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<int?>("VolumeNumber")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.HasIndex("ParentMangaId");
|
||||
|
||||
b.ToTable("Chapters");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.FileLibrary", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("BasePath")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("LibraryName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("FileLibraries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Manga", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("CoverFileNameInCache")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("CoverUrl")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("DirectoryName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(1024)
|
||||
.HasColumnType("character varying(1024)");
|
||||
|
||||
b.Property<float>("IgnoreChaptersBefore")
|
||||
.HasColumnType("real");
|
||||
|
||||
b.Property<string>("LibraryId")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("OriginalLanguage")
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b.Property<byte>("ReleaseStatus")
|
||||
.HasColumnType("smallint");
|
||||
|
||||
b.Property<long?>("Year")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.HasIndex("LibraryId");
|
||||
|
||||
b.ToTable("Mangas");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaConnectorId<API.Schema.MangaContext.Chapter>", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("IdOnConnectorSite")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("MangaConnectorName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.Property<string>("ObjId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<bool>("UseForDownload")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("WebsiteUrl")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.HasIndex("ObjId");
|
||||
|
||||
b.ToTable("MangaConnectorToChapter");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaConnectorId<API.Schema.MangaContext.Manga>", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("IdOnConnectorSite")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<string>("MangaConnectorName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)");
|
||||
|
||||
b.Property<string>("ObjId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<bool>("UseForDownload")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("WebsiteUrl")
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.HasIndex("ObjId");
|
||||
|
||||
b.ToTable("MangaConnectorToManga");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaTag", b =>
|
||||
{
|
||||
b.Property<string>("Tag")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.HasKey("Tag");
|
||||
|
||||
b.ToTable("Tags");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MetadataFetchers.MetadataEntry", b =>
|
||||
{
|
||||
b.Property<string>("MetadataFetcherName")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Identifier")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("MangaId")
|
||||
.IsRequired()
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.HasKey("MetadataFetcherName", "Identifier");
|
||||
|
||||
b.HasIndex("MangaId");
|
||||
|
||||
b.ToTable("MetadataEntries");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MetadataFetchers.MetadataFetcher", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("MetadataEntry")
|
||||
.IsRequired()
|
||||
.HasMaxLength(21)
|
||||
.HasColumnType("character varying(21)");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("MetadataFetcher");
|
||||
|
||||
b.HasDiscriminator<string>("MetadataEntry").HasValue("MetadataFetcher");
|
||||
|
||||
b.UseTphMappingStrategy();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("AuthorToManga", b =>
|
||||
{
|
||||
b.Property<string>("AuthorIds")
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("MangaIds")
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.HasKey("AuthorIds", "MangaIds");
|
||||
|
||||
b.HasIndex("MangaIds");
|
||||
|
||||
b.ToTable("AuthorToManga");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MangaTagToManga", b =>
|
||||
{
|
||||
b.Property<string>("MangaTagIds")
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("MangaIds")
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.HasKey("MangaTagIds", "MangaIds");
|
||||
|
||||
b.HasIndex("MangaIds");
|
||||
|
||||
b.ToTable("MangaTagToManga");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.MangaConnectors.ComickIo", b =>
|
||||
{
|
||||
b.HasBaseType("API.MangaConnectors.MangaConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue("ComickIo");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.MangaConnectors.Global", b =>
|
||||
{
|
||||
b.HasBaseType("API.MangaConnectors.MangaConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue("Global");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.MangaConnectors.MangaDex", b =>
|
||||
{
|
||||
b.HasBaseType("API.MangaConnectors.MangaConnector");
|
||||
|
||||
b.HasDiscriminator().HasValue("MangaDex");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MetadataFetchers.MyAnimeList", b =>
|
||||
{
|
||||
b.HasBaseType("API.Schema.MangaContext.MetadataFetchers.MetadataFetcher");
|
||||
|
||||
b.HasDiscriminator().HasValue("MyAnimeList");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Chapter", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Manga", "ParentManga")
|
||||
.WithMany("Chapters")
|
||||
.HasForeignKey("ParentMangaId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("ParentManga");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Manga", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.FileLibrary", "Library")
|
||||
.WithMany()
|
||||
.HasForeignKey("LibraryId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.OwnsMany("API.Schema.MangaContext.AltTitle", "AltTitles", b1 =>
|
||||
{
|
||||
b1.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b1.Property<string>("Language")
|
||||
.IsRequired()
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b1.Property<string>("MangaKey")
|
||||
.IsRequired()
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b1.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b1.HasKey("Key");
|
||||
|
||||
b1.HasIndex("MangaKey");
|
||||
|
||||
b1.ToTable("AltTitle");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("MangaKey");
|
||||
});
|
||||
|
||||
b.OwnsMany("API.Schema.MangaContext.Link", "Links", b1 =>
|
||||
{
|
||||
b1.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b1.Property<string>("LinkProvider")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b1.Property<string>("LinkUrl")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("character varying(2048)");
|
||||
|
||||
b1.Property<string>("MangaKey")
|
||||
.IsRequired()
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b1.HasKey("Key");
|
||||
|
||||
b1.HasIndex("MangaKey");
|
||||
|
||||
b1.ToTable("Link");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("MangaKey");
|
||||
});
|
||||
|
||||
b.Navigation("AltTitles");
|
||||
|
||||
b.Navigation("Library");
|
||||
|
||||
b.Navigation("Links");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaConnectorId<API.Schema.MangaContext.Chapter>", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Chapter", "Obj")
|
||||
.WithMany("MangaConnectorIds")
|
||||
.HasForeignKey("ObjId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Obj");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MangaConnectorId<API.Schema.MangaContext.Manga>", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Manga", "Obj")
|
||||
.WithMany("MangaConnectorIds")
|
||||
.HasForeignKey("ObjId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Obj");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.MetadataFetchers.MetadataEntry", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Manga", "Manga")
|
||||
.WithMany()
|
||||
.HasForeignKey("MangaId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("API.Schema.MangaContext.MetadataFetchers.MetadataFetcher", "MetadataFetcher")
|
||||
.WithMany()
|
||||
.HasForeignKey("MetadataFetcherName")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Manga");
|
||||
|
||||
b.Navigation("MetadataFetcher");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("AuthorToManga", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Author", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("AuthorIds")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("API.Schema.MangaContext.Manga", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("MangaIds")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MangaTagToManga", b =>
|
||||
{
|
||||
b.HasOne("API.Schema.MangaContext.Manga", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("MangaIds")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("API.Schema.MangaContext.MangaTag", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("MangaTagIds")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Chapter", b =>
|
||||
{
|
||||
b.Navigation("MangaConnectorIds");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.MangaContext.Manga", b =>
|
||||
{
|
||||
b.Navigation("Chapters");
|
||||
|
||||
b.Navigation("MangaConnectorIds");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
91
API/Migrations/Notifications/20250703191820_Initial.Designer.cs
generated
Normal file
91
API/Migrations/Notifications/20250703191820_Initial.Designer.cs
generated
Normal file
@@ -0,0 +1,91 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using API.Schema.NotificationsContext;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Notifications
|
||||
{
|
||||
[DbContext(typeof(NotificationsContext))]
|
||||
[Migration("20250703191820_Initial")]
|
||||
partial class Initial
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.5")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "hstore");
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("API.Schema.NotificationsContext.Notification", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<DateTime>("Date")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("IsSent")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Message")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<byte>("Urgency")
|
||||
.HasColumnType("smallint");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("Notifications");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.NotificationsContext.NotificationConnectors.NotificationConnector", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("Body")
|
||||
.IsRequired()
|
||||
.HasMaxLength(4096)
|
||||
.HasColumnType("character varying(4096)");
|
||||
|
||||
b.Property<Dictionary<string, string>>("Headers")
|
||||
.IsRequired()
|
||||
.HasColumnType("hstore");
|
||||
|
||||
b.Property<string>("HttpMethod")
|
||||
.IsRequired()
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b.Property<string>("Url")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("character varying(2048)");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("NotificationConnectors");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
60
API/Migrations/Notifications/20250703191820_Initial.cs
Normal file
60
API/Migrations/Notifications/20250703191820_Initial.cs
Normal file
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Notifications
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class Initial : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterDatabase()
|
||||
.Annotation("Npgsql:PostgresExtension:hstore", ",,");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "NotificationConnectors",
|
||||
columns: table => new
|
||||
{
|
||||
Name = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
|
||||
Url = table.Column<string>(type: "character varying(2048)", maxLength: 2048, nullable: false),
|
||||
Headers = table.Column<Dictionary<string, string>>(type: "hstore", nullable: false),
|
||||
HttpMethod = table.Column<string>(type: "character varying(8)", maxLength: 8, nullable: false),
|
||||
Body = table.Column<string>(type: "character varying(4096)", maxLength: 4096, nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_NotificationConnectors", x => x.Name);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Notifications",
|
||||
columns: table => new
|
||||
{
|
||||
Key = table.Column<string>(type: "text", nullable: false),
|
||||
Urgency = table.Column<byte>(type: "smallint", nullable: false),
|
||||
Title = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false),
|
||||
Message = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: false),
|
||||
Date = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
IsSent = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Notifications", x => x.Key);
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "NotificationConnectors");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Notifications");
|
||||
}
|
||||
}
|
||||
}
|
92
API/Migrations/Notifications/20250901194327_KeyLengthChange.Designer.cs
generated
Normal file
92
API/Migrations/Notifications/20250901194327_KeyLengthChange.Designer.cs
generated
Normal file
@@ -0,0 +1,92 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using API.Schema.NotificationsContext;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Notifications
|
||||
{
|
||||
[DbContext(typeof(NotificationsContext))]
|
||||
[Migration("20250901194327_KeyLengthChange")]
|
||||
partial class KeyLengthChange
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "hstore");
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("API.Schema.NotificationsContext.Notification", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<DateTime>("Date")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("IsSent")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Message")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<byte>("Urgency")
|
||||
.HasColumnType("smallint");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("Notifications");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.NotificationsContext.NotificationConnectors.NotificationConnector", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("Body")
|
||||
.IsRequired()
|
||||
.HasMaxLength(4096)
|
||||
.HasColumnType("character varying(4096)");
|
||||
|
||||
b.Property<Dictionary<string, string>>("Headers")
|
||||
.IsRequired()
|
||||
.HasColumnType("hstore");
|
||||
|
||||
b.Property<string>("HttpMethod")
|
||||
.IsRequired()
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b.Property<string>("Url")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("character varying(2048)");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("NotificationConnectors");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,36 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Notifications
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class KeyLengthChange : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "Notifications",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "text");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Key",
|
||||
table: "Notifications",
|
||||
type: "text",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "character varying(64)",
|
||||
oldMaxLength: 64);
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,89 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using API.Schema.NotificationsContext;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Migrations.Notifications
|
||||
{
|
||||
[DbContext(typeof(NotificationsContext))]
|
||||
partial class NotificationsContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.8")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "hstore");
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("API.Schema.NotificationsContext.Notification", b =>
|
||||
{
|
||||
b.Property<string>("Key")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<DateTime>("Date")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<bool>("IsSent")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Message")
|
||||
.IsRequired()
|
||||
.HasMaxLength(512)
|
||||
.HasColumnType("character varying(512)");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<byte>("Urgency")
|
||||
.HasColumnType("smallint");
|
||||
|
||||
b.HasKey("Key");
|
||||
|
||||
b.ToTable("Notifications");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Schema.NotificationsContext.NotificationConnectors.NotificationConnector", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)");
|
||||
|
||||
b.Property<string>("Body")
|
||||
.IsRequired()
|
||||
.HasMaxLength(4096)
|
||||
.HasColumnType("character varying(4096)");
|
||||
|
||||
b.Property<Dictionary<string, string>>("Headers")
|
||||
.IsRequired()
|
||||
.HasColumnType("hstore");
|
||||
|
||||
b.Property<string>("HttpMethod")
|
||||
.IsRequired()
|
||||
.HasMaxLength(8)
|
||||
.HasColumnType("character varying(8)");
|
||||
|
||||
b.Property<string>("Url")
|
||||
.IsRequired()
|
||||
.HasMaxLength(2048)
|
||||
.HasColumnType("character varying(2048)");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("NotificationConnectors");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
46
API/NamedSwaggerGenOptions.cs
Normal file
46
API/NamedSwaggerGenOptions.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using Asp.Versioning.ApiExplorer;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
|
||||
namespace API;
|
||||
|
||||
public class NamedSwaggerGenOptions : IConfigureNamedOptions<SwaggerGenOptions>
|
||||
{
|
||||
private readonly IApiVersionDescriptionProvider provider;
|
||||
public NamedSwaggerGenOptions(IApiVersionDescriptionProvider provider)
|
||||
{
|
||||
this.provider = provider;
|
||||
}
|
||||
|
||||
public void Configure(string? name, SwaggerGenOptions options)
|
||||
{
|
||||
Configure(options);
|
||||
}
|
||||
|
||||
public void Configure(SwaggerGenOptions options)
|
||||
{
|
||||
// add swagger document for every API version discovered
|
||||
foreach (var description in provider.ApiVersionDescriptions)
|
||||
{
|
||||
options.SwaggerDoc(
|
||||
description.GroupName,
|
||||
CreateVersionInfo(description));
|
||||
}
|
||||
}
|
||||
|
||||
private OpenApiInfo CreateVersionInfo(
|
||||
ApiVersionDescription description)
|
||||
{
|
||||
var info = new OpenApiInfo()
|
||||
{
|
||||
Title = "Tranga " + description.GroupName,
|
||||
Version = description.ApiVersion.ToString()
|
||||
};
|
||||
if (description.IsDeprecated)
|
||||
{
|
||||
info.Description += " This API version has been deprecated.";
|
||||
}
|
||||
return info;
|
||||
}
|
||||
}
|
143
API/Program.cs
Normal file
143
API/Program.cs
Normal file
@@ -0,0 +1,143 @@
|
||||
using System.Reflection;
|
||||
using API;
|
||||
using API.Schema.LibraryContext;
|
||||
using API.Schema.MangaContext;
|
||||
using API.Schema.NotificationsContext;
|
||||
using Asp.Versioning;
|
||||
using Asp.Versioning.Builder;
|
||||
using Asp.Versioning.Conventions;
|
||||
using log4net;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("AllowAll",
|
||||
policy =>
|
||||
{
|
||||
policy
|
||||
.AllowAnyOrigin()
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader();
|
||||
});
|
||||
});
|
||||
|
||||
builder.Services.AddApiVersioning(option =>
|
||||
{
|
||||
option.AssumeDefaultVersionWhenUnspecified = true;
|
||||
option.DefaultApiVersion = new ApiVersion(2);
|
||||
option.ReportApiVersions = true;
|
||||
option.ApiVersionReader = ApiVersionReader.Combine(
|
||||
new UrlSegmentApiVersionReader(),
|
||||
new QueryStringApiVersionReader("api-version"),
|
||||
new HeaderApiVersionReader("X-Version"),
|
||||
new MediaTypeApiVersionReader("x-version"));
|
||||
})
|
||||
.AddMvc(options =>
|
||||
{
|
||||
options.Conventions.Add(new VersionByNamespaceConvention());
|
||||
})
|
||||
.AddApiExplorer(options =>
|
||||
{
|
||||
options.GroupNameFormat = "'v'V";
|
||||
options.SubstituteApiVersionInUrl = true;
|
||||
});
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGenNewtonsoftSupport();
|
||||
builder.Services.AddSwaggerGen(opt =>
|
||||
{
|
||||
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
|
||||
opt.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
|
||||
});
|
||||
builder.Services.ConfigureOptions<NamedSwaggerGenOptions>();
|
||||
|
||||
string connectionString = $"Host={Environment.GetEnvironmentVariable("POSTGRES_HOST") ?? "localhost:5432"}; " +
|
||||
$"Database={Environment.GetEnvironmentVariable("POSTGRES_DB") ?? "postgres"}; " +
|
||||
$"Username={Environment.GetEnvironmentVariable("POSTGRES_USER") ?? "postgres"}; " +
|
||||
$"Password={Environment.GetEnvironmentVariable("POSTGRES_PASSWORD") ?? "postgres"}";
|
||||
|
||||
builder.Services.AddDbContext<MangaContext>(options =>
|
||||
options.UseNpgsql(connectionString));
|
||||
builder.Services.AddDbContext<NotificationsContext>(options =>
|
||||
options.UseNpgsql(connectionString));
|
||||
builder.Services.AddDbContext<LibraryContext>(options =>
|
||||
options.UseNpgsql(connectionString));
|
||||
|
||||
builder.Services.AddControllers(options =>
|
||||
{
|
||||
options.AllowEmptyInputInBodyModelBinding = true;
|
||||
});
|
||||
builder.Services.AddControllers().AddNewtonsoftJson(opts =>
|
||||
{
|
||||
opts.SerializerSettings.Converters.Add(new StringEnumConverter());
|
||||
opts.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
|
||||
});
|
||||
builder.Services.AddScoped<ILog>(_ => LogManager.GetLogger("API"));
|
||||
|
||||
builder.WebHost.UseUrls("http://*:6531");
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
ApiVersionSet apiVersionSet = app.NewApiVersionSet()
|
||||
.HasApiVersion(new ApiVersion(2))
|
||||
.ReportApiVersions()
|
||||
.Build();
|
||||
|
||||
|
||||
app.UseCors("AllowAll");
|
||||
|
||||
app.MapControllers()
|
||||
.WithApiVersionSet(apiVersionSet)
|
||||
.MapToApiVersion(2);
|
||||
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(options =>
|
||||
{
|
||||
options.SwaggerEndpoint($"/swagger/v2/swagger.json", "v2");
|
||||
});
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseMiddleware<RequestTimeMiddleware>();
|
||||
|
||||
using (IServiceScope scope = app.Services.CreateScope())
|
||||
{
|
||||
MangaContext context = scope.ServiceProvider.GetRequiredService<MangaContext>();
|
||||
context.Database.Migrate();
|
||||
|
||||
if (!context.FileLibraries.Any())
|
||||
context.FileLibraries.Add(new FileLibrary(Tranga.Settings.DownloadLocation, "Default FileLibrary"));
|
||||
|
||||
await context.Sync(CancellationToken.None);
|
||||
}
|
||||
|
||||
using (IServiceScope scope = app.Services.CreateScope())
|
||||
{
|
||||
NotificationsContext context = scope.ServiceProvider.GetRequiredService<NotificationsContext>();
|
||||
context.Database.Migrate();
|
||||
|
||||
context.Notifications.RemoveRange(context.Notifications);
|
||||
string[] emojis = { "(•‿•)", "(づ \u25d5‿\u25d5 )づ", "( \u02d8\u25bd\u02d8)っ\u2668", "=\uff3e\u25cf \u22cf \u25cf\uff3e=", "(ΦωΦ)", "(\u272a\u3268\u272a)", "( ノ・o・ )ノ", "(〜^\u2207^ )〜", "~(\u2267ω\u2266)~","૮ \u00b4• ﻌ \u00b4• ა", "(\u02c3ᆺ\u02c2)", "(=\ud83d\udf66 \u0f1d \ud83d\udf66=)"};
|
||||
context.Notifications.Add(new Notification("Tranga Started", emojis[Random.Shared.Next(0, emojis.Length - 1)], NotificationUrgency.High));
|
||||
|
||||
await context.Sync(CancellationToken.None);
|
||||
}
|
||||
|
||||
using (IServiceScope scope = app.Services.CreateScope())
|
||||
{
|
||||
LibraryContext context = scope.ServiceProvider.GetRequiredService<LibraryContext>();
|
||||
context.Database.Migrate();
|
||||
|
||||
await context.Sync(CancellationToken.None);
|
||||
}
|
||||
|
||||
Tranga.SetServiceProvider(app.Services);
|
||||
Tranga.StartLogger(new FileInfo("Log4Net.config.xml"));
|
||||
Tranga.AddDefaultWorkers();
|
||||
|
||||
app.UseCors("AllowAll");
|
||||
|
||||
app.Run();
|
47
API/Properties/launchSettings.json
Normal file
47
API/Properties/launchSettings.json
Normal file
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:5976",
|
||||
"sslPort": 44332,
|
||||
"environmentVariables": {
|
||||
"POSTGRES_Host": "localhost:5432"
|
||||
}
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "http://localhost:5287",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development",
|
||||
"POSTGRES_Host": "localhost:5432"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:7206;http://localhost:5287",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development",
|
||||
"POSTGRES_Host": "localhost:5432"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development",
|
||||
"POSTGRES_Host": "localhost:5432"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
24
API/Schema/Identifiable.cs
Normal file
24
API/Schema/Identifiable.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Schema;
|
||||
|
||||
[PrimaryKey("Key")]
|
||||
public abstract class Identifiable
|
||||
{
|
||||
protected Identifiable()
|
||||
{
|
||||
this.Key = TokenGen.CreateToken(this.GetType());
|
||||
}
|
||||
|
||||
protected Identifiable(string key)
|
||||
{
|
||||
this.Key = key;
|
||||
}
|
||||
|
||||
[Required]
|
||||
[StringLength(TokenGen.MaximumLength, MinimumLength = TokenGen.MinimumLength)]
|
||||
public string Key { get; init; }
|
||||
|
||||
public override string ToString() => Key;
|
||||
}
|
@@ -1,29 +1,22 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Logging;
|
||||
using Newtonsoft.Json;
|
||||
using JsonSerializer = System.Text.Json.JsonSerializer;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace Tranga.LibraryConnectors;
|
||||
namespace API.Schema.LibraryContext.LibraryConnectors;
|
||||
|
||||
public class Kavita : LibraryConnector
|
||||
{
|
||||
|
||||
public Kavita(GlobalBase clone, string baseUrl, string username, string password) :
|
||||
base(clone, baseUrl, GetToken(baseUrl, username, password, clone.logger), LibraryType.Kavita)
|
||||
public Kavita(string baseUrl, string auth) : base(LibraryType.Kavita, baseUrl, auth)
|
||||
{
|
||||
}
|
||||
|
||||
[JsonConstructor]
|
||||
public Kavita(GlobalBase clone, string baseUrl, string auth) : base(clone, baseUrl, auth, LibraryType.Kavita)
|
||||
public Kavita(string baseUrl, string username, string password) :
|
||||
this(baseUrl, GetToken(baseUrl, username, password))
|
||||
{
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"Kavita {baseUrl}";
|
||||
}
|
||||
|
||||
private static string GetToken(string baseUrl, string username, string password, Logger? logger = null)
|
||||
private static string GetToken(string baseUrl, string username, string password)
|
||||
{
|
||||
HttpClient client = new()
|
||||
{
|
||||
@@ -41,7 +34,6 @@ public class Kavita : LibraryConnector
|
||||
try
|
||||
{
|
||||
HttpResponseMessage response = client.Send(requestMessage);
|
||||
logger?.WriteLine($"Kavita | GetToken {requestMessage.RequestUri} -> {response.StatusCode}");
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
JsonObject? result = JsonSerializer.Deserialize<JsonObject>(response.Content.ReadAsStream());
|
||||
@@ -50,28 +42,25 @@ public class Kavita : LibraryConnector
|
||||
}
|
||||
else
|
||||
{
|
||||
logger?.WriteLine($"Kavita | {response.Content}");
|
||||
}
|
||||
}
|
||||
catch (HttpRequestException e)
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
logger?.WriteLine($"Kavita | Unable to retrieve token:\n\r{e}");
|
||||
|
||||
}
|
||||
logger?.WriteLine("Kavita | Did not receive token.");
|
||||
return "";
|
||||
}
|
||||
|
||||
protected override void UpdateLibraryInternal()
|
||||
{
|
||||
Log("Updating libraries.");
|
||||
foreach (KavitaLibrary lib in GetLibraries())
|
||||
NetClient.MakePost($"{baseUrl}/api/Library/scan?libraryId={lib.id}", "Bearer", auth, logger);
|
||||
NetClient.MakePost($"{BaseUrl}/api/ToFileLibrary/scan?libraryId={lib.id}", "Bearer", Auth);
|
||||
}
|
||||
|
||||
internal override bool Test()
|
||||
{
|
||||
foreach (KavitaLibrary lib in GetLibraries())
|
||||
if (NetClient.MakePost($"{baseUrl}/api/Library/scan?libraryId={lib.id}", "Bearer", auth, logger))
|
||||
if (NetClient.MakePost($"{BaseUrl}/api/ToFileLibrary/scan?libraryId={lib.id}", "Bearer", Auth))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
@@ -82,18 +71,17 @@ public class Kavita : LibraryConnector
|
||||
/// <returns>Array of KavitaLibrary</returns>
|
||||
private IEnumerable<KavitaLibrary> GetLibraries()
|
||||
{
|
||||
Log("Getting libraries.");
|
||||
Stream data = NetClient.MakeRequest($"{baseUrl}/api/Library/libraries", "Bearer", auth, logger);
|
||||
Stream data = NetClient.MakeRequest($"{BaseUrl}/api/ToFileLibrary/libraries", "Bearer", Auth);
|
||||
if (data == Stream.Null)
|
||||
{
|
||||
Log("No libraries returned");
|
||||
return Array.Empty<KavitaLibrary>();
|
||||
Log.Info("No libraries found");
|
||||
return [];
|
||||
}
|
||||
JsonArray? result = JsonSerializer.Deserialize<JsonArray>(data);
|
||||
if (result is null)
|
||||
{
|
||||
Log("No libraries returned");
|
||||
return Array.Empty<KavitaLibrary>();
|
||||
Log.Info("No libraries found");
|
||||
return [];
|
||||
}
|
||||
|
||||
List<KavitaLibrary> ret = new();
|
||||
@@ -103,7 +91,7 @@ public class Kavita : LibraryConnector
|
||||
JsonObject? jObject = (JsonObject?)jsonNode;
|
||||
if(jObject is null)
|
||||
continue;
|
||||
int libraryId = jObject!["id"]!.GetValue<int>();
|
||||
int libraryId = jObject["id"]!.GetValue<int>();
|
||||
string libraryName = jObject["name"]!.GetValue<string>();
|
||||
ret.Add(new KavitaLibrary(libraryId, libraryName));
|
||||
}
|
@@ -1,41 +1,29 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Newtonsoft.Json;
|
||||
using JsonSerializer = System.Text.Json.JsonSerializer;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace Tranga.LibraryConnectors;
|
||||
namespace API.Schema.LibraryContext.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)
|
||||
public Komga(string baseUrl, string auth) : base(LibraryType.Komga, baseUrl, auth)
|
||||
{
|
||||
}
|
||||
|
||||
[JsonConstructor]
|
||||
public Komga(GlobalBase clone, string baseUrl, string auth) : base(clone, baseUrl, auth, LibraryType.Komga)
|
||||
public Komga(string baseUrl, string username, string password)
|
||||
: this(baseUrl, Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}")))
|
||||
{
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"Komga {baseUrl}";
|
||||
}
|
||||
|
||||
protected override void UpdateLibraryInternal()
|
||||
{
|
||||
Log("Updating libraries.");
|
||||
foreach (KomgaLibrary lib in GetLibraries())
|
||||
NetClient.MakePost($"{baseUrl}/api/v1/libraries/{lib.id}/scan", "Basic", auth, logger);
|
||||
NetClient.MakePost($"{BaseUrl}/api/v1/libraries/{lib.id}/scan", "Basic", Auth);
|
||||
}
|
||||
|
||||
internal override bool Test()
|
||||
{
|
||||
foreach (KomgaLibrary lib in GetLibraries())
|
||||
if (NetClient.MakePost($"{baseUrl}/api/v1/libraries/{lib.id}/scan", "Basic", auth, logger))
|
||||
if (NetClient.MakePost($"{BaseUrl}/api/v1/libraries/{lib.id}/scan", "Basic", Auth))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
@@ -46,18 +34,17 @@ public class Komga : LibraryConnector
|
||||
/// <returns>Array of KomgaLibraries</returns>
|
||||
private IEnumerable<KomgaLibrary> GetLibraries()
|
||||
{
|
||||
Log("Getting Libraries");
|
||||
Stream data = NetClient.MakeRequest($"{baseUrl}/api/v1/libraries", "Basic", auth, logger);
|
||||
Stream data = NetClient.MakeRequest($"{BaseUrl}/api/v1/libraries", "Basic", Auth);
|
||||
if (data == Stream.Null)
|
||||
{
|
||||
Log("No libraries returned");
|
||||
return Array.Empty<KomgaLibrary>();
|
||||
Log.Info("No libraries found");
|
||||
return [];
|
||||
}
|
||||
JsonArray? result = JsonSerializer.Deserialize<JsonArray>(data);
|
||||
if (result is null)
|
||||
{
|
||||
Log("No libraries returned");
|
||||
return Array.Empty<KomgaLibrary>();
|
||||
Log.Info("No libraries found");
|
||||
return [];
|
||||
}
|
||||
|
||||
HashSet<KomgaLibrary> ret = new();
|
@@ -0,0 +1,48 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using log4net;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace API.Schema.LibraryContext.LibraryConnectors;
|
||||
|
||||
[PrimaryKey("Key")]
|
||||
public abstract class LibraryConnector : Identifiable
|
||||
{
|
||||
public LibraryType LibraryType { get; init; }
|
||||
[StringLength(256)] [Url] public string BaseUrl { get; init; }
|
||||
[StringLength(256)] public string Auth { get; init; }
|
||||
[NotMapped] protected ILog Log { get; init; }
|
||||
|
||||
protected LibraryConnector(LibraryType libraryType, string baseUrl, string auth)
|
||||
: base()
|
||||
{
|
||||
this.LibraryType = libraryType;
|
||||
this.BaseUrl = baseUrl;
|
||||
this.Auth = auth;
|
||||
this.Log = LogManager.GetLogger(GetType());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EF CORE ONLY!!!!
|
||||
/// </summary>
|
||||
internal LibraryConnector(string key, LibraryType libraryType, string baseUrl, string auth)
|
||||
: base(key)
|
||||
{
|
||||
this.LibraryType = libraryType;
|
||||
this.BaseUrl = baseUrl;
|
||||
this.Auth = auth;
|
||||
this.Log = LogManager.GetLogger(GetType());
|
||||
}
|
||||
|
||||
public override string ToString() => $"{base.ToString()} {this.LibraryType} {this.BaseUrl}";
|
||||
|
||||
protected abstract void UpdateLibraryInternal();
|
||||
internal abstract bool Test();
|
||||
}
|
||||
|
||||
public enum LibraryType : byte
|
||||
{
|
||||
Komga = 0,
|
||||
Kavita = 1
|
||||
}
|
73
API/Schema/LibraryContext/LibraryConnectors/NetClient.cs
Normal file
73
API/Schema/LibraryContext/LibraryConnectors/NetClient.cs
Normal file
@@ -0,0 +1,73 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using log4net;
|
||||
|
||||
namespace API.Schema.LibraryContext.LibraryConnectors;
|
||||
|
||||
public class NetClient
|
||||
{
|
||||
private static ILog Log = LogManager.GetLogger(typeof(NetClient));
|
||||
|
||||
public static Stream MakeRequest(string url, string authScheme, string auth)
|
||||
{
|
||||
Log.Debug($"Requesting {url}");
|
||||
HttpClient client = new();
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, auth);
|
||||
|
||||
HttpRequestMessage requestMessage = new()
|
||||
{
|
||||
Method = HttpMethod.Get,
|
||||
RequestUri = new Uri(url)
|
||||
};
|
||||
try
|
||||
{
|
||||
HttpResponseMessage response = client.Send(requestMessage);
|
||||
|
||||
if (response.StatusCode is HttpStatusCode.Unauthorized &&
|
||||
response.RequestMessage!.RequestUri!.AbsoluteUri != url)
|
||||
return MakeRequest(response.RequestMessage!.RequestUri!.AbsoluteUri, authScheme, auth);
|
||||
else if (response.IsSuccessStatusCode)
|
||||
return response.Content.ReadAsStream();
|
||||
else
|
||||
return Stream.Null;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
switch (e)
|
||||
{
|
||||
case HttpRequestException:
|
||||
Log.Debug(e);
|
||||
break;
|
||||
default:
|
||||
throw;
|
||||
}
|
||||
Log.Info("Failed to make request");
|
||||
return Stream.Null;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool MakePost(string url, string authScheme, string auth)
|
||||
{
|
||||
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);
|
||||
|
||||
if(response.StatusCode is HttpStatusCode.Unauthorized && response.RequestMessage!.RequestUri!.AbsoluteUri != url)
|
||||
return MakePost(response.RequestMessage!.RequestUri!.AbsoluteUri, authScheme, auth);
|
||||
else if (response.IsSuccessStatusCode)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
}
|
18
API/Schema/LibraryContext/LibraryContext.cs
Normal file
18
API/Schema/LibraryContext/LibraryContext.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using API.Schema.LibraryContext.LibraryConnectors;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Schema.LibraryContext;
|
||||
|
||||
public class LibraryContext(DbContextOptions<LibraryContext> options) : TrangaBaseContext<LibraryContext>(options)
|
||||
{
|
||||
public DbSet<LibraryConnector> LibraryConnectors { get; set; }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
//LibraryConnector Types
|
||||
modelBuilder.Entity<LibraryConnector>()
|
||||
.HasDiscriminator(l => l.LibraryType)
|
||||
.HasValue<Komga>(LibraryType.Komga)
|
||||
.HasValue<Kavita>(LibraryType.Kavita);
|
||||
}
|
||||
}
|
17
API/Schema/MangaContext/AltTitle.cs
Normal file
17
API/Schema/MangaContext/AltTitle.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Schema.MangaContext;
|
||||
|
||||
[PrimaryKey("Key")]
|
||||
public class AltTitle(string language, string title) : Identifiable(TokenGen.CreateToken("AltTitle"))
|
||||
{
|
||||
[StringLength(8)]
|
||||
[Required]
|
||||
public string Language { get; init; } = language;
|
||||
[StringLength(256)]
|
||||
[Required]
|
||||
public string Title { get; init; } = title;
|
||||
|
||||
public override string ToString() => $"{base.ToString()} {Language} {Title}";
|
||||
}
|
13
API/Schema/MangaContext/Author.cs
Normal file
13
API/Schema/MangaContext/Author.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Schema.MangaContext;
|
||||
|
||||
[PrimaryKey("Key")]
|
||||
public class Author(string authorName) : Identifiable(TokenGen.CreateToken(typeof(Author), authorName))
|
||||
{
|
||||
[StringLength(128)]
|
||||
public string AuthorName { get; init; } = authorName;
|
||||
|
||||
public override string ToString() => $"{base.ToString()} {AuthorName}";
|
||||
}
|
217
API/Schema/MangaContext/Chapter.cs
Normal file
217
API/Schema/MangaContext/Chapter.cs
Normal file
@@ -0,0 +1,217 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml.Linq;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Schema.MangaContext;
|
||||
|
||||
[PrimaryKey("Key")]
|
||||
public class Chapter : Identifiable, IComparable<Chapter>
|
||||
{
|
||||
[StringLength(64)] public string ParentMangaId { get; init; } = null!;
|
||||
public Manga ParentManga = null!;
|
||||
|
||||
[NotMapped] public Dictionary<string, string> IdsOnMangaConnectors =>
|
||||
MangaConnectorIds.ToDictionary(id => id.MangaConnectorName, id => id.IdOnConnectorSite);
|
||||
public ICollection<MangaConnectorId<Chapter>> MangaConnectorIds = null!;
|
||||
|
||||
public int? VolumeNumber { get; private set; }
|
||||
[StringLength(10)] public string ChapterNumber { get; private set; }
|
||||
|
||||
[StringLength(256)] public string? Title { get; private set; }
|
||||
|
||||
[StringLength(256)] public string FileName { get; private set; }
|
||||
|
||||
public bool Downloaded { get; internal set; }
|
||||
[NotMapped] public string FullArchiveFilePath => Path.Join(ParentManga.FullDirectoryPath, FileName);
|
||||
|
||||
public Chapter(Manga parentManga, string chapterNumber,
|
||||
int? volumeNumber, string? title = null)
|
||||
: base(TokenGen.CreateToken(typeof(Chapter), parentManga.Key, chapterNumber))
|
||||
{
|
||||
this.ParentManga = parentManga;
|
||||
this.MangaConnectorIds = [];
|
||||
this.VolumeNumber = volumeNumber;
|
||||
this.ChapterNumber = chapterNumber;
|
||||
this.Title = title;
|
||||
this.FileName = GetArchiveFilePath();
|
||||
this.Downloaded = false;
|
||||
this.MangaConnectorIds = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EF ONLY!!!
|
||||
/// </summary>
|
||||
internal Chapter(string key, int? volumeNumber, string chapterNumber, string? title, string fileName, bool downloaded)
|
||||
: base(key)
|
||||
{
|
||||
this.VolumeNumber = volumeNumber;
|
||||
this.ChapterNumber = chapterNumber;
|
||||
this.Title = title;
|
||||
this.FileName = fileName;
|
||||
this.Downloaded = downloaded;
|
||||
}
|
||||
|
||||
public int CompareTo(Chapter? other)
|
||||
{
|
||||
if (other is not { } otherChapter)
|
||||
throw new ArgumentException($"{other} can not be compared to {this}");
|
||||
return VolumeNumber?.CompareTo(otherChapter.VolumeNumber) switch
|
||||
{
|
||||
< 0 => -1,
|
||||
> 0 => 1,
|
||||
_ => CompareChapterNumbers(ChapterNumber, otherChapter.ChapterNumber)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Checks the filesystem if an archive at the ArchiveFilePath exists
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <returns>True if archive exists on disk</returns>
|
||||
/// <exception cref="KeyNotFoundException">Unable to load Chapter, Parent or Library</exception>
|
||||
public async Task<bool> CheckDownloaded(MangaContext context, CancellationToken? token = null)
|
||||
{
|
||||
if(await context.Chapters
|
||||
.Include(c => c.ParentManga)
|
||||
.ThenInclude(p => p.Library)
|
||||
.FirstOrDefaultAsync(c => c.Key == this.Key, token??CancellationToken.None) is not { } chapter)
|
||||
throw new KeyNotFoundException("Unable to find chapter");
|
||||
|
||||
//TODO Log here
|
||||
this.Downloaded = File.Exists(chapter.FullArchiveFilePath);
|
||||
await context.Sync(token??CancellationToken.None);
|
||||
return this.Downloaded;
|
||||
}
|
||||
|
||||
/// Placeholders:
|
||||
/// %M Obj Name
|
||||
/// %V Volume
|
||||
/// %C Chapter
|
||||
/// %T Title
|
||||
/// %A Author (first in list)
|
||||
/// %I Chapter Internal ID
|
||||
/// %i Obj Internal ID
|
||||
/// %Y Year (Obj)
|
||||
private static readonly Regex NullableRex = new(@"\?([a-zA-Z])\(([^\)]*)\)|(.+?)");
|
||||
private static readonly Regex ReplaceRexx = new(@"%([a-zA-Z])|(.+?)");
|
||||
private string GetArchiveFilePath()
|
||||
{
|
||||
string archiveNamingScheme = Tranga.Settings.ChapterNamingScheme;
|
||||
StringBuilder stringBuilder = new();
|
||||
foreach (Match nullable in NullableRex.Matches(archiveNamingScheme))
|
||||
{
|
||||
if (nullable.Groups[3].Success)
|
||||
{
|
||||
stringBuilder.Append(nullable.Groups[3].Value);
|
||||
continue;
|
||||
}
|
||||
|
||||
char placeholder = nullable.Groups[1].Value[0];
|
||||
bool isNull = placeholder switch
|
||||
{
|
||||
'M' => ParentManga?.Name is null,
|
||||
'V' => VolumeNumber is null,
|
||||
'C' => ChapterNumber is null,
|
||||
'T' => Title is null,
|
||||
'A' => ParentManga?.Authors?.FirstOrDefault()?.AuthorName is null,
|
||||
'Y' => ParentManga?.Year is null,
|
||||
_ => true
|
||||
};
|
||||
if(!isNull)
|
||||
stringBuilder.Append(nullable.Groups[2].Value);
|
||||
}
|
||||
|
||||
string checkedString = stringBuilder.ToString();
|
||||
stringBuilder = new();
|
||||
|
||||
foreach (Match replace in ReplaceRexx.Matches(checkedString))
|
||||
{
|
||||
if (replace.Groups[2].Success)
|
||||
{
|
||||
stringBuilder.Append(replace.Groups[2].Value);
|
||||
continue;
|
||||
}
|
||||
|
||||
char placeholder = replace.Groups[1].Value[0];
|
||||
string? value = placeholder switch
|
||||
{
|
||||
'M' => ParentManga?.Name,
|
||||
'V' => VolumeNumber?.ToString(),
|
||||
'C' => ChapterNumber,
|
||||
'T' => Title,
|
||||
'A' => ParentManga?.Authors?.FirstOrDefault()?.AuthorName,
|
||||
'Y' => ParentManga?.Year.ToString(),
|
||||
_ => null
|
||||
};
|
||||
stringBuilder.Append(value);
|
||||
}
|
||||
|
||||
stringBuilder.Append(".cbz");
|
||||
|
||||
return stringBuilder.ToString();
|
||||
}
|
||||
|
||||
public class ChapterComparer : IComparer<Chapter>
|
||||
{
|
||||
public int Compare(Chapter? x, Chapter? y)
|
||||
{
|
||||
if (x is null && y is null)
|
||||
return 0;
|
||||
if(x is null)
|
||||
return -1;
|
||||
if (y is null)
|
||||
return 1;
|
||||
return CompareChapterNumbers(x.ChapterNumber, y.ChapterNumber);
|
||||
}
|
||||
}
|
||||
|
||||
private static int CompareChapterNumbers(string ch1, string ch2)
|
||||
{
|
||||
int[] ch1Arr = ch1.Split('.').Select(c => int.TryParse(c, out int result) ? result : -1).ToArray();
|
||||
int[] ch2Arr = ch2.Split('.').Select(c => int.TryParse(c, out int result) ? result : -1).ToArray();
|
||||
|
||||
if (ch1Arr.Contains(-1) || ch2Arr.Contains(-1))
|
||||
throw new ArgumentException("Chapter number is not in correct format");
|
||||
|
||||
int i = 0, j = 0;
|
||||
|
||||
while (i < ch1Arr.Length && j < ch2Arr.Length)
|
||||
{
|
||||
if (ch1Arr[i] < ch2Arr[j])
|
||||
return -1;
|
||||
if (ch1Arr[i] > ch2Arr[j])
|
||||
return 1;
|
||||
i++;
|
||||
j++;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal string GetComicInfoXmlString()
|
||||
{
|
||||
XElement comicInfo = new("ComicInfo",
|
||||
new XElement("Number", ChapterNumber)
|
||||
);
|
||||
if(Title is not null)
|
||||
comicInfo.Add(new XElement("Title", Title));
|
||||
if(ParentManga.MangaTags.Count > 0)
|
||||
comicInfo.Add(new XElement("Tags", string.Join(',', ParentManga.MangaTags.Select(tag => tag.Tag))));
|
||||
if(VolumeNumber is not null)
|
||||
comicInfo.Add(new XElement("Volume", VolumeNumber));
|
||||
if(ParentManga.Authors.Count > 0)
|
||||
comicInfo.Add(new XElement("Writer", string.Join(',', ParentManga.Authors.Select(author => author.AuthorName))));
|
||||
if(ParentManga.OriginalLanguage is not null)
|
||||
comicInfo.Add(new XElement("LanguageISO", ParentManga.OriginalLanguage));
|
||||
if(ParentManga.Description != string.Empty)
|
||||
comicInfo.Add(new XElement("Summary", ParentManga.Description));
|
||||
return comicInfo.ToString();
|
||||
}
|
||||
|
||||
public override string ToString() => $"{base.ToString()} Vol.{VolumeNumber} Ch.{ChapterNumber} - {Title}";
|
||||
}
|
15
API/Schema/MangaContext/FileLibrary.cs
Normal file
15
API/Schema/MangaContext/FileLibrary.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Schema.MangaContext;
|
||||
|
||||
[PrimaryKey("Key")]
|
||||
public class FileLibrary(string basePath, string libraryName)
|
||||
: Identifiable(TokenGen.CreateToken(typeof(FileLibrary), basePath))
|
||||
{
|
||||
[StringLength(256)] public string BasePath { get; internal set; } = basePath;
|
||||
|
||||
[StringLength(512)] public string LibraryName { get; internal set; } = libraryName;
|
||||
|
||||
public override string ToString() => $"{base.ToString()} {LibraryName} - {BasePath}";
|
||||
}
|
16
API/Schema/MangaContext/Link.cs
Normal file
16
API/Schema/MangaContext/Link.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Schema.MangaContext;
|
||||
|
||||
[PrimaryKey("Key")]
|
||||
public class Link(string linkProvider, string linkUrl) : Identifiable(TokenGen.CreateToken(typeof(Link), linkProvider, linkUrl))
|
||||
{
|
||||
[StringLength(64)]
|
||||
public string LinkProvider { get; init; } = linkProvider;
|
||||
[StringLength(2048)]
|
||||
[Url]
|
||||
public string LinkUrl { get; init; } = linkUrl;
|
||||
|
||||
public override string ToString() => $"{base.ToString()} {LinkProvider} {LinkUrl}";
|
||||
}
|
184
API/Schema/MangaContext/Manga.cs
Normal file
184
API/Schema/MangaContext/Manga.cs
Normal file
@@ -0,0 +1,184 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using API.Workers;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.Formats.Jpeg;
|
||||
using SixLabors.ImageSharp.Processing;
|
||||
using SixLabors.ImageSharp.Processing.Processors.Transforms;
|
||||
using static System.IO.UnixFileMode;
|
||||
|
||||
namespace API.Schema.MangaContext;
|
||||
|
||||
[PrimaryKey("Key")]
|
||||
public class Manga : Identifiable
|
||||
{
|
||||
[StringLength(512)] public string Name { get; internal set; }
|
||||
[Required] public string Description { get; internal set; }
|
||||
[Url] [StringLength(512)] public string CoverUrl { get; internal set; }
|
||||
public MangaReleaseStatus ReleaseStatus { get; internal set; }
|
||||
[StringLength(64)] public string? LibraryId { get; private set; }
|
||||
public FileLibrary? Library = null!;
|
||||
|
||||
public ICollection<Author> Authors { get; internal set; } = null!;
|
||||
public ICollection<MangaTag> MangaTags { get; internal set; } = null!;
|
||||
public ICollection<Link> Links { get; internal set; } = null!;
|
||||
public ICollection<AltTitle> AltTitles { get; internal set; } = null!;
|
||||
public float IgnoreChaptersBefore { get; internal set; }
|
||||
[StringLength(1024)] [Required] public string DirectoryName { get; private set; }
|
||||
[StringLength(512)] public string? CoverFileNameInCache { get; internal set; }
|
||||
public uint? Year { get; internal init; }
|
||||
[StringLength(8)] public string? OriginalLanguage { get; internal init; }
|
||||
|
||||
[NotMapped] public string? FullDirectoryPath => Library is not null ? Path.Join(Library.BasePath, DirectoryName) : null;
|
||||
|
||||
[NotMapped] public ICollection<string> ChapterIds => Chapters.Select(c => c.Key).ToList();
|
||||
public ICollection<Chapter> Chapters = null!;
|
||||
|
||||
[NotMapped] public Dictionary<string, string> IdsOnMangaConnectors => MangaConnectorIds.ToDictionary(id => id.MangaConnectorName, id => id.IdOnConnectorSite);
|
||||
[NotMapped] public ICollection<string> MangaConnectorIdsIds => MangaConnectorIds.Select(id => id.Key).ToList();
|
||||
public ICollection<MangaConnectorId<Manga>> MangaConnectorIds = null!;
|
||||
|
||||
public Manga(string name, string description, string coverUrl, MangaReleaseStatus releaseStatus,
|
||||
ICollection<Author> authors, ICollection<MangaTag> mangaTags, ICollection<Link> links, ICollection<AltTitle> altTitles,
|
||||
FileLibrary? library = null, float ignoreChaptersBefore = 0f, uint? year = null, string? originalLanguage = null)
|
||||
:base(TokenGen.CreateToken(typeof(Manga), name))
|
||||
{
|
||||
this.Name = name;
|
||||
this.Description = description;
|
||||
this.CoverUrl = coverUrl;
|
||||
this.ReleaseStatus = releaseStatus;
|
||||
this.Library = library;
|
||||
this.Authors = authors;
|
||||
this.MangaTags = mangaTags;
|
||||
this.Links = links;
|
||||
this.AltTitles = altTitles;
|
||||
this.IgnoreChaptersBefore = ignoreChaptersBefore;
|
||||
this.DirectoryName = CleanDirectoryName(name);
|
||||
this.Year = year;
|
||||
this.OriginalLanguage = originalLanguage;
|
||||
this.Chapters = [];
|
||||
this.MangaConnectorIds = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EF ONLY!!!
|
||||
/// </summary>
|
||||
public Manga(string key, string name, string description, string coverUrl,
|
||||
MangaReleaseStatus releaseStatus,
|
||||
string directoryName, float ignoreChaptersBefore, string? libraryId, uint? year, string? originalLanguage)
|
||||
: base(key)
|
||||
{
|
||||
this.Name = name;
|
||||
this.Description = description;
|
||||
this.CoverUrl = coverUrl;
|
||||
this.ReleaseStatus = releaseStatus;
|
||||
this.DirectoryName = directoryName;
|
||||
this.LibraryId = libraryId;
|
||||
this.IgnoreChaptersBefore = ignoreChaptersBefore;
|
||||
this.Year = year;
|
||||
this.OriginalLanguage = originalLanguage;
|
||||
}
|
||||
|
||||
|
||||
public string CreatePublicationFolder()
|
||||
{
|
||||
string? publicationFolder = FullDirectoryPath;
|
||||
if (publicationFolder is null)
|
||||
throw new DirectoryNotFoundException("Publication folder not found");
|
||||
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;
|
||||
}
|
||||
|
||||
//https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file
|
||||
//less than 32 is control *forbidden*
|
||||
//34 is " *forbidden*
|
||||
//42 is * *forbidden*
|
||||
//47 is / *forbidden*
|
||||
//58 is : *forbidden*
|
||||
//60 is < *forbidden*
|
||||
//62 is > *forbidden*
|
||||
//63 is ? *forbidden*
|
||||
//92 is \ *forbidden*
|
||||
//124 is | *forbidden*
|
||||
//127 is delete *forbidden*
|
||||
//Below 127 all except *******
|
||||
private static readonly int[] ForbiddenCharsBelow127 = [34, 42, 47, 58, 60, 62, 63, 92, 124, 127];
|
||||
//Above 127 none except *******
|
||||
private static readonly int[] IncludeCharsAbove127 = [128, 138, 142];
|
||||
//128 is € include
|
||||
//138 is Š include
|
||||
//142 is Ž include
|
||||
//152 through 255 looks fine except 157, 172, 173, 175 *******
|
||||
private static readonly int[] ForbiddenCharsAbove152 = [157, 172, 173, 175];
|
||||
private static string CleanDirectoryName(string name)
|
||||
{
|
||||
StringBuilder sb = new ();
|
||||
foreach (char c in name)
|
||||
{
|
||||
if (c >= 32 && c < 127 && ForbiddenCharsBelow127.Contains(c) == false)
|
||||
sb.Append(c);
|
||||
else if (c > 127 && c < 152 && IncludeCharsAbove127.Contains(c))
|
||||
sb.Append(c);
|
||||
else if(c >= 152 && c <= 255 && ForbiddenCharsAbove152.Contains(c) == false)
|
||||
sb.Append(c);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Merges another Manga (MangaConnectorIds and Chapters)
|
||||
/// </summary>
|
||||
/// <param name="other">The other <see cref="Manga" /> to merge</param>
|
||||
/// <param name="context"><see cref="MangaContext"/> to use for Database operations</param>
|
||||
/// <returns>An array of <see cref="MoveFileOrFolderWorker"/> for moving <see cref="Chapter"/> to new Directory</returns>
|
||||
public BaseWorker[] MergeFrom(Manga other, MangaContext context)
|
||||
{
|
||||
context.Mangas.Remove(other);
|
||||
List<BaseWorker> newJobs = new();
|
||||
|
||||
this.MangaConnectorIds = this.MangaConnectorIds
|
||||
.UnionBy(other.MangaConnectorIds, id => id.MangaConnectorName)
|
||||
.ToList();
|
||||
|
||||
foreach (Chapter otherChapter in other.Chapters)
|
||||
{
|
||||
string oldPath = otherChapter.FullArchiveFilePath;
|
||||
Chapter newChapter = new(this, otherChapter.ChapterNumber, otherChapter.VolumeNumber,
|
||||
otherChapter.Title);
|
||||
this.Chapters.Add(newChapter);
|
||||
string newPath = newChapter.FullArchiveFilePath;
|
||||
newJobs.Add(new MoveFileOrFolderWorker(newPath, oldPath));
|
||||
}
|
||||
|
||||
return newJobs.ToArray();
|
||||
}
|
||||
|
||||
public async Task<(MemoryStream stream, FileInfo fileInfo)?> GetCoverImage(string cachePath, CancellationToken ct)
|
||||
{
|
||||
string fullPath = Path.Join(cachePath, CoverFileNameInCache);
|
||||
if (!File.Exists(fullPath))
|
||||
return null;
|
||||
|
||||
FileInfo fileInfo = new(fullPath);
|
||||
MemoryStream stream = new (await File.ReadAllBytesAsync(fullPath, ct));
|
||||
|
||||
return (stream, fileInfo);
|
||||
}
|
||||
|
||||
public override string ToString() => $"{base.ToString()} {Name}";
|
||||
}
|
||||
|
||||
public enum MangaReleaseStatus : byte
|
||||
{
|
||||
Continuing = 0,
|
||||
Completed = 1,
|
||||
OnHiatus = 2,
|
||||
Cancelled = 3,
|
||||
Unreleased = 4
|
||||
}
|
44
API/Schema/MangaContext/MangaConnectorId.cs
Normal file
44
API/Schema/MangaContext/MangaConnectorId.cs
Normal file
@@ -0,0 +1,44 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using API.MangaConnectors;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Schema.MangaContext;
|
||||
|
||||
[PrimaryKey("Key")]
|
||||
public class MangaConnectorId<T> : Identifiable where T : Identifiable
|
||||
{
|
||||
public T Obj = null!;
|
||||
[StringLength(64)] public string ObjId { get; internal set; }
|
||||
|
||||
[StringLength(32)] public string MangaConnectorName { get; private set; }
|
||||
|
||||
[StringLength(256)] public string IdOnConnectorSite { get; init; }
|
||||
[Url] [StringLength(512)] public string? WebsiteUrl { get; internal init; }
|
||||
public bool UseForDownload { get; internal set; }
|
||||
|
||||
public MangaConnectorId(T obj, MangaConnector mangaConnector, string idOnConnectorSite, string? websiteUrl, bool useForDownload = false)
|
||||
: base(TokenGen.CreateToken(typeof(MangaConnectorId<T>), mangaConnector.Name, idOnConnectorSite))
|
||||
{
|
||||
this.Obj = obj;
|
||||
this.ObjId = obj.Key;
|
||||
this.MangaConnectorName = mangaConnector.Name;
|
||||
this.IdOnConnectorSite = idOnConnectorSite;
|
||||
this.WebsiteUrl = websiteUrl;
|
||||
this.UseForDownload = useForDownload;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EF CORE ONLY!!!
|
||||
/// </summary>
|
||||
public MangaConnectorId(string key, string objId, string mangaConnectorName, string idOnConnectorSite, bool useForDownload, string? websiteUrl)
|
||||
: base(key)
|
||||
{
|
||||
this.ObjId = objId;
|
||||
this.MangaConnectorName = mangaConnectorName;
|
||||
this.IdOnConnectorSite = idOnConnectorSite;
|
||||
this.WebsiteUrl = websiteUrl;
|
||||
this.UseForDownload = useForDownload;
|
||||
}
|
||||
|
||||
public override string ToString() => $"{base.ToString()} {Obj}";
|
||||
}
|
127
API/Schema/MangaContext/MangaContext.cs
Normal file
127
API/Schema/MangaContext/MangaContext.cs
Normal file
@@ -0,0 +1,127 @@
|
||||
using API.MangaConnectors;
|
||||
using API.Schema.MangaContext.MetadataFetchers;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Query;
|
||||
|
||||
namespace API.Schema.MangaContext;
|
||||
|
||||
public class MangaContext(DbContextOptions<MangaContext> options) : TrangaBaseContext<MangaContext>(options)
|
||||
{
|
||||
public DbSet<Manga> Mangas { get; set; }
|
||||
public DbSet<FileLibrary> FileLibraries { get; set; }
|
||||
public DbSet<Chapter> Chapters { get; set; }
|
||||
public DbSet<Author> Authors { get; set; }
|
||||
public DbSet<MangaTag> Tags { get; set; }
|
||||
public DbSet<MangaConnectorId<Manga>> MangaConnectorToManga { get; set; }
|
||||
public DbSet<MangaConnectorId<Chapter>> MangaConnectorToChapter { get; set; }
|
||||
public DbSet<MetadataEntry> MetadataEntries { get; set; }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
//MangaConnector Types
|
||||
modelBuilder.Entity<MangaConnector>()
|
||||
.HasDiscriminator(c => c.Name)
|
||||
.HasValue<Global>("Global")
|
||||
.HasValue<MangaDex>("MangaDex")
|
||||
.HasValue<ComickIo>("ComickIo");
|
||||
|
||||
//Manga has many Chapters
|
||||
modelBuilder.Entity<Manga>()
|
||||
.HasMany<Chapter>(m => m.Chapters)
|
||||
.WithOne(c => c.ParentManga)
|
||||
.HasForeignKey(c => c.ParentMangaId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
//Chapter has MangaConnectorIds
|
||||
modelBuilder.Entity<Chapter>()
|
||||
.HasMany<MangaConnectorId<Chapter>>(c => c.MangaConnectorIds)
|
||||
.WithOne(id => id.Obj)
|
||||
.HasForeignKey(id => id.ObjId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
//Manga owns MangaAltTitles
|
||||
modelBuilder.Entity<Manga>()
|
||||
.OwnsMany<AltTitle>(m => m.AltTitles)
|
||||
.WithOwner();
|
||||
modelBuilder.Entity<Manga>()
|
||||
.Navigation(m => m.AltTitles)
|
||||
.AutoInclude();
|
||||
//Manga owns Links
|
||||
modelBuilder.Entity<Manga>()
|
||||
.OwnsMany<Link>(m => m.Links)
|
||||
.WithOwner();
|
||||
modelBuilder.Entity<Manga>()
|
||||
.Navigation(m => m.Links)
|
||||
.AutoInclude();
|
||||
//Manga has many Tags associated with many Obj
|
||||
modelBuilder.Entity<Manga>()
|
||||
.HasMany<MangaTag>(m => m.MangaTags)
|
||||
.WithMany()
|
||||
.UsingEntity("MangaTagToManga",
|
||||
l=> l.HasOne(typeof(MangaTag)).WithMany().HasForeignKey("MangaTagIds").HasPrincipalKey(nameof(MangaTag.Tag)),
|
||||
r => r.HasOne(typeof(Manga)).WithMany().HasForeignKey("MangaIds").HasPrincipalKey(nameof(Manga.Key)),
|
||||
j => j.HasKey("MangaTagIds", "MangaIds")
|
||||
);
|
||||
modelBuilder.Entity<Manga>()
|
||||
.Navigation(m => m.MangaTags)
|
||||
.AutoInclude();
|
||||
//Manga has many Authors associated with many Obj
|
||||
modelBuilder.Entity<Manga>()
|
||||
.HasMany<Author>(m => m.Authors)
|
||||
.WithMany()
|
||||
.UsingEntity("AuthorToManga",
|
||||
l=> l.HasOne(typeof(Author)).WithMany().HasForeignKey("AuthorIds").HasPrincipalKey(nameof(Author.Key)),
|
||||
r => r.HasOne(typeof(Manga)).WithMany().HasForeignKey("MangaIds").HasPrincipalKey(nameof(Manga.Key)),
|
||||
j => j.HasKey("AuthorIds", "MangaIds")
|
||||
);
|
||||
modelBuilder.Entity<Manga>()
|
||||
.Navigation(m => m.Authors)
|
||||
.AutoInclude();
|
||||
//Manga has many MangaIds
|
||||
modelBuilder.Entity<Manga>()
|
||||
.HasMany<MangaConnectorId<Manga>>(m => m.MangaConnectorIds)
|
||||
.WithOne(id => id.Obj)
|
||||
.HasForeignKey(id => id.ObjId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
|
||||
//FileLibrary has many Mangas
|
||||
modelBuilder.Entity<FileLibrary>()
|
||||
.HasMany<Manga>()
|
||||
.WithOne(m => m.Library)
|
||||
.HasForeignKey(m => m.LibraryId)
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
modelBuilder.Entity<MetadataFetcher>()
|
||||
.HasDiscriminator<string>(nameof(MetadataEntry))
|
||||
.HasValue<MyAnimeList>(nameof(MyAnimeList));
|
||||
//MetadataEntry
|
||||
modelBuilder.Entity<MetadataEntry>()
|
||||
.HasOne<Manga>(entry => entry.Manga)
|
||||
.WithMany()
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
modelBuilder.Entity<MetadataEntry>()
|
||||
.HasOne<MetadataFetcher>(entry => entry.MetadataFetcher)
|
||||
.WithMany()
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
|
||||
public async Task<Manga?> FindMangaLike(Manga other, CancellationToken token)
|
||||
{
|
||||
if (await MangaIncludeAll().FirstOrDefaultAsync(m => m.Key == other.Key, token) is { } f)
|
||||
return f;
|
||||
|
||||
return await MangaIncludeAll()
|
||||
.FirstOrDefaultAsync(m =>
|
||||
m.Links.Any(l => l.Key == other.Key) ||
|
||||
m.AltTitles.Any(t => other.AltTitles.Select(ot => ot.Title).Any(s => s.Equals(t.Title))), token);
|
||||
}
|
||||
|
||||
public IIncludableQueryable<Manga, ICollection<MangaConnectorId<Manga>>> MangaIncludeAll() =>
|
||||
Mangas
|
||||
.Include(m => m.Library)
|
||||
.Include(m => m.Authors)
|
||||
.Include(m => m.MangaTags)
|
||||
.Include(m => m.Links)
|
||||
.Include(m => m.AltTitles)
|
||||
.Include(m => m.Chapters)
|
||||
.Include(m => m.MangaConnectorIds);
|
||||
}
|
14
API/Schema/MangaContext/MangaTag.cs
Normal file
14
API/Schema/MangaContext/MangaTag.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Schema.MangaContext;
|
||||
|
||||
[PrimaryKey("Tag")]
|
||||
public class MangaTag(string tag)
|
||||
{
|
||||
[StringLength(64)]
|
||||
[Required]
|
||||
public string Tag { get; init; } = tag;
|
||||
|
||||
public override string ToString() => Tag;
|
||||
}
|
37
API/Schema/MangaContext/MetadataFetchers/MetadataEntry.cs
Normal file
37
API/Schema/MangaContext/MetadataFetchers/MetadataEntry.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace API.Schema.MangaContext.MetadataFetchers;
|
||||
|
||||
[PrimaryKey("MetadataFetcherName", "Identifier")]
|
||||
public class MetadataEntry
|
||||
{
|
||||
[JsonIgnore]
|
||||
public Manga Manga { get; init; } = null!;
|
||||
public string MangaId { get; init; }
|
||||
[JsonIgnore]
|
||||
public MetadataFetcher MetadataFetcher { get; init; } = null!;
|
||||
public string MetadataFetcherName { get; init; }
|
||||
public string Identifier { get; init; }
|
||||
|
||||
public MetadataEntry(MetadataFetcher fetcher, Manga manga, string identifier)
|
||||
{
|
||||
this.Manga = manga;
|
||||
this.MangaId = manga.Key;
|
||||
this.MetadataFetcher = fetcher;
|
||||
this.MetadataFetcherName = fetcher.Name;
|
||||
this.Identifier = identifier;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EFCORE only!!!!
|
||||
/// </summary>
|
||||
internal MetadataEntry(string mangaId, string identifier, string metadataFetcherName)
|
||||
{
|
||||
this.MangaId = mangaId;
|
||||
this.Identifier = identifier;
|
||||
this.MetadataFetcherName = metadataFetcherName;
|
||||
}
|
||||
|
||||
public override string ToString() => $"{GetType().FullName} {MangaId} {MetadataFetcherName}";
|
||||
}
|
35
API/Schema/MangaContext/MetadataFetchers/MetadataFetcher.cs
Normal file
35
API/Schema/MangaContext/MetadataFetchers/MetadataFetcher.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Schema.MangaContext.MetadataFetchers;
|
||||
|
||||
[PrimaryKey("Name")]
|
||||
public abstract class MetadataFetcher
|
||||
{
|
||||
// ReSharper disable once EntityFramework.ModelValidation.UnlimitedStringLength
|
||||
public string Name { get; init; }
|
||||
|
||||
protected MetadataFetcher()
|
||||
{
|
||||
this.Name = this.GetType().Name;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EFCORE ONLY!!!
|
||||
/// </summary>
|
||||
internal MetadataFetcher(string name)
|
||||
{
|
||||
this.Name = name;
|
||||
}
|
||||
|
||||
internal MetadataEntry CreateMetadataEntry(Manga manga, string identifier) =>
|
||||
new (this, manga, identifier);
|
||||
|
||||
public abstract MetadataSearchResult[] SearchMetadataEntry(Manga manga);
|
||||
|
||||
public abstract MetadataSearchResult[] SearchMetadataEntry(string searchTerm);
|
||||
|
||||
/// <summary>
|
||||
/// Updates the Manga linked in the MetadataEntry
|
||||
/// </summary>
|
||||
public abstract Task UpdateMetadata(MetadataEntry metadataEntry, MangaContext dbContext, CancellationToken token);
|
||||
}
|
@@ -0,0 +1,3 @@
|
||||
namespace API.Schema.MangaContext.MetadataFetchers;
|
||||
|
||||
public record MetadataSearchResult(string Identifier, string Name, string Url, string? Description = null, string? CoverUrl = null);
|
91
API/Schema/MangaContext/MetadataFetchers/MyAnimeList.cs
Normal file
91
API/Schema/MangaContext/MetadataFetchers/MyAnimeList.cs
Normal file
@@ -0,0 +1,91 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using JikanDotNet;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
|
||||
namespace API.Schema.MangaContext.MetadataFetchers;
|
||||
|
||||
public class MyAnimeList : MetadataFetcher
|
||||
{
|
||||
private static readonly Jikan Jikan = new ();
|
||||
private static readonly Regex GetIdFromUrl = new(@"https?:\/\/myanimelist\.net\/manga\/([0-9]+)\/?.*");
|
||||
|
||||
public override MetadataSearchResult[] SearchMetadataEntry(Manga manga)
|
||||
{
|
||||
if (manga.Links.Any(link => link.LinkProvider.Equals("MyAnimeList", StringComparison.InvariantCultureIgnoreCase)))
|
||||
{
|
||||
string url = manga.Links.First(link => link.LinkProvider.Equals("MyAnimeList", StringComparison.InvariantCultureIgnoreCase)).LinkUrl;
|
||||
Match m = GetIdFromUrl.Match(url);
|
||||
if (m.Success && m.Groups[1].Success)
|
||||
{
|
||||
long id = long.Parse(m.Groups[1].Value);
|
||||
JikanDotNet.Manga data = Jikan.GetMangaAsync(id).Result.Data;
|
||||
return [new MetadataSearchResult(id.ToString(), data.Titles.First().Title, data.Url, data.Synopsis)];
|
||||
}
|
||||
}
|
||||
|
||||
return SearchMetadataEntry(manga.Name);
|
||||
}
|
||||
|
||||
public override MetadataSearchResult[] SearchMetadataEntry(string searchTerm)
|
||||
{
|
||||
|
||||
ICollection<JikanDotNet.Manga> resultData = Jikan.SearchMangaAsync(searchTerm).Result.Data;
|
||||
if (resultData.Count < 1)
|
||||
return [];
|
||||
return resultData.Select(data =>
|
||||
new MetadataSearchResult(data.MalId.ToString(), data.Titles.First().Title, data.Url, data.Synopsis))
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the Manga linked in the MetadataEntry
|
||||
/// </summary>
|
||||
/// <param name="metadataEntry"></param>
|
||||
/// <param name="dbContext"></param>
|
||||
/// <param name="token"></param>
|
||||
/// <exception cref="FormatException"></exception>
|
||||
/// <exception cref="DbUpdateException"></exception>
|
||||
public override async Task UpdateMetadata(MetadataEntry metadataEntry, MangaContext dbContext, CancellationToken token)
|
||||
{
|
||||
Manga? dbManga = metadataEntry.Manga; //Might be null!
|
||||
if (dbManga is null)
|
||||
{
|
||||
if (await dbContext.Mangas.FirstOrDefaultAsync(m => m.Key == metadataEntry.MangaId, token) is not
|
||||
{ } update)
|
||||
throw new DbUpdateException("Manga not found");
|
||||
dbManga = update;
|
||||
}
|
||||
|
||||
// Load all collections (tags, links, authors)...
|
||||
foreach (CollectionEntry collectionEntry in dbContext.Entry(dbManga).Collections)
|
||||
{
|
||||
if(!collectionEntry.IsLoaded)
|
||||
await collectionEntry.LoadAsync(token);
|
||||
}
|
||||
await dbContext.Entry(dbManga).Reference(m => m.Library).LoadAsync(token);
|
||||
|
||||
MangaFull resultData;
|
||||
try
|
||||
{
|
||||
long id = long.Parse(metadataEntry.Identifier);
|
||||
if(await Jikan.GetMangaFullDataAsync(id, token) is not { } response)
|
||||
throw new DbUpdateException("Manga Data not found");
|
||||
resultData = response.Data;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw new FormatException("ID was not in correct format");
|
||||
}
|
||||
|
||||
dbManga.Name = resultData.Titles.First().Title;
|
||||
dbManga.Description = resultData.Synopsis;
|
||||
dbManga.AltTitles.Clear();
|
||||
dbManga.AltTitles = resultData.Titles.Select(t => new AltTitle(t.Type, t.Title)).ToList();
|
||||
dbManga.Authors.Clear();
|
||||
dbManga.Authors = resultData.Authors.Select(a => new Author(a.Name)).ToList();
|
||||
|
||||
await dbContext.Sync(token);
|
||||
}
|
||||
|
||||
}
|
56
API/Schema/NotificationsContext/Notification.cs
Normal file
56
API/Schema/NotificationsContext/Notification.cs
Normal file
@@ -0,0 +1,56 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Schema.NotificationsContext;
|
||||
|
||||
[PrimaryKey(nameof(Key))]
|
||||
public class Notification : Identifiable
|
||||
{
|
||||
[Required]
|
||||
public NotificationUrgency Urgency { get; init; }
|
||||
|
||||
[StringLength(128)]
|
||||
[Required]
|
||||
public string Title { get; init; }
|
||||
|
||||
[StringLength(512)]
|
||||
[Required]
|
||||
public string Message { get; init; }
|
||||
|
||||
[Required]
|
||||
public DateTime Date { get; init; }
|
||||
|
||||
public bool IsSent { get; internal set; }
|
||||
|
||||
public Notification(string title, string message = "", NotificationUrgency urgency = NotificationUrgency.Normal, DateTime? date = null)
|
||||
: base(TokenGen.CreateToken("Notification"))
|
||||
{
|
||||
this.Title = title;
|
||||
this.Message = message;
|
||||
this.Urgency = urgency;
|
||||
this.Date = date ?? DateTime.UtcNow;
|
||||
this.IsSent = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EF ONLY!!!
|
||||
/// </summary>
|
||||
public Notification(string key, string title, string message, NotificationUrgency urgency, DateTime date, bool isSent)
|
||||
: base(key)
|
||||
{
|
||||
this.Title = title;
|
||||
this.Message = message;
|
||||
this.Urgency = urgency;
|
||||
this.Date = date;
|
||||
this.IsSent = isSent;
|
||||
}
|
||||
|
||||
public override string ToString() => $"{base.ToString()} {Urgency} {Title} {Message}";
|
||||
}
|
||||
|
||||
public enum NotificationUrgency : byte
|
||||
{
|
||||
Low = 1,
|
||||
Normal = 3,
|
||||
High = 5
|
||||
}
|
@@ -0,0 +1,59 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Text;
|
||||
using log4net;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace API.Schema.NotificationsContext.NotificationConnectors;
|
||||
|
||||
[PrimaryKey("Name")]
|
||||
public class NotificationConnector(string name, string url, Dictionary<string, string> headers, string httpMethod, string body)
|
||||
{
|
||||
[StringLength(64)] public string Name { get; init; } = name;
|
||||
|
||||
[StringLength(2048)] [Url] public string Url { get; internal set; } = url;
|
||||
|
||||
[Required] public Dictionary<string, string> Headers { get; internal set; } = headers;
|
||||
|
||||
[StringLength(8)] public string HttpMethod { get; internal set; } = httpMethod;
|
||||
|
||||
[StringLength(4096)] public string Body { get; internal set; } = body;
|
||||
|
||||
[NotMapped] private readonly HttpClient Client = new()
|
||||
{
|
||||
DefaultRequestHeaders = { { "User-Agent", Tranga.Settings.UserAgent } }
|
||||
};
|
||||
|
||||
[JsonIgnore] protected ILog Log = LogManager.GetLogger(name);
|
||||
|
||||
public void SendNotification(string title, string notificationText)
|
||||
{
|
||||
Log.Info($"Sending notification: {title} - {notificationText}");
|
||||
string formattedUrl = FormatStr(Url, title, notificationText);
|
||||
string formattedBody = FormatStr(Body, title, notificationText);
|
||||
Dictionary<string, string> formattedHeaders = Headers.ToDictionary(h => h.Key,
|
||||
h => FormatStr(h.Value, title, notificationText));
|
||||
|
||||
HttpRequestMessage request = new(System.Net.Http.HttpMethod.Parse(HttpMethod), formattedUrl);
|
||||
foreach (var (key, value) in formattedHeaders)
|
||||
request.Headers.Add(key, value);
|
||||
request.Content = new StringContent(formattedBody);
|
||||
request.Content.Headers.ContentType = new ("application/json");
|
||||
Log.Debug($"Request: {request}");
|
||||
|
||||
HttpResponseMessage response = Client.Send(request);
|
||||
Log.Debug($"Response status code: {response.StatusCode} {response.Content.ReadAsStringAsync().Result}");
|
||||
}
|
||||
|
||||
private string FormatStr(string str, string title, string text)
|
||||
{
|
||||
StringBuilder sb = new (str);
|
||||
sb.Replace("%title", title);
|
||||
sb.Replace("%text", text);
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public override string ToString() => $"{GetType().Name} {Name}";
|
||||
}
|
10
API/Schema/NotificationsContext/NotificationsContext.cs
Normal file
10
API/Schema/NotificationsContext/NotificationsContext.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
using API.Schema.NotificationsContext.NotificationConnectors;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Schema.NotificationsContext;
|
||||
|
||||
public class NotificationsContext(DbContextOptions<NotificationsContext> options) : TrangaBaseContext<NotificationsContext>(options)
|
||||
{
|
||||
public DbSet<NotificationConnector> NotificationConnectors { get; set; }
|
||||
public DbSet<Notification> Notifications { get; set; }
|
||||
}
|
40
API/Schema/TrangaBaseContext.cs
Normal file
40
API/Schema/TrangaBaseContext.cs
Normal file
@@ -0,0 +1,40 @@
|
||||
using log4net;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
|
||||
namespace API.Schema;
|
||||
|
||||
public abstract class TrangaBaseContext<T> : DbContext where T : DbContext
|
||||
{
|
||||
private ILog Log { get; init; }
|
||||
|
||||
protected TrangaBaseContext(DbContextOptions<T> options) : base(options)
|
||||
{
|
||||
this.Log = LogManager.GetLogger(GetType());
|
||||
}
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
base.OnConfiguring(optionsBuilder);
|
||||
optionsBuilder.LogTo(s =>
|
||||
{
|
||||
Log.Debug(s);
|
||||
}, Array.Empty<string>(), LogLevel.Warning, DbContextLoggerOptions.Level | DbContextLoggerOptions.Category | DbContextLoggerOptions.UtcTime);
|
||||
}
|
||||
|
||||
internal async Task<(bool success, string? exceptionMessage)> Sync(CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
await this.SaveChangesAsync(token);
|
||||
return (true, null);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Error(null, e);
|
||||
return (false, e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString() => $"{GetType().Name} {typeof(T).Name}";
|
||||
}
|
37
API/TokenGen.cs
Normal file
37
API/TokenGen.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace API;
|
||||
|
||||
public static class TokenGen
|
||||
{
|
||||
public const int MinimumLength = 16;
|
||||
public const int MaximumLength = 64;
|
||||
private const string Chars = "abcdefghijklmnopqrstuvwxyz0123456789";
|
||||
|
||||
public static string CreateToken(Type t, params string[] identifiers) => CreateToken(t.Name, identifiers);
|
||||
|
||||
public static string CreateToken(string prefix, params string[] identifiers)
|
||||
{
|
||||
if (prefix.Length + 1 >= MaximumLength - MinimumLength)
|
||||
throw new ArgumentException("Prefix to long to create Token of meaningful length.");
|
||||
|
||||
int tokenLength = MaximumLength - prefix.Length - 1;
|
||||
|
||||
if (identifiers.Length == 0)
|
||||
{
|
||||
// No identifier, just create a random token
|
||||
byte[] rng = new byte[tokenLength];
|
||||
RandomNumberGenerator.Create().GetBytes(rng);
|
||||
string key = new(rng.Select(b => Chars[b % Chars.Length]).ToArray());
|
||||
key = string.Join('-', prefix, key);
|
||||
return key;
|
||||
}
|
||||
|
||||
// Identifier provided, create a token based on the identifier hashed
|
||||
byte[] hash = MD5.HashData(Encoding.UTF8.GetBytes(string.Join("", identifiers)));
|
||||
string token = Convert.ToHexStringLower(hash);
|
||||
|
||||
return string.Join('-', prefix, token);
|
||||
}
|
||||
}
|
227
API/Tranga.cs
Normal file
227
API/Tranga.cs
Normal file
@@ -0,0 +1,227 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using API.MangaConnectors;
|
||||
using API.Schema.LibraryContext;
|
||||
using API.Schema.MangaContext;
|
||||
using API.Schema.MangaContext.MetadataFetchers;
|
||||
using API.Schema.NotificationsContext;
|
||||
using API.Workers;
|
||||
using API.Workers.MaintenanceWorkers;
|
||||
using log4net;
|
||||
using log4net.Config;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API;
|
||||
|
||||
public static class Tranga
|
||||
{
|
||||
private static IServiceProvider? ServiceProvider;
|
||||
|
||||
private static readonly ILog Log = LogManager.GetLogger(typeof(Tranga));
|
||||
internal static readonly MetadataFetcher[] MetadataFetchers = [new MyAnimeList()];
|
||||
internal static readonly MangaConnector[] MangaConnectors = [new Global(), new MangaDex(), new ComickIo()];
|
||||
internal static TrangaSettings Settings = TrangaSettings.Load();
|
||||
|
||||
internal static readonly UpdateMetadataWorker UpdateMetadataWorker = new ();
|
||||
internal static readonly SendNotificationsWorker SendNotificationsWorker = new();
|
||||
internal static readonly UpdateChaptersDownloadedWorker UpdateChaptersDownloadedWorker = new();
|
||||
internal static readonly CheckForNewChaptersWorker CheckForNewChaptersWorker = new();
|
||||
internal static readonly CleanupMangaCoversWorker CleanupMangaCoversWorker = new();
|
||||
internal static readonly StartNewChapterDownloadsWorker StartNewChapterDownloadsWorker = new();
|
||||
internal static readonly RemoveOldNotificationsWorker RemoveOldNotificationsWorker = new();
|
||||
internal static readonly UpdateCoversWorker UpdateCoversWorker = new();
|
||||
|
||||
internal static void StartLogger(FileInfo loggerConfigFile)
|
||||
{
|
||||
XmlConfigurator.ConfigureAndWatch(loggerConfigFile);
|
||||
Log.Info("Logger Configured.");
|
||||
Log.Info(Constants.TRANGA);
|
||||
}
|
||||
|
||||
internal static void AddDefaultWorkers()
|
||||
{
|
||||
AddWorker(UpdateMetadataWorker);
|
||||
AddWorker(SendNotificationsWorker);
|
||||
AddWorker(UpdateChaptersDownloadedWorker);
|
||||
AddWorker(CheckForNewChaptersWorker);
|
||||
AddWorker(CleanupMangaCoversWorker);
|
||||
AddWorker(StartNewChapterDownloadsWorker);
|
||||
AddWorker(RemoveOldNotificationsWorker);
|
||||
AddWorker(UpdateCoversWorker);
|
||||
}
|
||||
|
||||
internal static void SetServiceProvider(IServiceProvider serviceProvider)
|
||||
{
|
||||
ServiceProvider = serviceProvider;
|
||||
}
|
||||
|
||||
internal static bool TryGetMangaConnector(string name, [NotNullWhen(true)]out MangaConnector? mangaConnector)
|
||||
{
|
||||
mangaConnector =
|
||||
MangaConnectors.FirstOrDefault(c => c.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
|
||||
return mangaConnector != null;
|
||||
}
|
||||
|
||||
internal static readonly ConcurrentDictionary<IPeriodic, Task> PeriodicWorkers = new ();
|
||||
|
||||
public static void AddWorker(BaseWorker worker)
|
||||
{
|
||||
Log.Debug($"Adding Worker {worker}");
|
||||
StartWorker(worker);
|
||||
if(worker is IPeriodic periodic)
|
||||
AddPeriodicWorker(worker, periodic);
|
||||
}
|
||||
|
||||
private static void AddPeriodicWorker(BaseWorker worker, IPeriodic periodic)
|
||||
{
|
||||
Log.Debug($"Adding Periodic {worker}");
|
||||
Task periodicTask = PeriodicTask(worker, periodic);
|
||||
PeriodicWorkers.TryAdd((worker as IPeriodic)!, periodicTask);
|
||||
periodicTask.Start();
|
||||
}
|
||||
|
||||
private static Task PeriodicTask(BaseWorker worker, IPeriodic periodic) => new (() =>
|
||||
{
|
||||
Log.Debug($"Waiting {periodic.Interval} for next run of {worker}");
|
||||
Thread.Sleep(periodic.Interval);
|
||||
StartWorker(worker, RefreshTask(worker, periodic));
|
||||
});
|
||||
|
||||
private static Action RefreshTask(BaseWorker worker, IPeriodic periodic) => () =>
|
||||
{
|
||||
if (worker.State < WorkerExecutionState.Created) //Failed
|
||||
return;
|
||||
Log.Debug($"Refreshing {worker}");
|
||||
Task periodicTask = PeriodicTask(worker, periodic);
|
||||
PeriodicWorkers.AddOrUpdate((worker as IPeriodic)!, periodicTask, (_, _) => periodicTask);
|
||||
periodicTask.Start();
|
||||
};
|
||||
|
||||
public static void AddWorkers(IEnumerable<BaseWorker> workers)
|
||||
{
|
||||
foreach (BaseWorker baseWorker in workers)
|
||||
AddWorker(baseWorker);
|
||||
}
|
||||
|
||||
private static readonly ConcurrentDictionary<BaseWorker, Task<BaseWorker[]>> RunningWorkers = new();
|
||||
public static BaseWorker[] GetRunningWorkers() => RunningWorkers.Keys.ToArray();
|
||||
|
||||
internal static void StartWorker(BaseWorker worker, Action? callback = null)
|
||||
{
|
||||
Log.Debug($"Starting {worker}");
|
||||
if (ServiceProvider is null)
|
||||
{
|
||||
Log.Fatal("ServiceProvider is null");
|
||||
return;
|
||||
}
|
||||
Action afterWorkCallback = AfterWork(worker, callback);
|
||||
|
||||
while (RunningWorkers.Count > Settings.MaxConcurrentWorkers)
|
||||
{
|
||||
Log.Warn($"{worker}: Max worker concurrency reached ({Settings.MaxConcurrentWorkers})! Waiting {Settings.WorkCycleTimeoutMs}ms...");
|
||||
Thread.Sleep(Settings.WorkCycleTimeoutMs);
|
||||
}
|
||||
|
||||
if (worker is BaseWorkerWithContext<MangaContext> mangaContextWorker)
|
||||
{
|
||||
mangaContextWorker.SetScope(ServiceProvider.CreateScope());
|
||||
RunningWorkers.TryAdd(mangaContextWorker, mangaContextWorker.DoWork(afterWorkCallback));
|
||||
}else if (worker is BaseWorkerWithContext<NotificationsContext> notificationContextWorker)
|
||||
{
|
||||
notificationContextWorker.SetScope(ServiceProvider.CreateScope());
|
||||
RunningWorkers.TryAdd(notificationContextWorker, notificationContextWorker.DoWork(afterWorkCallback));
|
||||
}else if (worker is BaseWorkerWithContext<LibraryContext> libraryContextWorker)
|
||||
{
|
||||
libraryContextWorker.SetScope(ServiceProvider.CreateScope());
|
||||
RunningWorkers.TryAdd(libraryContextWorker, libraryContextWorker.DoWork(afterWorkCallback));
|
||||
}else
|
||||
RunningWorkers.TryAdd(worker, worker.DoWork(afterWorkCallback));
|
||||
}
|
||||
|
||||
private static Action AfterWork(BaseWorker worker, Action? callback = null) => () =>
|
||||
{
|
||||
Log.Debug($"AfterWork {worker}");
|
||||
if (RunningWorkers.TryGetValue(worker, out Task<BaseWorker[]>? task))
|
||||
{
|
||||
Log.Debug($"Waiting for Children to exit {worker}");
|
||||
task.Wait();
|
||||
if (task.IsCompleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
BaseWorker[] newWorkers = task.Result;
|
||||
Log.Debug($"{worker} created {newWorkers.Length} new Workers.");
|
||||
AddWorkers(newWorkers);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Error(e);
|
||||
}
|
||||
}else Log.Warn($"Children failed: {worker}");
|
||||
}
|
||||
RunningWorkers.Remove(worker, out _);
|
||||
callback?.Invoke();
|
||||
};
|
||||
|
||||
internal static void StopWorker(BaseWorker worker)
|
||||
{
|
||||
Log.Debug($"Stopping {worker}");
|
||||
if(worker is IPeriodic periodicWorker)
|
||||
PeriodicWorkers.Remove(periodicWorker, out _);
|
||||
worker.Cancel();
|
||||
RunningWorkers.Remove(worker, out _);
|
||||
}
|
||||
|
||||
internal static async Task<bool> AddMangaToContext(this MangaContext context, (Manga, MangaConnectorId<Manga>) addManga, CancellationToken token) =>
|
||||
await AddMangaToContext(context, addManga.Item1, addManga.Item2, token);
|
||||
|
||||
internal static async Task<bool> AddMangaToContext(this MangaContext context, Manga addManga, MangaConnectorId<Manga> addMcId,
|
||||
CancellationToken token)
|
||||
{
|
||||
context.ChangeTracker.Clear();
|
||||
Manga? manga = await context.FindMangaLike(addManga, token);
|
||||
if (manga is not null)
|
||||
{
|
||||
foreach (MangaConnectorId<Manga> mcId in addManga.MangaConnectorIds)
|
||||
{
|
||||
mcId.Obj = manga;
|
||||
mcId.ObjId = manga.Key;
|
||||
}
|
||||
manga.MangaTags = manga.MangaTags.UnionBy(addManga.MangaTags, tag => tag.Tag).ToList();
|
||||
manga.Authors = manga.Authors.UnionBy(addManga.Authors, author => author.Key).ToList();
|
||||
manga.Links = manga.Links.UnionBy(addManga.Links, link => link.Key).ToList();
|
||||
manga.AltTitles = manga.AltTitles.UnionBy(addManga.AltTitles, altTitle => altTitle.Key).ToList();
|
||||
manga.Chapters = manga.Chapters.UnionBy(addManga.Chapters, chapter => chapter.Key).ToList();
|
||||
manga.MangaConnectorIds = manga.MangaConnectorIds.UnionBy(addManga.MangaConnectorIds, id => id.MangaConnectorName).ToList();
|
||||
|
||||
addManga = manga;
|
||||
}
|
||||
else
|
||||
{
|
||||
manga = addManga;
|
||||
IEnumerable<MangaTag> mergedTags = manga.MangaTags.Select(mt =>
|
||||
{
|
||||
MangaTag? inDb = context.Tags.Find(mt.Tag);
|
||||
return inDb ?? mt;
|
||||
});
|
||||
manga.MangaTags = mergedTags.ToList();
|
||||
|
||||
IEnumerable<Author> mergedAuthors = manga.Authors.Select(ma =>
|
||||
{
|
||||
Author? inDb = context.Authors.Find(ma.Key);
|
||||
return inDb ?? ma;
|
||||
});
|
||||
manga.Authors = mergedAuthors.ToList();
|
||||
|
||||
context.Mangas.Add(manga);
|
||||
}
|
||||
|
||||
if (await context.Sync(token) is { success: false })
|
||||
return false;
|
||||
|
||||
DownloadCoverFromMangaconnectorWorker downloadCoverWorker = new (addMcId);
|
||||
AddWorker(downloadCoverWorker);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
125
API/TrangaSettings.cs
Normal file
125
API/TrangaSettings.cs
Normal file
@@ -0,0 +1,125 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using API.MangaDownloadClients;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace API;
|
||||
|
||||
public struct TrangaSettings()
|
||||
{
|
||||
|
||||
[JsonIgnore]
|
||||
public static string workingDirectory => Path.Join(RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "/usr/share" : Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "tranga-api");
|
||||
[JsonIgnore]
|
||||
public static string settingsFilePath => Path.Join(workingDirectory, "settings.json");
|
||||
[JsonIgnore] public static string coverImageCache => Path.Join(workingDirectory, "imageCache");
|
||||
[JsonIgnore] public static string coverImageCacheOriginal => Path.Join(coverImageCache, "original");
|
||||
[JsonIgnore] public static string coverImageCacheLarge => Path.Join(coverImageCache, "large");
|
||||
[JsonIgnore] public static string coverImageCacheMedium => Path.Join(coverImageCache, "medium");
|
||||
[JsonIgnore] public static string coverImageCacheSmall => Path.Join(coverImageCache, "small");
|
||||
public string DownloadLocation => RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "/Manga" : Path.Join(Directory.GetCurrentDirectory(), "Manga");
|
||||
[JsonIgnore]
|
||||
internal static readonly string DefaultUserAgent = $"Tranga/2.0 ({Enum.GetName(Environment.OSVersion.Platform)}; {(Environment.Is64BitOperatingSystem ? "x64" : "")})";
|
||||
public string UserAgent { get; set; } = DefaultUserAgent;
|
||||
public int ImageCompression{ get; set; } = 40;
|
||||
public bool BlackWhiteImages { get; set; } = false;
|
||||
public string FlareSolverrUrl { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// Placeholders:
|
||||
/// %M Obj Name
|
||||
/// %V Volume
|
||||
/// %C Chapter
|
||||
/// %T Title
|
||||
/// %A Author (first in list)
|
||||
/// %I Chapter Internal ID
|
||||
/// %i Obj Internal ID
|
||||
/// %Y Year (Obj)
|
||||
///
|
||||
/// ?_(...) replace _ with a value from above:
|
||||
/// Everything inside the braces will only be added if the value of %_ is not null
|
||||
/// </summary>
|
||||
public string ChapterNamingScheme { get; set; } = "%M - ?V(Vol.%V )Ch.%C?T( - %T)";
|
||||
public int WorkCycleTimeoutMs { get; set; } = 20000;
|
||||
[JsonIgnore]
|
||||
internal static readonly Dictionary<RequestType, int> DefaultRequestLimits = new ()
|
||||
{
|
||||
{RequestType.MangaInfo, 360},
|
||||
{RequestType.MangaDexFeed, 360},
|
||||
{RequestType.MangaDexImage, 60},
|
||||
{RequestType.MangaImage, 240},
|
||||
{RequestType.MangaCover, 60},
|
||||
{RequestType.Default, 360}
|
||||
};
|
||||
public Dictionary<RequestType, int> RequestLimits { get; set; } = DefaultRequestLimits;
|
||||
|
||||
public string DownloadLanguage { get; set; } = "en";
|
||||
|
||||
public int MaxConcurrentDownloads { get; set; } = 5;
|
||||
|
||||
public int MaxConcurrentWorkers { get; set; } = 10;
|
||||
|
||||
public static TrangaSettings Load()
|
||||
{
|
||||
if (!File.Exists(settingsFilePath))
|
||||
new TrangaSettings().Save();
|
||||
return JsonConvert.DeserializeObject<TrangaSettings>(File.ReadAllText(settingsFilePath));
|
||||
}
|
||||
|
||||
public void Save()
|
||||
{
|
||||
File.WriteAllText(settingsFilePath, JsonConvert.SerializeObject(this, Formatting.Indented));
|
||||
}
|
||||
|
||||
public void SetUserAgent(string value)
|
||||
{
|
||||
this.UserAgent = value;
|
||||
Save();
|
||||
}
|
||||
|
||||
public void SetRequestLimit(RequestType type, int value)
|
||||
{
|
||||
this.RequestLimits[type] = value;
|
||||
Save();
|
||||
}
|
||||
|
||||
public void ResetRequestLimits()
|
||||
{
|
||||
this.RequestLimits = DefaultRequestLimits;
|
||||
Save();
|
||||
}
|
||||
|
||||
public void UpdateImageCompression(int value)
|
||||
{
|
||||
this.ImageCompression = value;
|
||||
Save();
|
||||
}
|
||||
|
||||
public void SetBlackWhiteImageEnabled(bool enabled)
|
||||
{
|
||||
this.BlackWhiteImages = enabled;
|
||||
Save();
|
||||
}
|
||||
|
||||
public void SetChapterNamingScheme(string scheme)
|
||||
{
|
||||
this.ChapterNamingScheme = scheme;
|
||||
Save();
|
||||
}
|
||||
|
||||
public void SetFlareSolverrUrl(string url)
|
||||
{
|
||||
this.FlareSolverrUrl = url;
|
||||
Save();
|
||||
}
|
||||
|
||||
public void SetDownloadLanguage(string language)
|
||||
{
|
||||
this.DownloadLanguage = language;
|
||||
Save();
|
||||
}
|
||||
|
||||
public void SetMaxConcurrentDownloads(int value)
|
||||
{
|
||||
this.MaxConcurrentDownloads = value;
|
||||
Save();
|
||||
}
|
||||
}
|
128
API/Workers/BaseWorker.cs
Normal file
128
API/Workers/BaseWorker.cs
Normal file
@@ -0,0 +1,128 @@
|
||||
using API.Schema;
|
||||
using log4net;
|
||||
|
||||
namespace API.Workers;
|
||||
|
||||
public abstract class BaseWorker : Identifiable
|
||||
{
|
||||
/// <summary>
|
||||
/// Workers this Worker depends on being completed before running.
|
||||
/// </summary>
|
||||
private BaseWorker[] DependsOn { get; init; }
|
||||
/// <summary>
|
||||
/// Dependencies and dependencies of dependencies. See also <see cref="DependsOn"/>.
|
||||
/// </summary>
|
||||
internal IEnumerable<BaseWorker> AllDependencies => DependsOn.Select(d => d.AllDependencies).SelectMany(x => x);
|
||||
/// <summary>
|
||||
/// <see cref="AllDependencies"/> and Self.
|
||||
/// </summary>
|
||||
internal IEnumerable<BaseWorker> DependenciesAndSelf => AllDependencies.Append(this);
|
||||
/// <summary>
|
||||
/// <see cref="DependsOn"/> where <see cref="WorkerExecutionState"/> is less than Completed.
|
||||
/// </summary>
|
||||
internal IEnumerable<BaseWorker> MissingDependencies => DependsOn.Where(d => d.State < WorkerExecutionState.Completed);
|
||||
public bool AllDependenciesFulfilled => DependsOn.All(d => d.State >= WorkerExecutionState.Completed);
|
||||
internal WorkerExecutionState State { get; private set; }
|
||||
private CancellationTokenSource _cancellationTokenSource = new ();
|
||||
protected CancellationToken CancellationToken => _cancellationTokenSource.Token;
|
||||
protected ILog Log { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Stops worker, and marks as <see cref="WorkerExecutionState"/>.Cancelled
|
||||
/// </summary>
|
||||
public void Cancel()
|
||||
{
|
||||
Log.Debug($"Cancelled {this}");
|
||||
this.State = WorkerExecutionState.Cancelled;
|
||||
_cancellationTokenSource.Cancel();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops worker, and marks as <see cref="WorkerExecutionState"/>.Failed
|
||||
/// </summary>
|
||||
protected void Fail()
|
||||
{
|
||||
Log.Debug($"Failed {this}");
|
||||
this.State = WorkerExecutionState.Failed;
|
||||
_cancellationTokenSource.Cancel();
|
||||
}
|
||||
|
||||
protected BaseWorker(IEnumerable<BaseWorker>? dependsOn = null)
|
||||
{
|
||||
this.DependsOn = dependsOn?.ToArray() ?? [];
|
||||
this.Log = LogManager.GetLogger(GetType());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets States during worker-run.
|
||||
/// States:
|
||||
/// <list type="bullet">
|
||||
/// <item><see cref="WorkerExecutionState"/>.Waiting when waiting for <see cref="MissingDependencies"/></item>
|
||||
/// <item><see cref="WorkerExecutionState"/>.Running when running</item>
|
||||
/// <item><see cref="WorkerExecutionState"/>.Completed after finished</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// <list type="bullet">
|
||||
/// <item>If <see cref="BaseWorker"/> has <see cref="MissingDependencies"/>, missing dependencies.</item>
|
||||
/// <item>If <see cref="MissingDependencies"/> are <see cref="WorkerExecutionState"/>.Running, itself after waiting for dependencies.</item>
|
||||
/// <item>If <see cref="BaseWorker"/> has run, additional <see cref="BaseWorker"/>.</item>
|
||||
/// </list>
|
||||
/// </returns>
|
||||
public Task<BaseWorker[]> DoWork(Action? callback = null)
|
||||
{
|
||||
// Start the worker
|
||||
Log.Debug($"Checking {this}");
|
||||
this._cancellationTokenSource = new(TimeSpan.FromMinutes(10));
|
||||
this.State = WorkerExecutionState.Waiting;
|
||||
|
||||
// Wait for dependencies, start them if necessary
|
||||
BaseWorker[] missingDependenciesThatNeedStarting = MissingDependencies.Where(d => d.State < WorkerExecutionState.Waiting).ToArray();
|
||||
if(missingDependenciesThatNeedStarting.Any())
|
||||
return new Task<BaseWorker[]>(() => missingDependenciesThatNeedStarting);
|
||||
|
||||
if (MissingDependencies.Any())
|
||||
return new Task<BaseWorker[]>(WaitForDependencies);
|
||||
|
||||
// Run the actual work
|
||||
Log.Info($"Running {this}");
|
||||
DateTime startTime = DateTime.UtcNow;
|
||||
Task<BaseWorker[]> task = new Task<BaseWorker[]>(() => DoWorkInternal().Result);
|
||||
task.GetAwaiter().OnCompleted(Finish(startTime, callback));
|
||||
this.State = WorkerExecutionState.Running;
|
||||
task.Start();
|
||||
return task;
|
||||
}
|
||||
|
||||
private Action Finish(DateTime startTime, Action? callback = null) => () =>
|
||||
{
|
||||
DateTime endTime = DateTime.UtcNow;
|
||||
Log.Info($"Completed {this}\n\t{endTime.Subtract(startTime).TotalMilliseconds} ms");
|
||||
this.State = WorkerExecutionState.Completed;
|
||||
if(this is IPeriodic periodic)
|
||||
periodic.LastExecution = DateTime.UtcNow;
|
||||
callback?.Invoke();
|
||||
};
|
||||
|
||||
protected abstract Task<BaseWorker[]> DoWorkInternal();
|
||||
|
||||
private BaseWorker[] WaitForDependencies()
|
||||
{
|
||||
Log.Info($"Waiting for {MissingDependencies.Count()} Dependencies {this}:\n\t{string.Join("\n\t", MissingDependencies.Select(d => d.ToString()))}");
|
||||
while (_cancellationTokenSource.IsCancellationRequested == false && MissingDependencies.Any())
|
||||
{
|
||||
Thread.Sleep(Tranga.Settings.WorkCycleTimeoutMs);
|
||||
}
|
||||
return [this];
|
||||
}
|
||||
}
|
||||
|
||||
public enum WorkerExecutionState
|
||||
{
|
||||
Failed = 0,
|
||||
Cancelled = 32,
|
||||
Created = 64,
|
||||
Waiting = 96,
|
||||
Running = 128,
|
||||
Completed = 192
|
||||
}
|
24
API/Workers/BaseWorkerWithContext.cs
Normal file
24
API/Workers/BaseWorkerWithContext.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using System.Configuration;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Workers;
|
||||
|
||||
public abstract class BaseWorkerWithContext<T>(IEnumerable<BaseWorker>? dependsOn = null) : BaseWorker(dependsOn) where T : DbContext
|
||||
{
|
||||
protected T DbContext = null!;
|
||||
private IServiceScope? _scope;
|
||||
|
||||
public void SetScope(IServiceScope scope)
|
||||
{
|
||||
this._scope = scope;
|
||||
this.DbContext = scope.ServiceProvider.GetRequiredService<T>();
|
||||
}
|
||||
|
||||
/// <exception cref="ConfigurationErrorsException">Scope has not been set. <see cref="SetScope"/></exception>
|
||||
public new Task<BaseWorker[]> DoWork()
|
||||
{
|
||||
if (DbContext is null)
|
||||
throw new ConfigurationErrorsException("Scope has not been set.");
|
||||
return base.DoWork();
|
||||
}
|
||||
}
|
9
API/Workers/IPeriodic.cs
Normal file
9
API/Workers/IPeriodic.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace API.Workers;
|
||||
|
||||
public interface IPeriodic
|
||||
{
|
||||
internal DateTime LastExecution { get; set; }
|
||||
public TimeSpan Interval { get; set; }
|
||||
public DateTime NextExecution => LastExecution.Add(Interval);
|
||||
public bool IsDue => NextExecution <= DateTime.UtcNow;
|
||||
}
|
@@ -0,0 +1,236 @@
|
||||
using System.IO.Compression;
|
||||
using System.Runtime.InteropServices;
|
||||
using API.MangaConnectors;
|
||||
using API.MangaDownloadClients;
|
||||
using API.Schema.MangaContext;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.Formats.Jpeg;
|
||||
using SixLabors.ImageSharp.Processing;
|
||||
using SixLabors.ImageSharp.Processing.Processors.Binarization;
|
||||
using static System.IO.UnixFileMode;
|
||||
|
||||
namespace API.Workers;
|
||||
|
||||
/// <summary>
|
||||
/// Downloads single chapter for Manga from Mangaconnector
|
||||
/// </summary>
|
||||
/// <param name="chId"></param>
|
||||
/// <param name="dependsOn"></param>
|
||||
public class DownloadChapterFromMangaconnectorWorker(MangaConnectorId<Chapter> chId, IEnumerable<BaseWorker>? dependsOn = null)
|
||||
: BaseWorkerWithContext<MangaContext>(dependsOn)
|
||||
{
|
||||
internal readonly string MangaConnectorIdId = chId.Key;
|
||||
protected override async Task<BaseWorker[]> DoWorkInternal()
|
||||
{
|
||||
Log.Debug($"Downloading chapter for MangaConnectorId {MangaConnectorIdId}...");
|
||||
// Getting MangaConnector info
|
||||
if (await DbContext.MangaConnectorToChapter
|
||||
.Include(id => id.Obj)
|
||||
.ThenInclude(c => c.ParentManga)
|
||||
.ThenInclude(m => m.Library)
|
||||
.FirstOrDefaultAsync(c => c.Key == MangaConnectorIdId, CancellationToken) is not { } mangaConnectorId)
|
||||
{
|
||||
Log.Error("Could not get MangaConnectorId.");
|
||||
return []; //TODO Exception?
|
||||
}
|
||||
|
||||
// Check if Chapter already exists...
|
||||
if (await mangaConnectorId.Obj.CheckDownloaded(DbContext, CancellationToken))
|
||||
{
|
||||
Log.Warn("Chapter already exists!");
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!Tranga.TryGetMangaConnector(mangaConnectorId.MangaConnectorName, out MangaConnector? mangaConnector))
|
||||
{
|
||||
Log.Error("Could not get MangaConnector.");
|
||||
return []; //TODO Exception?
|
||||
}
|
||||
Log.Debug($"Downloading chapter for MangaConnectorId {mangaConnectorId}...");
|
||||
|
||||
Chapter chapter = mangaConnectorId.Obj;
|
||||
if (chapter.Downloaded)
|
||||
{
|
||||
Log.Info("Chapter was already downloaded.");
|
||||
return [];
|
||||
}
|
||||
if (chapter.ParentManga.LibraryId is null)
|
||||
{
|
||||
Log.Info($"Library is not set for {chapter.ParentManga} {chapter}");
|
||||
return [];
|
||||
}
|
||||
|
||||
string[] imageUrls = mangaConnector.GetChapterImageUrls(mangaConnectorId);
|
||||
if (imageUrls.Length < 1)
|
||||
{
|
||||
Log.Info($"No imageUrls for chapter {chapter}");
|
||||
mangaConnectorId.UseForDownload = false; // Do not try to download from this again
|
||||
if(await DbContext.Sync(CancellationToken) is { success: false } result)
|
||||
Log.Error(result.exceptionMessage);
|
||||
return [];
|
||||
}
|
||||
string saveArchiveFilePath = chapter.FullArchiveFilePath;
|
||||
Log.Debug($"Chapter path: {saveArchiveFilePath}");
|
||||
|
||||
//Check if Publication Directory already exists
|
||||
string? directoryPath = Path.GetDirectoryName(saveArchiveFilePath);
|
||||
if (directoryPath is null)
|
||||
{
|
||||
Log.Error($"Directory path could not be found: {saveArchiveFilePath}");
|
||||
this.Fail();
|
||||
return [];
|
||||
}
|
||||
if (!Directory.Exists(directoryPath))
|
||||
{
|
||||
Log.Info($"Creating publication Directory: {directoryPath}");
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
Directory.CreateDirectory(directoryPath,
|
||||
UserRead | UserWrite | UserExecute | GroupRead | GroupWrite | GroupExecute );
|
||||
else
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
}
|
||||
|
||||
if (File.Exists(saveArchiveFilePath)) //Don't download twice. Redownload
|
||||
{
|
||||
Log.Info($"Archive {saveArchiveFilePath} already existed, but deleting and re-downloading.");
|
||||
File.Delete(saveArchiveFilePath);
|
||||
}
|
||||
|
||||
//Create a temporary folder to store images
|
||||
string tempFolder = Directory.CreateTempSubdirectory("trangatemp").FullName;
|
||||
Log.Debug($"Created temp folder: {tempFolder}");
|
||||
|
||||
Log.Info($"Downloading images: {chapter}");
|
||||
int chapterNum = 0;
|
||||
//Download all Images to temporary Folder
|
||||
foreach (string imageUrl in imageUrls)
|
||||
{
|
||||
string extension = imageUrl.Split('.')[^1].Split('?')[0];
|
||||
string imagePath = Path.Join(tempFolder, $"{chapterNum++}.{extension}");
|
||||
bool status = DownloadImage(imageUrl, imagePath);
|
||||
if (status is false)
|
||||
{
|
||||
Log.Error($"Failed to download image: {imageUrl}");
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
await CopyCoverFromCacheToDownloadLocation(chapter.ParentManga);
|
||||
|
||||
Log.Debug($"Creating ComicInfo.xml {chapter}");
|
||||
foreach (CollectionEntry collectionEntry in DbContext.Entry(chapter.ParentManga).Collections)
|
||||
await collectionEntry.LoadAsync(CancellationToken);
|
||||
await File.WriteAllTextAsync(Path.Join(tempFolder, "ComicInfo.xml"), chapter.GetComicInfoXmlString(), CancellationToken);
|
||||
|
||||
Log.Debug($"Packaging images to archive {chapter}");
|
||||
//ZIP-it and ship-it
|
||||
ZipFile.CreateFromDirectory(tempFolder, saveArchiveFilePath);
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
File.SetUnixFileMode(saveArchiveFilePath, UserRead | UserWrite | UserExecute | GroupRead | GroupWrite | GroupExecute | OtherRead | OtherExecute);
|
||||
Directory.Delete(tempFolder, true); //Cleanup
|
||||
|
||||
DbContext.Entry(chapter).Property(c => c.Downloaded).CurrentValue = true;
|
||||
if(await DbContext.Sync(CancellationToken) is { success: false } e)
|
||||
Log.Error($"Failed to save database changes: {e.exceptionMessage}");
|
||||
|
||||
Log.Debug($"Downloaded chapter {chapter}.");
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
private void ProcessImage(string imagePath)
|
||||
{
|
||||
if (!Tranga.Settings.BlackWhiteImages && Tranga.Settings.ImageCompression == 100)
|
||||
{
|
||||
Log.Debug("No processing requested for image");
|
||||
return;
|
||||
}
|
||||
|
||||
Log.Debug($"Processing image: {imagePath}");
|
||||
|
||||
try
|
||||
{
|
||||
using Image image = Image.Load(imagePath);
|
||||
if (Tranga.Settings.BlackWhiteImages)
|
||||
image.Mutate(i => i.ApplyProcessor(new AdaptiveThresholdProcessor()));
|
||||
File.Delete(imagePath);
|
||||
image.SaveAsJpeg(imagePath, new JpegEncoder()
|
||||
{
|
||||
Quality = Tranga.Settings.ImageCompression
|
||||
});
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (e is UnknownImageFormatException or NotSupportedException)
|
||||
{
|
||||
//If the Image-Format is not processable by ImageSharp, we can't modify it.
|
||||
Log.Debug($"Unable to process {imagePath}: Not supported image format");
|
||||
}else if (e is InvalidImageContentException)
|
||||
{
|
||||
Log.Debug($"Unable to process {imagePath}: Invalid Content");
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.Error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CopyCoverFromCacheToDownloadLocation(Manga manga)
|
||||
{
|
||||
//Check if Publication already has a Folder and cover
|
||||
string publicationFolder = manga.CreatePublicationFolder();
|
||||
DirectoryInfo dirInfo = new (publicationFolder);
|
||||
if (dirInfo.EnumerateFiles().Any(info => info.Name.Contains("cover", StringComparison.InvariantCultureIgnoreCase)))
|
||||
{
|
||||
Log.Debug($"Cover already exists at {publicationFolder}");
|
||||
return;
|
||||
}
|
||||
|
||||
//TODO MangaConnector Selection
|
||||
await DbContext.Entry(manga).Collection(m => m.MangaConnectorIds).LoadAsync(CancellationToken);
|
||||
MangaConnectorId<Manga> mangaConnectorId = manga.MangaConnectorIds.First();
|
||||
if (!Tranga.TryGetMangaConnector(mangaConnectorId.MangaConnectorName, out MangaConnector? mangaConnector))
|
||||
{
|
||||
Log.Error($"MangaConnector with name {mangaConnectorId.MangaConnectorName} could not be found");
|
||||
return;
|
||||
}
|
||||
|
||||
Log.Info($"Copying cover to {publicationFolder}");
|
||||
await DbContext.Entry(mangaConnectorId).Navigation(nameof(MangaConnectorId<Manga>.Obj)).LoadAsync(CancellationToken);
|
||||
string? coverFileNameInCache = manga.CoverFileNameInCache ?? mangaConnector.SaveCoverImageToCache(mangaConnectorId);
|
||||
if (coverFileNameInCache is null)
|
||||
{
|
||||
Log.Error($"File {coverFileNameInCache} does not exist");
|
||||
return;
|
||||
}
|
||||
|
||||
string fullCoverPath = Path.Join(TrangaSettings.coverImageCacheOriginal, coverFileNameInCache);
|
||||
string newFilePath = Path.Join(publicationFolder, $"cover.{Path.GetFileName(coverFileNameInCache).Split('.')[^1]}" );
|
||||
File.Copy(fullCoverPath, newFilePath, true);
|
||||
if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
File.SetUnixFileMode(newFilePath, GroupRead | GroupWrite | UserRead | UserWrite | OtherRead | OtherWrite);
|
||||
Log.Debug($"Copied cover from {fullCoverPath} to {newFilePath}");
|
||||
}
|
||||
|
||||
private bool DownloadImage(string imageUrl, string savePath)
|
||||
{
|
||||
HttpDownloadClient downloadClient = new();
|
||||
RequestResult requestResult = downloadClient.MakeRequest(imageUrl, RequestType.MangaImage);
|
||||
|
||||
if ((int)requestResult.statusCode < 200 || (int)requestResult.statusCode >= 300)
|
||||
return false;
|
||||
if (requestResult.result == Stream.Null)
|
||||
return false;
|
||||
|
||||
FileStream fs = new(savePath, FileMode.Create, FileAccess.Write, FileShare.None);
|
||||
requestResult.result.CopyTo(fs);
|
||||
fs.Close();
|
||||
ProcessImage(savePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
public override string ToString() => $"{base.ToString()} {MangaConnectorIdId}";
|
||||
}
|
@@ -0,0 +1,47 @@
|
||||
using API.MangaConnectors;
|
||||
using API.Schema.MangaContext;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Workers;
|
||||
|
||||
/// <summary>
|
||||
/// Downloads the cover for Manga from Mangaconnector
|
||||
/// </summary>
|
||||
public class DownloadCoverFromMangaconnectorWorker(MangaConnectorId<Manga> mcId, IEnumerable<BaseWorker>? dependsOn = null)
|
||||
: BaseWorkerWithContext<MangaContext>(dependsOn)
|
||||
{
|
||||
internal readonly string MangaConnectorIdId = mcId.Key;
|
||||
protected override async Task<BaseWorker[]> DoWorkInternal()
|
||||
{
|
||||
Log.Debug($"Getting Cover for MangaConnectorId {MangaConnectorIdId}...");
|
||||
// Getting MangaConnector info
|
||||
if (await DbContext.MangaConnectorToManga
|
||||
.Include(id => id.Obj)
|
||||
.FirstOrDefaultAsync(c => c.Key == MangaConnectorIdId, CancellationToken) is not { } mangaConnectorId)
|
||||
{
|
||||
Log.Error("Could not get MangaConnectorId.");
|
||||
return []; //TODO Exception?
|
||||
}
|
||||
if (!Tranga.TryGetMangaConnector(mangaConnectorId.MangaConnectorName, out MangaConnector? mangaConnector))
|
||||
{
|
||||
Log.Error("Could not get MangaConnector.");
|
||||
return []; //TODO Exception?
|
||||
}
|
||||
Log.Debug($"Getting Cover for MangaConnectorId {mangaConnectorId}...");
|
||||
|
||||
string? coverFileName = mangaConnector.SaveCoverImageToCache(mangaConnectorId);
|
||||
if (coverFileName is null)
|
||||
{
|
||||
Log.Error($"Could not get Cover for MangaConnectorId {mangaConnectorId}.");
|
||||
return [];
|
||||
}
|
||||
DbContext.Entry(mangaConnectorId.Obj).Property(m => m.CoverFileNameInCache).CurrentValue = coverFileName;
|
||||
|
||||
if(await DbContext.Sync(CancellationToken) is { success: false } e)
|
||||
Log.Error($"Failed to save database changes: {e.exceptionMessage}");
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
public override string ToString() => $"{base.ToString()} {MangaConnectorIdId}";
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user