Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e732b3b614 | ||
|
|
69f8767be5 | ||
|
|
6cbba6d170 | ||
|
|
888ab4dc8f | ||
|
|
753c19e700 | ||
|
|
4f9390332a | ||
|
|
ffddd85800 | ||
|
|
652b0f20e0 | ||
|
|
598f08b916 | ||
|
|
55cedba693 | ||
|
|
10caf68d8b | ||
|
|
f4ed816f6e | ||
|
|
ba77f41325 | ||
|
|
ea567fcbf0 | ||
|
|
edb05abcbe | ||
|
|
46811219ca | ||
|
|
0aab0cac73 | ||
|
|
3257a36892 | ||
|
|
f10b680b0e | ||
|
|
c2b1950cd5 | ||
|
|
00c8ff8ac4 | ||
|
|
0ca6e86177 | ||
|
|
ab17992ebb | ||
|
|
570371cc82 | ||
|
|
674b47bdbd | ||
|
|
8cff413c4d | ||
|
|
fd744af75d | ||
|
|
6208d5e264 | ||
|
|
42dc36cc10 | ||
|
|
c23d35db4a | ||
|
|
fca580505c | ||
|
|
19da54a7ae | ||
|
|
9c87f0fbde | ||
|
|
e21f943712 | ||
|
|
4bb553f51d | ||
|
|
0615637f58 | ||
|
|
a6c55deac6 | ||
|
|
2de8df7e0d | ||
|
|
4c1d7a9f6b | ||
|
|
9489905602 | ||
|
|
5e7c0c9d34 | ||
|
|
b5da0df42a | ||
|
|
0959f84fd5 | ||
|
|
84777319d7 | ||
|
|
d85bef6c38 | ||
|
|
8ad9f4e3b7 | ||
|
|
cde3888e17 | ||
|
|
387678a771 | ||
|
|
c451daad3c | ||
|
|
224915bba1 | ||
|
|
d598054195 | ||
|
|
088778969d | ||
|
|
0ed4d81da2 | ||
|
|
9478325c23 | ||
|
|
7c715f34dc | ||
|
|
00686ec1f2 | ||
|
|
83d331c89b | ||
|
|
f6338a9fda | ||
|
|
73efef17bd | ||
|
|
74725b68b0 | ||
|
|
efbdd0b6e3 | ||
|
|
1134f54be4 | ||
|
|
2d4ca23d0c | ||
|
|
6157f5027c | ||
|
|
5e48a64b15 | ||
|
|
36a7ff19bc | ||
|
|
1b4f0d0967 | ||
|
|
181117f916 | ||
|
|
32741be6c8 | ||
|
|
f64fe5d835 | ||
|
|
0db93a6036 | ||
|
|
a4bf028537 | ||
|
|
47625a616d | ||
|
|
87635a5ace | ||
|
|
a9713bd497 | ||
|
|
8cef72b847 | ||
|
|
fbed304df8 | ||
|
|
e3bf369ad6 | ||
|
|
d229f71151 | ||
|
|
3aef161cb8 | ||
|
|
cabcace3f0 | ||
|
|
424e493946 | ||
|
|
848302f69e | ||
|
|
8bdd95fc45 | ||
|
|
9c7a834cec | ||
|
|
51a2f36966 | ||
|
|
b64645e5f5 | ||
|
|
bed8957eae | ||
|
|
0ce8c19e88 | ||
|
|
5a1f3d8eec | ||
|
|
315584690d | ||
|
|
f14faff308 | ||
|
|
6f782c5687 | ||
|
|
7f7fc884c2 | ||
|
|
92084bab71 | ||
|
|
f00471baf5 | ||
|
|
9ed0774d19 | ||
|
|
eb20db55a4 | ||
|
|
a91724edb0 | ||
|
|
5ad6b7fa64 | ||
|
|
c1be944a48 | ||
|
|
e2c3c08d65 | ||
|
|
4fece545e4 | ||
|
|
876a11dc58 | ||
|
|
486914905e | ||
|
|
d47af66499 | ||
|
|
832ec80f1a | ||
|
|
85d1aab6a8 | ||
|
|
8db0d004b6 | ||
|
|
c13eac91c8 | ||
|
|
cf3b619c73 | ||
|
|
269ab0e04e | ||
|
|
47168f5ce9 | ||
|
|
73d7306627 | ||
|
|
dd1cbb1018 | ||
|
|
91fdf57b46 | ||
|
|
d77d682ee0 | ||
|
|
e2eed3d311 | ||
|
|
54a47cfc18 | ||
|
|
b5dac9e1a7 | ||
|
|
b00abd283a | ||
|
|
4821b2b34c | ||
|
|
0e31be5357 | ||
|
|
dc19d40db1 | ||
|
|
02b5409b95 | ||
|
|
63cebcd849 | ||
|
|
99e91e622e | ||
|
|
36ef81dd91 | ||
|
|
2700b4f0d1 | ||
|
|
d73f9fdd6f | ||
|
|
be89c25a90 | ||
|
|
c5e9526fc8 | ||
|
|
a99960e6c5 | ||
|
|
8105f54ebb | ||
|
|
d01010812b | ||
|
|
02fbef3dba | ||
|
|
eb8b0096a1 | ||
|
|
38b0af9ea2 | ||
|
|
83b5d0f22b | ||
|
|
38c58bd7c9 | ||
|
|
6276806c0e | ||
|
|
97a8fc661f | ||
|
|
0569c644a3 | ||
|
|
3565e5f068 | ||
|
|
8b8bc1b688 | ||
|
|
ff9dabadf1 | ||
|
|
a75d0caa02 | ||
|
|
eb872865a5 | ||
|
|
8031fff5af | ||
|
|
ac1ae66246 | ||
|
|
310443afc5 | ||
|
|
25c9aba469 | ||
|
|
3a3c8ad2a4 | ||
|
|
10816c7f6d | ||
|
|
adcfd8afe8 | ||
|
|
74a386a284 | ||
|
|
fceca5cc08 | ||
|
|
13b515d3ab | ||
|
|
d2015dd998 | ||
|
|
3959a8eddd | ||
|
|
ca63d343bd | ||
|
|
ecc6e00bfc | ||
|
|
c1114cd786 | ||
|
|
cf01bd7ad4 | ||
|
|
cf1b3bb37f | ||
|
|
70fefa2f11 | ||
|
|
80df8b1fa6 | ||
|
|
cac33165dc | ||
|
|
bf2ab66362 | ||
|
|
5e14b4bf41 | ||
|
|
a6fdd8ab36 | ||
|
|
d091b9d8b9 | ||
|
|
2eb7c0d3f0 | ||
|
|
54eb30e2b9 | ||
|
|
47f44d71cf | ||
|
|
654095054f | ||
|
|
8544702bb2 | ||
|
|
a3b5d2eac7 | ||
|
|
bba7812a07 | ||
|
|
458d0d1e3d | ||
|
|
6d6d5ac097 | ||
|
|
560e8e132d | ||
|
|
3433b62864 | ||
|
|
d8fbf967b3 | ||
|
|
902368efa7 | ||
|
|
c5571fc359 | ||
|
|
132c17151a | ||
|
|
1ce1aee35e | ||
|
|
4dc8948199 | ||
|
|
7db6481704 | ||
|
|
6b11d0b4f3 | ||
|
|
c30d550ee1 | ||
|
|
c902fe1c5a | ||
|
|
a6fe639e2f | ||
|
|
e1bce5d5fe | ||
|
|
5057e68b84 | ||
|
|
f88e776b1f | ||
|
|
957c906e53 | ||
|
|
cfda7f109a | ||
|
|
9fcd636533 | ||
|
|
0e50794d9b | ||
|
|
714c19f558 | ||
|
|
c2d2db913e | ||
|
|
e3537235ca | ||
|
|
dc5663f21f | ||
|
|
dcc091e354 | ||
|
|
4ad747decf | ||
|
|
0d07e445de | ||
|
|
9e7efb187b | ||
|
|
d480c55bcb | ||
|
|
0ff1feaef0 | ||
|
|
0bfe6de62a | ||
|
|
776eeccc67 | ||
|
|
b632f1b9a2 | ||
|
|
9aab6d90f7 | ||
|
|
5cd914f007 | ||
|
|
3a899afcce | ||
|
|
7418c2c0b4 | ||
|
|
91e36b2c7e | ||
|
|
e86833a2a9 | ||
|
|
f3a4df1759 | ||
|
|
4fe28028ea | ||
|
|
e2c88b3a33 | ||
|
|
f58c8eb916 | ||
|
|
8938598aab | ||
|
|
7472cdf43f | ||
|
|
6f5af36ecf | ||
|
|
7c1d372086 | ||
|
|
37b9ee9b0d | ||
|
|
bcfdeacf15 | ||
|
|
cb588c2c82 | ||
|
|
0b777c47bb | ||
|
|
4dce8abb1d | ||
|
|
f27d62e22c | ||
|
|
0eb8583dce | ||
|
|
6f969ed6a6 | ||
|
|
707c41c48a | ||
|
|
054256067a | ||
|
|
8c0891a078 | ||
|
|
cc0fbd7ce8 | ||
|
|
4e245def8f | ||
|
|
50be750460 | ||
|
|
5127061775 | ||
|
|
0d2611c8a0 | ||
|
|
521b46e60d | ||
|
|
36a99b0b5c | ||
|
|
d32ad1d5ca | ||
|
|
7029fa8b60 | ||
|
|
8c98b91a25 | ||
|
|
feac864e73 | ||
|
|
d75adfe85e | ||
|
|
4e67a56ed2 | ||
|
|
dbdaa0884e | ||
|
|
2b2ccb1710 | ||
|
|
4583fc8023 | ||
|
|
1b1b7455d2 | ||
|
|
daaf7337ab | ||
|
|
2c9d4d2487 | ||
|
|
af09b50153 | ||
|
|
b8c3674be9 | ||
|
|
65a29ed4c9 | ||
|
|
854a7d020d | ||
|
|
a215b73e39 | ||
|
|
6bfe022de0 | ||
|
|
c6cde961b6 | ||
|
|
d08acdc3cc | ||
|
|
86e6161b89 | ||
|
|
646937272a | ||
|
|
6dd7a023f3 | ||
|
|
f0077e73a8 | ||
|
|
e485f10e9e | ||
|
|
81a0b15a3d | ||
|
|
89577914ba | ||
|
|
c289cb5d4b | ||
|
|
fd88dd2383 | ||
|
|
80bcfb12de | ||
|
|
46f111cd6e | ||
|
|
bcb72d780f | ||
|
|
3d9594cfaa | ||
|
|
bc0e218e73 | ||
|
|
f9267ba391 | ||
|
|
eb02c9e5d4 | ||
|
|
2f6322b0ee | ||
|
|
22a93a28e2 | ||
|
|
1ee49791f4 | ||
|
|
90bccb86ef | ||
|
|
ff6b341c36 | ||
|
|
9d3b2b007b | ||
|
|
dbf104787c | ||
|
|
bf31e675db | ||
|
|
7e24890991 | ||
|
|
4cf4c4dfe6 | ||
|
|
efc7ce31d2 | ||
|
|
4ccc2c0aec | ||
|
|
4512ab4524 | ||
|
|
0ef9e46133 | ||
|
|
88a06deb8c | ||
|
|
e4f1ce9c5a | ||
|
|
f5048ee1a8 | ||
|
|
e531bc0f0c | ||
|
|
f78a2367a2 | ||
|
|
928ed10c2e | ||
|
|
e7c2a85fd4 | ||
|
|
32d120bd39 | ||
|
|
be5247a2ef | ||
|
|
ee7f393e67 | ||
|
|
14bb01010d | ||
|
|
71686e4490 | ||
|
|
ea1ba54a9d | ||
|
|
0afba50953 | ||
|
|
659535f5de | ||
|
|
d977d1b81b | ||
|
|
24fdadbeb6 | ||
|
|
08527ae3ce | ||
|
|
01215aaa68 | ||
|
|
ed600a9aeb | ||
|
|
e542151652 | ||
|
|
e49402649d | ||
|
|
89e9958222 | ||
|
|
21989c3ccf | ||
|
|
42924d9508 | ||
|
|
f9390ceea5 | ||
|
|
dc7a0575dd | ||
|
|
a972447dbc | ||
|
|
87b200cc13 | ||
|
|
14e57e3714 | ||
|
|
d45ed1c921 | ||
|
|
344c0c7bc3 | ||
|
|
190ee09e60 | ||
|
|
e6031844d5 | ||
|
|
7c6347442f | ||
|
|
16255870a8 | ||
|
|
65bcffc129 | ||
|
|
b28547b248 | ||
|
|
8873381290 | ||
|
|
ebb7ddec44 | ||
|
|
b07541a251 | ||
|
|
85a66a3bfe | ||
|
|
f493d4e4e5 | ||
|
|
5d8908db49 | ||
|
|
14b044d055 | ||
|
|
9b0b82ec1b | ||
|
|
881b48729c | ||
|
|
812265324d | ||
|
|
621f8debea | ||
|
|
43040f6162 | ||
|
|
0bf3bb381f | ||
|
|
2bfbbfd4ba | ||
|
|
6cb1449ff3 | ||
|
|
92fbc9c792 | ||
|
|
f9cfb38ad3 | ||
|
|
e5dc7e2834 | ||
|
|
0af52f2053 | ||
|
|
2fff002699 | ||
|
|
5a87c1c4b3 | ||
|
|
38a7454e7a | ||
|
|
f0b770224a | ||
|
|
4c3fc90830 | ||
|
|
d6798fb286 | ||
|
|
6315f40800 | ||
|
|
1b73d8a7e4 | ||
|
|
54a0ddaab5 | ||
|
|
a84c316e3d | ||
|
|
985e59ad68 | ||
|
|
5334acac37 | ||
|
|
0a53719394 | ||
|
|
3cc89d4ca0 | ||
|
|
2eee5fbdd8 | ||
|
|
e0b2734d66 | ||
|
|
9926e03009 | ||
|
|
3aa0c82795 | ||
|
|
85368c89dd | ||
|
|
75499b989c | ||
|
|
bf89bbc8bc | ||
|
|
deb1ff37b2 | ||
|
|
2927b5d544 | ||
|
|
bf9313ddeb | ||
|
|
c2ffa940cd | ||
|
|
b94e1df518 | ||
|
|
2eb4f77a23 | ||
|
|
d5059979d5 | ||
|
|
4fa7520598 | ||
|
|
e8cb84136b | ||
|
|
8a3409e911 | ||
|
|
abedb13473 | ||
|
|
366a65f99f | ||
|
|
cd01aaa69e | ||
|
|
d4502713ff | ||
|
|
c523463591 | ||
|
|
cca8158bdf | ||
|
|
b9085129a7 | ||
|
|
cb073daca3 | ||
|
|
c40c8a2255 | ||
|
|
e42e11e2a4 | ||
|
|
07bf9047b0 | ||
|
|
230573dc7a | ||
|
|
94df767c28 | ||
|
|
fea8a9d40d | ||
|
|
54d9d33e53 | ||
|
|
1eb9cd44dc | ||
|
|
eb6563480f | ||
|
|
2f39e51e1c | ||
|
|
24252e09b4 | ||
|
|
0e7eed4d3c | ||
|
|
884f7666fa | ||
|
|
c54e9fe588 | ||
|
|
d82944d08c | ||
|
|
97764acbcd | ||
|
|
53f0647c5d | ||
|
|
b5ee07eba8 | ||
|
|
5fe13f53bf | ||
|
|
338441f116 | ||
|
|
31380f2af9 | ||
|
|
13dc0b9c8e | ||
|
|
78d45f0208 | ||
|
|
d0e166140f | ||
|
|
2617fa8af4 | ||
|
|
89a1dcfbf6 | ||
|
|
9d619ae5c7 | ||
|
|
10d0542e05 | ||
|
|
111c93c391 | ||
|
|
1d9471b252 | ||
|
|
88cb58c285 | ||
|
|
7e5d8978ae | ||
|
|
eea01b0ff5 | ||
|
|
d755878bd2 | ||
|
|
2d7cf1e6d3 | ||
|
|
b8a770a470 | ||
|
|
481237dc77 | ||
|
|
5e9dfc0724 | ||
|
|
ce720f40fe | ||
|
|
c92115faf3 | ||
|
|
a1f9f03fc1 | ||
|
|
6a504673e5 | ||
|
|
839118e4f1 | ||
|
|
fd730f6609 | ||
|
|
1be0ff9620 | ||
|
|
6717683ac3 | ||
|
|
0f9b5d08e9 | ||
|
|
1eb77c9cd4 | ||
|
|
ca92dbb168 | ||
|
|
8bc1f03164 | ||
|
|
d8d9d405e9 | ||
|
|
8f2f6f5c91 | ||
|
|
4c01af340f | ||
|
|
88783257b4 | ||
|
|
c2474aa91d | ||
|
|
d2860fc374 | ||
|
|
87a1971d74 | ||
|
|
a9359bc1db | ||
|
|
c7f0293568 | ||
|
|
22affedafc | ||
|
|
4d79c593f7 | ||
|
|
87b82424d5 | ||
|
|
5f81084e66 | ||
|
|
095074f977 | ||
|
|
acd3c8d103 | ||
|
|
3733fd442f | ||
|
|
4eb9845ff7 | ||
|
|
ec6efafbed | ||
|
|
10668571e8 | ||
|
|
878fd85c63 | ||
|
|
3827d46d66 | ||
|
|
7feff3b55c | ||
|
|
4523a12708 | ||
|
|
7a8d054b28 | ||
|
|
a56d1c80ae | ||
|
|
074aed6997 | ||
|
|
2f8db1f7f0 | ||
|
|
b3d878bae8 | ||
|
|
9b12852544 | ||
|
|
a7d58386eb | ||
|
|
fe78222142 | ||
|
|
68531a44d8 | ||
|
|
d3233b4b9c | ||
|
|
0e9ad0f831 | ||
|
|
c53a516887 | ||
|
|
bdac7a3257 | ||
|
|
0d359e9e57 | ||
|
|
c4fad3cd20 | ||
|
|
9b520b1941 | ||
|
|
de3f883992 | ||
|
|
2afce66486 | ||
|
|
2ae80d3007 | ||
|
|
e31763d388 | ||
|
|
9955e348a0 | ||
|
|
bcf4a479ac | ||
|
|
26fb9921b2 | ||
|
|
ba383643f5 | ||
|
|
6bd01c2d2b | ||
|
|
26c8e15436 | ||
|
|
fd993b5063 | ||
|
|
abc923ade4 | ||
|
|
3aa72c8afb | ||
|
|
bee6a3593d | ||
|
|
a335dd75a1 | ||
|
|
96fb2c1439 | ||
|
|
9def910924 | ||
|
|
ab3d4e4f21 | ||
|
|
ecda717bed | ||
|
|
4ed0633edf | ||
|
|
34fec0ed97 | ||
|
|
249017a4fa | ||
|
|
84f432830c | ||
|
|
ca9fc74541 | ||
|
|
d9a2a7a1e8 | ||
|
|
d0d9985370 | ||
|
|
e6ccd42f89 | ||
|
|
12d46d33d9 | ||
|
|
8d9f301aea | ||
|
|
0ff3f0f426 | ||
|
|
b2f5853b12 | ||
|
|
f8adcbb691 | ||
|
|
a0728b07d0 | ||
|
|
e3b895755d | ||
|
|
e33e4ac4ac | ||
|
|
2f515b725b | ||
|
|
a1d7dc5c28 | ||
|
|
1c5d1e24f7 | ||
|
|
8df45d150d | ||
|
|
a59d20bd0f | ||
|
|
e3be7595e2 | ||
|
|
e33a7a3f08 | ||
|
|
8c02ffb1cb | ||
|
|
7367e96d2b | ||
|
|
2d80187faa | ||
|
|
1d3a768dfe | ||
|
|
c09e1ed203 | ||
|
|
99e50bafc4 | ||
|
|
155cf04536 | ||
|
|
ebe7cd7ba4 | ||
|
|
2d470e0ce1 | ||
|
|
87c0b15f5f | ||
|
|
02d2c2bbf8 | ||
|
|
6996e813b5 | ||
|
|
840f4d2010 | ||
|
|
3cda0a0f32 | ||
|
|
a6931b4936 | ||
|
|
9536b2c322 | ||
|
|
099dbf95e7 | ||
|
|
23d5463213 | ||
|
|
a2ceeb678f | ||
|
|
092329c9e6 | ||
|
|
de989783e8 | ||
|
|
1d7dcce98d | ||
|
|
551828f8cf | ||
|
|
d26964ab08 | ||
|
|
0fe12fe598 | ||
|
|
b0e8024f08 | ||
|
|
bc1c097271 | ||
|
|
f98cb3d8fb | ||
|
|
488005962f | ||
|
|
6d6f8c1b1f | ||
|
|
c4a38087d9 | ||
|
|
f468b9e6e3 | ||
|
|
53a16c5a6f | ||
|
|
108caa0898 | ||
|
|
a0b776cbd1 | ||
|
|
4719797aff | ||
|
|
60cc0c9395 | ||
|
|
ded4cb7a19 | ||
|
|
f5f16a3dd2 | ||
|
|
c5f2323c8a | ||
|
|
ea89fe07d8 | ||
|
|
5d86bb0ba0 | ||
|
|
05032aed3c | ||
|
|
7e46f9c0b1 | ||
|
|
5e15cac598 | ||
|
|
d0551274dc | ||
|
|
99c05650a1 | ||
|
|
617ee3d781 | ||
|
|
47aa3254c7 | ||
|
|
0717b9493c | ||
|
|
824ebc4d76 | ||
|
|
cbaa61bbb7 | ||
|
|
dbac685985 | ||
|
|
b25c024b66 | ||
|
|
bc65180c32 | ||
|
|
10c66b6e63 | ||
|
|
c29b1696f7 | ||
|
|
c974cd048e | ||
|
|
24e9bf2728 | ||
|
|
ff46af9c49 | ||
|
|
0a7345186d | ||
|
|
cb0d9ec95c |
@@ -11,7 +11,7 @@ assignees: ''
|
||||
|
||||
After 6 years of more or less intensive programming on Calibre-Web, I need a break.
|
||||
The last few months, maintaining Calibre-Web has felt more like work than a hobby. I felt pressured and teased by people to solve "their" problems and merge PRs for "their" Calibre-Web.
|
||||
I have turned off all notifications from Github/Discord and will now concentrate undisturbed on the development of “my” Calibre-Web over the next few weeks/months.
|
||||
I have turned off all notifications from GitHub/Discord and will now concentrate undisturbed on the development of “my” Calibre-Web over the next few weeks/months.
|
||||
I will look into the issues and maybe also the PRs from time to time, but don't expect a quick response from me.
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ assignees: ''
|
||||
|
||||
After 6 years of more or less intensive programming on Calibre-Web, I need a break.
|
||||
The last few months, maintaining Calibre-Web has felt more like work than a hobby. I felt pressured and teased by people to solve "their" problems and merge PRs for "their" Calibre-Web.
|
||||
I have turned off all notifications from Github/Discord and will now concentrate undisturbed on the development of “my” Calibre-Web over the next few weeks/months.
|
||||
I have turned off all notifications from GitHub/Discord and will now concentrate undisturbed on the development of “my” Calibre-Web over the next few weeks/months.
|
||||
I will look into the issues and maybe also the PRs from time to time, but don't expect a quick response from me.
|
||||
|
||||
Please have a look at our [Contributing Guidelines](https://github.com/janeczku/calibre-web/blob/master/CONTRIBUTING.md)
|
||||
|
||||
+4
-4
@@ -20,7 +20,7 @@ Some of the user languages in Calibre-Web having missing translations. We are ha
|
||||
|
||||
### **Documentation**
|
||||
|
||||
The Calibre-Web documentation is hosted in the Github [Wiki](https://github.com/janeczku/calibre-web/wiki). The Wiki is open to everybody, if you find a problem, feel free to correct it. If information is missing, you are welcome to add it. The content will be reviewed time by time. Please try to be consistent with the form with the other Wiki pages (e.g. the project name is Calibre-Web with 2 capital letters and a dash in between).
|
||||
The Calibre-Web documentation is hosted in the GitHub [Wiki](https://github.com/janeczku/calibre-web/wiki). The Wiki is open to everybody, if you find a problem, feel free to correct it. If information is missing, you are welcome to add it. The content will be reviewed time by time. Please try to be consistent with the form with the other Wiki pages (e.g. the project name is Calibre-Web with 2 capital letters and a dash in between).
|
||||
|
||||
### **Reporting a bug**
|
||||
|
||||
@@ -28,12 +28,12 @@ Do not open up a GitHub issue if the bug is a **security vulnerability** in Cali
|
||||
|
||||
Ensure the **bug was not already reported** by searching on GitHub under [Issues](https://github.com/janeczku/calibre-web/issues). Please also check if a solution for your problem can be found in the [wiki](https://github.com/janeczku/calibre-web/wiki).
|
||||
|
||||
If you're unable to find an **open issue** addressing the problem, open a [new one](https://github.com/janeczku/calibre-web/issues/new/choose). Be sure to include a **title** and **clear description**, as much relevant information as possible, the **issue form** helps you providing the right information. Deleting the form and just pasting the stack trace doesn't speed up fixing the problem. If your issue could be resolved, consider closing the issue.
|
||||
If you're unable to find an **open issue** addressing the problem, open a [new one](https://github.com/janeczku/calibre-web/issues/new/choose). Be sure to include a **title** and **clear description**, as much relevant information as possible, the **issue form** helps you provide the right information. Deleting the form and just pasting the stack trace doesn't speed up fixing the problem. If your issue could be resolved, consider closing the issue.
|
||||
|
||||
### **Feature Request**
|
||||
|
||||
If there is a feature missing in Calibre-Web and you can't find a feature request in the [Issues](https://github.com/janeczku/calibre-web/issues) section, you could create a [feature request](https://github.com/janeczku/calibre-web/issues/new?assignees=&labels=&template=feature_request.md&title=).
|
||||
We will not extend Calibre-Web with any more login abilities or add further files storages, or file syncing ability. Furthermore Calibre-Web is made for home usage for company in-house usage, so requests regarding any sorts of social interaction capability, payment routines, search engine or web site analytics integration will not be implemented.
|
||||
We will not extend Calibre-Web with any more login abilities or add further files storages, or file syncing ability. Calibre-Web is made for home usage for company in-house usage, so requests regarding any sorts of social interaction capability, payment routines, search engine or website analytics integration will not be implemented.
|
||||
|
||||
### **Contributing code to Calibre-Web**
|
||||
|
||||
@@ -42,5 +42,5 @@ Open a new GitHub pull request with the patch. Ensure the PR description clearly
|
||||
In case your code enhances features of Calibre-Web: Create your pull request for the development branch if your enhancement consists of more than some lines of code in a local section of Calibre-Webs code. This makes it easier to test it and check all implication before it's made public.
|
||||
|
||||
Please check if your code runs with python 3, python 2 is no longer supported. If possible and the feature is related to operating system functions, try to check it on Windows and Linux.
|
||||
Calibre-Web is automatically tested on Linux in combination with python 3.8. The code for testing is in a [separate repo](https://github.com/OzzieIsaacs/calibre-web-test) on Github. It uses unit tests and performs real system tests with selenium; it would be great if you could consider also writing some tests.
|
||||
Calibre-Web is automatically tested on Linux in combination with python 3.8. The code for testing is in a [separate repo](https://github.com/OzzieIsaacs/calibre-web-test) on GitHub. It uses unit tests and performs real system tests with selenium; it would be great if you could consider also writing some tests.
|
||||
A static code analysis is done by Codacy, but it's partly broken and doesn't run automatically. You could check your code with ESLint before contributing, a configuration file can be found in the projects root folder.
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
graft src/calibreweb
|
||||
global-exclude __pycache__
|
||||
global-exclude *.pyc
|
||||
|
||||
@@ -1,10 +1,3 @@
|
||||
# Short Notice from the maintainer
|
||||
|
||||
After 6 years of more or less intensive programming on Calibre-Web, I need a break.
|
||||
The last few months, maintaining Calibre-Web has felt more like work than a hobby. I felt pressured and teased by people to solve "their" problems and merge PRs for "their" Calibre-Web.
|
||||
I have turned off all notifications from Github/Discord and will now concentrate undisturbed on the development of “my” Calibre-Web over the next few weeks/months.
|
||||
I will look into the issues and maybe also the PRs from time to time, but don't expect a quick response from me.
|
||||
|
||||
# Calibre-Web
|
||||
|
||||
Calibre-Web is a web app that offers a clean and intuitive interface for browsing, reading, and downloading eBooks using a valid [Calibre](https://calibre-ebook.com) database.
|
||||
@@ -26,13 +19,13 @@ Calibre-Web is a web app that offers a clean and intuitive interface for browsin
|
||||
- [Quick start](#quick-start)
|
||||
- [Requirements](#requirements)
|
||||
4. [Docker Images](#docker-images)
|
||||
5. [Contributor Recognition](#contributor-recognition)
|
||||
6. [Contact](#contact)
|
||||
7. [Contributing to Calibre-Web](#contributing-to-calibre-web)
|
||||
5. [Troubleshooting](#troubleshooting)
|
||||
6. [Contributor Recognition](#contributor-recognition)
|
||||
7. [Contact](#contact)
|
||||
8. [Contributing to Calibre-Web](#contributing-to-calibre-web)
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
*This software is a fork of [library](https://github.com/mutschler/calibreserver) and licensed under the GPL v3 License.*
|
||||
|
||||

|
||||
@@ -64,51 +57,103 @@ Calibre-Web is a web app that offers a clean and intuitive interface for browsin
|
||||
|
||||
## Installation
|
||||
|
||||
#### Installation via pip (recommended)
|
||||
1. Create a virtual environment for Calibre-Web to avoid conflicts with existing Python dependencies
|
||||
2. Install Calibre-Web via pip: `pip install calibreweb` (or `pip3` depending on your OS/distro)
|
||||
3. Install optional features via pip as needed, see [this page](https://github.com/janeczku/calibre-web/wiki/Dependencies-in-Calibre-Web-Linux-and-Windows) for details
|
||||
4. Start Calibre-Web by typing `cps`
|
||||
### Installation via pip (recommended)
|
||||
|
||||
*Note: Raspberry Pi OS users may encounter issues during installation. If so, please update pip (`./venv/bin/python3 -m pip install --upgrade pip`) and/or install cargo (`sudo apt install cargo`) before retrying the installation.*
|
||||
1. **Create a virtual environment**: It’s essential to isolate your Calibre-Web installation to avoid dependency conflicts. You can create a virtual environment by running:
|
||||
```
|
||||
python3 -m venv calibre-web-env
|
||||
```
|
||||
2. **Activate the virtual environment**:
|
||||
```
|
||||
source calibre-web-env/bin/activate
|
||||
```
|
||||
3. **Install Calibre-Web**: Use pip to install the application:
|
||||
```
|
||||
pip install calibreweb
|
||||
```
|
||||
4. **Install optional features**: For additional functionality, you may need to install optional features. Refer to [this page](https://github.com/janeczku/calibre-web/wiki/Dependencies-in-Calibre-Web-Linux-and-Windows) for details on what can be installed.
|
||||
5. **Start Calibre-Web**: After installation, you can start the application with:
|
||||
```
|
||||
cps
|
||||
```
|
||||
|
||||
Refer to the Wiki for additional installation examples: [manual installation](https://github.com/janeczku/calibre-web/wiki/Manual-installation), [Linux Mint](https://github.com/janeczku/calibre-web/wiki/How-To:-Install-Calibre-Web-in-Linux-Mint-19-or-20), [Cloud Provider](https://github.com/janeczku/calibre-web/wiki/How-To:-Install-Calibre-Web-on-a-Cloud-Provider).
|
||||
*Note: Users of Raspberry Pi OS may encounter installation issues. If you do, try upgrading pip and/or installing cargo as follows:*
|
||||
```
|
||||
./venv/bin/python3 -m pip install --upgrade pip
|
||||
sudo apt install cargo
|
||||
```
|
||||
|
||||
### Important Links
|
||||
- For additional installation examples, check the following:
|
||||
- [Manual installation](https://github.com/janeczku/calibre-web/wiki/Manual-installation)
|
||||
- [Linux Mint installation](https://github.com/janeczku/calibre-web/wiki/How-To:-Install-Calibre-Web-in-Linux-Mint-19-or-20)
|
||||
- [Cloud Provider setup](https://github.com/janeczku/calibre-web/wiki/How-To:-Install-Calibre-Web-on-a-Cloud-Provider)
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. Open your browser and navigate to `http://localhost:8083` or `http://localhost:8083/opds` for the OPDS catalog
|
||||
2. Log in with the default admin credentials
|
||||
3. If you don't have a Calibre database, you can use [this database](https://github.com/janeczku/calibre-web/raw/master/library/metadata.db) (move it out of the Calibre-Web folder to prevent overwriting during updates)
|
||||
4. Set `Location of Calibre database` to the path of the folder containing your Calibre library (metadata.db) and click "Save"
|
||||
5. Optionally, use Google Drive to host your Calibre library by following the [Google Drive integration guide](https://github.com/janeczku/calibre-web/wiki/G-Drive-Setup#using-google-drive-integration)
|
||||
6. Configure your Calibre-Web instance via the admin page, referring to the [Basic Configuration](https://github.com/janeczku/calibre-web/wiki/Configuration#basic-configuration) and [UI Configuration](https://github.com/janeczku/calibre-web/wiki/Configuration#ui-configuration) guides
|
||||
|
||||
#### Default Admin Login:
|
||||
- **Username:** admin
|
||||
- **Password:** admin123
|
||||
1. **Access Calibre-Web**: Open your browser and navigate to:
|
||||
```
|
||||
http://localhost:8083
|
||||
```
|
||||
or for the OPDS catalog:
|
||||
```
|
||||
http://localhost:8083/opds
|
||||
```
|
||||
2. **Log in**: Use the default admin credentials:
|
||||
- **Username:** admin
|
||||
- **Password:** admin123
|
||||
3. **Database Setup**: If you do not have a Calibre database, download a sample from:
|
||||
```
|
||||
https://github.com/janeczku/calibre-web/raw/master/library/metadata.db
|
||||
```
|
||||
Move it out of the Calibre-Web folder to avoid overwriting during updates.
|
||||
4. **Configure Calibre Database**: In the admin interface, set the `Location of Calibre database` to the path of the folder containing your Calibre library (where `metadata.db` is located) and click "Save".
|
||||
5. **Google Drive Integration**: For hosting your Calibre library on Google Drive, refer to the [Google Drive integration guide](https://github.com/janeczku/calibre-web/wiki/G-Drive-Setup#using-google-drive-integration).
|
||||
6. **Admin Configuration**: Configure your instance via the admin page, referring to the [Basic Configuration](https://github.com/janeczku/calibre-web/wiki/Configuration#basic-configuration) and [UI Configuration](https://github.com/janeczku/calibre-web/wiki/Configuration#ui-configuration) guides.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Python 3.5+
|
||||
- [Imagemagick](https://imagemagick.org/script/download.php) for cover extraction from EPUBs (Windows users may need to install [Ghostscript](https://ghostscript.com/releases/gsdnld.html) for PDF cover extraction)
|
||||
- Optional: [Calibre desktop program](https://calibre-ebook.com/download) for on-the-fly conversion and metadata editing (set "calibre's converter tool" path on the setup page)
|
||||
- Optional: [Kepubify tool](https://github.com/pgaskin/kepubify/releases/latest) for Kobo device support (place the binary in `/opt/kepubify` on Linux or `C:\Program Files\kepubify` on Windows)
|
||||
- **Python Version**: Ensure you have Python 3.7 or newer.
|
||||
- **Imagemagick**: Required for cover extraction from EPUBs. Windows users may also need to install [Ghostscript](https://ghostscript.com/releases/gsdnld.html) for PDF cover extraction.
|
||||
- **Optional Tools**:
|
||||
- **Calibre desktop program**: Recommended for on-the-fly conversion and metadata editing. Set the path to Calibre’s converter tool on the setup page.
|
||||
- **Kepubify tool**: Needed for Kobo device support. Download the tool and place the binary in `/opt/kepubify` on Linux or `C:\Program Files\kepubify` on Windows.
|
||||
|
||||
## Docker Images
|
||||
|
||||
Pre-built Docker images are available in the following Docker Hub repositories (maintained by the LinuxServer team):
|
||||
Pre-built Docker images are available:
|
||||
|
||||
#### **LinuxServer - x64, aarch64**
|
||||
- [Docker Hub](https://hub.docker.com/r/linuxserver/calibre-web)
|
||||
- [GitHub](https://github.com/linuxserver/docker-calibre-web)
|
||||
- [GitHub - Optional Calibre layer](https://github.com/linuxserver/docker-mods/tree/universal-calibre)
|
||||
### **LinuxServer - x64, aarch64**
|
||||
- **Docker Hub**: [linuxserver/calibre-web](https://hub.docker.com/r/linuxserver/calibre-web)
|
||||
- **GitHub**: [linuxserver/docker-calibre-web](https://github.com/linuxserver/docker-calibre-web)
|
||||
- **Optional Calibre layer**: [linuxserver/docker-mods](https://github.com/linuxserver/docker-mods/tree/universal-calibre)
|
||||
|
||||
Include the environment variable `DOCKER_MODS=linuxserver/mods:universal-calibre` in your Docker run/compose file to add the Calibre `ebook-convert` binary (x64 only). Omit this variable for a lightweight image.
|
||||
To include the Calibre `ebook-convert` binary (x64 only), add the environment variable:
|
||||
```
|
||||
DOCKER_MODS=linuxserver/mods:universal-calibre
|
||||
```
|
||||
in your Docker run/compose file. Omit this variable for a lightweight image.
|
||||
|
||||
Both the Calibre-Web and Calibre-Mod images are automatically rebuilt on new releases and updates.
|
||||
- **Paths Configuration**:
|
||||
- Set **Path to Calibre Binaries** to `/usr/bin`.
|
||||
- Set **Path to Unrar** to `/usr/bin/unrar`.
|
||||
|
||||
- Set "path to convertertool" to `/usr/bin/ebook-convert`
|
||||
- Set "path to unrar" to `/usr/bin/unrar`
|
||||
## Troubleshooting
|
||||
|
||||
- **Common Issues**:
|
||||
- If you experience issues starting the application, check the log files located in the `logs` directory for error messages.
|
||||
- If eBooks fail to load, verify that the `Location of Calibre database` is correctly set and that the database file is accessible.
|
||||
- You need to enable uploads under `Basic settings` for this option to appear
|
||||
|
||||
- **Configuration Errors**: Ensure that your Calibre database is compatible and properly formatted. Refer to the Calibre documentation for guidance on maintaining the database.
|
||||
|
||||
- **Performance Problems**:
|
||||
- If the application is slow, consider increasing the allocated resources (CPU/RAM) to your server or optimizing the Calibre database by removing duplicates and unnecessary entries.
|
||||
- Regularly clear the cache in your web browser to improve loading times.
|
||||
|
||||
- **User Management Issues**: If users are unable to log in or register, check the user permission settings in the admin interface. Ensure that registration is enabled and that users are being assigned appropriate roles.
|
||||
|
||||
- **Support Resources**: For additional help, consider visiting the [FAQ section](https://github.com/janeczku/calibre-web/wiki/FAQ) of the wiki or posting your questions in the [Discord community](https://discord.gg/h2VsJ2NEfB).
|
||||
|
||||
## Contributor Recognition
|
||||
|
||||
@@ -122,4 +167,21 @@ For more information, How To's, and FAQs, please visit the [Wiki](https://github
|
||||
|
||||
## Contributing to Calibre-Web
|
||||
|
||||
Check out our [Contributing Guidelines](https://github.com/janeczku/calibre-web/blob/master/CONTRIBUTING.md)
|
||||
To contribute, please check our [Contributing Guidelines](https://github.com/janeczku/calibre-web/blob/master/CONTRIBUTING.md). We welcome issues, feature requests, and pull requests from the community.
|
||||
|
||||
### Reporting Bugs
|
||||
|
||||
If you encounter bugs or issues, please report them in the [issues section](https://github.com/janeczku/calibre-web/issues) of the repository. Be sure to include detailed information about your setup and the problem encountered.
|
||||
|
||||
### Feature Requests
|
||||
|
||||
We welcome suggestions for new features. Please create a new issue in the repository to discuss your ideas.
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- **Documentation**: Comprehensive documentation is available on the [Calibre-Web wiki](https://github.com/janeczku/calibre-web/wiki).
|
||||
- **Community Contributions**: Explore the [community contributions](https://github.com/janeczku/calibre-web/pulls) to see ongoing work and how you can get involved.
|
||||
|
||||
---
|
||||
|
||||
Thank you for using Calibre-Web! We hope you enjoy managing your eBook library with our tool.
|
||||
|
||||
+40
-35
@@ -10,41 +10,46 @@ To receive fixes for security vulnerabilities it is required to always upgrade t
|
||||
|
||||
## History
|
||||
|
||||
| Fixed in | Description |CVE number |
|
||||
|---------------|--------------------------------------------------------------------------------------------------------------------|---------|
|
||||
| 3rd July 2018 | Guest access acts as a backdoor ||
|
||||
| V 0.6.7 | Hardcoded secret key for sessions |CVE-2020-12627 |
|
||||
| V 0.6.13 | Calibre-Web Metadata cross site scripting |CVE-2021-25964|
|
||||
| V 0.6.13 | Name of Shelves are only visible to users who can access the corresponding shelf Thanks to @ibarrionuevo ||
|
||||
| V 0.6.13 | JavaScript could get executed in the description field. Thanks to @ranjit-git and Hagai Wechsler (WhiteSource) ||
|
||||
| V 0.6.13 | JavaScript could get executed in a custom column of type "comment" field ||
|
||||
| V 0.6.13 | JavaScript could get executed after converting a book to another format with a title containing javascript code ||
|
||||
| V 0.6.13 | JavaScript could get executed after converting a book to another format with a username containing javascript code ||
|
||||
| V 0.6.13 | JavaScript could get executed in the description series, categories or publishers title ||
|
||||
| V 0.6.13 | JavaScript could get executed in the shelf title ||
|
||||
| V 0.6.13 | Login with the old session cookie after logout. Thanks to @ibarrionuevo ||
|
||||
| V 0.6.14 | CSRF was possible. Thanks to @mik317 and Hagai Wechsler (WhiteSource) |CVE-2021-25965|
|
||||
| V 0.6.14 | Migrated some routes to POST-requests (CSRF protection). Thanks to @scara31 |CVE-2021-4164|
|
||||
| V 0.6.15 | Fix for "javascript:" script links in identifier. Thanks to @scara31 |CVE-2021-4170|
|
||||
| V 0.6.15 | Cross-Site Scripting vulnerability on uploaded cover file names. Thanks to @ibarrionuevo ||
|
||||
| V 0.6.15 | Creating public shelfs is now denied if user is missing the edit public shelf right. Thanks to @ibarrionuevo ||
|
||||
| V 0.6.15 | Changed error message in case of trying to delete a shelf unauthorized. Thanks to @ibarrionuevo ||
|
||||
| V 0.6.16 | JavaScript could get executed on authors page. Thanks to @alicaz |CVE-2022-0352|
|
||||
| V 0.6.16 | Localhost can no longer be used to upload covers. Thanks to @scara31 |CVE-2022-0339|
|
||||
| V 0.6.16 | Another case where public shelfs could be created without permission is prevented. Thanks to @nhiephon |CVE-2022-0273|
|
||||
| V 0.6.16 | It's prevented to get the name of a private shelfs. Thanks to @nhiephon |CVE-2022-0405|
|
||||
| V 0.6.17 | The SSRF Protection can no longer be bypassed via an HTTP redirect. Thanks to @416e6e61 |CVE-2022-0767|
|
||||
| V 0.6.17 | The SSRF Protection can no longer be bypassed via 0.0.0.0 and it's ipv6 equivalent. Thanks to @r0hanSH |CVE-2022-0766|
|
||||
| V 0.6.18 | Possible SQL Injection is prevented in user table Thanks to Iman Sharafaldin (Forward Security) |CVE-2022-30765|
|
||||
| V 0.6.18 | The SSRF protection no longer can be bypassed by IPV6/IPV4 embedding. Thanks to @416e6e61 |CVE-2022-0939|
|
||||
| V 0.6.18 | The SSRF protection no longer can be bypassed to connect to other servers in the local network. Thanks to @michaellrowley |CVE-2022-0990|
|
||||
| V 0.6.20 | Credentials for emails are now stored encrypted ||
|
||||
| V 0.6.20 | Login is rate limited ||
|
||||
| V 0.6.20 | Passwordstrength can be forced ||
|
||||
| V 0.6.21 | SMTP server credentials are no longer returned to client ||
|
||||
| V 0.6.21 | Cross-site scripting (XSS) stored in href bypasses filter using data wrapper no longer possible ||
|
||||
| V 0.6.21 | Cross-site scripting (XSS) is no longer possible via pathchooser ||
|
||||
| V 0.6.21 | Error Handling at non existent rating, language, and user downloaded books was fixed ||
|
||||
| Fixed in | Description | CVE number |
|
||||
|---------------|----------------------------------------------------------------------------------------------------------------------------------|----------------|
|
||||
| 3rd July 2018 | Guest access acts as a backdoor | |
|
||||
| V 0.6.7 | Hardcoded secret key for sessions | CVE-2020-12627 |
|
||||
| V 0.6.13 | Calibre-Web Metadata cross site scripting | CVE-2021-25964 |
|
||||
| V 0.6.13 | Name of Shelves are only visible to users who can access the corresponding shelf Thanks to @ibarrionuevo | |
|
||||
| V 0.6.13 | JavaScript could get executed in the description field. Thanks to @ranjit-git and Hagai Wechsler (WhiteSource) | |
|
||||
| V 0.6.13 | JavaScript could get executed in a custom column of type "comment" field | |
|
||||
| V 0.6.13 | JavaScript could get executed after converting a book to another format with a title containing javascript code | |
|
||||
| V 0.6.13 | JavaScript could get executed after converting a book to another format with a username containing javascript code | |
|
||||
| V 0.6.13 | JavaScript could get executed in the description series, categories or publishers title | |
|
||||
| V 0.6.13 | JavaScript could get executed in the shelf title | |
|
||||
| V 0.6.13 | Login with the old session cookie after logout. Thanks to @ibarrionuevo | |
|
||||
| V 0.6.14 | CSRF was possible. Thanks to @mik317 and Hagai Wechsler (WhiteSource) | CVE-2021-25965 |
|
||||
| V 0.6.14 | Migrated some routes to POST-requests (CSRF protection). Thanks to @scara31 | CVE-2021-4164 |
|
||||
| V 0.6.15 | Fix for "javascript:" script links in identifier. Thanks to @scara31 | CVE-2021-4170 |
|
||||
| V 0.6.15 | Cross-Site Scripting vulnerability on uploaded cover file names. Thanks to @ibarrionuevo | |
|
||||
| V 0.6.15 | Creating public shelfs is now denied if user is missing the edit public shelf right. Thanks to @ibarrionuevo | |
|
||||
| V 0.6.15 | Changed error message in case of trying to delete a shelf unauthorized. Thanks to @ibarrionuevo | |
|
||||
| V 0.6.16 | JavaScript could get executed on authors page. Thanks to @alicaz | CVE-2022-0352 |
|
||||
| V 0.6.16 | Localhost can no longer be used to upload covers. Thanks to @scara31 | CVE-2022-0339 |
|
||||
| V 0.6.16 | Another case where public shelfs could be created without permission is prevented. Thanks to @nhiephon | CVE-2022-0273 |
|
||||
| V 0.6.16 | It's prevented to get the name of a private shelfs. Thanks to @nhiephon | CVE-2022-0405 |
|
||||
| V 0.6.17 | The SSRF Protection can no longer be bypassed via an HTTP redirect. Thanks to @416e6e61 | CVE-2022-0767 |
|
||||
| V 0.6.17 | The SSRF Protection can no longer be bypassed via 0.0.0.0 and it's ipv6 equivalent. Thanks to @r0hanSH | CVE-2022-0766 |
|
||||
| V 0.6.18 | Possible SQL Injection is prevented in user table Thanks to Iman Sharafaldin (Forward Security) | CVE-2022-30765 |
|
||||
| V 0.6.18 | The SSRF protection no longer can be bypassed by IPV6/IPV4 embedding. Thanks to @416e6e61 | CVE-2022-0939 |
|
||||
| V 0.6.18 | The SSRF protection no longer can be bypassed to connect to other servers in the local network. Thanks to @michaellrowley | CVE-2022-0990 |
|
||||
| V 0.6.20 | Credentials for emails are now stored encrypted | |
|
||||
| V 0.6.20 | Login is rate limited | |
|
||||
| V 0.6.20 | Passwordstrength can be forced | |
|
||||
| V 0.6.21 | SMTP server credentials are no longer returned to client | |
|
||||
| V 0.6.21 | Cross-site scripting (XSS) stored in href bypasses filter using data wrapper no longer possible | |
|
||||
| V 0.6.21 | Cross-site scripting (XSS) is no longer possible via pathchooser | |
|
||||
| V 0.6.21 | Error Handling at non existent rating, language, and user downloaded books was fixed | |
|
||||
| V 0.6.22 | Upload mimetype is checked to prevent malicious file content in the books library | |
|
||||
| V 0.6.22 | Cross-site scripting (XSS) stored in comments section is prevented better (switching from lxml to bleach for sanitizing strings) | |
|
||||
| V 0.6.23 | Cookies are no longer stored for opds basic authentication and proxy authentication | |
|
||||
|
||||
|
||||
|
||||
|
||||
## Statement regarding Log4j (CVE-2021-44228 and related)
|
||||
|
||||
@@ -30,25 +30,38 @@ from cps.main import main
|
||||
|
||||
def hide_console_windows():
|
||||
import ctypes
|
||||
import os
|
||||
|
||||
hwnd = ctypes.windll.kernel32.GetConsoleWindow()
|
||||
if hwnd != 0:
|
||||
try:
|
||||
import win32process
|
||||
except ImportError:
|
||||
print("To hide console window install 'pywin32' using 'pip install pywin32'")
|
||||
return
|
||||
ctypes.windll.user32.ShowWindow(hwnd, 0)
|
||||
ctypes.windll.kernel32.CloseHandle(hwnd)
|
||||
_, pid = win32process.GetWindowThreadProcessId(hwnd)
|
||||
os.system('taskkill /PID ' + str(pid) + ' /f')
|
||||
kernel32 = ctypes.WinDLL('kernel32')
|
||||
user32 = ctypes.WinDLL('user32')
|
||||
|
||||
SW_HIDE = 0
|
||||
|
||||
hWnd = kernel32.GetConsoleWindow()
|
||||
if hWnd:
|
||||
user32.ShowWindow(hWnd, SW_HIDE)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if os.name == "nt":
|
||||
# Only hide the console window on Windows when there is no interactive
|
||||
# console attached. This preserves the ability to use Ctrl+C from a
|
||||
# terminal (stdin is a tty) to stop the server.
|
||||
if os.name == "nt" and not sys.stdin.isatty():
|
||||
hide_console_windows()
|
||||
main()
|
||||
|
||||
try:
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
# Allow stopping the server with Ctrl+C from an interactive console, after reboot of calibre-web
|
||||
# (initally the SIGINT signal CTRL+C is catched in server.py via the signal callback).
|
||||
try:
|
||||
# Try to perform a graceful stop if web_server is available.
|
||||
# Import here to avoid import-time side-effects when not needed.
|
||||
from cps import web_server
|
||||
web_server.stop()
|
||||
except Exception:
|
||||
pass
|
||||
print('\nCalibre-Web: received interrupt, shutting down')
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
|
||||
|
||||
+4
-20
@@ -20,11 +20,8 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
from flask_login import LoginManager, confirm_login
|
||||
from flask import session, current_app
|
||||
from flask_login.utils import decode_cookie
|
||||
from flask_login.signals import user_loaded_from_cookie
|
||||
from .cw_login import LoginManager
|
||||
from flask import session
|
||||
|
||||
|
||||
class MyLoginManager(LoginManager):
|
||||
@@ -36,18 +33,5 @@ class MyLoginManager(LoginManager):
|
||||
return super(). _session_protection_failed()
|
||||
return False
|
||||
|
||||
def _load_user_from_remember_cookie(self, cookie):
|
||||
user_id = decode_cookie(cookie)
|
||||
if user_id is not None:
|
||||
session["_user_id"] = user_id
|
||||
session["_fresh"] = False
|
||||
user = None
|
||||
if self._user_callback:
|
||||
user = self._user_callback(user_id)
|
||||
if user is not None:
|
||||
app = current_app._get_current_object()
|
||||
user_loaded_from_cookie.send(app, user=user)
|
||||
# if session was restored from remember me cookie make login valid
|
||||
confirm_login()
|
||||
return user
|
||||
return None
|
||||
|
||||
|
||||
|
||||
Executable → Regular
+31
-20
@@ -26,17 +26,16 @@ import os
|
||||
import mimetypes
|
||||
|
||||
from flask import Flask
|
||||
from flask.sessions import SecureCookieSessionInterface
|
||||
from .MyLoginManager import MyLoginManager
|
||||
from flask_principal import Principal
|
||||
|
||||
from . import logger
|
||||
from .cli import CliParameter
|
||||
from .constants import CONFIG_DIR
|
||||
from .reverseproxy import ReverseProxied
|
||||
from .server import WebServer
|
||||
from .dep_check import dependency_check
|
||||
from .updater import Updater
|
||||
from .babel import babel, get_locale
|
||||
from . import config_sql
|
||||
from . import cache_buster
|
||||
from . import ub, db
|
||||
@@ -57,26 +56,30 @@ mimetypes.init()
|
||||
mimetypes.add_type('application/xhtml+xml', '.xhtml')
|
||||
mimetypes.add_type('application/epub+zip', '.epub')
|
||||
mimetypes.add_type('application/epub+zip', '.kepub')
|
||||
mimetypes.add_type('text/xml', '.fb2')
|
||||
mimetypes.add_type('application/octet-stream', '.mobi')
|
||||
mimetypes.add_type('application/fb2+zip', '.fb2')
|
||||
mimetypes.add_type('application/x-mobipocket-ebook', '.mobi')
|
||||
mimetypes.add_type('application/octet-stream', '.prc')
|
||||
mimetypes.add_type('application/vnd.amazon.ebook', '.azw')
|
||||
mimetypes.add_type('application/x-mobi8-ebook', '.azw3')
|
||||
mimetypes.add_type('application/x-rar', '.cbr')
|
||||
mimetypes.add_type('application/zip', '.cbz')
|
||||
mimetypes.add_type('application/x-mobipocket-ebook', '.azw')
|
||||
mimetypes.add_type('application/x-mobipocket-ebook', '.azw3')
|
||||
mimetypes.add_type('application/x-cbr', '.cbr')
|
||||
mimetypes.add_type('application/x-cbz', '.cbz')
|
||||
mimetypes.add_type('application/x-tar', '.cbt')
|
||||
mimetypes.add_type('application/x-7z-compressed', '.cb7')
|
||||
mimetypes.add_type('image/vnd.djv', '.djv')
|
||||
mimetypes.add_type('image/vnd.djv', '.djvu')
|
||||
mimetypes.add_type('image/vnd.djvu', '.djv')
|
||||
mimetypes.add_type('image/vnd.djvu', '.djvu')
|
||||
mimetypes.add_type('application/mpeg', '.mpeg')
|
||||
mimetypes.add_type('audio/mpeg', '.mp3')
|
||||
mimetypes.add_type('application/mp4', '.m4a')
|
||||
mimetypes.add_type('application/mp4', '.m4b')
|
||||
mimetypes.add_type('audio/x-m4a', '.m4a')
|
||||
mimetypes.add_type('audio/x-m4a', '.m4b')
|
||||
mimetypes.add_type('audio/x-hx-aac-adts', '.aac')
|
||||
mimetypes.add_type('audio/vnd.dolby.dd-raw', '.ac3')
|
||||
mimetypes.add_type('video/x-ms-asf', '.asf')
|
||||
mimetypes.add_type('audio/ogg', '.ogg')
|
||||
mimetypes.add_type('application/ogg', '.oga')
|
||||
mimetypes.add_type('text/css', '.css')
|
||||
mimetypes.add_type('application/x-ms-reader', '.lit')
|
||||
mimetypes.add_type('text/javascript; charset=UTF-8', '.js')
|
||||
mimetypes.add_type('text/javascript', '.js')
|
||||
mimetypes.add_type('text/rtf', '.rtf')
|
||||
|
||||
log = logger.create()
|
||||
|
||||
@@ -84,8 +87,10 @@ app = Flask(__name__)
|
||||
app.config.update(
|
||||
SESSION_COOKIE_HTTPONLY=True,
|
||||
SESSION_COOKIE_SAMESITE='Lax',
|
||||
REMEMBER_COOKIE_SAMESITE='Lax', # will be available in flask-login 0.5.1 earliest
|
||||
WTF_CSRF_SSL_STRICT=False
|
||||
REMEMBER_COOKIE_SAMESITE='Strict',
|
||||
WTF_CSRF_SSL_STRICT=False,
|
||||
SESSION_COOKIE_NAME=os.environ.get('COOKIE_PREFIX', "") + "session",
|
||||
REMEMBER_COOKIE_NAME=os.environ.get('COOKIE_PREFIX', "") + "remember_token"
|
||||
)
|
||||
|
||||
lm = MyLoginManager()
|
||||
@@ -99,19 +104,26 @@ if wtf_present:
|
||||
else:
|
||||
csrf = None
|
||||
|
||||
calibre_db = db.CalibreDB()
|
||||
calibre_db = db.CalibreDB(app)
|
||||
|
||||
web_server = WebServer()
|
||||
|
||||
updater_thread = Updater()
|
||||
|
||||
if limiter_present:
|
||||
limiter = Limiter(key_func=True, headers_enabled=True, auto_check=False, swallow_errors=False)
|
||||
limiter = Limiter(key_func=True, headers_enabled=True, in_memory_fallback_enabled=True, default_limits=[],
|
||||
swallow_errors=True)
|
||||
else:
|
||||
limiter = None
|
||||
|
||||
class ScriptNameSessionInterface(SecureCookieSessionInterface):
|
||||
def get_cookie_path(self, app):
|
||||
# Called once per response, after request context exists
|
||||
return app.wsgi_app.script_name.rstrip("/") or "/"
|
||||
|
||||
|
||||
def create_app():
|
||||
app.session_interface = ScriptNameSessionInterface()
|
||||
if csrf:
|
||||
csrf.init_app(app)
|
||||
|
||||
@@ -143,9 +155,7 @@ def create_app():
|
||||
lm.anonymous_user = ub.Anonymous
|
||||
lm.session_protection = 'strong' if config.config_session == 1 else "basic"
|
||||
|
||||
db.CalibreDB.update_config(config)
|
||||
db.CalibreDB.setup_db(config.config_calibre_dir, cli_param.settings_path)
|
||||
calibre_db.init_db()
|
||||
db.CalibreDB.update_config(config, config.config_calibre_dir, cli_param.settings_path)
|
||||
|
||||
updater_thread.init_updater(config, web_server)
|
||||
# Perform dry run of updater and exit afterward
|
||||
@@ -178,6 +188,7 @@ def create_app():
|
||||
app.secret_key = os.getenv('SECRET_KEY', config_sql.get_flask_session_key(ub.session))
|
||||
|
||||
web_server.init_app(app, config)
|
||||
from .cw_babel import babel, get_locale
|
||||
if hasattr(babel, "localeselector"):
|
||||
babel.init_app(app)
|
||||
babel.localeselector(get_locale)
|
||||
|
||||
+8
-7
@@ -23,15 +23,15 @@
|
||||
import sys
|
||||
import platform
|
||||
import sqlite3
|
||||
from importlib.metadata import metadata
|
||||
from collections import OrderedDict
|
||||
|
||||
import flask
|
||||
import flask_login
|
||||
import jinja2
|
||||
from flask_babel import gettext as _
|
||||
|
||||
from . import db, calibre_db, converter, uploader, constants, dep_check
|
||||
from .render_template import render_title_template
|
||||
from .usermanagement import user_login_required
|
||||
|
||||
|
||||
about = flask.Blueprint('about', __name__)
|
||||
@@ -41,17 +41,18 @@ req = dep_check.load_dependencies(False)
|
||||
opt = dep_check.load_dependencies(True)
|
||||
for i in (req + opt):
|
||||
modules[i[1]] = i[0]
|
||||
modules['Jinja2'] = jinja2.__version__
|
||||
modules['pySqlite'] = sqlite3.version
|
||||
modules['Jinja2'] = metadata("jinja2")["Version"]
|
||||
if sys.version_info < (3, 12):
|
||||
modules['pySqlite'] = sqlite3.version
|
||||
modules['SQLite'] = sqlite3.sqlite_version
|
||||
sorted_modules = OrderedDict((sorted(modules.items(), key=lambda x: x[0].casefold())))
|
||||
|
||||
|
||||
def collect_stats():
|
||||
if constants.NIGHTLY_VERSION[0] == "$Format:%H$":
|
||||
calibre_web_version = constants.STABLE_VERSION['version'].replace("b", " Beta")
|
||||
calibre_web_version = constants.STABLE_VERSION.replace("b", " Beta")
|
||||
else:
|
||||
calibre_web_version = (constants.STABLE_VERSION['version'].replace("b", " Beta") + ' - '
|
||||
calibre_web_version = (constants.STABLE_VERSION.replace("b", " Beta") + ' - '
|
||||
+ constants.NIGHTLY_VERSION[0].replace('%', '%%') + ' - '
|
||||
+ constants.NIGHTLY_VERSION[1].replace('%', '%%'))
|
||||
|
||||
@@ -74,7 +75,7 @@ def collect_stats():
|
||||
|
||||
|
||||
@about.route("/stats")
|
||||
@flask_login.login_required
|
||||
@user_login_required
|
||||
def stats():
|
||||
counter = calibre_db.session.query(db.Books).count()
|
||||
authors = calibre_db.session.query(db.Authors).count()
|
||||
|
||||
Executable → Regular
+147
-115
@@ -32,15 +32,15 @@ from datetime import time as datetime_time
|
||||
from functools import wraps
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from flask import Blueprint, flash, redirect, url_for, abort, request, make_response, send_from_directory, g, Response
|
||||
from flask import Blueprint, flash, redirect, url_for, abort, request, make_response, \
|
||||
send_from_directory, g, jsonify
|
||||
from markupsafe import Markup
|
||||
from flask_login import login_required, current_user, logout_user
|
||||
from .cw_login import current_user
|
||||
from flask_babel import gettext as _
|
||||
from flask_babel import get_locale, format_time, format_datetime, format_timedelta
|
||||
from flask import session as flask_session
|
||||
from sqlalchemy import and_
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError, InvalidRequestError
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError, InvalidRequestError, ArgumentError
|
||||
from sqlalchemy.sql.expression import func, or_, text
|
||||
|
||||
from . import constants, logger, helper, services, cli_param
|
||||
@@ -52,8 +52,10 @@ from .embed_helper import get_calibre_binarypath
|
||||
from .gdriveutils import is_gdrive_ready, gdrive_support
|
||||
from .render_template import render_title_template, get_sidebar_config
|
||||
from .services.worker import WorkerThread
|
||||
from .babel import get_available_translations, get_available_locale, get_user_locale_language
|
||||
from .usermanagement import user_login_required
|
||||
from .cw_babel import get_available_translations, get_available_locale, get_user_locale_language
|
||||
from . import debug_info
|
||||
from .string_helper import strip_whitespaces
|
||||
|
||||
log = logger.create()
|
||||
|
||||
@@ -103,13 +105,13 @@ def admin_required(f):
|
||||
|
||||
@admi.before_app_request
|
||||
def before_request():
|
||||
try:
|
||||
if not ub.check_user_session(current_user.id,
|
||||
flask_session.get('_id')) and 'opds' not in request.path \
|
||||
and config.config_session == 1:
|
||||
logout_user()
|
||||
except AttributeError:
|
||||
pass # ? fails on requesting /ajax/emailstat during restart ?
|
||||
#try:
|
||||
#if not ub.check_user_session(current_user.id,
|
||||
# flask_session.get('_id')) and 'opds' not in request.path \
|
||||
# and config.config_session == 1:
|
||||
# logout_user()
|
||||
#except AttributeError:
|
||||
# pass # ? fails on requesting /ajax/emailstat during restart ?
|
||||
g.constants = constants
|
||||
g.google_site_verification = os.getenv('GOOGLE_SITE_VERIFICATION', '')
|
||||
g.allow_registration = config.config_public_reg
|
||||
@@ -117,7 +119,7 @@ def before_request():
|
||||
g.allow_upload = config.config_uploading
|
||||
g.current_theme = config.config_theme
|
||||
g.config_authors_max = config.config_authors_max
|
||||
if '/static/' not in request.path and not config.db_configured and \
|
||||
if ('/static/' not in request.path and not config.db_configured and
|
||||
request.endpoint not in ('admin.ajax_db_config',
|
||||
'admin.simulatedbchange',
|
||||
'admin.db_configuration',
|
||||
@@ -125,25 +127,24 @@ def before_request():
|
||||
'web.login_post',
|
||||
'web.logout',
|
||||
'admin.load_dialogtexts',
|
||||
'admin.ajax_pathchooser'):
|
||||
'admin.ajax_pathchooser')):
|
||||
return redirect(url_for('admin.db_configuration'))
|
||||
|
||||
|
||||
@admi.route("/admin")
|
||||
@login_required
|
||||
def admin_forbidden():
|
||||
abort(403)
|
||||
#@admi.route("/admin")
|
||||
#@user_login_required
|
||||
#def admin_forbidden():
|
||||
# abort(403)
|
||||
|
||||
|
||||
@admi.route("/shutdown", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def shutdown():
|
||||
task = request.get_json().get('parameter', -1)
|
||||
show_text = {}
|
||||
if task in (0, 1): # valid commandos received
|
||||
# close all database connections
|
||||
calibre_db.dispose()
|
||||
ub.dispose()
|
||||
|
||||
if task == 0:
|
||||
@@ -165,7 +166,7 @@ def shutdown():
|
||||
|
||||
|
||||
@admi.route("/metadata_backup", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def queue_metadata_backup():
|
||||
show_text = {}
|
||||
@@ -188,8 +189,8 @@ def reconnect():
|
||||
|
||||
|
||||
@admi.route("/ajax/updateThumbnails", methods=['POST'])
|
||||
@user_login_required
|
||||
@admin_required
|
||||
@login_required
|
||||
def update_thumbnails():
|
||||
content = config.get_scheduled_task_settings()
|
||||
if content['schedule_generate_book_covers']:
|
||||
@@ -199,7 +200,7 @@ def update_thumbnails():
|
||||
|
||||
|
||||
@admi.route("/admin/view")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def admin():
|
||||
version = updater_thread.get_current_version_info()
|
||||
@@ -233,7 +234,7 @@ def admin():
|
||||
|
||||
|
||||
@admi.route("/admin/dbconfig", methods=["GET", "POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def db_configuration():
|
||||
if request.method == "POST":
|
||||
@@ -242,7 +243,7 @@ def db_configuration():
|
||||
|
||||
|
||||
@admi.route("/admin/config", methods=["GET"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def configuration():
|
||||
return render_title_template("config_edit.html",
|
||||
@@ -253,28 +254,28 @@ def configuration():
|
||||
|
||||
|
||||
@admi.route("/admin/ajaxconfig", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def ajax_config():
|
||||
return _configuration_update_helper()
|
||||
|
||||
|
||||
@admi.route("/admin/ajaxdbconfig", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def ajax_db_config():
|
||||
return _db_configuration_update_helper()
|
||||
|
||||
|
||||
@admi.route("/admin/alive", methods=["GET"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def calibreweb_alive():
|
||||
return "", 200
|
||||
|
||||
|
||||
@admi.route("/admin/viewconfig")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def view_configuration():
|
||||
read_column = calibre_db.session.query(db.CustomColumns) \
|
||||
@@ -291,7 +292,7 @@ def view_configuration():
|
||||
|
||||
|
||||
@admi.route("/admin/usertable")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def edit_user_table():
|
||||
visibility = current_user.view_settings.get('useredit', {})
|
||||
@@ -305,7 +306,15 @@ def edit_user_table():
|
||||
.group_by(text('books_tags_link.tag')) \
|
||||
.order_by(db.Tags.name).all()
|
||||
if config.config_restricted_column:
|
||||
custom_values = calibre_db.session.query(db.cc_classes[config.config_restricted_column]).all()
|
||||
try:
|
||||
custom_values = calibre_db.session.query(db.cc_classes[config.config_restricted_column]).all()
|
||||
except (KeyError, AttributeError, IndexError):
|
||||
custom_values = []
|
||||
log.error("Custom Column No.{} does not exist in calibre database".format(
|
||||
config.config_restricted_column))
|
||||
flash(_("Custom Column No.%(column)d does not exist in calibre database",
|
||||
column=config.config_restricted_column),
|
||||
category="error")
|
||||
else:
|
||||
custom_values = []
|
||||
if not config.config_anonbrowse:
|
||||
@@ -326,7 +335,7 @@ def edit_user_table():
|
||||
|
||||
|
||||
@admi.route("/ajax/listusers")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def list_users():
|
||||
off = int(request.args.get("offset") or 0)
|
||||
@@ -340,8 +349,9 @@ def list_users():
|
||||
if sort not in ub.User.__table__.columns.keys():
|
||||
sort = "id"
|
||||
order = request.args.get("order", "").lower()
|
||||
|
||||
if sort != "state" and order:
|
||||
if not order in ["asc", "desc"]:
|
||||
order = "asc"
|
||||
order = text(sort + " " + order)
|
||||
elif not state:
|
||||
order = ub.User.id.asc()
|
||||
@@ -370,29 +380,25 @@ def list_users():
|
||||
user.default = get_user_locale_language(user.default_language)
|
||||
|
||||
table_entries = {'totalNotFiltered': total_count, 'total': filtered_count, "rows": users}
|
||||
js_list = json.dumps(table_entries, cls=db.AlchemyEncoder)
|
||||
response = make_response(js_list)
|
||||
response.headers["Content-Type"] = "application/json; charset=utf-8"
|
||||
return response
|
||||
return make_response(json.dumps(table_entries, cls=db.AlchemyEncoder))
|
||||
|
||||
|
||||
@admi.route("/ajax/deleteuser", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def delete_user():
|
||||
user_ids = request.form.to_dict(flat=False)
|
||||
users = None
|
||||
user_ids = request.get_json().get("userid")
|
||||
message = ""
|
||||
if "userid[]" in user_ids:
|
||||
users = ub.session.query(ub.User).filter(ub.User.id.in_(user_ids['userid[]'])).all()
|
||||
elif "userid" in user_ids:
|
||||
users = ub.session.query(ub.User).filter(ub.User.id == user_ids['userid'][0]).all()
|
||||
try:
|
||||
users = ub.session.query(ub.User).filter(ub.User.id.in_(user_ids)).all()
|
||||
except (ArgumentError):
|
||||
users = None
|
||||
count = 0
|
||||
errors = list()
|
||||
success = list()
|
||||
if not users:
|
||||
log.error("User not found")
|
||||
return Response(json.dumps({'type': "danger", 'message': _("User not found")}), mimetype='application/json')
|
||||
return make_response(jsonify(type="danger", message=_("User not found")))
|
||||
for user in users:
|
||||
try:
|
||||
message = _delete_user(user)
|
||||
@@ -402,17 +408,17 @@ def delete_user():
|
||||
errors.append({'type': "danger", 'message': str(ex)})
|
||||
|
||||
if count == 1:
|
||||
log.info("User {} deleted".format(user_ids))
|
||||
log.info("User {} deleted".format(user_ids[0]))
|
||||
success = [{'type': "success", 'message': message}]
|
||||
elif count > 1:
|
||||
log.info("Users {} deleted".format(user_ids))
|
||||
log.info("Users {} deleted".format(", ".join([str(user_id) for user_id in user_ids])))
|
||||
success = [{'type': "success", 'message': _("{} users deleted successfully").format(count)}]
|
||||
success.extend(errors)
|
||||
return Response(json.dumps(success), mimetype='application/json')
|
||||
return make_response(jsonify(success))
|
||||
|
||||
|
||||
@admi.route("/ajax/getlocale")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def table_get_locale():
|
||||
locale = get_available_locale()
|
||||
@@ -420,11 +426,11 @@ def table_get_locale():
|
||||
current_locale = get_locale()
|
||||
for loc in locale:
|
||||
ret.append({'value': str(loc), 'text': loc.get_language_name(current_locale)})
|
||||
return json.dumps(ret)
|
||||
return json.dumps(sorted(ret, key=lambda x: x['text']))
|
||||
|
||||
|
||||
@admi.route("/ajax/getdefaultlanguage")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def table_get_default_lang():
|
||||
languages = calibre_db.speaking_language()
|
||||
@@ -432,11 +438,11 @@ def table_get_default_lang():
|
||||
ret.append({'value': 'all', 'text': _('Show All')})
|
||||
for lang in languages:
|
||||
ret.append({'value': lang.lang_code, 'text': lang.name})
|
||||
return json.dumps(ret)
|
||||
return json.dumps(sorted(ret, key=lambda x: x['text']))
|
||||
|
||||
|
||||
@admi.route("/ajax/editlistusers/<param>", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def edit_list_user(param):
|
||||
vals = request.form.to_dict(flat=False)
|
||||
@@ -463,9 +469,9 @@ def edit_list_user(param):
|
||||
if 'value[]' in vals:
|
||||
setattr(user, param, prepare_tags(user, vals['action'][0], param, vals['value[]']))
|
||||
else:
|
||||
setattr(user, param, vals['value'].strip())
|
||||
setattr(user, param, strip_whitespaces(vals['value']))
|
||||
else:
|
||||
vals['value'] = vals['value'].strip()
|
||||
vals['value'] = strip_whitespaces(vals['value'])
|
||||
if param == 'name':
|
||||
if user.name == "Guest":
|
||||
raise Exception(_("Guest Name can't be changed"))
|
||||
@@ -490,10 +496,10 @@ def edit_list_user(param):
|
||||
if not ub.session.query(ub.User). \
|
||||
filter(ub.User.role.op('&')(constants.ROLE_ADMIN) == constants.ROLE_ADMIN,
|
||||
ub.User.id != user.id).count():
|
||||
return Response(
|
||||
json.dumps([{'type': "danger",
|
||||
return make_response(
|
||||
jsonify([{'type': "danger",
|
||||
'message': _("No admin user remaining, can't remove admin role",
|
||||
nick=user.name)}]), mimetype='application/json')
|
||||
nick=user.name)}]))
|
||||
user.role &= ~value
|
||||
else:
|
||||
raise Exception(_("Value has to be true or false"))
|
||||
@@ -541,7 +547,7 @@ def edit_list_user(param):
|
||||
|
||||
|
||||
@admi.route("/ajax/user_table_settings", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def update_table_settings():
|
||||
current_user.view_settings['useredit'] = json.loads(request.data)
|
||||
@@ -558,7 +564,7 @@ def update_table_settings():
|
||||
|
||||
|
||||
@admi.route("/admin/viewconfig", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def update_view_configuration():
|
||||
to_save = request.form.to_dict()
|
||||
@@ -566,7 +572,7 @@ def update_view_configuration():
|
||||
_config_string(to_save, "config_calibre_web_title")
|
||||
_config_string(to_save, "config_columns_to_ignore")
|
||||
if _config_string(to_save, "config_title_regex"):
|
||||
calibre_db.update_title_sort(config)
|
||||
calibre_db.create_functions(config)
|
||||
|
||||
if not check_valid_read_column(to_save.get("config_read_column", "0")):
|
||||
flash(_("Invalid Read Column"), category="error")
|
||||
@@ -603,7 +609,7 @@ def update_view_configuration():
|
||||
|
||||
|
||||
@admi.route("/ajax/loaddialogtexts/<element_id>", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def load_dialogtexts(element_id):
|
||||
texts = {"header": "", "main": "", "valid": 1}
|
||||
if element_id == "config_delete_kobo_token":
|
||||
@@ -612,6 +618,8 @@ def load_dialogtexts(element_id):
|
||||
texts["main"] = _('Do you really want to delete this domain?')
|
||||
elif element_id == "btndeluser":
|
||||
texts["main"] = _('Do you really want to delete this user?')
|
||||
elif element_id == "btndelbook":
|
||||
texts["main"] = _('Do you really want to delete this book?')
|
||||
elif element_id == "delete_shelf":
|
||||
texts["main"] = _('Are you sure you want to delete this shelf?')
|
||||
elif element_id == "select_locale":
|
||||
@@ -620,6 +628,10 @@ def load_dialogtexts(element_id):
|
||||
texts["main"] = _('Are you sure you want to change visible book languages for selected user(s)?')
|
||||
elif element_id == "role":
|
||||
texts["main"] = _('Are you sure you want to change the selected role for the selected user(s)?')
|
||||
elif element_id == "archive_books":
|
||||
texts["main"] = _('Are you sure you want to change the archive status for the selected book(s)?')
|
||||
elif element_id == "read_books":
|
||||
texts["main"] = _('Are you sure you want to change the read status for the selected book(s)?')
|
||||
elif element_id == "restrictions":
|
||||
texts["main"] = _('Are you sure you want to change the selected restrictions for the selected user(s)?')
|
||||
elif element_id == "sidebar_view":
|
||||
@@ -639,7 +651,7 @@ def load_dialogtexts(element_id):
|
||||
|
||||
|
||||
@admi.route("/ajax/editdomain/<int:allow>", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def edit_domain(allow):
|
||||
# POST /post
|
||||
@@ -653,7 +665,7 @@ def edit_domain(allow):
|
||||
|
||||
|
||||
@admi.route("/ajax/adddomain/<int:allow>", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def add_domain(allow):
|
||||
domain_name = request.form.to_dict()['domainname'].replace('*', '%').replace('?', '_').lower()
|
||||
@@ -667,7 +679,7 @@ def add_domain(allow):
|
||||
|
||||
|
||||
@admi.route("/ajax/deletedomain", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def delete_domain():
|
||||
try:
|
||||
@@ -685,12 +697,12 @@ def delete_domain():
|
||||
|
||||
|
||||
@admi.route("/ajax/domainlist/<int:allow>")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def list_domain(allow):
|
||||
answer = ub.session.query(ub.Registration).filter(ub.Registration.allow == allow).all()
|
||||
json_dumps = json.dumps([{"domain": r.domain.replace('%', '*').replace('_', '?'), "id": r.id} for r in answer])
|
||||
js = json.dumps(json_dumps.replace('"', "'")).lstrip('"').strip('"')
|
||||
js = json.dumps(json_dumps.replace('"', "'")).strip('"')
|
||||
response = make_response(js.replace("'", '"'))
|
||||
response.headers["Content-Type"] = "application/json; charset=utf-8"
|
||||
return response
|
||||
@@ -698,7 +710,7 @@ def list_domain(allow):
|
||||
|
||||
@admi.route("/ajax/editrestriction/<int:res_type>", defaults={"user_id": 0}, methods=['POST'])
|
||||
@admi.route("/ajax/editrestriction/<int:res_type>/<int:user_id>", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def edit_restriction(res_type, user_id):
|
||||
element = request.form.to_dict()
|
||||
@@ -764,14 +776,14 @@ def edit_restriction(res_type, user_id):
|
||||
|
||||
|
||||
@admi.route("/ajax/addrestriction/<int:res_type>", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def add_user_0_restriction(res_type):
|
||||
return add_restriction(res_type, 0)
|
||||
|
||||
|
||||
@admi.route("/ajax/addrestriction/<int:res_type>/<int:user_id>", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def add_restriction(res_type, user_id):
|
||||
element = request.form.to_dict()
|
||||
@@ -817,14 +829,14 @@ def add_restriction(res_type, user_id):
|
||||
|
||||
|
||||
@admi.route("/ajax/deleterestriction/<int:res_type>", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def delete_user_0_restriction(res_type):
|
||||
return delete_restriction(res_type, 0)
|
||||
|
||||
|
||||
@admi.route("/ajax/deleterestriction/<int:res_type>/<int:user_id>", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def delete_restriction(res_type, user_id):
|
||||
element = request.form.to_dict()
|
||||
@@ -872,7 +884,7 @@ def delete_restriction(res_type, user_id):
|
||||
|
||||
@admi.route("/ajax/listrestriction/<int:res_type>", defaults={"user_id": 0})
|
||||
@admi.route("/ajax/listrestriction/<int:res_type>/<int:user_id>")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def list_restriction(res_type, user_id):
|
||||
if res_type == 0: # Tags as template
|
||||
@@ -916,20 +928,20 @@ def list_restriction(res_type, user_id):
|
||||
|
||||
|
||||
@admi.route("/ajax/fullsync", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def ajax_self_fullsync():
|
||||
return do_full_kobo_sync(current_user.id)
|
||||
|
||||
|
||||
@admi.route("/ajax/fullsync/<int:userid>", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def ajax_fullsync(userid):
|
||||
return do_full_kobo_sync(userid)
|
||||
|
||||
|
||||
@admi.route("/ajax/pathchooser/")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def ajax_pathchooser():
|
||||
return pathchooser()
|
||||
@@ -939,7 +951,7 @@ def do_full_kobo_sync(userid):
|
||||
count = ub.session.query(ub.KoboSyncedBooks).filter(userid == ub.KoboSyncedBooks.user_id).delete()
|
||||
message = _("{} sync entries deleted").format(count)
|
||||
ub.session_commit(message)
|
||||
return Response(json.dumps([{"type": "success", "message": message}]), mimetype='application/json')
|
||||
return make_response(jsonify(type="success", message=message))
|
||||
|
||||
|
||||
def check_valid_read_column(column):
|
||||
@@ -981,8 +993,14 @@ def prepare_tags(user, action, tags_name, id_list):
|
||||
raise Exception(_("Tag not found"))
|
||||
new_tags_list = [x.name for x in tags]
|
||||
else:
|
||||
tags = calibre_db.session.query(db.cc_classes[config.config_restricted_column]) \
|
||||
.filter(db.cc_classes[config.config_restricted_column].id.in_(id_list)).all()
|
||||
try:
|
||||
tags = calibre_db.session.query(db.cc_classes[config.config_restricted_column]) \
|
||||
.filter(db.cc_classes[config.config_restricted_column].id.in_(id_list)).all()
|
||||
except (KeyError, AttributeError, IndexError):
|
||||
log.error("Custom Column No.{} does not exist in calibre database".format(
|
||||
config.config_restricted_column))
|
||||
raise Exception(_("Custom Column No.%(column)d does not exist in calibre database",
|
||||
column=config.config_restricted_column))
|
||||
new_tags_list = [x.value for x in tags]
|
||||
saved_tags_list = user.__dict__[tags_name].split(",") if len(user.__dict__[tags_name]) else []
|
||||
if action == "remove":
|
||||
@@ -1100,7 +1118,7 @@ def _config_checkbox_int(to_save, x):
|
||||
|
||||
|
||||
def _config_string(to_save, x):
|
||||
return config.set_from_dictionary(to_save, x, lambda y: y.strip().strip(u'\u200B\u200C\u200D\ufeff') if y else y)
|
||||
return config.set_from_dictionary(to_save, x, lambda y: strip_whitespaces(y) if y else y)
|
||||
|
||||
|
||||
def _configuration_gdrive_helper(to_save):
|
||||
@@ -1246,15 +1264,15 @@ def _configuration_ldap_helper(to_save):
|
||||
|
||||
|
||||
@admi.route("/ajax/simulatedbchange", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def simulatedbchange():
|
||||
db_change, db_valid = _db_simulate_change()
|
||||
return Response(json.dumps({"change": db_change, "valid": db_valid}), mimetype='application/json')
|
||||
return make_response(jsonify(change=db_change, valid=db_valid))
|
||||
|
||||
|
||||
@admi.route("/admin/user/new", methods=["GET", "POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def new_user():
|
||||
content = ub.User()
|
||||
@@ -1276,7 +1294,7 @@ def new_user():
|
||||
|
||||
|
||||
@admi.route("/admin/mailsettings", methods=["GET"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def edit_mailsettings():
|
||||
content = config.get_mail_settings()
|
||||
@@ -1285,7 +1303,7 @@ def edit_mailsettings():
|
||||
|
||||
|
||||
@admi.route("/admin/mailsettings", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def update_mailsettings():
|
||||
to_save = request.form.to_dict()
|
||||
@@ -1311,9 +1329,9 @@ def update_mailsettings():
|
||||
if to_save.get("mail_password_e", ""):
|
||||
_config_string(to_save, "mail_password_e")
|
||||
_config_int(to_save, "mail_size", lambda y: int(y) * 1024 * 1024)
|
||||
config.mail_server = to_save.get('mail_server', "").strip()
|
||||
config.mail_from = to_save.get('mail_from', "").strip()
|
||||
config.mail_login = to_save.get('mail_login', "").strip()
|
||||
config.mail_server = strip_whitespaces(to_save.get('mail_server', ""))
|
||||
config.mail_from = strip_whitespaces(to_save.get('mail_from', ""))
|
||||
config.mail_login = strip_whitespaces(to_save.get('mail_login', ""))
|
||||
try:
|
||||
config.save()
|
||||
except (OperationalError, InvalidRequestError) as e:
|
||||
@@ -1342,7 +1360,7 @@ def update_mailsettings():
|
||||
|
||||
|
||||
@admi.route("/admin/scheduledtasks")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def edit_scheduledtasks():
|
||||
content = config.get_scheduled_task_settings()
|
||||
@@ -1363,7 +1381,7 @@ def edit_scheduledtasks():
|
||||
|
||||
|
||||
@admi.route("/admin/scheduledtasks", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def update_scheduledtasks():
|
||||
error = False
|
||||
@@ -1406,7 +1424,7 @@ def update_scheduledtasks():
|
||||
|
||||
|
||||
@admi.route("/admin/user/<int:user_id>", methods=["GET", "POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def edit_user(user_id):
|
||||
content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() # type: ub.User
|
||||
@@ -1435,7 +1453,7 @@ def edit_user(user_id):
|
||||
|
||||
|
||||
@admi.route("/admin/resetpassword/<int:user_id>", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def reset_user_password(user_id):
|
||||
if current_user is not None and current_user.is_authenticated:
|
||||
@@ -1453,7 +1471,7 @@ def reset_user_password(user_id):
|
||||
|
||||
|
||||
@admi.route("/admin/logfile")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def view_logfile():
|
||||
logfiles = {0: logger.get_logfile(config.config_logfile),
|
||||
@@ -1467,7 +1485,7 @@ def view_logfile():
|
||||
|
||||
|
||||
@admi.route("/ajax/log/<int:logtype>")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def send_logfile(logtype):
|
||||
if logtype == 1:
|
||||
@@ -1483,7 +1501,7 @@ def send_logfile(logtype):
|
||||
|
||||
|
||||
@admi.route("/admin/logdownload/<int:logtype>")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def download_log(logtype):
|
||||
if logtype == 0:
|
||||
@@ -1498,14 +1516,14 @@ def download_log(logtype):
|
||||
|
||||
|
||||
@admi.route("/admin/debug")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def download_debug():
|
||||
return debug_info.send_debug()
|
||||
|
||||
|
||||
@admi.route("/get_update_status", methods=['GET'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def get_update_status():
|
||||
if feature_support['updater']:
|
||||
@@ -1516,7 +1534,7 @@ def get_update_status():
|
||||
|
||||
|
||||
@admi.route("/get_updater_status", methods=['GET', 'POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def get_updater_status():
|
||||
status = {}
|
||||
@@ -1611,7 +1629,7 @@ def ldap_import_create_user(user, user_data):
|
||||
|
||||
|
||||
@admi.route('/import_ldap_users', methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def import_ldap_users():
|
||||
showtext = {}
|
||||
@@ -1666,7 +1684,7 @@ def import_ldap_users():
|
||||
|
||||
|
||||
@admi.route("/ajax/canceltask", methods=['POST'])
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def cancel_task():
|
||||
task_id = request.get_json().get('task_id', None)
|
||||
@@ -1678,10 +1696,10 @@ def cancel_task():
|
||||
def _db_simulate_change():
|
||||
param = request.form.to_dict()
|
||||
to_save = dict()
|
||||
to_save['config_calibre_dir'] = re.sub(r'[\\/]metadata\.db$',
|
||||
to_save['config_calibre_dir'] = strip_whitespaces(re.sub(r'[\\/]metadata\.db$',
|
||||
'',
|
||||
param['config_calibre_dir'],
|
||||
flags=re.IGNORECASE).strip()
|
||||
flags=re.IGNORECASE))
|
||||
db_valid, db_change = calibre_db.check_valid_db(to_save["config_calibre_dir"],
|
||||
ub.app_DB_path,
|
||||
config.config_calibre_uuid)
|
||||
@@ -1715,14 +1733,19 @@ def _db_configuration_update_helper():
|
||||
db_change = True
|
||||
except Exception as ex:
|
||||
return _db_configuration_result('{}'.format(ex), gdrive_error)
|
||||
|
||||
if db_change or not db_valid or not config.db_configured \
|
||||
or config.config_calibre_dir != to_save["config_calibre_dir"]:
|
||||
config.config_calibre_split = to_save.get('config_calibre_split', 0) == "on"
|
||||
if config.config_calibre_split:
|
||||
split_dir = to_save.get("config_calibre_split_dir")
|
||||
if not os.path.exists(split_dir):
|
||||
return _db_configuration_result(_("Books path not valid"), gdrive_error)
|
||||
else:
|
||||
_config_string(to_save, "config_calibre_split_dir")
|
||||
if (db_change or not db_valid or not config.db_configured
|
||||
or config.config_calibre_dir != to_save["config_calibre_dir"]):
|
||||
if not os.path.exists(metadata_db) or not to_save['config_calibre_dir']:
|
||||
return _db_configuration_result(_('DB Location is not Valid, Please Enter Correct Path'), gdrive_error)
|
||||
else:
|
||||
calibre_db.setup_db(to_save['config_calibre_dir'], ub.app_DB_path)
|
||||
config.store_calibre_uuid(calibre_db, db.Library_Id)
|
||||
# if db changed -> delete shelfs, delete download books, delete read books, kobo sync...
|
||||
if db_change:
|
||||
log.info("Calibre Database changed, all Calibre-Web info related to old Database gets deleted")
|
||||
@@ -1736,13 +1759,20 @@ def _db_configuration_update_helper():
|
||||
ub.session.query(ub.KoboSyncedBooks).delete()
|
||||
helper.delete_thumbnail_cache()
|
||||
ub.session_commit()
|
||||
# deleted visibilities based on custom column and tags
|
||||
config.config_restricted_column = 0
|
||||
config.config_denied_tags = ""
|
||||
config.config_allowed_tags = ""
|
||||
config.config_columns_to_ignore = ""
|
||||
config.config_denied_column_value = ""
|
||||
config.config_allowed_column_value = ""
|
||||
config.config_read_column = 0
|
||||
_config_string(to_save, "config_calibre_dir")
|
||||
calibre_db.update_config(config)
|
||||
calibre_db.update_config(config, config.config_calibre_dir, ub.app_DB_path)
|
||||
config.store_calibre_uuid(calibre_db, db.Library_Id)
|
||||
if not os.access(os.path.join(config.config_calibre_dir, "metadata.db"), os.W_OK):
|
||||
flash(_("DB is not Writeable"), category="warning")
|
||||
_config_string(to_save, "config_calibre_split_dir")
|
||||
config.config_calibre_split = to_save.get('config_calibre_split', 0) == "on"
|
||||
calibre_db.update_config(config)
|
||||
calibre_db.update_config(config, config.config_calibre_dir, ub.app_DB_path)
|
||||
config.save()
|
||||
return _db_configuration_result(None, gdrive_error)
|
||||
|
||||
@@ -1775,9 +1805,8 @@ def _configuration_update_helper():
|
||||
|
||||
if "config_upload_formats" in to_save:
|
||||
to_save["config_upload_formats"] = ','.join(
|
||||
helper.uniq([x.lstrip().rstrip().lower() for x in to_save["config_upload_formats"].split(',')]))
|
||||
helper.uniq([x.strip().lower() for x in to_save["config_upload_formats"].split(',')]))
|
||||
_config_string(to_save, "config_upload_formats")
|
||||
# constants.EXTENSIONS_UPLOAD = config.config_upload_formats.split(',')
|
||||
|
||||
_config_string(to_save, "config_calibre")
|
||||
_config_string(to_save, "config_binariesdir")
|
||||
@@ -1810,6 +1839,9 @@ def _configuration_update_helper():
|
||||
services.goodreads_support.connect(config.config_goodreads_api_key,
|
||||
config.config_use_goodreads)
|
||||
|
||||
# Google Books API configuration
|
||||
reboot_required |=_config_string(to_save, "config_googlebooks_api_key")
|
||||
|
||||
_config_int(to_save, "config_updatechannel")
|
||||
|
||||
# Reverse proxy login configuration
|
||||
@@ -1871,7 +1903,7 @@ def _configuration_result(error_flash=None, reboot=False):
|
||||
resp['result'] = [{'type': "success", 'message': _("Calibre-Web configuration updated")}]
|
||||
resp['reboot'] = reboot
|
||||
resp['config_upload'] = config.config_upload_formats
|
||||
return Response(json.dumps(resp), mimetype='application/json')
|
||||
return make_response(jsonify(resp))
|
||||
|
||||
|
||||
def _db_configuration_result(error_flash=None, gdrive_error=None):
|
||||
@@ -2076,7 +2108,7 @@ def _handle_edit_user(to_save, content, languages, translations, kobo_support):
|
||||
|
||||
|
||||
def extract_user_data_from_field(user, field):
|
||||
match = re.search(field + r"=([@\.\d\s\w-]+)", user, re.IGNORECASE | re.UNICODE)
|
||||
match = re.search(field + r"=(.*?)($|(?<!\\),)", user, re.IGNORECASE | re.UNICODE)
|
||||
if match:
|
||||
return match.group(1)
|
||||
else:
|
||||
@@ -2084,7 +2116,7 @@ def extract_user_data_from_field(user, field):
|
||||
|
||||
|
||||
def extract_dynamic_field_from_filter(user, filtr):
|
||||
match = re.search("([a-zA-Z0-9-]+)=%s", filtr, re.IGNORECASE | re.UNICODE)
|
||||
match = re.search(r"([a-zA-Z0-9-]+)=%s", filtr, re.IGNORECASE | re.UNICODE)
|
||||
if match:
|
||||
return match.group(1)
|
||||
else:
|
||||
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2024 Ozzieisaacs
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import mutagen
|
||||
import base64
|
||||
from . import cover, logger
|
||||
|
||||
from cps.constants import BookMeta
|
||||
|
||||
log = logger.create()
|
||||
|
||||
def get_audio_file_info(tmp_file_path, original_file_extension, original_file_name, no_cover_processing):
|
||||
tmp_cover_name = None
|
||||
audio_file = mutagen.File(tmp_file_path)
|
||||
comments = None
|
||||
if original_file_extension in [".mp3", ".wav", ".aiff"]:
|
||||
cover_data = list()
|
||||
for key, val in audio_file.tags.items():
|
||||
if key.startswith("APIC:"):
|
||||
cover_data.append(val)
|
||||
if key.startswith("COMM:"):
|
||||
comments = val.text[0]
|
||||
title = audio_file.tags.get('TIT2').text[0] if "TIT2" in audio_file.tags else None
|
||||
author = audio_file.tags.get('TPE1').text[0] if "TPE1" in audio_file.tags else None
|
||||
if author is None:
|
||||
author = audio_file.tags.get('TPE2').text[0] if "TPE2" in audio_file.tags else None
|
||||
tags = audio_file.tags.get('TCON').text[0] if "TCON" in audio_file.tags else None # Genre
|
||||
series = audio_file.tags.get('TALB').text[0] if "TALB" in audio_file.tags else None# Album
|
||||
series_id = audio_file.tags.get('TRCK').text[0] if "TRCK" in audio_file.tags else None # track no.
|
||||
publisher = audio_file.tags.get('TPUB').text[0] if "TPUB" in audio_file.tags else None
|
||||
pubdate = str(audio_file.tags.get('TDRL').text[0]) if "TDRL" in audio_file.tags else None
|
||||
if not pubdate:
|
||||
pubdate = str(audio_file.tags.get('TDRC').text[0]) if "TDRC" in audio_file.tags else None
|
||||
if not pubdate:
|
||||
pubdate = str(audio_file.tags.get('TDOR').text[0]) if "TDOR" in audio_file.tags else None
|
||||
if cover_data and not no_cover_processing:
|
||||
cover_info = cover_data[0]
|
||||
for dat in cover_data:
|
||||
if dat.type == mutagen.id3.PictureType.COVER_FRONT:
|
||||
cover_info = dat
|
||||
break
|
||||
tmp_cover_name = cover.cover_processing(tmp_file_path, cover_info.data, "." + cover_info.mime[-3:])
|
||||
elif original_file_extension in [".ogg", ".flac", ".opus", ".ogv"]:
|
||||
title = audio_file.tags.get('TITLE')[0] if "TITLE" in audio_file else None
|
||||
author = audio_file.tags.get('ARTIST')[0] if "ARTIST" in audio_file else None
|
||||
comments = audio_file.tags.get('COMMENTS')[0] if "COMMENTS" in audio_file else None
|
||||
tags = audio_file.tags.get('GENRE')[0] if "GENRE" in audio_file else None # Genre
|
||||
series = audio_file.tags.get('ALBUM')[0] if "ALBUM" in audio_file else None
|
||||
series_id = audio_file.tags.get('TRACKNUMBER')[0] if "TRACKNUMBER" in audio_file else None
|
||||
publisher = audio_file.tags.get('LABEL')[0] if "LABEL" in audio_file else None
|
||||
pubdate = audio_file.tags.get('DATE')[0] if "DATE" in audio_file else None
|
||||
cover_data = audio_file.tags.get('METADATA_BLOCK_PICTURE')
|
||||
if not no_cover_processing:
|
||||
if cover_data:
|
||||
cover_info = mutagen.flac.Picture(base64.b64decode(cover_data[0]))
|
||||
tmp_cover_name = cover.cover_processing(tmp_file_path, cover_info.data, "." + cover_info.mime[-3:])
|
||||
if hasattr(audio_file, "pictures"):
|
||||
cover_info = audio_file.pictures[0]
|
||||
for dat in audio_file.pictures:
|
||||
if dat.type == mutagen.id3.PictureType.COVER_FRONT:
|
||||
cover_info = dat
|
||||
break
|
||||
tmp_cover_name = cover.cover_processing(tmp_file_path, cover_info.data, "." + cover_info.mime[-3:])
|
||||
elif original_file_extension in [".aac"]:
|
||||
title = audio_file.tags.get('Title').value if "Title" in audio_file else None
|
||||
author = audio_file.tags.get('Artist').value if "Artist" in audio_file else None
|
||||
comments = audio_file.tags.get('Comment').value if "Comment" in audio_file else None
|
||||
tags = audio_file.tags.get('Genre').value if "Genre" in audio_file else None
|
||||
series = audio_file.tags.get('Album').value if "Album" in audio_file else None
|
||||
series_id = audio_file.tags.get('Track').value if "Track" in audio_file else None
|
||||
publisher = audio_file.tags.get('Label').value if "Label" in audio_file else None
|
||||
pubdate = audio_file.tags.get('Year').value if "Year" in audio_file else None
|
||||
cover_data = audio_file.tags['Cover Art (Front)']
|
||||
if cover_data and not no_cover_processing:
|
||||
tmp_cover_name = tmp_file_path + '.jpg'
|
||||
with open(tmp_cover_name, "wb") as cover_file:
|
||||
cover_file.write(cover_data.value.split(b"\x00",1)[1])
|
||||
elif original_file_extension in [".asf"]:
|
||||
title = audio_file.tags.get('Title')[0].value if "Title" in audio_file else None
|
||||
author = audio_file.tags.get('Artist')[0].value if "Artist" in audio_file else None
|
||||
comments = audio_file.tags.get('Comments')[0].value if "Comments" in audio_file else None
|
||||
tags = audio_file.tags.get('Genre')[0].value if "Genre" in audio_file else None
|
||||
series = audio_file.tags.get('Album')[0].value if "Album" in audio_file else None
|
||||
series_id = audio_file.tags.get('Track')[0].value if "Track" in audio_file else None
|
||||
publisher = audio_file.tags.get('Label')[0].value if "Label" in audio_file else None
|
||||
pubdate = audio_file.tags.get('Year')[0].value if "Year" in audio_file else None
|
||||
cover_data = audio_file.tags.get('WM/Picture', None)
|
||||
if cover_data and not no_cover_processing:
|
||||
tmp_cover_name = tmp_file_path + '.jpg'
|
||||
with open(tmp_cover_name, "wb") as cover_file:
|
||||
cover_file.write(cover_data[0].value)
|
||||
elif original_file_extension in [".mp4", ".m4a", ".m4b"]:
|
||||
title = audio_file.tags.get('©nam')[0] if "©nam" in audio_file.tags else None
|
||||
author = audio_file.tags.get('©ART')[0] if "©ART" in audio_file.tags else None
|
||||
comments = audio_file.tags.get('©cmt')[0] if "©cmt" in audio_file.tags else None
|
||||
tags = audio_file.tags.get('©gen')[0] if "©gen" in audio_file.tags else None
|
||||
series = audio_file.tags.get('©alb')[0] if "©alb" in audio_file.tags else None
|
||||
series_id = str(audio_file.tags.get('trkn')[0][0]) if "trkn" in audio_file.tags else None
|
||||
publisher = ""
|
||||
pubdate = audio_file.tags.get('©day')[0] if "©day" in audio_file.tags else None
|
||||
cover_data = audio_file.tags.get('covr', None)
|
||||
if cover_data and not no_cover_processing:
|
||||
cover_type = None
|
||||
for c in cover_data:
|
||||
if c.imageformat == mutagen.mp4.AtomDataType.JPEG:
|
||||
cover_type =".jpg"
|
||||
cover_bin = c
|
||||
break
|
||||
elif c.imageformat == mutagen.mp4.AtomDataType.PNG:
|
||||
cover_type = ".png"
|
||||
cover_bin = c
|
||||
break
|
||||
if cover_type:
|
||||
tmp_cover_name = cover.cover_processing(tmp_file_path, cover_bin, cover_type)
|
||||
else:
|
||||
logger.error("Unknown covertype in file {} ".format(original_file_name))
|
||||
|
||||
return BookMeta(
|
||||
file_path=tmp_file_path,
|
||||
extension=original_file_extension,
|
||||
title=title or original_file_name ,
|
||||
author="Unknown" if author is None else author,
|
||||
cover=tmp_cover_name,
|
||||
description="" if comments is None else comments,
|
||||
tags="" if tags is None else tags,
|
||||
series="" if series is None else series,
|
||||
series_id="1" if series_id is None else series_id.split("/")[0],
|
||||
languages="",
|
||||
publisher= "" if publisher is None else publisher,
|
||||
pubdate="" if pubdate is None else pubdate,
|
||||
identifiers=[],
|
||||
)
|
||||
@@ -0,0 +1,89 @@
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11,
|
||||
# andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh,
|
||||
# falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe,
|
||||
# ruben-herold, marblepebble, JackED42, SiphonSquirrel,
|
||||
# apetresc, nanu-c, mutschler, carderne
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
from flask import Blueprint
|
||||
from flask_babel import gettext as _
|
||||
from flask_babel import get_locale
|
||||
from flask import request, redirect, url_for
|
||||
|
||||
from . import logger, isoLanguages
|
||||
from . import db, config
|
||||
from . import calibre_db
|
||||
from .usermanagement import login_required_if_no_ano
|
||||
from .render_template import render_title_template
|
||||
from .web import get_sort_function
|
||||
|
||||
try:
|
||||
from natsort import natsorted as sort
|
||||
except ImportError:
|
||||
sort = sorted # Just use regular sort then, may cause issues with badly named pages in cbz/cbr files
|
||||
|
||||
basic = Blueprint('basic', __name__)
|
||||
|
||||
log = logger.create()
|
||||
|
||||
|
||||
@basic.route("/basic", methods=["GET"])
|
||||
@login_required_if_no_ano
|
||||
def index():
|
||||
term = request.args.get("query", "") # default to showing all books
|
||||
limit = 15
|
||||
page = int(request.args.get("page") or 1)
|
||||
off = (page - 1) * limit
|
||||
order = get_sort_function("stored", "search")
|
||||
join = db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series
|
||||
entries, result_count, pagination = calibre_db.get_search_results(term,
|
||||
config,
|
||||
off,
|
||||
order,
|
||||
limit,
|
||||
*join)
|
||||
return render_title_template('basic_index.html',
|
||||
searchterm=term,
|
||||
pagination=pagination,
|
||||
query=term,
|
||||
adv_searchterm=term,
|
||||
entries=entries,
|
||||
result_count=result_count,
|
||||
title=_("Search"),
|
||||
page="search",
|
||||
order=order[1])
|
||||
|
||||
|
||||
@basic.route("/basic_book/<int:book_id>")
|
||||
@login_required_if_no_ano
|
||||
def show_book(book_id):
|
||||
entries = calibre_db.get_book_read_archived(book_id, config.config_read_column, allow_show_archived=True)
|
||||
if entries:
|
||||
entry = entries[0]
|
||||
for lang_index in range(0, len(entry.languages)):
|
||||
entry.languages[lang_index].language_name = isoLanguages.get_language_name(get_locale(), entry.languages[
|
||||
lang_index].lang_code)
|
||||
entry.ordered_authors = calibre_db.order_authors([entry])
|
||||
|
||||
return render_title_template('basic_detail.html',
|
||||
entry=entry,
|
||||
is_xhr=request.headers.get('X-Requested-With') == 'XMLHttpRequest',
|
||||
title=entry.title,
|
||||
page="book")
|
||||
else:
|
||||
log.debug("Selected book is unavailable. File does not exist or is not accessible")
|
||||
return redirect(url_for("basic.index"))
|
||||
+7
-2
@@ -35,8 +35,13 @@ def clean_string(unsafe_text, book_id=0):
|
||||
try:
|
||||
if bleach:
|
||||
allowed_tags = list(ALLOWED_TAGS)
|
||||
allowed_tags.extend(['p', 'span', 'div', 'pre'])
|
||||
safe_text = clean_html(unsafe_text, tags=set(allowed_tags))
|
||||
allowed_tags.extend(["p", "span", "div", "pre", "br", "h1", "h2", "h3", "h4", "h5", "h6", "img"])
|
||||
allowed_attributes = {
|
||||
"*": ["class", "style"],
|
||||
"a": ["href", "title", "rel"],
|
||||
"img": ["src", "alt", "title", "width", "height"],
|
||||
}
|
||||
safe_text = clean_html(unsafe_text, tags=set(allowed_tags), attributes=allowed_attributes)
|
||||
else:
|
||||
safe_text = clean_html(unsafe_text)
|
||||
except ParserError as e:
|
||||
|
||||
+2
-2
@@ -29,8 +29,8 @@ from .constants import DEFAULT_SETTINGS_FILE, DEFAULT_GDRIVE_FILE
|
||||
|
||||
def version_info():
|
||||
if _NIGHTLY_VERSION[1].startswith('$Format'):
|
||||
return "Calibre-Web version: %s - unknown git-clone" % _STABLE_VERSION['version'].replace("b", " Beta")
|
||||
return "Calibre-Web version: %s -%s" % (_STABLE_VERSION['version'].replace("b", " Beta"), _NIGHTLY_VERSION[1])
|
||||
return "Calibre-Web version: %s - unknown git-clone" % _STABLE_VERSION.replace("b", " Beta")
|
||||
return "Calibre-Web version: %s -%s" % (_STABLE_VERSION.replace("b", " Beta"), _NIGHTLY_VERSION[1])
|
||||
|
||||
|
||||
class CliParameter(object):
|
||||
|
||||
+21
-14
@@ -65,7 +65,7 @@ def _extract_cover_from_archive(original_file_extension, tmp_file_name, rar_exec
|
||||
cover_data = extension = None
|
||||
if original_file_extension.upper() == '.CBZ':
|
||||
cf = zipfile.ZipFile(tmp_file_name)
|
||||
for name in cf.namelist():
|
||||
for name in sorted(cf.namelist()):
|
||||
ext = os.path.splitext(name)
|
||||
if len(ext) > 1:
|
||||
extension = ext[1].lower()
|
||||
@@ -74,7 +74,7 @@ def _extract_cover_from_archive(original_file_extension, tmp_file_name, rar_exec
|
||||
break
|
||||
elif original_file_extension.upper() == '.CBT':
|
||||
cf = tarfile.TarFile(tmp_file_name)
|
||||
for name in cf.getnames():
|
||||
for name in sorted(cf.getnames()):
|
||||
ext = os.path.splitext(name)
|
||||
if len(ext) > 1:
|
||||
extension = ext[1].lower()
|
||||
@@ -85,18 +85,18 @@ def _extract_cover_from_archive(original_file_extension, tmp_file_name, rar_exec
|
||||
try:
|
||||
rarfile.UNRAR_TOOL = rar_executable
|
||||
cf = rarfile.RarFile(tmp_file_name)
|
||||
for name in cf.namelist():
|
||||
for name in sorted(cf.namelist()):
|
||||
ext = os.path.splitext(name)
|
||||
if len(ext) > 1:
|
||||
extension = ext[1].lower()
|
||||
if extension in cover.COVER_EXTENSIONS:
|
||||
cover_data = cf.read([name])
|
||||
cover_data = cf.read(name)
|
||||
break
|
||||
except Exception as ex:
|
||||
log.error('Rarfile failed with error: {}'.format(ex))
|
||||
elif original_file_extension.upper() == '.CB7' and use_7zip:
|
||||
cf = py7zr.SevenZipFile(tmp_file_name)
|
||||
for name in cf.getnames():
|
||||
for name in sorted(cf.getnames()):
|
||||
ext = os.path.splitext(name)
|
||||
if len(ext) > 1:
|
||||
extension = ext[1].lower()
|
||||
@@ -109,13 +109,13 @@ def _extract_cover_from_archive(original_file_extension, tmp_file_name, rar_exec
|
||||
return cover_data, extension
|
||||
|
||||
|
||||
def _extract_cover(tmp_file_name, original_file_extension, rar_executable):
|
||||
def _extract_cover(tmp_file_path, original_file_extension, rar_executable):
|
||||
cover_data = extension = None
|
||||
if use_comic_meta:
|
||||
try:
|
||||
archive = ComicArchive(tmp_file_name, rar_exe_path=rar_executable)
|
||||
archive = ComicArchive(tmp_file_path, rar_exe_path=rar_executable)
|
||||
except TypeError:
|
||||
archive = ComicArchive(tmp_file_name)
|
||||
archive = ComicArchive(tmp_file_path)
|
||||
name_list = archive.getPageNameList if hasattr(archive, "getPageNameList") else archive.get_page_name_list
|
||||
for index, name in enumerate(name_list()):
|
||||
ext = os.path.splitext(name)
|
||||
@@ -126,11 +126,11 @@ def _extract_cover(tmp_file_name, original_file_extension, rar_executable):
|
||||
cover_data = get_page(index)
|
||||
break
|
||||
else:
|
||||
cover_data, extension = _extract_cover_from_archive(original_file_extension, tmp_file_name, rar_executable)
|
||||
return cover.cover_processing(tmp_file_name, cover_data, extension)
|
||||
cover_data, extension = _extract_cover_from_archive(original_file_extension, tmp_file_path, rar_executable)
|
||||
return cover.cover_processing(tmp_file_path, cover_data, extension)
|
||||
|
||||
|
||||
def get_comic_info(tmp_file_path, original_file_name, original_file_extension, rar_executable):
|
||||
def get_comic_info(tmp_file_path, original_file_name, original_file_extension, rar_executable, no_cover_processing):
|
||||
if use_comic_meta:
|
||||
try:
|
||||
archive = ComicArchive(tmp_file_path, rar_exe_path=rar_executable)
|
||||
@@ -155,14 +155,17 @@ def get_comic_info(tmp_file_path, original_file_name, original_file_extension, r
|
||||
|
||||
lang = loaded_metadata.language or ""
|
||||
loaded_metadata.language = isoLanguages.get_lang3(lang)
|
||||
|
||||
if not no_cover_processing:
|
||||
cover_file = _extract_cover(tmp_file_path, original_file_extension, rar_executable)
|
||||
else:
|
||||
cover_file = None
|
||||
return BookMeta(
|
||||
file_path=tmp_file_path,
|
||||
extension=original_file_extension,
|
||||
title=loaded_metadata.title or original_file_name,
|
||||
author=" & ".join([credit["person"]
|
||||
for credit in loaded_metadata.credits if credit["role"] == "Writer"]) or 'Unknown',
|
||||
cover=_extract_cover(tmp_file_path, original_file_extension, rar_executable),
|
||||
cover=cover_file,
|
||||
description=loaded_metadata.comments or "",
|
||||
tags="",
|
||||
series=loaded_metadata.series or "",
|
||||
@@ -171,13 +174,17 @@ def get_comic_info(tmp_file_path, original_file_name, original_file_extension, r
|
||||
publisher="",
|
||||
pubdate="",
|
||||
identifiers=[])
|
||||
if not no_cover_processing:
|
||||
cover_file = _extract_cover(tmp_file_path, original_file_extension, rar_executable)
|
||||
else:
|
||||
cover_file = None
|
||||
|
||||
return BookMeta(
|
||||
file_path=tmp_file_path,
|
||||
extension=original_file_extension,
|
||||
title=original_file_name,
|
||||
author='Unknown',
|
||||
cover=_extract_cover(tmp_file_path, original_file_extension, rar_executable),
|
||||
cover=cover_file,
|
||||
description="",
|
||||
tags="",
|
||||
series="",
|
||||
|
||||
+26
-34
@@ -35,7 +35,7 @@ except ImportError:
|
||||
|
||||
from . import constants, logger
|
||||
from .subproc_wrapper import process_wait
|
||||
|
||||
from .string_helper import strip_whitespaces
|
||||
|
||||
log = logger.create()
|
||||
_Base = declarative_base()
|
||||
@@ -84,8 +84,8 @@ class _Settings(_Base):
|
||||
config_authors_max = Column(Integer, default=0)
|
||||
config_read_column = Column(Integer, default=0)
|
||||
config_title_regex = Column(String,
|
||||
default=r'^(A|The|An|Der|Die|Das|Den|Ein|Eine'
|
||||
r'|Einen|Dem|Des|Einem|Eines|Le|La|Les|L\'|Un|Une)\s+')
|
||||
default=r"^(A|The|An|Der|Die|Das|Den|Ein|Eine"
|
||||
r"|Einen|Dem|Des|Einem|Eines|Le|La|Les|L'|Un|Une)(\s+|(?<='))")
|
||||
config_theme = Column(Integer, default=0)
|
||||
|
||||
config_log_level = Column(SmallInteger, default=logger.DEFAULT_LOG_LEVEL)
|
||||
@@ -117,6 +117,7 @@ class _Settings(_Base):
|
||||
|
||||
config_use_goodreads = Column(Boolean, default=False)
|
||||
config_goodreads_api_key = Column(String)
|
||||
config_googlebooks_api_key = Column(String, default='')
|
||||
config_register_email = Column(Boolean, default=False)
|
||||
config_login_type = Column(Integer, default=0)
|
||||
|
||||
@@ -182,26 +183,6 @@ class _Settings(_Base):
|
||||
class ConfigSQL(object):
|
||||
# pylint: disable=no-member
|
||||
def __init__(self):
|
||||
'''self.config_calibre_uuid = None
|
||||
self.config_calibre_split_dir = None
|
||||
self.dirty = None
|
||||
self.config_logfile = None
|
||||
self.config_upload_formats = None
|
||||
self.mail_gmail_token = None
|
||||
self.mail_server_type = None
|
||||
self.mail_server = None
|
||||
self.config_log_level = None
|
||||
self.config_allowed_column_value = None
|
||||
self.config_denied_column_value = None
|
||||
self.config_allowed_tags = None
|
||||
self.config_denied_tags = None
|
||||
self.config_default_show = None
|
||||
self.config_default_role = None
|
||||
self.config_keyfile = None
|
||||
self.config_certfile = None
|
||||
self.config_rarfile_location = None
|
||||
self.config_kepubifypath = None
|
||||
self.config_binariesdir = None'''
|
||||
self.__dict__["dirty"] = list()
|
||||
|
||||
def init_config(self, session, secret_key, cli):
|
||||
@@ -288,19 +269,19 @@ class ConfigSQL(object):
|
||||
|
||||
def list_denied_tags(self):
|
||||
mct = self.config_denied_tags or ""
|
||||
return [t.strip() for t in mct.split(",")]
|
||||
return [strip_whitespaces(t) for t in mct.split(",")]
|
||||
|
||||
def list_allowed_tags(self):
|
||||
mct = self.config_allowed_tags or ""
|
||||
return [t.strip() for t in mct.split(",")]
|
||||
return [strip_whitespaces(t) for t in mct.split(",")]
|
||||
|
||||
def list_denied_column_values(self):
|
||||
mct = self.config_denied_column_value or ""
|
||||
return [t.strip() for t in mct.split(",")]
|
||||
return [strip_whitespaces(t) for t in mct.split(",")]
|
||||
|
||||
def list_allowed_column_values(self):
|
||||
mct = self.config_allowed_column_value or ""
|
||||
return [t.strip() for t in mct.split(",")]
|
||||
return [strip_whitespaces(t) for t in mct.split(",")]
|
||||
|
||||
def get_log_level(self):
|
||||
return logger.get_level_name(self.config_log_level)
|
||||
@@ -345,7 +326,9 @@ class ConfigSQL(object):
|
||||
def to_dict(self):
|
||||
storage = {}
|
||||
for k, v in self.__dict__.items():
|
||||
if k[0] != '_' and not k.endswith("_e") and not k == "cli":
|
||||
if k[0] != '_' and not k.endswith("_e") and not k == "cli" \
|
||||
and 'api' not in k.lower() and 'token' not in k.lower() \
|
||||
and 'secret' not in k.lower():
|
||||
storage[k] = v
|
||||
return storage
|
||||
|
||||
@@ -372,7 +355,7 @@ class ConfigSQL(object):
|
||||
db_file = os.path.join(self.config_calibre_dir, 'metadata.db')
|
||||
have_metadata_db = os.path.isfile(db_file)
|
||||
self.db_configured = have_metadata_db
|
||||
# constants.EXTENSIONS_UPLOAD = [x.lstrip().rstrip().lower() for x in self.config_upload_formats.split(',')]
|
||||
|
||||
from . import cli_param
|
||||
if os.environ.get('FLASK_DEBUG'):
|
||||
logfile = logger.setup(logger.LOG_TO_STDOUT, logger.logging.DEBUG)
|
||||
@@ -422,14 +405,16 @@ class ConfigSQL(object):
|
||||
self.save()
|
||||
|
||||
def get_book_path(self):
|
||||
return self.config_calibre_split_dir if self.config_calibre_split_dir else self.config_calibre_dir
|
||||
return self.config_calibre_split_dir if self.config_calibre_split else self.config_calibre_dir
|
||||
|
||||
def store_calibre_uuid(self, calibre_db, Library_table):
|
||||
from . import app
|
||||
try:
|
||||
calibre_uuid = calibre_db.session.query(Library_table).one_or_none()
|
||||
if self.config_calibre_uuid != calibre_uuid.uuid:
|
||||
self.config_calibre_uuid = calibre_uuid.uuid
|
||||
self.save()
|
||||
with app.app_context():
|
||||
calibre_uuid = calibre_db.session.query(Library_table).one_or_none()
|
||||
if self.config_calibre_uuid != calibre_uuid.uuid:
|
||||
self.config_calibre_uuid = calibre_uuid.uuid
|
||||
self.save()
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
@@ -503,6 +488,8 @@ def autodetect_calibre_binaries():
|
||||
"C:\\program files(x86)\\calibre\\",
|
||||
"C:\\program files(x86)\\calibre2\\",
|
||||
"C:\\program files\\calibre2\\"]
|
||||
elif sys.platform.startswith("freebsd"):
|
||||
calibre_path = ["/usr/local/bin/"]
|
||||
else:
|
||||
calibre_path = ["/opt/calibre/"]
|
||||
for element in calibre_path:
|
||||
@@ -533,6 +520,8 @@ def autodetect_unrar_binary():
|
||||
if sys.platform == "win32":
|
||||
calibre_path = ["C:\\program files\\WinRar\\unRAR.exe",
|
||||
"C:\\program files(x86)\\WinRar\\unRAR.exe"]
|
||||
elif sys.platform.startswith("freebsd"):
|
||||
calibre_path = ["/usr/local/bin/unrar"]
|
||||
else:
|
||||
calibre_path = ["/usr/bin/unrar"]
|
||||
for element in calibre_path:
|
||||
@@ -545,6 +534,8 @@ def autodetect_kepubify_binary():
|
||||
if sys.platform == "win32":
|
||||
calibre_path = ["C:\\program files\\kepubify\\kepubify-windows-64Bit.exe",
|
||||
"C:\\program files(x86)\\kepubify\\kepubify-windows-64Bit.exe"]
|
||||
elif sys.platform.startswith("freebsd"):
|
||||
calibre_path = ["/usr/local/bin/kepubify"]
|
||||
else:
|
||||
calibre_path = ["/opt/kepubify/kepubify-linux-64bit", "/opt/kepubify/kepubify-linux-32bit"]
|
||||
for element in calibre_path:
|
||||
@@ -594,6 +585,7 @@ def get_encryption_key(key_path):
|
||||
try:
|
||||
with open(key_file, "wb") as f:
|
||||
f.write(key)
|
||||
os.chmod(key_file, 0o600)
|
||||
except PermissionError as e:
|
||||
error = e
|
||||
return key, error
|
||||
|
||||
+7
-7
@@ -19,9 +19,6 @@
|
||||
import sys
|
||||
import os
|
||||
from collections import namedtuple
|
||||
from sqlalchemy import __version__ as sql_version
|
||||
|
||||
sqlalchemy_version2 = ([int(x) for x in sql_version.split('.')] >= [2, 0, 0])
|
||||
|
||||
# APP_MODE - production, development, or test
|
||||
APP_MODE = os.environ.get('APP_MODE', 'production')
|
||||
@@ -40,9 +37,12 @@ STATIC_DIR = os.path.join(BASE_DIR, 'cps', 'static')
|
||||
TEMPLATES_DIR = os.path.join(BASE_DIR, 'cps', 'templates')
|
||||
TRANSLATIONS_DIR = os.path.join(BASE_DIR, 'cps', 'translations')
|
||||
|
||||
# Cache dir - use CACHE_DIR environment variable, otherwise use the default directory: cps/cache
|
||||
# Cache dir - use CACHE_DIRECTORY environment variable, otherwise CACHE_DIR (for backwards compatibility),
|
||||
# otherwise use the default directory: cps/cache
|
||||
DEFAULT_CACHE_DIR = os.path.join(BASE_DIR, 'cps', 'cache')
|
||||
CACHE_DIR = os.environ.get('CACHE_DIR', DEFAULT_CACHE_DIR)
|
||||
CACHE_DIRECTORY = os.environ.get(
|
||||
'CACHE_DIRECTORY', os.environ.get('CACHE_DIR', DEFAULT_CACHE_DIR)
|
||||
)
|
||||
|
||||
if HOME_CONFIG:
|
||||
home_dir = os.path.join(os.path.expanduser("~"), ".calibre-web")
|
||||
@@ -175,7 +175,7 @@ BookMeta = namedtuple('BookMeta', 'file_path, extension, title, author, cover, d
|
||||
'series_id, languages, publisher, pubdate, identifiers')
|
||||
|
||||
# python build process likes to have x.y.zbw -> b for beta and w a counting number
|
||||
STABLE_VERSION = {'version': '0.6.22'}
|
||||
STABLE_VERSION = '0.6.27b'
|
||||
|
||||
NIGHTLY_VERSION = dict()
|
||||
NIGHTLY_VERSION[0] = '$Format:%H$'
|
||||
@@ -193,7 +193,7 @@ THUMBNAIL_TYPE_AUTHOR = 3
|
||||
COVER_THUMBNAIL_ORIGINAL = 0
|
||||
COVER_THUMBNAIL_SMALL = 1
|
||||
COVER_THUMBNAIL_MEDIUM = 2
|
||||
COVER_THUMBNAIL_LARGE = 3
|
||||
COVER_THUMBNAIL_LARGE = 4
|
||||
|
||||
# clean-up the module namespace
|
||||
del sys, os, namedtuple
|
||||
|
||||
+4
-3
@@ -29,13 +29,14 @@ NO_JPEG_EXTENSIONS = ['.png', '.webp', '.bmp']
|
||||
COVER_EXTENSIONS = ['.png', '.webp', '.bmp', '.jpg', '.jpeg']
|
||||
|
||||
|
||||
def cover_processing(tmp_file_name, img, extension):
|
||||
tmp_cover_name = os.path.join(os.path.dirname(tmp_file_name), 'cover.jpg')
|
||||
def cover_processing(tmp_file_path, img, extension):
|
||||
# tmp_cover_name = os.path.join(os.path.dirname(tmp_file_name), 'cover.jpg')
|
||||
tmp_cover_name = tmp_file_path + '.jpg'
|
||||
if extension in NO_JPEG_EXTENSIONS:
|
||||
if use_IM:
|
||||
with Image(blob=img) as imgc:
|
||||
imgc.format = 'jpeg'
|
||||
imgc.transform_colorspace('rgb')
|
||||
imgc.transform_colorspace('srgb')
|
||||
imgc.save(filename=tmp_cover_name)
|
||||
return tmp_cover_name
|
||||
else:
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
#
|
||||
# Copyright 2015 Jordan Milne
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# Source: https://github.com/JordanMilne/Advocate
|
||||
|
||||
|
||||
from .adapters import ValidatingHTTPAdapter
|
||||
from .api import *
|
||||
from .addrvalidator import AddrValidator
|
||||
from .exceptions import UnacceptableAddressException
|
||||
@@ -0,0 +1,48 @@
|
||||
#
|
||||
# Copyright 2015 Jordan Milne
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# Source: https://github.com/JordanMilne/Advocate
|
||||
|
||||
from requests.adapters import HTTPAdapter, DEFAULT_POOLBLOCK
|
||||
|
||||
from .addrvalidator import AddrValidator
|
||||
from .exceptions import ProxyDisabledException
|
||||
from .poolmanager import ValidatingPoolManager
|
||||
|
||||
|
||||
class ValidatingHTTPAdapter(HTTPAdapter):
|
||||
__attrs__ = HTTPAdapter.__attrs__ + ['_validator']
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self._validator = kwargs.pop('validator', None)
|
||||
if not self._validator:
|
||||
self._validator = AddrValidator()
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK,
|
||||
**pool_kwargs):
|
||||
self._pool_connections = connections
|
||||
self._pool_maxsize = maxsize
|
||||
self._pool_block = block
|
||||
self.poolmanager = ValidatingPoolManager(
|
||||
num_pools=connections,
|
||||
maxsize=maxsize,
|
||||
block=block,
|
||||
validator=self._validator,
|
||||
**pool_kwargs
|
||||
)
|
||||
|
||||
def proxy_manager_for(self, proxy, **proxy_kwargs):
|
||||
raise ProxyDisabledException("Proxies cannot be used with Advocate")
|
||||
@@ -0,0 +1,281 @@
|
||||
#
|
||||
# Copyright 2015 Jordan Milne
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# Source: https://github.com/JordanMilne/Advocate
|
||||
|
||||
import functools
|
||||
import fnmatch
|
||||
import ipaddress
|
||||
import re
|
||||
|
||||
try:
|
||||
import netifaces
|
||||
HAVE_NETIFACES = True
|
||||
except ImportError:
|
||||
netifaces = None
|
||||
HAVE_NETIFACES = False
|
||||
|
||||
from .exceptions import NameserverException, ConfigException
|
||||
|
||||
|
||||
def canonicalize_hostname(hostname):
|
||||
"""Lowercase and punycodify a hostname"""
|
||||
# We do the lowercasing after IDNA encoding because we only want to
|
||||
# lowercase the *ASCII* chars.
|
||||
# TODO: The differences between IDNA2003 and IDNA2008 might be relevant
|
||||
# to us, but both specs are damn confusing.
|
||||
return str(hostname.encode("idna").lower(), 'utf-8')
|
||||
|
||||
|
||||
def determine_local_addresses():
|
||||
"""Get all IPs that refer to this machine according to netifaces"""
|
||||
if not HAVE_NETIFACES:
|
||||
raise ConfigException("Tried to determine local addresses, "
|
||||
"but netifaces module was not importable")
|
||||
ips = []
|
||||
for interface in netifaces.interfaces():
|
||||
if_families = netifaces.ifaddresses(interface)
|
||||
for family_kind in {netifaces.AF_INET, netifaces.AF_INET6}:
|
||||
addrs = if_families.get(family_kind, [])
|
||||
for addr in (x.get("addr", "") for x in addrs):
|
||||
if family_kind == netifaces.AF_INET6:
|
||||
# We can't do anything sensible with the scope here
|
||||
addr = addr.split("%")[0]
|
||||
ips.append(ipaddress.ip_network(addr))
|
||||
return ips
|
||||
|
||||
|
||||
def add_local_address_arg(func):
|
||||
"""Add the "_local_addresses" kwarg if it's missing
|
||||
|
||||
IMO this information shouldn't be cached between calls (what if one of the
|
||||
adapters got a new IP at runtime?,) and we don't want each function to
|
||||
recalculate it. Just recalculate it if the caller didn't provide it for us.
|
||||
"""
|
||||
@functools.wraps(func)
|
||||
def wrapper(self, *args, **kwargs):
|
||||
if "_local_addresses" not in kwargs:
|
||||
if self.autodetect_local_addresses:
|
||||
kwargs["_local_addresses"] = determine_local_addresses()
|
||||
else:
|
||||
kwargs["_local_addresses"] = []
|
||||
return func(self, *args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
|
||||
class AddrValidator:
|
||||
_6TO4_RELAY_NET = ipaddress.ip_network("192.88.99.0/24")
|
||||
# Just the well known prefix, DNS64 servers can set their own
|
||||
# prefix, but in practice most probably don't.
|
||||
_DNS64_WK_PREFIX = ipaddress.ip_network("64:ff9b::/96")
|
||||
DEFAULT_PORT_WHITELIST = {80, 8080, 443, 8443, 8000}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ip_blacklist=None,
|
||||
ip_whitelist=None,
|
||||
port_whitelist=None,
|
||||
port_blacklist=None,
|
||||
hostname_blacklist=None,
|
||||
allow_ipv6=False,
|
||||
allow_teredo=False,
|
||||
allow_6to4=False,
|
||||
allow_dns64=False,
|
||||
# Must be explicitly set to "False" if you don't want to try
|
||||
# detecting local interface addresses with netifaces.
|
||||
autodetect_local_addresses=True,
|
||||
):
|
||||
if not port_blacklist and not port_whitelist:
|
||||
# An assortment of common HTTPS? ports.
|
||||
port_whitelist = self.DEFAULT_PORT_WHITELIST.copy()
|
||||
self.ip_blacklist = ip_blacklist or set()
|
||||
self.ip_whitelist = ip_whitelist or set()
|
||||
self.port_blacklist = port_blacklist or set()
|
||||
self.port_whitelist = port_whitelist or set()
|
||||
# TODO: ATM this can contain either regexes or globs that are converted
|
||||
# to regexes upon every check. Create a collection that automagically
|
||||
# converts them to regexes on insert?
|
||||
self.hostname_blacklist = hostname_blacklist or set()
|
||||
self.allow_ipv6 = allow_ipv6
|
||||
self.allow_teredo = allow_teredo
|
||||
self.allow_6to4 = allow_6to4
|
||||
self.allow_dns64 = allow_dns64
|
||||
self.autodetect_local_addresses = autodetect_local_addresses
|
||||
|
||||
@add_local_address_arg
|
||||
def is_ip_allowed(self, addr_ip, _local_addresses=None):
|
||||
if not isinstance(addr_ip,
|
||||
(ipaddress.IPv4Address, ipaddress.IPv6Address)):
|
||||
addr_ip = ipaddress.ip_address(addr_ip)
|
||||
|
||||
# The whitelist should take precedence over the blacklist so we can
|
||||
# punch holes in blacklisted ranges
|
||||
if any(addr_ip in net for net in self.ip_whitelist):
|
||||
return True
|
||||
|
||||
if any(addr_ip in net for net in self.ip_blacklist):
|
||||
return False
|
||||
|
||||
if any(addr_ip in net for net in _local_addresses):
|
||||
return False
|
||||
|
||||
if addr_ip.version == 4:
|
||||
if not addr_ip.is_private:
|
||||
# IPs for carrier-grade NAT. Seems weird that it doesn't set
|
||||
# `is_private`, but we need to check `not is_global`
|
||||
if not ipaddress.ip_network(addr_ip).is_global:
|
||||
return False
|
||||
elif addr_ip.version == 6:
|
||||
# You'd better have a good reason for enabling IPv6
|
||||
# because Advocate's techniques don't work well without NAT.
|
||||
if not self.allow_ipv6:
|
||||
return False
|
||||
|
||||
# v6 addresses can also map to IPv4 addresses! Tricky!
|
||||
v4_nested = []
|
||||
if addr_ip.ipv4_mapped:
|
||||
v4_nested.append(addr_ip.ipv4_mapped)
|
||||
# WTF IPv6? Why you gotta have a billion tunneling mechanisms?
|
||||
# XXX: Do we even really care about these? If we're tunneling
|
||||
# through public servers we shouldn't be able to access
|
||||
# addresses on our private network, right?
|
||||
if addr_ip.sixtofour:
|
||||
if not self.allow_6to4:
|
||||
return False
|
||||
v4_nested.append(addr_ip.sixtofour)
|
||||
if addr_ip.teredo:
|
||||
if not self.allow_teredo:
|
||||
return False
|
||||
# Check both the client *and* server IPs
|
||||
v4_nested.extend(addr_ip.teredo)
|
||||
if addr_ip in self._DNS64_WK_PREFIX:
|
||||
if not self.allow_dns64:
|
||||
return False
|
||||
# When using the well-known prefix the last 4 bytes
|
||||
# are the IPv4 addr
|
||||
v4_nested.append(ipaddress.ip_address(addr_ip.packed[-4:]))
|
||||
|
||||
if not all(self.is_ip_allowed(addr_v4) for addr_v4 in v4_nested):
|
||||
return False
|
||||
|
||||
# fec0::*, apparently deprecated?
|
||||
if addr_ip.is_site_local:
|
||||
return False
|
||||
else:
|
||||
raise ValueError("Unsupported IP version(?): %r" % addr_ip)
|
||||
|
||||
# 169.254.XXX.XXX, AWS uses these for autoconfiguration
|
||||
if addr_ip.is_link_local:
|
||||
return False
|
||||
# 127.0.0.1, ::1, etc.
|
||||
if addr_ip.is_loopback:
|
||||
return False
|
||||
if addr_ip.is_multicast:
|
||||
return False
|
||||
# 192.168.XXX.XXX, 10.XXX.XXX.XXX
|
||||
if addr_ip.is_private:
|
||||
return False
|
||||
# 255.255.255.255, ::ffff:XXXX:XXXX (v6->v4) mapping
|
||||
if addr_ip.is_reserved:
|
||||
return False
|
||||
# There's no reason to connect directly to a 6to4 relay
|
||||
if addr_ip in self._6TO4_RELAY_NET:
|
||||
return False
|
||||
# 0.0.0.0
|
||||
if addr_ip.is_unspecified:
|
||||
return False
|
||||
|
||||
# It doesn't look bad, so... it's must be ok!
|
||||
return True
|
||||
|
||||
def _hostname_matches_pattern(self, hostname, pattern):
|
||||
# If they specified a string, just assume they only want basic globbing.
|
||||
# This stops people from not realizing they're dealing in REs and
|
||||
# not escaping their periods unless they specifically pass in an RE.
|
||||
# This has the added benefit of letting us sanely handle globbed
|
||||
# IDNs by default.
|
||||
if isinstance(pattern, str):
|
||||
# convert the glob to a punycode glob, then a regex
|
||||
pattern = fnmatch.translate(canonicalize_hostname(pattern))
|
||||
|
||||
hostname = canonicalize_hostname(hostname)
|
||||
# Down the line the hostname may get treated as a null-terminated string
|
||||
# (as with `socket.getaddrinfo`.) Try to account for that.
|
||||
#
|
||||
# >>> socket.getaddrinfo("example.com\x00aaaa", 80)
|
||||
# [(2, 1, 6, '', ('93.184.216.34', 80)), [...]
|
||||
no_null_hostname = hostname.split("\x00")[0]
|
||||
|
||||
return any(re.match(pattern, x.strip(".")) for x
|
||||
in (no_null_hostname, hostname))
|
||||
|
||||
def is_hostname_allowed(self, hostname):
|
||||
# Sometimes (like with "external" services that your IP has privileged
|
||||
# access to) you might not always know the IP range to blacklist access
|
||||
# to, or the `A` record might change without you noticing.
|
||||
# For e.x.: `foocorp.external.org`.
|
||||
#
|
||||
# Another option is doing something like:
|
||||
#
|
||||
# for addrinfo in socket.getaddrinfo("foocorp.external.org", 80):
|
||||
# global_validator.ip_blacklist.add(ip_address(addrinfo[4][0]))
|
||||
#
|
||||
# but that's not always a good idea if they're behind a third-party lb.
|
||||
for pattern in self.hostname_blacklist:
|
||||
if self._hostname_matches_pattern(hostname, pattern):
|
||||
return False
|
||||
return True
|
||||
|
||||
@add_local_address_arg
|
||||
def is_addrinfo_allowed(self, addrinfo, _local_addresses=None):
|
||||
assert(len(addrinfo) == 5)
|
||||
# XXX: Do we care about any of the other elements? Guessing not.
|
||||
family, socktype, proto, canonname, sockaddr = addrinfo
|
||||
|
||||
# The 4th elem inaddrinfo may either be a touple of two or four items,
|
||||
# depending on whether we're dealing with IPv4 or v6
|
||||
if len(sockaddr) == 2:
|
||||
# v4
|
||||
ip, port = sockaddr
|
||||
elif len(sockaddr) == 4:
|
||||
# v6
|
||||
# XXX: what *are* `flow_info` and `scope_id`? Anything useful?
|
||||
# Seems like we can figure out all we need about the scope from
|
||||
# the `is_<x>` properties.
|
||||
ip, port, flow_info, scope_id = sockaddr
|
||||
else:
|
||||
raise ValueError("Unexpected addrinfo format %r" % sockaddr)
|
||||
|
||||
# Probably won't help protect against SSRF, but might prevent our being
|
||||
# used to attack others' non-HTTP services. See
|
||||
# http://www.remote.org/jochen/sec/hfpa/
|
||||
if self.port_whitelist and port not in self.port_whitelist:
|
||||
return False
|
||||
if port in self.port_blacklist:
|
||||
return False
|
||||
|
||||
if self.hostname_blacklist:
|
||||
if not canonname:
|
||||
raise NameserverException(
|
||||
"addrinfo must contain the canon name to do blacklisting "
|
||||
"based on hostname. Make sure you use the "
|
||||
"`socket.AI_CANONNAME` flag, and that each record contains "
|
||||
"the canon name. Your DNS server might also be garbage."
|
||||
)
|
||||
|
||||
if not self.is_hostname_allowed(canonname):
|
||||
return False
|
||||
|
||||
return self.is_ip_allowed(ip, _local_addresses=_local_addresses)
|
||||
@@ -0,0 +1,202 @@
|
||||
#
|
||||
# Copyright 2015 Jordan Milne
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# Source: https://github.com/JordanMilne/Advocate
|
||||
|
||||
"""
|
||||
advocate.api
|
||||
~~~~~~~~~~~~
|
||||
|
||||
This module implements the Requests API, largely a copy/paste from `requests`
|
||||
itself.
|
||||
|
||||
:copyright: (c) 2015 by Jordan Milne.
|
||||
:license: Apache2, see LICENSE for more details.
|
||||
|
||||
"""
|
||||
from collections import OrderedDict
|
||||
import hashlib
|
||||
import pickle
|
||||
|
||||
from requests import Session as RequestsSession
|
||||
|
||||
# import cw_advocate
|
||||
from .adapters import ValidatingHTTPAdapter
|
||||
from .exceptions import MountDisabledException
|
||||
|
||||
|
||||
class Session(RequestsSession):
|
||||
"""Convenience wrapper around `requests.Session` set up for `advocate`ing"""
|
||||
|
||||
__attrs__ = RequestsSession.__attrs__ + ["validator"]
|
||||
DEFAULT_VALIDATOR = None
|
||||
"""
|
||||
User-replaceable default validator to use for all Advocate sessions,
|
||||
includes sessions created by advocate.get()
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.validator = kwargs.pop("validator", None) or self.DEFAULT_VALIDATOR
|
||||
adapter_kwargs = kwargs.pop("_adapter_kwargs", {})
|
||||
|
||||
# `Session.__init__()` calls `mount()` internally, so we need to allow
|
||||
# it temporarily
|
||||
self.__mount_allowed = True
|
||||
RequestsSession.__init__(self, *args, **kwargs)
|
||||
|
||||
# Drop any existing adapters
|
||||
self.adapters = OrderedDict()
|
||||
|
||||
self.mount("http://", ValidatingHTTPAdapter(validator=self.validator, **adapter_kwargs))
|
||||
self.mount("https://", ValidatingHTTPAdapter(validator=self.validator, **adapter_kwargs))
|
||||
self.__mount_allowed = False
|
||||
|
||||
def mount(self, *args, **kwargs):
|
||||
"""Wrapper around `mount()` to prevent a protection bypass"""
|
||||
if self.__mount_allowed:
|
||||
super().mount(*args, **kwargs)
|
||||
else:
|
||||
raise MountDisabledException(
|
||||
"mount() is disabled to prevent protection bypasses"
|
||||
)
|
||||
|
||||
|
||||
def session(*args, **kwargs):
|
||||
return Session(*args, **kwargs)
|
||||
|
||||
|
||||
def request(method, url, **kwargs):
|
||||
"""Constructs and sends a :class:`Request <Request>`.
|
||||
|
||||
:param method: method for the new :class:`Request` object.
|
||||
:param url: URL for the new :class:`Request` object.
|
||||
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
|
||||
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
|
||||
:param json: (optional) json data to send in the body of the :class:`Request`.
|
||||
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
|
||||
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
|
||||
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload.
|
||||
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
|
||||
:param timeout: (optional) How long to wait for the server to send data
|
||||
before giving up, as a float, or a (`connect timeout, read timeout
|
||||
<user/advanced.html#timeouts>`_) tuple.
|
||||
:type timeout: float or tuple
|
||||
:param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
|
||||
:type allow_redirects: bool
|
||||
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
|
||||
:param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
|
||||
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
|
||||
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
|
||||
:return: :class:`Response <Response>` object
|
||||
:rtype: requests.Response
|
||||
"""
|
||||
|
||||
validator = kwargs.pop("validator", None)
|
||||
with Session(validator=validator) as sess:
|
||||
response = sess.request(method=method, url=url, **kwargs)
|
||||
return response
|
||||
|
||||
|
||||
def get(url, **kwargs):
|
||||
"""Sends a GET request.
|
||||
|
||||
:param url: URL for the new :class:`Request` object.
|
||||
:param **kwargs: Optional arguments that ``request`` takes.
|
||||
:return: :class:`Response <Response>` object
|
||||
:rtype: requests.Response
|
||||
"""
|
||||
|
||||
kwargs.setdefault('allow_redirects', True)
|
||||
return request('get', url, **kwargs)
|
||||
|
||||
|
||||
class RequestsAPIWrapper:
|
||||
"""Provides a `requests.api`-like interface with a specific validator"""
|
||||
|
||||
# Due to how the classes are dynamically constructed pickling may not work
|
||||
# correctly unless loaded within the same interpreter instance.
|
||||
# Enable at your peril.
|
||||
SUPPORT_WRAPPER_PICKLING = False
|
||||
|
||||
def __init__(self, validator):
|
||||
# Do this here to avoid circular import issues
|
||||
try:
|
||||
from .futures import FuturesSession
|
||||
have_requests_futures = True
|
||||
except ImportError as e:
|
||||
have_requests_futures = False
|
||||
|
||||
self.validator = validator
|
||||
outer_self = self
|
||||
|
||||
class _WrappedSession(Session):
|
||||
"""An `advocate.Session` that uses the wrapper's blacklist
|
||||
|
||||
the wrapper is meant to be a transparent replacement for `requests`,
|
||||
so people should be able to subclass `wrapper.Session` and still
|
||||
get the desired validation behaviour
|
||||
"""
|
||||
DEFAULT_VALIDATOR = outer_self.validator
|
||||
|
||||
self._make_wrapper_cls_global(_WrappedSession)
|
||||
|
||||
if have_requests_futures:
|
||||
|
||||
class _WrappedFuturesSession(FuturesSession):
|
||||
"""Like _WrappedSession, but for `FuturesSession`s"""
|
||||
DEFAULT_VALIDATOR = outer_self.validator
|
||||
self._make_wrapper_cls_global(_WrappedFuturesSession)
|
||||
|
||||
self.FuturesSession = _WrappedFuturesSession
|
||||
|
||||
self.request = self._default_arg_wrapper(request)
|
||||
self.get = self._default_arg_wrapper(get)
|
||||
self.Session = _WrappedSession
|
||||
|
||||
def __getattr__(self, item):
|
||||
# This class is meant to mimic the requests base module, so if we don't
|
||||
# have this attribute, it might be on the base module (like the Request
|
||||
# class, etc.)
|
||||
try:
|
||||
return object.__getattribute__(self, item)
|
||||
except AttributeError:
|
||||
from . import cw_advocate
|
||||
return getattr(cw_advocate, item)
|
||||
|
||||
def _default_arg_wrapper(self, fun):
|
||||
def wrapped_func(*args, **kwargs):
|
||||
kwargs.setdefault("validator", self.validator)
|
||||
return fun(*args, **kwargs)
|
||||
return wrapped_func
|
||||
|
||||
def _make_wrapper_cls_global(self, cls):
|
||||
if not self.SUPPORT_WRAPPER_PICKLING:
|
||||
return
|
||||
# Gnarly, but necessary to give pickle a consistent module-level
|
||||
# reference for each wrapper.
|
||||
wrapper_hash = hashlib.sha256(pickle.dumps(self)).hexdigest()
|
||||
cls.__name__ = "_".join((cls.__name__, wrapper_hash))
|
||||
cls.__qualname__ = ".".join((__name__, cls.__name__))
|
||||
if not globals().get(cls.__name__):
|
||||
globals()[cls.__name__] = cls
|
||||
|
||||
|
||||
__all__ = (
|
||||
"get",
|
||||
"request",
|
||||
"session",
|
||||
"Session",
|
||||
"RequestsAPIWrapper",
|
||||
)
|
||||
@@ -0,0 +1,201 @@
|
||||
#
|
||||
# Copyright 2015 Jordan Milne
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# Source: https://github.com/JordanMilne/Advocate
|
||||
|
||||
import ipaddress
|
||||
import socket
|
||||
from socket import timeout as SocketTimeout
|
||||
|
||||
from urllib3.connection import HTTPSConnection, HTTPConnection
|
||||
from urllib3.exceptions import ConnectTimeoutError
|
||||
from urllib3.util.connection import _set_socket_options
|
||||
from urllib3.util.connection import create_connection as old_create_connection
|
||||
|
||||
from . import addrvalidator
|
||||
from .exceptions import UnacceptableAddressException
|
||||
|
||||
|
||||
def advocate_getaddrinfo(host, port, get_canonname=False):
|
||||
addrinfo = socket.getaddrinfo(
|
||||
host,
|
||||
port,
|
||||
0,
|
||||
socket.SOCK_STREAM,
|
||||
0,
|
||||
# We need what the DNS client sees the hostname as, correctly handles
|
||||
# IDNs and tricky things like `private.foocorp.org\x00.google.com`.
|
||||
# All IDNs will be converted to punycode.
|
||||
socket.AI_CANONNAME if get_canonname else 0,
|
||||
)
|
||||
return fix_addrinfo(addrinfo)
|
||||
|
||||
|
||||
def fix_addrinfo(records):
|
||||
"""
|
||||
Propagate the canonname across records and parse IPs
|
||||
|
||||
I'm not sure if this is just the behaviour of `getaddrinfo` on Linux, but
|
||||
it seems like only the first record in the set has the canonname field
|
||||
populated.
|
||||
"""
|
||||
def fix_record(record, canonname):
|
||||
sa = record[4]
|
||||
sa = (ipaddress.ip_address(sa[0]),) + sa[1:]
|
||||
return record[0], record[1], record[2], canonname, sa
|
||||
|
||||
canonname = None
|
||||
if records:
|
||||
# Apparently the canonical name is only included in the first record?
|
||||
# Add it to all of them.
|
||||
assert(len(records[0]) == 5)
|
||||
canonname = records[0][3]
|
||||
return tuple(fix_record(x, canonname) for x in records)
|
||||
|
||||
|
||||
# Lifted from requests' urllib3, which in turn lifted it from `socket.py`. Oy!
|
||||
def validating_create_connection(address,
|
||||
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
|
||||
source_address=None, socket_options=None,
|
||||
validator=None):
|
||||
"""Connect to *address* and return the socket object.
|
||||
|
||||
Convenience function. Connect to *address* (a 2-tuple ``(host,
|
||||
port)``) and return the socket object. Passing the optional
|
||||
*timeout* parameter will set the timeout on the socket instance
|
||||
before attempting to connect. If no *timeout* is supplied, the
|
||||
global default timeout setting returned by :func:`getdefaulttimeout`
|
||||
is used. If *source_address* is set it must be a tuple of (host, port)
|
||||
for the socket to bind as a source address before making the connection.
|
||||
An host of '' or port 0 tells the OS to use the default.
|
||||
"""
|
||||
|
||||
host, port = address
|
||||
# We can skip asking for the canon name if we're not doing hostname-based
|
||||
# blacklisting.
|
||||
need_canonname = False
|
||||
if validator.hostname_blacklist:
|
||||
need_canonname = True
|
||||
# We check both the non-canonical and canonical hostnames so we can
|
||||
# catch both of these:
|
||||
# CNAME from nonblacklisted.com -> blacklisted.com
|
||||
# CNAME from blacklisted.com -> nonblacklisted.com
|
||||
if not validator.is_hostname_allowed(host):
|
||||
raise UnacceptableAddressException(host)
|
||||
|
||||
err = None
|
||||
addrinfo = advocate_getaddrinfo(host, port, get_canonname=need_canonname)
|
||||
if addrinfo:
|
||||
if validator.autodetect_local_addresses:
|
||||
local_addresses = addrvalidator.determine_local_addresses()
|
||||
else:
|
||||
local_addresses = []
|
||||
for res in addrinfo:
|
||||
# Are we allowed to connect with this result?
|
||||
if not validator.is_addrinfo_allowed(
|
||||
res,
|
||||
_local_addresses=local_addresses,
|
||||
):
|
||||
continue
|
||||
af, socktype, proto, canonname, sa = res
|
||||
# Unparse the validated IP
|
||||
sa = (sa[0].exploded,) + sa[1:]
|
||||
sock = None
|
||||
try:
|
||||
sock = socket.socket(af, socktype, proto)
|
||||
|
||||
# If provided, set socket level options before connecting.
|
||||
# This is the only addition urllib3 makes to this function.
|
||||
_set_socket_options(sock, socket_options)
|
||||
|
||||
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
|
||||
sock.settimeout(timeout)
|
||||
if source_address:
|
||||
sock.bind(source_address)
|
||||
sock.connect(sa)
|
||||
return sock
|
||||
|
||||
except socket.error as _:
|
||||
err = _
|
||||
if sock is not None:
|
||||
sock.close()
|
||||
sock = None
|
||||
|
||||
if err is None:
|
||||
# If we got here, none of the results were acceptable
|
||||
err = UnacceptableAddressException(address)
|
||||
if err is not None:
|
||||
raise err
|
||||
else:
|
||||
raise socket.error("getaddrinfo returns an empty list")
|
||||
|
||||
|
||||
# TODO: Is there a better way to add this to multiple classes with different
|
||||
# base classes? I tried a mixin, but it used the base method instead.
|
||||
def _validating_new_conn(self):
|
||||
""" Establish a socket connection and set nodelay settings on it.
|
||||
|
||||
:return: New socket connection.
|
||||
"""
|
||||
extra_kw = {}
|
||||
if self.source_address:
|
||||
extra_kw['source_address'] = self.source_address
|
||||
|
||||
if self.socket_options:
|
||||
extra_kw['socket_options'] = self.socket_options
|
||||
|
||||
try:
|
||||
# Hack around HTTPretty's patched sockets
|
||||
# TODO: some better method of hacking around it that checks if we
|
||||
# _would have_ connected to a private addr?
|
||||
conn_func = validating_create_connection
|
||||
if socket.getaddrinfo.__module__.startswith("httpretty"):
|
||||
conn_func = old_create_connection
|
||||
else:
|
||||
extra_kw["validator"] = self._validator
|
||||
|
||||
conn = conn_func(
|
||||
(self.host, self.port),
|
||||
self.timeout,
|
||||
**extra_kw
|
||||
)
|
||||
|
||||
except SocketTimeout:
|
||||
raise ConnectTimeoutError(
|
||||
self, "Connection to %s timed out. (connect timeout=%s)" %
|
||||
(self.host, self.timeout))
|
||||
|
||||
return conn
|
||||
|
||||
|
||||
# Don't silently break if the private API changes across urllib3 versions
|
||||
assert(hasattr(HTTPConnection, '_new_conn'))
|
||||
assert(hasattr(HTTPSConnection, '_new_conn'))
|
||||
|
||||
|
||||
class ValidatingHTTPConnection(HTTPConnection):
|
||||
_new_conn = _validating_new_conn
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self._validator = kwargs.pop("validator")
|
||||
HTTPConnection.__init__(self, *args, **kwargs)
|
||||
|
||||
|
||||
class ValidatingHTTPSConnection(HTTPSConnection):
|
||||
_new_conn = _validating_new_conn
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self._validator = kwargs.pop("validator")
|
||||
HTTPSConnection.__init__(self, *args, **kwargs)
|
||||
@@ -0,0 +1,39 @@
|
||||
#
|
||||
# Copyright 2015 Jordan Milne
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# Source: https://github.com/JordanMilne/Advocate
|
||||
|
||||
from urllib3 import HTTPConnectionPool, HTTPSConnectionPool
|
||||
|
||||
from .connection import (
|
||||
ValidatingHTTPConnection,
|
||||
ValidatingHTTPSConnection,
|
||||
)
|
||||
|
||||
# Don't silently break if the private API changes across urllib3 versions
|
||||
assert(hasattr(HTTPConnectionPool, 'ConnectionCls'))
|
||||
assert(hasattr(HTTPSConnectionPool, 'ConnectionCls'))
|
||||
assert(hasattr(HTTPConnectionPool, 'scheme'))
|
||||
assert(hasattr(HTTPSConnectionPool, 'scheme'))
|
||||
|
||||
|
||||
class ValidatingHTTPConnectionPool(HTTPConnectionPool):
|
||||
scheme = 'http'
|
||||
ConnectionCls = ValidatingHTTPConnection
|
||||
|
||||
|
||||
class ValidatingHTTPSConnectionPool(HTTPSConnectionPool):
|
||||
scheme = 'https'
|
||||
ConnectionCls = ValidatingHTTPSConnection
|
||||
@@ -0,0 +1,39 @@
|
||||
#
|
||||
# Copyright 2015 Jordan Milne
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# Source: https://github.com/JordanMilne/Advocate
|
||||
|
||||
class AdvocateException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UnacceptableAddressException(AdvocateException):
|
||||
pass
|
||||
|
||||
|
||||
class NameserverException(AdvocateException):
|
||||
pass
|
||||
|
||||
|
||||
class MountDisabledException(AdvocateException):
|
||||
pass
|
||||
|
||||
|
||||
class ProxyDisabledException(NotImplementedError, AdvocateException):
|
||||
pass
|
||||
|
||||
|
||||
class ConfigException(AdvocateException):
|
||||
pass
|
||||
@@ -0,0 +1,61 @@
|
||||
#
|
||||
# Copyright 2015 Jordan Milne
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# Source: https://github.com/JordanMilne/Advocate
|
||||
|
||||
import collections
|
||||
import functools
|
||||
|
||||
from urllib3 import PoolManager
|
||||
from urllib3.poolmanager import _default_key_normalizer, PoolKey
|
||||
|
||||
from .connectionpool import (
|
||||
ValidatingHTTPSConnectionPool,
|
||||
ValidatingHTTPConnectionPool,
|
||||
)
|
||||
|
||||
pool_classes_by_scheme = {
|
||||
"http": ValidatingHTTPConnectionPool,
|
||||
"https": ValidatingHTTPSConnectionPool,
|
||||
}
|
||||
|
||||
AdvocatePoolKey = collections.namedtuple('AdvocatePoolKey',
|
||||
PoolKey._fields + ('key_validator',))
|
||||
|
||||
|
||||
def key_normalizer(key_class, request_context):
|
||||
request_context = request_context.copy()
|
||||
# TODO: add ability to serialize validator rules to dict,
|
||||
# allowing pool to be shared between sessions with the same
|
||||
# rules.
|
||||
request_context["validator"] = id(request_context["validator"])
|
||||
return _default_key_normalizer(key_class, request_context)
|
||||
|
||||
|
||||
key_fn_by_scheme = {
|
||||
'http': functools.partial(key_normalizer, AdvocatePoolKey),
|
||||
'https': functools.partial(key_normalizer, AdvocatePoolKey),
|
||||
}
|
||||
|
||||
|
||||
class ValidatingPoolManager(PoolManager):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
# Make sure the API hasn't changed
|
||||
assert (hasattr(self, 'pool_classes_by_scheme'))
|
||||
|
||||
self.pool_classes_by_scheme = pool_classes_by_scheme
|
||||
self.key_fn_by_scheme = key_fn_by_scheme.copy()
|
||||
@@ -2,7 +2,7 @@ from babel import negotiate_locale
|
||||
from flask_babel import Babel, Locale
|
||||
from babel.core import UnknownLocaleError
|
||||
from flask import request
|
||||
from flask_login import current_user
|
||||
from .cw_login import current_user
|
||||
|
||||
from . import logger
|
||||
|
||||
@@ -34,7 +34,7 @@ def get_user_locale_language(user_language):
|
||||
|
||||
|
||||
def get_available_locale():
|
||||
return [Locale('en')] + babel.list_translations()
|
||||
return sorted(babel.list_translations(), key=lambda x: x.display_name.lower())
|
||||
|
||||
|
||||
def get_available_translations():
|
||||
@@ -0,0 +1,98 @@
|
||||
# from .__about__ import __version__
|
||||
from .config import AUTH_HEADER_NAME
|
||||
from .config import COOKIE_DURATION
|
||||
from .config import COOKIE_HTTPONLY
|
||||
from .config import COOKIE_NAME
|
||||
from .config import COOKIE_SECURE
|
||||
from .config import ID_ATTRIBUTE
|
||||
from .config import LOGIN_MESSAGE
|
||||
from .config import LOGIN_MESSAGE_CATEGORY
|
||||
from .config import REFRESH_MESSAGE
|
||||
from .config import REFRESH_MESSAGE_CATEGORY
|
||||
from .login_manager import LoginManager
|
||||
from .mixins import AnonymousUserMixin
|
||||
from .mixins import UserMixin
|
||||
from .signals import session_protected
|
||||
from .signals import user_accessed
|
||||
from .signals import user_loaded_from_cookie
|
||||
from .signals import user_loaded_from_request
|
||||
from .signals import user_logged_in
|
||||
from .signals import user_logged_out
|
||||
from .signals import user_login_confirmed
|
||||
from .signals import user_needs_refresh
|
||||
from .signals import user_unauthorized
|
||||
# from .test_client import FlaskLoginClient
|
||||
from .utils import confirm_login
|
||||
from .utils import current_user
|
||||
from .utils import decode_cookie
|
||||
from .utils import encode_cookie
|
||||
from .utils import fresh_login_required
|
||||
from .utils import login_fresh
|
||||
from .utils import login_remembered
|
||||
from .utils import login_required
|
||||
from .utils import login_url
|
||||
from .utils import login_user
|
||||
from .utils import logout_user
|
||||
from .utils import make_next_param
|
||||
from .utils import set_login_view
|
||||
|
||||
__version_info__ = ("0", "6", "3")
|
||||
__version__ = ".".join(__version_info__)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"__version__",
|
||||
"AUTH_HEADER_NAME",
|
||||
"COOKIE_DURATION",
|
||||
"COOKIE_HTTPONLY",
|
||||
"COOKIE_NAME",
|
||||
"COOKIE_SECURE",
|
||||
"ID_ATTRIBUTE",
|
||||
"LOGIN_MESSAGE",
|
||||
"LOGIN_MESSAGE_CATEGORY",
|
||||
"REFRESH_MESSAGE",
|
||||
"REFRESH_MESSAGE_CATEGORY",
|
||||
"LoginManager",
|
||||
"AnonymousUserMixin",
|
||||
"UserMixin",
|
||||
"session_protected",
|
||||
"user_accessed",
|
||||
"user_loaded_from_cookie",
|
||||
"user_loaded_from_request",
|
||||
"user_logged_in",
|
||||
"user_logged_out",
|
||||
"user_login_confirmed",
|
||||
"user_needs_refresh",
|
||||
"user_unauthorized",
|
||||
# "FlaskLoginClient",
|
||||
"confirm_login",
|
||||
"current_user",
|
||||
"decode_cookie",
|
||||
"encode_cookie",
|
||||
"fresh_login_required",
|
||||
"login_fresh",
|
||||
"login_remembered",
|
||||
"login_required",
|
||||
"login_url",
|
||||
"login_user",
|
||||
"logout_user",
|
||||
"make_next_param",
|
||||
"set_login_view",
|
||||
]
|
||||
|
||||
|
||||
def __getattr__(name):
|
||||
if name == "user_loaded_from_header":
|
||||
import warnings
|
||||
from .signals import _user_loaded_from_header
|
||||
|
||||
warnings.warn(
|
||||
"'user_loaded_from_header' is deprecated and will be"
|
||||
" removed in Flask-Login 0.7. Use"
|
||||
" 'user_loaded_from_request' instead.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return _user_loaded_from_header
|
||||
|
||||
raise AttributeError(name)
|
||||
@@ -0,0 +1,55 @@
|
||||
from datetime import timedelta
|
||||
|
||||
#: The default name of the "remember me" cookie (``remember_token``)
|
||||
COOKIE_NAME = "remember_token"
|
||||
|
||||
#: The default time before the "remember me" cookie expires (365 days).
|
||||
COOKIE_DURATION = timedelta(days=365)
|
||||
|
||||
#: Whether the "remember me" cookie requires Secure; defaults to ``False``
|
||||
COOKIE_SECURE = False
|
||||
|
||||
#: Whether the "remember me" cookie uses HttpOnly or not; defaults to ``True``
|
||||
COOKIE_HTTPONLY = True
|
||||
|
||||
#: Whether the "remember me" cookie requires same origin; defaults to ``None``
|
||||
COOKIE_SAMESITE = None
|
||||
|
||||
#: The default flash message to display when users need to log in.
|
||||
LOGIN_MESSAGE = "Please log in to access this page."
|
||||
|
||||
#: The default flash message category to display when users need to log in.
|
||||
LOGIN_MESSAGE_CATEGORY = "message"
|
||||
|
||||
#: The default flash message to display when users need to reauthenticate.
|
||||
REFRESH_MESSAGE = "Please reauthenticate to access this page."
|
||||
|
||||
#: The default flash message category to display when users need to
|
||||
#: reauthenticate.
|
||||
REFRESH_MESSAGE_CATEGORY = "message"
|
||||
|
||||
#: The default attribute to retreive the str id of the user
|
||||
ID_ATTRIBUTE = "get_id"
|
||||
|
||||
#: Default name of the auth header (``Authorization``)
|
||||
AUTH_HEADER_NAME = "Authorization"
|
||||
|
||||
#: A set of session keys that are populated by Flask-Login. Use this set to
|
||||
#: purge keys safely and accurately.
|
||||
SESSION_KEYS = {
|
||||
"_user_id",
|
||||
"_remember",
|
||||
"_remember_seconds",
|
||||
"_id",
|
||||
"_fresh",
|
||||
"next",
|
||||
}
|
||||
|
||||
#: A set of HTTP methods which are exempt from `login_required` and
|
||||
#: `fresh_login_required`. By default, this is just ``OPTIONS``.
|
||||
EXEMPT_METHODS = {"OPTIONS"}
|
||||
|
||||
#: If true, the page the user is attempting to access is stored in the session
|
||||
#: rather than a url parameter when redirecting to the login view; defaults to
|
||||
#: ``False``.
|
||||
USE_SESSION_FOR_NEXT = False
|
||||
@@ -0,0 +1,523 @@
|
||||
from datetime import datetime
|
||||
from datetime import timezone
|
||||
from datetime import timedelta
|
||||
import hashlib
|
||||
|
||||
from flask import abort
|
||||
from flask import current_app
|
||||
from flask import flash
|
||||
from flask import g
|
||||
from flask import redirect
|
||||
from flask import request
|
||||
from flask import session
|
||||
from itsdangerous import URLSafeSerializer
|
||||
from flask.json.tag import TaggedJSONSerializer
|
||||
|
||||
from .config import AUTH_HEADER_NAME
|
||||
from .config import COOKIE_DURATION
|
||||
from .config import COOKIE_HTTPONLY
|
||||
from .config import COOKIE_NAME
|
||||
from .config import COOKIE_SAMESITE
|
||||
from .config import COOKIE_SECURE
|
||||
from .config import ID_ATTRIBUTE
|
||||
from .config import LOGIN_MESSAGE
|
||||
from .config import LOGIN_MESSAGE_CATEGORY
|
||||
from .config import REFRESH_MESSAGE
|
||||
from .config import REFRESH_MESSAGE_CATEGORY
|
||||
from .config import SESSION_KEYS
|
||||
from .config import USE_SESSION_FOR_NEXT
|
||||
from .mixins import AnonymousUserMixin
|
||||
from .signals import session_protected
|
||||
from .signals import user_accessed
|
||||
from .signals import user_loaded_from_cookie
|
||||
from .signals import user_loaded_from_request
|
||||
from .signals import user_needs_refresh
|
||||
from .signals import user_unauthorized
|
||||
from .utils import _create_identifier
|
||||
from .utils import _user_context_processor
|
||||
from .utils import confirm_login
|
||||
from .utils import expand_login_view
|
||||
from .utils import login_url as make_login_url
|
||||
from .utils import make_next_param
|
||||
|
||||
|
||||
class LoginManager:
|
||||
"""This object is used to hold the settings used for logging in. Instances
|
||||
of :class:`LoginManager` are *not* bound to specific apps, so you can
|
||||
create one in the main body of your code and then bind it to your
|
||||
app in a factory function.
|
||||
"""
|
||||
|
||||
def __init__(self, app=None, add_context_processor=True):
|
||||
#: A class or factory function that produces an anonymous user, which
|
||||
#: is used when no one is logged in.
|
||||
self.anonymous_user = AnonymousUserMixin
|
||||
|
||||
#: The name of the view to redirect to when the user needs to log in.
|
||||
#: (This can be an absolute URL as well, if your authentication
|
||||
#: machinery is external to your application.)
|
||||
self.login_view = None
|
||||
|
||||
#: Names of views to redirect to when the user needs to log in,
|
||||
#: per blueprint. If the key value is set to None the value of
|
||||
#: :attr:`login_view` will be used instead.
|
||||
self.blueprint_login_views = {}
|
||||
|
||||
#: The message to flash when a user is redirected to the login page.
|
||||
self.login_message = LOGIN_MESSAGE
|
||||
|
||||
#: The message category to flash when a user is redirected to the login
|
||||
#: page.
|
||||
self.login_message_category = LOGIN_MESSAGE_CATEGORY
|
||||
|
||||
#: The name of the view to redirect to when the user needs to
|
||||
#: reauthenticate.
|
||||
self.refresh_view = None
|
||||
|
||||
#: The message to flash when a user is redirected to the 'needs
|
||||
#: refresh' page.
|
||||
self.needs_refresh_message = REFRESH_MESSAGE
|
||||
|
||||
#: The message category to flash when a user is redirected to the
|
||||
#: 'needs refresh' page.
|
||||
self.needs_refresh_message_category = REFRESH_MESSAGE_CATEGORY
|
||||
|
||||
#: The mode to use session protection in. This can be either
|
||||
#: ``'basic'`` (the default) or ``'strong'``, or ``None`` to disable
|
||||
#: it.
|
||||
self.session_protection = "basic"
|
||||
|
||||
#: If present, used to translate flash messages ``self.login_message``
|
||||
#: and ``self.needs_refresh_message``
|
||||
self.localize_callback = None
|
||||
|
||||
self.unauthorized_callback = None
|
||||
|
||||
self.needs_refresh_callback = None
|
||||
|
||||
self.id_attribute = ID_ATTRIBUTE
|
||||
|
||||
self._user_callback = None
|
||||
|
||||
self._header_callback = None
|
||||
|
||||
self._request_callback = None
|
||||
|
||||
self._session_identifier_generator = _create_identifier
|
||||
|
||||
if app is not None:
|
||||
self.init_app(app, add_context_processor)
|
||||
|
||||
def setup_app(self, app, add_context_processor=True): # pragma: no cover
|
||||
"""
|
||||
This method has been deprecated. Please use
|
||||
:meth:`LoginManager.init_app` instead.
|
||||
"""
|
||||
import warnings
|
||||
|
||||
warnings.warn(
|
||||
"'setup_app' is deprecated and will be removed in"
|
||||
" Flask-Login 0.7. Use 'init_app' instead.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
self.init_app(app, add_context_processor)
|
||||
|
||||
def init_app(self, app, add_context_processor=True):
|
||||
"""
|
||||
Configures an application. This registers an `after_request` call, and
|
||||
attaches this `LoginManager` to it as `app.login_manager`.
|
||||
|
||||
:param app: The :class:`flask.Flask` object to configure.
|
||||
:type app: :class:`flask.Flask`
|
||||
:param add_context_processor: Whether to add a context processor to
|
||||
the app that adds a `current_user` variable to the template.
|
||||
Defaults to ``True``.
|
||||
:type add_context_processor: bool
|
||||
"""
|
||||
app.login_manager = self
|
||||
app.after_request(self._update_remember_cookie)
|
||||
|
||||
if add_context_processor:
|
||||
app.context_processor(_user_context_processor)
|
||||
|
||||
def unauthorized(self):
|
||||
"""
|
||||
This is called when the user is required to log in. If you register a
|
||||
callback with :meth:`LoginManager.unauthorized_handler`, then it will
|
||||
be called. Otherwise, it will take the following actions:
|
||||
|
||||
- Flash :attr:`LoginManager.login_message` to the user.
|
||||
|
||||
- If the app is using blueprints find the login view for
|
||||
the current blueprint using `blueprint_login_views`. If the app
|
||||
is not using blueprints or the login view for the current
|
||||
blueprint is not specified use the value of `login_view`.
|
||||
|
||||
- Redirect the user to the login view. (The page they were
|
||||
attempting to access will be passed in the ``next`` query
|
||||
string variable, so you can redirect there if present instead
|
||||
of the homepage. Alternatively, it will be added to the session
|
||||
as ``next`` if USE_SESSION_FOR_NEXT is set.)
|
||||
|
||||
If :attr:`LoginManager.login_view` is not defined, then it will simply
|
||||
raise a HTTP 401 (Unauthorized) error instead.
|
||||
|
||||
This should be returned from a view or before/after_request function,
|
||||
otherwise the redirect will have no effect.
|
||||
"""
|
||||
user_unauthorized.send(current_app._get_current_object())
|
||||
|
||||
if self.unauthorized_callback:
|
||||
return self.unauthorized_callback()
|
||||
|
||||
if request.blueprint in self.blueprint_login_views:
|
||||
login_view = self.blueprint_login_views[request.blueprint]
|
||||
else:
|
||||
login_view = self.login_view
|
||||
|
||||
if not login_view:
|
||||
abort(401)
|
||||
|
||||
if self.login_message:
|
||||
if self.localize_callback is not None:
|
||||
flash(
|
||||
self.localize_callback(self.login_message),
|
||||
category=self.login_message_category,
|
||||
)
|
||||
else:
|
||||
flash(self.login_message, category=self.login_message_category)
|
||||
|
||||
config = current_app.config
|
||||
if config.get("USE_SESSION_FOR_NEXT", USE_SESSION_FOR_NEXT):
|
||||
login_url = expand_login_view(login_view)
|
||||
session["_id"] = self._session_identifier_generator()
|
||||
session["next"] = make_next_param(login_url, request.url)
|
||||
redirect_url = make_login_url(login_view)
|
||||
else:
|
||||
redirect_url = make_login_url(login_view, next_url=request.url)
|
||||
|
||||
return redirect(redirect_url)
|
||||
|
||||
def user_loader(self, callback):
|
||||
"""
|
||||
This sets the callback for reloading a user from the session. The
|
||||
function you set should take a user ID (a ``str``) and return a
|
||||
user object, or ``None`` if the user does not exist.
|
||||
|
||||
:param callback: The callback for retrieving a user object.
|
||||
:type callback: callable
|
||||
"""
|
||||
self._user_callback = callback
|
||||
return self.user_callback
|
||||
|
||||
@property
|
||||
def user_callback(self):
|
||||
"""Gets the user_loader callback set by user_loader decorator."""
|
||||
return self._user_callback
|
||||
|
||||
def request_loader(self, callback):
|
||||
"""
|
||||
This sets the callback for loading a user from a Flask request.
|
||||
The function you set should take Flask request object and
|
||||
return a user object, or `None` if the user does not exist.
|
||||
|
||||
:param callback: The callback for retrieving a user object.
|
||||
:type callback: callable
|
||||
"""
|
||||
self._request_callback = callback
|
||||
return self.request_callback
|
||||
|
||||
@property
|
||||
def request_callback(self):
|
||||
"""Gets the request_loader callback set by request_loader decorator."""
|
||||
return self._request_callback
|
||||
|
||||
def unauthorized_handler(self, callback):
|
||||
"""
|
||||
This will set the callback for the `unauthorized` method, which among
|
||||
other things is used by `login_required`. It takes no arguments, and
|
||||
should return a response to be sent to the user instead of their
|
||||
normal view.
|
||||
|
||||
:param callback: The callback for unauthorized users.
|
||||
:type callback: callable
|
||||
"""
|
||||
self.unauthorized_callback = callback
|
||||
return callback
|
||||
|
||||
def needs_refresh_handler(self, callback):
|
||||
"""
|
||||
This will set the callback for the `needs_refresh` method, which among
|
||||
other things is used by `fresh_login_required`. It takes no arguments,
|
||||
and should return a response to be sent to the user instead of their
|
||||
normal view.
|
||||
|
||||
:param callback: The callback for unauthorized users.
|
||||
:type callback: callable
|
||||
"""
|
||||
self.needs_refresh_callback = callback
|
||||
return callback
|
||||
|
||||
def needs_refresh(self):
|
||||
"""
|
||||
This is called when the user is logged in, but they need to be
|
||||
reauthenticated because their session is stale. If you register a
|
||||
callback with `needs_refresh_handler`, then it will be called.
|
||||
Otherwise, it will take the following actions:
|
||||
|
||||
- Flash :attr:`LoginManager.needs_refresh_message` to the user.
|
||||
|
||||
- Redirect the user to :attr:`LoginManager.refresh_view`. (The page
|
||||
they were attempting to access will be passed in the ``next``
|
||||
query string variable, so you can redirect there if present
|
||||
instead of the homepage.)
|
||||
|
||||
If :attr:`LoginManager.refresh_view` is not defined, then it will
|
||||
simply raise a HTTP 401 (Unauthorized) error instead.
|
||||
|
||||
This should be returned from a view or before/after_request function,
|
||||
otherwise the redirect will have no effect.
|
||||
"""
|
||||
user_needs_refresh.send(current_app._get_current_object())
|
||||
|
||||
if self.needs_refresh_callback:
|
||||
return self.needs_refresh_callback()
|
||||
|
||||
if not self.refresh_view:
|
||||
abort(401)
|
||||
|
||||
if self.needs_refresh_message:
|
||||
if self.localize_callback is not None:
|
||||
flash(
|
||||
self.localize_callback(self.needs_refresh_message),
|
||||
category=self.needs_refresh_message_category,
|
||||
)
|
||||
else:
|
||||
flash(
|
||||
self.needs_refresh_message,
|
||||
category=self.needs_refresh_message_category,
|
||||
)
|
||||
|
||||
config = current_app.config
|
||||
if config.get("USE_SESSION_FOR_NEXT", USE_SESSION_FOR_NEXT):
|
||||
login_url = expand_login_view(self.refresh_view)
|
||||
session["_id"] = self._session_identifier_generator()
|
||||
session["next"] = make_next_param(login_url, request.url)
|
||||
redirect_url = make_login_url(self.refresh_view)
|
||||
else:
|
||||
login_url = self.refresh_view
|
||||
redirect_url = make_login_url(login_url, next_url=request.url)
|
||||
|
||||
return redirect(redirect_url)
|
||||
|
||||
def _update_request_context_with_user(self, user=None):
|
||||
"""Store the given user as ctx.user."""
|
||||
|
||||
if user is None:
|
||||
user = self.anonymous_user()
|
||||
|
||||
g._login_user = user
|
||||
|
||||
def _load_user(self):
|
||||
"""Loads user from session or remember_me cookie as applicable"""
|
||||
|
||||
if self._user_callback is None and self._request_callback is None:
|
||||
raise Exception(
|
||||
"Missing user_loader or request_loader. Refer to "
|
||||
"https://flask-login.readthedocs.io/#how-it-works "
|
||||
"for more info."
|
||||
)
|
||||
|
||||
user_accessed.send(current_app._get_current_object())
|
||||
|
||||
# Check SESSION_PROTECTION
|
||||
if self._session_protection_failed():
|
||||
return self._update_request_context_with_user()
|
||||
|
||||
user = None
|
||||
|
||||
# Load user from Flask Session
|
||||
user_id = session.get("_user_id")
|
||||
user_random = session.get("_random")
|
||||
user_session_key = session.get("_id")
|
||||
if (user_id is not None
|
||||
and user_random is not None
|
||||
and user_session_key is not None
|
||||
and self._user_callback is not None):
|
||||
user = self._user_callback(user_id, user_random, user_session_key)
|
||||
|
||||
# Load user from Remember Me Cookie or Request Loader
|
||||
if user is None:
|
||||
config = current_app.config
|
||||
cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
|
||||
header_name = config.get("AUTH_HEADER_NAME", AUTH_HEADER_NAME)
|
||||
has_cookie = (
|
||||
cookie_name in request.cookies and session.get("_remember") != "clear"
|
||||
)
|
||||
if has_cookie:
|
||||
cookie = request.cookies[cookie_name]
|
||||
user = self._load_user_from_remember_cookie(cookie)
|
||||
elif self._request_callback:
|
||||
user = self._load_user_from_request(request)
|
||||
elif header_name in request.headers:
|
||||
header = request.headers[header_name]
|
||||
user = self._load_user_from_header(header)
|
||||
if not user:
|
||||
self._update_request_context_with_user()
|
||||
return self._update_request_context_with_user(user)
|
||||
|
||||
def _session_protection_failed(self):
|
||||
sess = session._get_current_object()
|
||||
ident = self._session_identifier_generator()
|
||||
|
||||
app = current_app._get_current_object()
|
||||
mode = app.config.get("SESSION_PROTECTION", self.session_protection)
|
||||
|
||||
if not mode or mode not in ["basic", "strong"]:
|
||||
return False
|
||||
|
||||
# if the sess is empty, it's an anonymous user or just logged out
|
||||
# so we can skip this
|
||||
if sess and ident != sess.get("_id", None):
|
||||
if mode == "basic" or sess.permanent:
|
||||
if sess.get("_fresh") is not False:
|
||||
sess["_fresh"] = False
|
||||
session_protected.send(app)
|
||||
return False
|
||||
elif mode == "strong":
|
||||
for k in SESSION_KEYS:
|
||||
sess.pop(k, None)
|
||||
|
||||
sess["_remember"] = "clear"
|
||||
session_protected.send(app)
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def _load_user_from_remember_cookie(self, cookie):
|
||||
signer_kwargs = dict(
|
||||
key_derivation="hmac", digest_method=hashlib.sha1
|
||||
)
|
||||
try:
|
||||
remember_dict = URLSafeSerializer(
|
||||
current_app.secret_key,
|
||||
salt="remember",
|
||||
serializer=TaggedJSONSerializer(),
|
||||
signer_kwargs=signer_kwargs,
|
||||
).loads(cookie)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
if remember_dict['user'] is not None:
|
||||
session["_user_id"] = remember_dict['user']
|
||||
if "_random" not in session:
|
||||
session["_random"] = remember_dict['random']
|
||||
session["_fresh"] = False
|
||||
user = None
|
||||
if self._user_callback:
|
||||
user = self._user_callback(remember_dict['user'], session["_random"], None)
|
||||
if user is not None:
|
||||
app = current_app._get_current_object()
|
||||
user_loaded_from_cookie.send(app, user=user)
|
||||
# if session was restored from remember me cookie make login valid
|
||||
confirm_login()
|
||||
return user
|
||||
return None
|
||||
|
||||
def _load_user_from_header(self, header):
|
||||
if self._header_callback:
|
||||
user = self._header_callback(header)
|
||||
if user is not None:
|
||||
app = current_app._get_current_object()
|
||||
|
||||
from .signals import _user_loaded_from_header
|
||||
|
||||
_user_loaded_from_header.send(app, user=user)
|
||||
return user
|
||||
return None
|
||||
|
||||
def _load_user_from_request(self, request):
|
||||
if self._request_callback:
|
||||
user = self._request_callback(request)
|
||||
if user is not None:
|
||||
app = current_app._get_current_object()
|
||||
user_loaded_from_request.send(app, user=user)
|
||||
return user
|
||||
return None
|
||||
|
||||
def _update_remember_cookie(self, response):
|
||||
# Don't modify the session unless there's something to do.
|
||||
if "_remember" not in session and current_app.config.get(
|
||||
"REMEMBER_COOKIE_REFRESH_EACH_REQUEST"
|
||||
):
|
||||
session["_remember"] = "set"
|
||||
|
||||
if "_remember" in session:
|
||||
operation = session.pop("_remember", None)
|
||||
|
||||
if operation == "set" and "_user_id" in session:
|
||||
self._set_cookie(response)
|
||||
elif operation == "clear":
|
||||
self._clear_cookie(response)
|
||||
|
||||
return response
|
||||
|
||||
def _set_cookie(self, response):
|
||||
# cookie settings
|
||||
config = current_app.config
|
||||
cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
|
||||
domain = config.get("REMEMBER_COOKIE_DOMAIN")
|
||||
path = config.get("REMEMBER_COOKIE_PATH", current_app.wsgi_app.script_name)
|
||||
|
||||
secure = config.get("REMEMBER_COOKIE_SECURE", COOKIE_SECURE)
|
||||
httponly = config.get("REMEMBER_COOKIE_HTTPONLY", COOKIE_HTTPONLY)
|
||||
samesite = config.get("REMEMBER_COOKIE_SAMESITE", COOKIE_SAMESITE)
|
||||
|
||||
if "_remember_seconds" in session:
|
||||
duration = timedelta(seconds=session["_remember_seconds"])
|
||||
else:
|
||||
duration = config.get("REMEMBER_COOKIE_DURATION", COOKIE_DURATION)
|
||||
|
||||
# prepare data
|
||||
max_age = int(current_app.permanent_session_lifetime.total_seconds())
|
||||
signer_kwargs = dict(
|
||||
key_derivation="hmac", digest_method=hashlib.sha1
|
||||
)
|
||||
# save
|
||||
data = URLSafeSerializer(
|
||||
current_app.secret_key,
|
||||
salt="remember",
|
||||
serializer=TaggedJSONSerializer(),
|
||||
signer_kwargs=signer_kwargs,
|
||||
).dumps({"user":session["_user_id"], "random":session["_random"]})
|
||||
|
||||
if isinstance(duration, int):
|
||||
duration = timedelta(seconds=duration)
|
||||
|
||||
try:
|
||||
expires = datetime.now(timezone.utc) + duration
|
||||
except TypeError as e:
|
||||
raise Exception(
|
||||
"REMEMBER_COOKIE_DURATION must be a datetime.timedelta,"
|
||||
f" instead got: {duration}"
|
||||
) from e
|
||||
|
||||
# actually set it
|
||||
response.set_cookie(
|
||||
cookie_name,
|
||||
value=data,
|
||||
expires=expires,
|
||||
domain=domain,
|
||||
path=path,
|
||||
secure=secure,
|
||||
httponly=httponly,
|
||||
samesite=samesite,
|
||||
)
|
||||
|
||||
def _clear_cookie(self, response):
|
||||
config = current_app.config
|
||||
cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
|
||||
domain = config.get("REMEMBER_COOKIE_DOMAIN")
|
||||
path = config.get("REMEMBER_COOKIE_PATH", current_app.wsgi_app.script_name)
|
||||
response.delete_cookie(cookie_name, domain=domain, path=path)
|
||||
@@ -0,0 +1,65 @@
|
||||
class UserMixin:
|
||||
"""
|
||||
This provides default implementations for the methods that Flask-Login
|
||||
expects user objects to have.
|
||||
"""
|
||||
|
||||
# Python 3 implicitly set __hash__ to None if we override __eq__
|
||||
# We set it back to its default implementation
|
||||
__hash__ = object.__hash__
|
||||
|
||||
@property
|
||||
def is_active(self):
|
||||
return True
|
||||
|
||||
@property
|
||||
def is_authenticated(self):
|
||||
return self.is_active
|
||||
|
||||
@property
|
||||
def is_anonymous(self):
|
||||
return False
|
||||
|
||||
def get_id(self):
|
||||
try:
|
||||
return str(self.id)
|
||||
except AttributeError:
|
||||
raise NotImplementedError("No `id` attribute - override `get_id`") from None
|
||||
|
||||
def __eq__(self, other):
|
||||
"""
|
||||
Checks the equality of two `UserMixin` objects using `get_id`.
|
||||
"""
|
||||
if isinstance(other, UserMixin):
|
||||
return self.get_id() == other.get_id()
|
||||
return NotImplemented
|
||||
|
||||
def __ne__(self, other):
|
||||
"""
|
||||
Checks the inequality of two `UserMixin` objects using `get_id`.
|
||||
"""
|
||||
equal = self.__eq__(other)
|
||||
if equal is NotImplemented:
|
||||
return NotImplemented
|
||||
return not equal
|
||||
|
||||
|
||||
class AnonymousUserMixin:
|
||||
"""
|
||||
This is the default object for representing an anonymous user.
|
||||
"""
|
||||
|
||||
@property
|
||||
def is_authenticated(self):
|
||||
return False
|
||||
|
||||
@property
|
||||
def is_active(self):
|
||||
return False
|
||||
|
||||
@property
|
||||
def is_anonymous(self):
|
||||
return True
|
||||
|
||||
def get_id(self):
|
||||
return
|
||||
@@ -0,0 +1,61 @@
|
||||
from flask.signals import Namespace
|
||||
|
||||
_signals = Namespace()
|
||||
|
||||
#: Sent when a user is logged in. In addition to the app (which is the
|
||||
#: sender), it is passed `user`, which is the user being logged in.
|
||||
user_logged_in = _signals.signal("logged-in")
|
||||
|
||||
#: Sent when a user is logged out. In addition to the app (which is the
|
||||
#: sender), it is passed `user`, which is the user being logged out.
|
||||
user_logged_out = _signals.signal("logged-out")
|
||||
|
||||
#: Sent when the user is loaded from the cookie. In addition to the app (which
|
||||
#: is the sender), it is passed `user`, which is the user being reloaded.
|
||||
user_loaded_from_cookie = _signals.signal("loaded-from-cookie")
|
||||
|
||||
#: Sent when the user is loaded from the header. In addition to the app (which
|
||||
#: is the #: sender), it is passed `user`, which is the user being reloaded.
|
||||
_user_loaded_from_header = _signals.signal("loaded-from-header")
|
||||
|
||||
#: Sent when the user is loaded from the request. In addition to the app (which
|
||||
#: is the #: sender), it is passed `user`, which is the user being reloaded.
|
||||
user_loaded_from_request = _signals.signal("loaded-from-request")
|
||||
|
||||
#: Sent when a user's login is confirmed, marking it as fresh. (It is not
|
||||
#: called for a normal login.)
|
||||
#: It receives no additional arguments besides the app.
|
||||
user_login_confirmed = _signals.signal("login-confirmed")
|
||||
|
||||
#: Sent when the `unauthorized` method is called on a `LoginManager`. It
|
||||
#: receives no additional arguments besides the app.
|
||||
user_unauthorized = _signals.signal("unauthorized")
|
||||
|
||||
#: Sent when the `needs_refresh` method is called on a `LoginManager`. It
|
||||
#: receives no additional arguments besides the app.
|
||||
user_needs_refresh = _signals.signal("needs-refresh")
|
||||
|
||||
#: Sent whenever the user is accessed/loaded
|
||||
#: receives no additional arguments besides the app.
|
||||
user_accessed = _signals.signal("accessed")
|
||||
|
||||
#: Sent whenever session protection takes effect, and a session is either
|
||||
#: marked non-fresh or deleted. It receives no additional arguments besides
|
||||
#: the app.
|
||||
session_protected = _signals.signal("session-protected")
|
||||
|
||||
|
||||
def __getattr__(name):
|
||||
if name == "user_loaded_from_header":
|
||||
import warnings
|
||||
|
||||
warnings.warn(
|
||||
"'user_loaded_from_header' is deprecated and will be"
|
||||
" removed in Flask-Login 0.7. Use"
|
||||
" 'user_loaded_from_request' instead.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return _user_loaded_from_header
|
||||
|
||||
raise AttributeError(name)
|
||||
@@ -0,0 +1,424 @@
|
||||
import hmac
|
||||
import os
|
||||
from functools import wraps
|
||||
from hashlib import sha512
|
||||
from urllib.parse import parse_qs
|
||||
from urllib.parse import urlencode
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.parse import urlunsplit
|
||||
|
||||
from flask import current_app
|
||||
from flask import g
|
||||
from flask import has_request_context
|
||||
from flask import request
|
||||
from flask import session
|
||||
from flask import url_for
|
||||
from werkzeug.local import LocalProxy
|
||||
|
||||
from .config import COOKIE_NAME
|
||||
from .config import EXEMPT_METHODS
|
||||
from .signals import user_logged_in
|
||||
from .signals import user_logged_out
|
||||
from .signals import user_login_confirmed
|
||||
|
||||
#: A proxy for the current user. If no user is logged in, this will be an
|
||||
#: anonymous user
|
||||
current_user = LocalProxy(lambda: _get_user())
|
||||
|
||||
|
||||
def encode_cookie(payload, key=None):
|
||||
"""
|
||||
This will encode a ``str`` value into a cookie, and sign that cookie
|
||||
with the app's secret key.
|
||||
|
||||
:param payload: The value to encode, as `str`.
|
||||
:type payload: str
|
||||
|
||||
:param key: The key to use when creating the cookie digest. If not
|
||||
specified, the SECRET_KEY value from app config will be used.
|
||||
:type key: str
|
||||
"""
|
||||
return f"{payload}|{_cookie_digest(payload, key=key)}"
|
||||
|
||||
|
||||
def decode_cookie(cookie, key=None):
|
||||
"""
|
||||
This decodes a cookie given by `encode_cookie`. If verification of the
|
||||
cookie fails, ``None`` will be implicitly returned.
|
||||
|
||||
:param cookie: An encoded cookie.
|
||||
:type cookie: str
|
||||
|
||||
:param key: The key to use when creating the cookie digest. If not
|
||||
specified, the SECRET_KEY value from app config will be used.
|
||||
:type key: str
|
||||
"""
|
||||
try:
|
||||
payload, digest = cookie.rsplit("|", 1)
|
||||
if hasattr(digest, "decode"):
|
||||
digest = digest.decode("ascii") # pragma: no cover
|
||||
except ValueError:
|
||||
return
|
||||
|
||||
if hmac.compare_digest(_cookie_digest(payload, key=key), digest):
|
||||
return payload
|
||||
|
||||
|
||||
def make_next_param(login_url, current_url):
|
||||
"""
|
||||
Reduces the scheme and host from a given URL so it can be passed to
|
||||
the given `login` URL more efficiently.
|
||||
|
||||
:param login_url: The login URL being redirected to.
|
||||
:type login_url: str
|
||||
:param current_url: The URL to reduce.
|
||||
:type current_url: str
|
||||
"""
|
||||
l_url = urlsplit(login_url)
|
||||
c_url = urlsplit(current_url)
|
||||
|
||||
if (not l_url.scheme or l_url.scheme == c_url.scheme) and (
|
||||
not l_url.netloc or l_url.netloc == c_url.netloc
|
||||
):
|
||||
return urlunsplit(("", "", c_url.path, c_url.query, ""))
|
||||
return current_url
|
||||
|
||||
|
||||
def expand_login_view(login_view):
|
||||
"""
|
||||
Returns the url for the login view, expanding the view name to a url if
|
||||
needed.
|
||||
|
||||
:param login_view: The name of the login view or a URL for the login view.
|
||||
:type login_view: str
|
||||
"""
|
||||
if login_view.startswith(("https://", "http://", "/")):
|
||||
return login_view
|
||||
|
||||
return url_for(login_view)
|
||||
|
||||
|
||||
def login_url(login_view, next_url=None, next_field="next"):
|
||||
"""
|
||||
Creates a URL for redirecting to a login page. If only `login_view` is
|
||||
provided, this will just return the URL for it. If `next_url` is provided,
|
||||
however, this will append a ``next=URL`` parameter to the query string
|
||||
so that the login view can redirect back to that URL. Flask-Login's default
|
||||
unauthorized handler uses this function when redirecting to your login url.
|
||||
To force the host name used, set `FORCE_HOST_FOR_REDIRECTS` to a host. This
|
||||
prevents from redirecting to external sites if request headers Host or
|
||||
X-Forwarded-For are present.
|
||||
|
||||
:param login_view: The name of the login view. (Alternately, the actual
|
||||
URL to the login view.)
|
||||
:type login_view: str
|
||||
:param next_url: The URL to give the login view for redirection.
|
||||
:type next_url: str
|
||||
:param next_field: What field to store the next URL in. (It defaults to
|
||||
``next``.)
|
||||
:type next_field: str
|
||||
"""
|
||||
base = expand_login_view(login_view)
|
||||
|
||||
if next_url is None:
|
||||
return base
|
||||
|
||||
parsed_result = urlsplit(base)
|
||||
md = parse_qs(parsed_result.query, keep_blank_values=True)
|
||||
md[next_field] = make_next_param(base, next_url)
|
||||
netloc = current_app.config.get("FORCE_HOST_FOR_REDIRECTS") or parsed_result.netloc
|
||||
parsed_result = parsed_result._replace(
|
||||
netloc=netloc, query=urlencode(md, doseq=True)
|
||||
)
|
||||
return urlunsplit(parsed_result)
|
||||
|
||||
|
||||
def login_fresh():
|
||||
"""
|
||||
This returns ``True`` if the current login is fresh.
|
||||
"""
|
||||
return session.get("_fresh", False)
|
||||
|
||||
|
||||
def login_remembered():
|
||||
"""
|
||||
This returns ``True`` if the current login is remembered across sessions.
|
||||
"""
|
||||
config = current_app.config
|
||||
cookie_name = config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
|
||||
has_cookie = cookie_name in request.cookies and session.get("_remember") != "clear"
|
||||
if has_cookie:
|
||||
cookie = request.cookies[cookie_name]
|
||||
user_id = decode_cookie(cookie)
|
||||
return user_id is not None
|
||||
return False
|
||||
|
||||
|
||||
def login_user(user, remember=False, duration=None, force=False, fresh=True):
|
||||
"""
|
||||
Logs a user in. You should pass the actual user object to this. If the
|
||||
user's `is_active` property is ``False``, they will not be logged in
|
||||
unless `force` is ``True``.
|
||||
|
||||
This will return ``True`` if the log in attempt succeeds, and ``False`` if
|
||||
it fails (i.e. because the user is inactive).
|
||||
|
||||
:param user: The user object to log in.
|
||||
:type user: object
|
||||
:param remember: Whether to remember the user after their session expires.
|
||||
Defaults to ``False``.
|
||||
:type remember: bool
|
||||
:param duration: The amount of time before the remember cookie expires. If
|
||||
``None`` the value set in the settings is used. Defaults to ``None``.
|
||||
:type duration: :class:`datetime.timedelta`
|
||||
:param force: If the user is inactive, setting this to ``True`` will log
|
||||
them in regardless. Defaults to ``False``.
|
||||
:type force: bool
|
||||
:param fresh: setting this to ``False`` will log in the user with a session
|
||||
marked as not "fresh". Defaults to ``True``.
|
||||
:type fresh: bool
|
||||
"""
|
||||
if not force and not user.is_active:
|
||||
return False
|
||||
|
||||
user_id = getattr(user, current_app.login_manager.id_attribute)()
|
||||
session["_user_id"] = user_id
|
||||
session["_fresh"] = fresh
|
||||
session["_id"] = current_app.login_manager._session_identifier_generator()
|
||||
session["_random"] = os.urandom(10).hex()
|
||||
|
||||
if remember:
|
||||
session["_remember"] = "set"
|
||||
if duration is not None:
|
||||
try:
|
||||
# equal to timedelta.total_seconds() but works with Python 2.6
|
||||
session["_remember_seconds"] = (
|
||||
duration.microseconds
|
||||
+ (duration.seconds + duration.days * 24 * 3600) * 10**6
|
||||
) / 10.0**6
|
||||
except AttributeError as e:
|
||||
raise Exception(
|
||||
f"duration must be a datetime.timedelta, instead got: {duration}"
|
||||
) from e
|
||||
|
||||
current_app.login_manager._update_request_context_with_user(user)
|
||||
user_logged_in.send(current_app._get_current_object(), user=_get_user())
|
||||
return True
|
||||
|
||||
|
||||
def logout_user():
|
||||
"""
|
||||
Logs a user out. (You do not need to pass the actual user.) This will
|
||||
also clean up the remember me cookie if it exists.
|
||||
"""
|
||||
|
||||
user = _get_user()
|
||||
|
||||
if "_user_id" in session:
|
||||
session.pop("_user_id")
|
||||
|
||||
if "_fresh" in session:
|
||||
session.pop("_fresh")
|
||||
|
||||
if "_id" in session:
|
||||
session.pop("_id")
|
||||
|
||||
if "_random" in session:
|
||||
session.pop("_random")
|
||||
|
||||
|
||||
cookie_name = current_app.config.get("REMEMBER_COOKIE_NAME", COOKIE_NAME)
|
||||
if cookie_name in request.cookies:
|
||||
session["_remember"] = "clear"
|
||||
if "_remember_seconds" in session:
|
||||
session.pop("_remember_seconds")
|
||||
|
||||
user_logged_out.send(current_app._get_current_object(), user=user)
|
||||
|
||||
current_app.login_manager._update_request_context_with_user()
|
||||
return True
|
||||
|
||||
|
||||
def confirm_login():
|
||||
"""
|
||||
This sets the current session as fresh. Sessions become stale when they
|
||||
are reloaded from a cookie.
|
||||
"""
|
||||
session["_fresh"] = True
|
||||
session["_id"] = current_app.login_manager._session_identifier_generator()
|
||||
user_login_confirmed.send(current_app._get_current_object())
|
||||
|
||||
|
||||
def login_required(func):
|
||||
"""
|
||||
If you decorate a view with this, it will ensure that the current user is
|
||||
logged in and authenticated before calling the actual view. (If they are
|
||||
not, it calls the :attr:`LoginManager.unauthorized` callback.) For
|
||||
example::
|
||||
|
||||
@app.route('/post')
|
||||
@user_login_required
|
||||
def post():
|
||||
pass
|
||||
|
||||
If there are only certain times you need to require that your user is
|
||||
logged in, you can do so with::
|
||||
|
||||
if not current_user.is_authenticated:
|
||||
return current_app.login_manager.unauthorized()
|
||||
|
||||
...which is essentially the code that this function adds to your views.
|
||||
|
||||
It can be convenient to globally turn off authentication when unit testing.
|
||||
To enable this, if the application configuration variable `LOGIN_DISABLED`
|
||||
is set to `True`, this decorator will be ignored.
|
||||
|
||||
.. Note ::
|
||||
|
||||
Per `W3 guidelines for CORS preflight requests
|
||||
<http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_,
|
||||
HTTP ``OPTIONS`` requests are exempt from login checks.
|
||||
|
||||
:param func: The view function to decorate.
|
||||
:type func: function
|
||||
"""
|
||||
|
||||
@wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
if request.method in EXEMPT_METHODS or current_app.config.get("LOGIN_DISABLED"):
|
||||
pass
|
||||
elif not current_user.is_authenticated:
|
||||
return current_app.login_manager.unauthorized()
|
||||
|
||||
# flask 1.x compatibility
|
||||
# current_app.ensure_sync is only available in Flask >= 2.0
|
||||
if callable(getattr(current_app, "ensure_sync", None)):
|
||||
return current_app.ensure_sync(func)(*args, **kwargs)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return decorated_view
|
||||
|
||||
|
||||
def fresh_login_required(func):
|
||||
"""
|
||||
If you decorate a view with this, it will ensure that the current user's
|
||||
login is fresh - i.e. their session was not restored from a 'remember me'
|
||||
cookie. Sensitive operations, like changing a password or e-mail, should
|
||||
be protected with this, to impede the efforts of cookie thieves.
|
||||
|
||||
If the user is not authenticated, :meth:`LoginManager.unauthorized` is
|
||||
called as normal. If they are authenticated, but their session is not
|
||||
fresh, it will call :meth:`LoginManager.needs_refresh` instead. (In that
|
||||
case, you will need to provide a :attr:`LoginManager.refresh_view`.)
|
||||
|
||||
Behaves identically to the :func:`login_required` decorator with respect
|
||||
to configuration variables.
|
||||
|
||||
.. Note ::
|
||||
|
||||
Per `W3 guidelines for CORS preflight requests
|
||||
<http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_,
|
||||
HTTP ``OPTIONS`` requests are exempt from login checks.
|
||||
|
||||
:param func: The view function to decorate.
|
||||
:type func: function
|
||||
"""
|
||||
|
||||
@wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
if request.method in EXEMPT_METHODS or current_app.config.get("LOGIN_DISABLED"):
|
||||
pass
|
||||
elif not current_user.is_authenticated:
|
||||
return current_app.login_manager.unauthorized()
|
||||
elif not login_fresh():
|
||||
return current_app.login_manager.needs_refresh()
|
||||
try:
|
||||
# current_app.ensure_sync available in Flask >= 2.0
|
||||
return current_app.ensure_sync(func)(*args, **kwargs)
|
||||
except AttributeError: # pragma: no cover
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return decorated_view
|
||||
|
||||
|
||||
def set_login_view(login_view, blueprint=None):
|
||||
"""
|
||||
Sets the login view for the app or blueprint. If a blueprint is passed,
|
||||
the login view is set for this blueprint on ``blueprint_login_views``.
|
||||
|
||||
:param login_view: The user object to log in.
|
||||
:type login_view: str
|
||||
:param blueprint: The blueprint which this login view should be set on.
|
||||
Defaults to ``None``.
|
||||
:type blueprint: object
|
||||
"""
|
||||
|
||||
num_login_views = len(current_app.login_manager.blueprint_login_views)
|
||||
if blueprint is not None or num_login_views != 0:
|
||||
(current_app.login_manager.blueprint_login_views[blueprint.name]) = login_view
|
||||
|
||||
if (
|
||||
current_app.login_manager.login_view is not None
|
||||
and None not in current_app.login_manager.blueprint_login_views
|
||||
):
|
||||
(
|
||||
current_app.login_manager.blueprint_login_views[None]
|
||||
) = current_app.login_manager.login_view
|
||||
|
||||
current_app.login_manager.login_view = None
|
||||
else:
|
||||
current_app.login_manager.login_view = login_view
|
||||
|
||||
|
||||
def _get_user():
|
||||
if has_request_context():
|
||||
if "flask_httpauth_user" in g:
|
||||
if g.flask_httpauth_user is not None:
|
||||
return g.flask_httpauth_user
|
||||
if "_login_user" not in g:
|
||||
current_app.login_manager._load_user()
|
||||
|
||||
return g._login_user
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _cookie_digest(payload, key=None):
|
||||
key = _secret_key(key)
|
||||
|
||||
return hmac.new(key, payload.encode("utf-8"), sha512).hexdigest()
|
||||
|
||||
|
||||
def _get_remote_addr():
|
||||
address = request.headers.get("X-Forwarded-For", request.remote_addr)
|
||||
if address is not None:
|
||||
# An 'X-Forwarded-For' header includes a comma separated list of the
|
||||
# addresses, the first address being the actual remote address.
|
||||
address = address.encode("utf-8").split(b",")[0].strip()
|
||||
return address
|
||||
|
||||
|
||||
def _create_identifier():
|
||||
user_agent = request.headers.get("User-Agent")
|
||||
if user_agent is not None:
|
||||
user_agent = user_agent.encode("utf-8")
|
||||
base = f"{_get_remote_addr()}|{user_agent}"
|
||||
if str is bytes:
|
||||
base = str(base, "utf-8", errors="replace") # pragma: no cover
|
||||
h = sha512()
|
||||
h.update(base.encode("utf8"))
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def _user_context_processor():
|
||||
return dict(current_user=_get_user())
|
||||
|
||||
|
||||
def _secret_key(key=None):
|
||||
if key is None:
|
||||
key = current_app.config["SECRET_KEY"]
|
||||
|
||||
if isinstance(key, str): # pragma: no cover
|
||||
key = key.encode("latin1") # ensure bytes
|
||||
|
||||
return key
|
||||
@@ -20,15 +20,17 @@
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import quote
|
||||
import unidecode
|
||||
# from weakref import WeakSet
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlite3 import OperationalError as sqliteOperationalError
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy import Table, Column, ForeignKey, CheckConstraint
|
||||
from sqlalchemy import String, Integer, Boolean, TIMESTAMP, Float
|
||||
from sqlalchemy.orm import relationship, sessionmaker, scoped_session
|
||||
from sqlalchemy.orm import relationship, sessionmaker, scoped_session, selectinload
|
||||
from sqlalchemy.orm.collections import InstrumentedList
|
||||
from sqlalchemy.ext.declarative import DeclarativeMeta
|
||||
from sqlalchemy.exc import OperationalError
|
||||
@@ -40,16 +42,14 @@ except ImportError:
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from sqlalchemy.sql.expression import and_, true, false, text, func, or_
|
||||
from sqlalchemy.ext.associationproxy import association_proxy
|
||||
from flask_login import current_user
|
||||
from .cw_login import current_user
|
||||
from flask_babel import gettext as _
|
||||
from flask_babel import get_locale
|
||||
from flask import flash
|
||||
from flask import flash, g, Flask
|
||||
|
||||
from . import logger, ub, isoLanguages
|
||||
from .pagination import Pagination
|
||||
|
||||
from weakref import WeakSet
|
||||
|
||||
from .string_helper import strip_whitespaces
|
||||
|
||||
log = logger.create()
|
||||
|
||||
@@ -102,6 +102,16 @@ class Identifiers(Base):
|
||||
type = Column(String(collation='NOCASE'), nullable=False, default="isbn")
|
||||
val = Column(String(collation='NOCASE'), nullable=False)
|
||||
book = Column(Integer, ForeignKey('books.id'), nullable=False)
|
||||
amazon = {
|
||||
"jp": "co.jp",
|
||||
"uk": "co.uk",
|
||||
"us": "com",
|
||||
"au": "com.au",
|
||||
"be": "com.be",
|
||||
"br": "com.br",
|
||||
"tr": "com.tr",
|
||||
"mx": "com.mx",
|
||||
}
|
||||
|
||||
def __init__(self, val, id_type, book):
|
||||
super().__init__()
|
||||
@@ -114,7 +124,11 @@ class Identifiers(Base):
|
||||
if format_type == 'amazon':
|
||||
return "Amazon"
|
||||
elif format_type.startswith("amazon_"):
|
||||
return "Amazon.{0}".format(format_type[7:])
|
||||
label_amazon = "Amazon.{0}"
|
||||
country_code = format_type[7:].lower()
|
||||
if country_code not in self.amazon:
|
||||
return label_amazon.format(country_code)
|
||||
return label_amazon.format(self.amazon[country_code])
|
||||
elif format_type == "isbn":
|
||||
return "ISBN"
|
||||
elif format_type == "doi":
|
||||
@@ -137,6 +151,12 @@ class Identifiers(Base):
|
||||
return "ISSN"
|
||||
elif format_type == "isfdb":
|
||||
return "ISFDB"
|
||||
elif format_type == "storygraph":
|
||||
return "StoryGraph"
|
||||
elif format_type == "ebooks":
|
||||
return "eBooks.com"
|
||||
elif format_type == "smashwords":
|
||||
return "Smashwords"
|
||||
if format_type == "lubimyczytac":
|
||||
return "Lubimyczytac"
|
||||
if format_type == "databazeknih":
|
||||
@@ -149,7 +169,11 @@ class Identifiers(Base):
|
||||
if format_type == "amazon" or format_type == "asin":
|
||||
return "https://amazon.com/dp/{0}".format(self.val)
|
||||
elif format_type.startswith('amazon_'):
|
||||
return "https://amazon.{0}/dp/{1}".format(format_type[7:], self.val)
|
||||
link_amazon = "https://amazon.{0}/dp/{1}"
|
||||
country_code = format_type[7:].lower()
|
||||
if country_code not in self.amazon:
|
||||
return link_amazon.format(country_code, self.val)
|
||||
return link_amazon.format(self.amazon[country_code], self.val)
|
||||
elif format_type == "isbn":
|
||||
return "https://www.worldcat.org/isbn/{0}".format(self.val)
|
||||
elif format_type == "doi":
|
||||
@@ -173,9 +197,15 @@ class Identifiers(Base):
|
||||
elif format_type == "issn":
|
||||
return "https://portal.issn.org/resource/ISSN/{0}".format(self.val)
|
||||
elif format_type == "isfdb":
|
||||
return "http://www.isfdb.org/cgi-bin/pl.cgi?{0}".format(self.val)
|
||||
return "https://www.isfdb.org/cgi-bin/pl.cgi?{0}".format(self.val)
|
||||
elif format_type == "databazeknih":
|
||||
return "https://www.databazeknih.cz/knihy/{0}".format(self.val)
|
||||
elif format_type == "storygraph":
|
||||
return "https://app.thestorygraph.com/books/{0}".format(self.val)
|
||||
elif format_type == "ebooks":
|
||||
return "https://www.ebooks.com/en-us/book/{0}".format(self.val)
|
||||
elif format_type == "smashwords":
|
||||
return "https://www.smashwords.com/books/view/{0}".format(self.val)
|
||||
elif self.val.lower().startswith("javascript:"):
|
||||
return quote(self.val)
|
||||
elif self.val.lower().startswith("data:"):
|
||||
@@ -379,15 +409,15 @@ class Books(Base):
|
||||
title = Column(String(collation='NOCASE'), nullable=False, default='Unknown')
|
||||
sort = Column(String(collation='NOCASE'))
|
||||
author_sort = Column(String(collation='NOCASE'))
|
||||
timestamp = Column(TIMESTAMP, default=datetime.utcnow)
|
||||
timestamp = Column(TIMESTAMP, default=lambda: datetime.now(timezone.utc))
|
||||
pubdate = Column(TIMESTAMP, default=DEFAULT_PUBDATE)
|
||||
series_index = Column(String, nullable=False, default="1.0")
|
||||
last_modified = Column(TIMESTAMP, default=datetime.utcnow)
|
||||
last_modified = Column(TIMESTAMP, default=lambda: datetime.now(timezone.utc))
|
||||
path = Column(String, default="", nullable=False)
|
||||
has_cover = Column(Integer, default=0)
|
||||
uuid = Column(String)
|
||||
isbn = Column(String(collation='NOCASE'), default="")
|
||||
flags = Column(Integer, nullable=False, default=1)
|
||||
# isbn = Column(String(collation='NOCASE'), default="")
|
||||
# flags = Column(Integer, nullable=False, default=1)
|
||||
|
||||
authors = relationship(Authors, secondary=books_authors_link, backref='books')
|
||||
tags = relationship(Tags, secondary=books_tags_link, backref='books', order_by="Tags.name")
|
||||
@@ -419,7 +449,14 @@ class Books(Base):
|
||||
|
||||
@property
|
||||
def atom_timestamp(self):
|
||||
return self.timestamp.strftime('%Y-%m-%dT%H:%M:%S+00:00') or ''
|
||||
# OPDS atom:updated is defined as "the most recent instant in time
|
||||
# when the entry was modified". Books.timestamp is the date added and
|
||||
# never changes after import, so metadata and cover edits were
|
||||
# invisible to OPDS sync clients. Use last_modified, which Calibre
|
||||
# updates on every metadata or cover change; fall back to timestamp
|
||||
# only if last_modified happens to be missing.
|
||||
t = self.last_modified or self.timestamp
|
||||
return t.strftime('%Y-%m-%dT%H:%M:%S+00:00') if t else ''
|
||||
|
||||
|
||||
class CustomColumns(Base):
|
||||
@@ -510,34 +547,25 @@ class AlchemyEncoder(json.JSONEncoder):
|
||||
|
||||
|
||||
class CalibreDB:
|
||||
_init = False
|
||||
engine = None
|
||||
config = None
|
||||
session_factory = None
|
||||
# This is a WeakSet so that references here don't keep other CalibreDB
|
||||
# instances alive once they reach the end of their respective scopes
|
||||
instances = WeakSet()
|
||||
config_calibre_dir = None
|
||||
app_db_path = None
|
||||
|
||||
def __init__(self, expire_on_commit=True, init=False):
|
||||
def __init__(self, _app: Flask=None): # , expire_on_commit=True, init=False):
|
||||
""" Initialize a new CalibreDB session
|
||||
"""
|
||||
self.session = None
|
||||
if init:
|
||||
self.init_db(expire_on_commit)
|
||||
self.Session = None
|
||||
#if init:
|
||||
# self.init_db(expire_on_commit)
|
||||
if _app is not None and not _app._got_first_request:
|
||||
self.init_app(_app)
|
||||
|
||||
def init_db(self, expire_on_commit=True):
|
||||
if self._init:
|
||||
self.init_session(expire_on_commit)
|
||||
|
||||
self.instances.add(self)
|
||||
|
||||
def init_session(self, expire_on_commit=True):
|
||||
self.session = self.session_factory()
|
||||
self.session.expire_on_commit = expire_on_commit
|
||||
self.update_title_sort(self.config)
|
||||
def init_app(self, _app):
|
||||
_app.teardown_appcontext(self.teardown)
|
||||
|
||||
@classmethod
|
||||
def setup_db_cc_classes(cls, cc):
|
||||
global cc_classes
|
||||
cc_ids = []
|
||||
books_custom_column_links = {}
|
||||
for row in cc:
|
||||
@@ -605,8 +633,6 @@ class CalibreDB:
|
||||
secondary=books_custom_column_links[cc_id[0]],
|
||||
backref='books'))
|
||||
|
||||
return cc_classes
|
||||
|
||||
@classmethod
|
||||
def check_valid_db(cls, config_calibre_dir, app_db_path, config_calibre_uuid):
|
||||
if not config_calibre_dir:
|
||||
@@ -621,12 +647,11 @@ class CalibreDB:
|
||||
connect_args={'check_same_thread': False},
|
||||
poolclass=StaticPool)
|
||||
with check_engine.begin() as connection:
|
||||
connection.execute(text("attach database '{}' as calibre;".format(dbpath)))
|
||||
connection.execute(text("attach database '{}' as app_settings;".format(app_db_path)))
|
||||
connection.execute(text("attach database '{}' as calibre;".format(dbpath.replace("'", "''"))))
|
||||
connection.execute(text("attach database '{}' as app_settings;".format(app_db_path.replace("'", "''"))))
|
||||
local_session = scoped_session(sessionmaker())
|
||||
local_session.configure(bind=connection)
|
||||
database_uuid = local_session().query(Library_Id).one_or_none()
|
||||
# local_session.dispose()
|
||||
|
||||
check_engine.connect()
|
||||
db_change = config_calibre_uuid != database_uuid.uuid
|
||||
@@ -634,13 +659,30 @@ class CalibreDB:
|
||||
return False, False
|
||||
return True, db_change
|
||||
|
||||
def teardown(self, exception):
|
||||
ctx = g.get("lib_sql")
|
||||
if ctx:
|
||||
ctx.close()
|
||||
|
||||
@property
|
||||
def session(self):
|
||||
# connect or get active connection
|
||||
if not g.get("lib_sql"):
|
||||
g.lib_sql = self.connect()
|
||||
return g.lib_sql
|
||||
|
||||
@classmethod
|
||||
def update_config(cls, config):
|
||||
def update_config(cls, config, config_calibre_dir, app_db_path):
|
||||
cls.config = config
|
||||
cls.config_calibre_dir = config_calibre_dir
|
||||
cls.app_db_path = app_db_path
|
||||
|
||||
|
||||
def connect(self):
|
||||
return self.setup_db(self.config_calibre_dir, self.app_db_path)
|
||||
|
||||
@classmethod
|
||||
def setup_db(cls, config_calibre_dir, app_db_path):
|
||||
cls.dispose()
|
||||
|
||||
if not config_calibre_dir:
|
||||
cls.config.invalidate()
|
||||
@@ -652,16 +694,17 @@ class CalibreDB:
|
||||
return None
|
||||
|
||||
try:
|
||||
cls.engine = create_engine('sqlite://',
|
||||
engine = create_engine('sqlite://',
|
||||
echo=False,
|
||||
isolation_level="SERIALIZABLE",
|
||||
connect_args={'check_same_thread': False},
|
||||
poolclass=StaticPool)
|
||||
with cls.engine.begin() as connection:
|
||||
connection.execute(text("attach database '{}' as calibre;".format(dbpath)))
|
||||
connection.execute(text("attach database '{}' as app_settings;".format(app_db_path)))
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text('PRAGMA cache_size = 10000;'))
|
||||
connection.execute(text("attach database '{}' as calibre;".format(dbpath.replace("'", "''"))))
|
||||
connection.execute(text("attach database '{}' as app_settings;".format(app_db_path.replace("'", "''"))))
|
||||
|
||||
conn = cls.engine.connect()
|
||||
conn = engine.connect()
|
||||
# conn.text_factory = lambda b: b.decode(errors = 'ignore') possible fix for #1302
|
||||
except Exception as ex:
|
||||
cls.config.invalidate(ex)
|
||||
@@ -677,13 +720,10 @@ class CalibreDB:
|
||||
log.error_or_exception(e)
|
||||
return None
|
||||
|
||||
cls.session_factory = scoped_session(sessionmaker(autocommit=False,
|
||||
autoflush=True,
|
||||
bind=cls.engine, future=True))
|
||||
for inst in cls.instances:
|
||||
inst.init_session()
|
||||
return scoped_session(sessionmaker(autocommit=False,
|
||||
autoflush=False,
|
||||
bind=engine, future=True))
|
||||
|
||||
cls._init = True
|
||||
|
||||
def get_book(self, book_id):
|
||||
return self.session.query(Books).filter(Books.id == book_id).first()
|
||||
@@ -713,7 +753,8 @@ class CalibreDB:
|
||||
.filter(self.common_filters(allow_show_archived)).first())
|
||||
|
||||
def get_book_by_uuid(self, book_uuid):
|
||||
return self.session.query(Books).filter(Books.uuid == book_uuid).first()
|
||||
return self.session.query(Books).filter(Books.uuid == book_uuid). \
|
||||
filter(self.common_filters()).first()
|
||||
|
||||
def get_book_format(self, book_id, file_format):
|
||||
return self.session.query(Data).filter(Data.book == book_id).filter(Data.format == file_format).first()
|
||||
@@ -868,27 +909,36 @@ class CalibreDB:
|
||||
for entry in entries:
|
||||
if combined:
|
||||
sort_authors = entry.Books.author_sort.split('&')
|
||||
ids = [a.id for a in entry.Books.authors]
|
||||
|
||||
authors_list = entry.Books.authors
|
||||
else:
|
||||
sort_authors = entry.author_sort.split('&')
|
||||
ids = [a.id for a in entry.authors]
|
||||
authors_ordered = list()
|
||||
# error = False
|
||||
authors_list = entry.authors
|
||||
|
||||
# Create dictionary for O(1) lookup instead of nested loops
|
||||
authors_by_sort = {}
|
||||
authors_by_id = {}
|
||||
for author in authors_list:
|
||||
authors_by_sort[author.sort] = author
|
||||
authors_by_id[author.id] = author
|
||||
|
||||
authors_ordered = []
|
||||
ids_remaining = set(authors_by_id.keys())
|
||||
|
||||
# Order authors based on sort field using dictionary lookup
|
||||
for auth in sort_authors:
|
||||
results = self.session.query(Authors).filter(Authors.sort == auth.lstrip().strip()).all()
|
||||
# ToDo: How to handle not found author name
|
||||
if not len(results):
|
||||
log.error("Author {} not found to display name in right order".format(auth.strip()))
|
||||
# error = True
|
||||
break
|
||||
for r in results:
|
||||
if r.id in ids:
|
||||
authors_ordered.append(r)
|
||||
ids.remove(r.id)
|
||||
for author_id in ids:
|
||||
result = self.session.query(Authors).filter(Authors.id == author_id).first()
|
||||
authors_ordered.append(result)
|
||||
auth = strip_whitespaces(auth)
|
||||
if auth in authors_by_sort:
|
||||
author = authors_by_sort[auth]
|
||||
authors_ordered.append(author)
|
||||
ids_remaining.discard(author.id)
|
||||
else:
|
||||
# This can happen if author_sort has stale data or formatting issues
|
||||
book_id = entry.id if isinstance(entry, Books) else (entry.Books.id if combined else entry.id)
|
||||
log.warning("Author '{}' of book {} not found in author list, skipping in sort order".format(auth, book_id))
|
||||
|
||||
# Add any remaining authors not in sort order
|
||||
for author_id in ids_remaining:
|
||||
authors_ordered.append(authors_by_id[author_id])
|
||||
|
||||
if list_return:
|
||||
if combined:
|
||||
@@ -901,15 +951,14 @@ class CalibreDB:
|
||||
|
||||
def get_typeahead(self, database, query, replace=('', ''), tag_filter=true()):
|
||||
query = query or ''
|
||||
self.session.connection().connection.connection.create_function("lower", 1, lcase)
|
||||
self.create_functions()
|
||||
entries = self.session.query(database).filter(tag_filter). \
|
||||
filter(func.lower(database.name).ilike("%" + query + "%")).all()
|
||||
# json_dumps = json.dumps([dict(name=escape(r.name.replace(*replace))) for r in entries])
|
||||
json_dumps = json.dumps([dict(name=r.name.replace(*replace)) for r in entries])
|
||||
return json_dumps
|
||||
|
||||
def check_exists_book(self, authr, title):
|
||||
self.session.connection().connection.connection.create_function("lower", 1, lcase)
|
||||
self.create_functions()
|
||||
q = list()
|
||||
author_terms = re.split(r'\s*&\s*', authr)
|
||||
for author_term in author_terms:
|
||||
@@ -919,35 +968,93 @@ class CalibreDB:
|
||||
.filter(and_(Books.authors.any(and_(*q)), func.lower(Books.title).ilike("%" + title + "%"))).first()
|
||||
|
||||
def search_query(self, term, config, *join):
|
||||
term.strip().lower()
|
||||
self.session.connection().connection.connection.create_function("lower", 1, lcase)
|
||||
q = list()
|
||||
author_terms = re.split("[, ]+", term)
|
||||
for author_term in author_terms:
|
||||
q.append(Books.authors.any(func.lower(Authors.name).ilike("%" + author_term + "%")))
|
||||
query = self.generate_linked_query(config.config_read_column, Books)
|
||||
if len(join) == 6:
|
||||
query = query.outerjoin(join[0], join[1]).outerjoin(join[2]).outerjoin(join[3], join[4]).outerjoin(join[5])
|
||||
if len(join) == 3:
|
||||
query = query.outerjoin(join[0], join[1]).outerjoin(join[2])
|
||||
elif len(join) == 2:
|
||||
query = query.outerjoin(join[0], join[1])
|
||||
elif len(join) == 1:
|
||||
query = query.outerjoin(join[0])
|
||||
term = strip_whitespaces(term).lower()
|
||||
self.create_functions()
|
||||
|
||||
# Try FTS5 search first for better performance
|
||||
fts_ids = None
|
||||
# Check if FTS5 table exists before attempting search
|
||||
if not hasattr(self, '_fts_available'):
|
||||
try:
|
||||
result = self.session.execute(
|
||||
text("SELECT name FROM sqlite_master WHERE type='table' AND name='books_fts'")
|
||||
).fetchone()
|
||||
self._fts_available = result is not None
|
||||
except Exception:
|
||||
self._fts_available = False
|
||||
|
||||
if self._fts_available:
|
||||
try:
|
||||
# Escape FTS5 special characters to prevent query errors
|
||||
term_fts = term.replace('"', '""')
|
||||
# Wrap in quotes for phrase matching and better accuracy
|
||||
fts_results = self.session.execute(
|
||||
text("SELECT DISTINCT rowid FROM books_fts WHERE books_fts MATCH :term"),
|
||||
{"term": f'"{term_fts}"'}
|
||||
).fetchall()
|
||||
if fts_results:
|
||||
fts_ids = [r[0] for r in fts_results]
|
||||
except Exception as ex:
|
||||
# FTS5 query failed, fall back to traditional search
|
||||
log.debug("FTS5 search failed for term '{}', using fallback: {}".format(term, ex))
|
||||
|
||||
# Build base query with optimized joins
|
||||
base_query = self.generate_linked_query(config.config_read_column, Books)
|
||||
base_query = base_query.filter(self.common_filters(True))
|
||||
|
||||
# Apply eager loading for authors to avoid N+1 queries
|
||||
base_query = base_query.options(selectinload(Books.authors))
|
||||
|
||||
if len(join) == 6:
|
||||
base_query = base_query.outerjoin(join[0], join[1]).outerjoin(join[2]).outerjoin(join[3], join[4]).outerjoin(join[5])
|
||||
if len(join) == 3:
|
||||
base_query = base_query.outerjoin(join[0], join[1]).outerjoin(join[2])
|
||||
elif len(join) == 2:
|
||||
base_query = base_query.outerjoin(join[0], join[1])
|
||||
elif len(join) == 1:
|
||||
base_query = base_query.outerjoin(join[0])
|
||||
|
||||
# If FTS5 found results, use those IDs
|
||||
if fts_ids:
|
||||
return base_query.filter(Books.id.in_(fts_ids))
|
||||
|
||||
# Fallback to traditional search with optimized subqueries
|
||||
author_terms = re.split("[, ]+", term)
|
||||
|
||||
# Use subquery for authors to avoid expensive .any() with OR
|
||||
author_subquery = self.session.query(books_authors_link.c.book).join(
|
||||
Authors, books_authors_link.c.author == Authors.id
|
||||
)
|
||||
author_filters = []
|
||||
for author_term in author_terms:
|
||||
author_filters.append(func.lower(Authors.name).ilike("%" + author_term + "%"))
|
||||
if author_filters:
|
||||
author_subquery = author_subquery.filter(and_(*author_filters))
|
||||
|
||||
# Build optimized filter expressions
|
||||
cc = self.get_cc_columns(config, filter_config_custom_read=True)
|
||||
filter_expression = [Books.tags.any(func.lower(Tags.name).ilike("%" + term + "%")),
|
||||
Books.series.any(func.lower(Series.name).ilike("%" + term + "%")),
|
||||
Books.authors.any(and_(*q)),
|
||||
Books.publishers.any(func.lower(Publishers.name).ilike("%" + term + "%")),
|
||||
func.lower(Books.title).ilike("%" + term + "%")]
|
||||
filter_expression = [
|
||||
Books.id.in_(self.session.query(books_tags_link.c.book).join(
|
||||
Tags, books_tags_link.c.tag == Tags.id
|
||||
).filter(func.lower(Tags.name).ilike("%" + term + "%"))),
|
||||
Books.id.in_(self.session.query(books_series_link.c.book).join(
|
||||
Series, books_series_link.c.series == Series.id
|
||||
).filter(func.lower(Series.name).ilike("%" + term + "%"))),
|
||||
Books.id.in_(author_subquery),
|
||||
Books.id.in_(self.session.query(books_publishers_link.c.book).join(
|
||||
Publishers, books_publishers_link.c.publisher == Publishers.id
|
||||
).filter(func.lower(Publishers.name).ilike("%" + term + "%"))),
|
||||
func.lower(Books.title).ilike("%" + term + "%")
|
||||
]
|
||||
|
||||
for c in cc:
|
||||
if c.datatype not in ["datetime", "rating", "bool", "int", "float"]:
|
||||
filter_expression.append(
|
||||
getattr(Books,
|
||||
'custom_column_' + str(c.id)).any(
|
||||
func.lower(cc_classes[c.id].value).ilike("%" + term + "%")))
|
||||
return query.filter(self.common_filters(True)).filter(or_(*filter_expression))
|
||||
|
||||
return base_query.filter(or_(*filter_expression))
|
||||
|
||||
def get_cc_columns(self, config, filter_config_custom_read=False):
|
||||
tmp_cc = self.session.query(CustomColumns).filter(CustomColumns.datatype.notin_(cc_exceptions)).all()
|
||||
@@ -969,18 +1076,32 @@ class CalibreDB:
|
||||
def get_search_results(self, term, config, offset=None, order=None, limit=None, *join):
|
||||
order = order[0] if order else [Books.sort]
|
||||
pagination = None
|
||||
result = self.search_query(term, config, *join).order_by(*order).all()
|
||||
result_count = len(result)
|
||||
|
||||
if offset is not None and limit is not None:
|
||||
offset = int(offset)
|
||||
limit_all = offset + int(limit)
|
||||
pagination = Pagination((offset / (int(limit)) + 1), limit, result_count)
|
||||
limit_int = int(limit)
|
||||
|
||||
# Use LIMIT+1 pattern to estimate total count without expensive count()
|
||||
query = self.search_query(term, config, *join).order_by(*order)
|
||||
result = query.limit(offset + limit_int + 1).all()
|
||||
|
||||
# Check if there are more results
|
||||
has_more = len(result) > (offset + limit_int)
|
||||
if has_more:
|
||||
result_count = offset + limit_int + 1 # Estimate: at least this many
|
||||
else:
|
||||
result_count = len(result)
|
||||
|
||||
# Extract the page of results
|
||||
result = result[offset:offset + limit_int]
|
||||
pagination = Pagination((offset / limit_int + 1), limit_int, result_count)
|
||||
else:
|
||||
offset = 0
|
||||
limit_all = result_count
|
||||
# No pagination, fetch all results
|
||||
result = self.search_query(term, config, *join).order_by(*order).all()
|
||||
result_count = len(result)
|
||||
|
||||
ub.store_combo_ids(result)
|
||||
entries = self.order_authors(result[offset:limit_all], list_return=True, combined=True)
|
||||
entries = self.order_authors(result, list_return=True, combined=True)
|
||||
|
||||
return entries, result_count, pagination
|
||||
|
||||
@@ -1005,7 +1126,7 @@ class CalibreDB:
|
||||
.filter(self.common_filters())
|
||||
.count())
|
||||
if no_lang_count:
|
||||
tags.append([Category(_("None"), "none"), no_lang_count])
|
||||
tags.append([Category(_("None"), "None", "none"), no_lang_count])
|
||||
return sorted(tags, key=lambda x: x[0].name.lower(), reverse=reverse_order)
|
||||
else:
|
||||
if not languages:
|
||||
@@ -1018,7 +1139,7 @@ class CalibreDB:
|
||||
lang.name = isoLanguages.get_language_name(get_locale(), lang.lang_code)
|
||||
return sorted(languages, key=lambda x: x.name, reverse=reverse_order)
|
||||
|
||||
def update_title_sort(self, config, conn=None):
|
||||
def create_functions(self, config=None):
|
||||
# user defined sort function for calibre databases (Series, etc.)
|
||||
def _title_sort(title):
|
||||
# calibre sort stuff
|
||||
@@ -1027,56 +1148,27 @@ class CalibreDB:
|
||||
if match:
|
||||
prep = match.group(1)
|
||||
title = title[len(prep):] + ', ' + prep
|
||||
return title.strip()
|
||||
return strip_whitespaces(title)
|
||||
|
||||
try:
|
||||
# sqlalchemy <1.4.24
|
||||
conn = conn or self.session.connection().connection.driver_connection
|
||||
# sqlalchemy <1.4.24 and sqlalchemy 2.0
|
||||
conn = self.session.connection().connection.driver_connection
|
||||
except AttributeError:
|
||||
# sqlalchemy >1.4.24 and sqlalchemy 2.0
|
||||
conn = conn or self.session.connection().connection.connection
|
||||
# sqlalchemy >1.4.24
|
||||
conn = self.session.connection().connection.connection
|
||||
try:
|
||||
conn.create_function("title_sort", 1, _title_sort)
|
||||
if config:
|
||||
conn.create_function("title_sort", 1, _title_sort)
|
||||
conn.create_function('uuid4', 0, lambda: str(uuid4()))
|
||||
conn.create_function("lower", 1, lcase)
|
||||
except sqliteOperationalError:
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def dispose(cls):
|
||||
# global session
|
||||
|
||||
for inst in cls.instances:
|
||||
old_session = inst.session
|
||||
inst.session = None
|
||||
if old_session:
|
||||
try:
|
||||
old_session.close()
|
||||
except Exception:
|
||||
pass
|
||||
if old_session.bind:
|
||||
try:
|
||||
old_session.bind.dispose()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
for attr in list(Books.__dict__.keys()):
|
||||
if attr.startswith("custom_column_"):
|
||||
setattr(Books, attr, None)
|
||||
|
||||
for db_class in cc_classes.values():
|
||||
Base.metadata.remove(db_class.__table__)
|
||||
cc_classes.clear()
|
||||
|
||||
for table in reversed(Base.metadata.sorted_tables):
|
||||
name = table.key
|
||||
if name.startswith("custom_column_") or name.startswith("books_custom_column_"):
|
||||
if table is not None:
|
||||
Base.metadata.remove(table)
|
||||
|
||||
def reconnect_db(self, config, app_db_path):
|
||||
self.dispose()
|
||||
self.engine.dispose()
|
||||
# self.dispose()
|
||||
# self.engine.dispose()
|
||||
self.setup_db(config.config_calibre_dir, app_db_path)
|
||||
self.update_config(config)
|
||||
self.update_config(config, config.config_calibre_dir, app_db_path)
|
||||
|
||||
|
||||
def lcase(s):
|
||||
@@ -1088,14 +1180,25 @@ def lcase(s):
|
||||
return s.lower()
|
||||
|
||||
|
||||
def title_sort(title, config):
|
||||
# calibre sort stuff
|
||||
title_pat = re.compile(config.config_title_regex, re.IGNORECASE)
|
||||
match = title_pat.search(title)
|
||||
if match:
|
||||
prep = match.group(1)
|
||||
title = title[len(prep):] + ', ' + prep
|
||||
return strip_whitespaces(title)
|
||||
|
||||
class Category:
|
||||
name = None
|
||||
sort = None
|
||||
id = None
|
||||
count = None
|
||||
rating = None
|
||||
|
||||
def __init__(self, name, cat_id, rating=None):
|
||||
self.name = name
|
||||
self.sort = name
|
||||
self.id = cat_id
|
||||
self.rating = rating
|
||||
self.count = 1
|
||||
|
||||
+6
-4
@@ -23,10 +23,10 @@ import zipfile
|
||||
import json
|
||||
from io import BytesIO
|
||||
from flask_babel.speaklater import LazyString
|
||||
|
||||
from importlib.metadata import metadata
|
||||
import os
|
||||
|
||||
from flask import send_file, __version__
|
||||
from flask import send_file
|
||||
|
||||
from . import logger, config
|
||||
from .about import collect_stats
|
||||
@@ -49,7 +49,8 @@ def assemble_logfiles(file_name):
|
||||
with open(f, 'rb') as fd:
|
||||
shutil.copyfileobj(fd, wfd)
|
||||
wfd.seek(0)
|
||||
if int(__version__.split('.')[0]) < 2:
|
||||
version = metadata("flask")["Version"]
|
||||
if int(version.split('.')[0]) < 2:
|
||||
return send_file(wfd,
|
||||
as_attachment=True,
|
||||
attachment_filename=os.path.basename(file_name))
|
||||
@@ -72,7 +73,8 @@ def send_debug():
|
||||
for fp in file_list:
|
||||
zf.write(fp, os.path.basename(fp))
|
||||
memory_zip.seek(0)
|
||||
if int(__version__.split('.')[0]) < 2:
|
||||
version = metadata("flask")["Version"]
|
||||
if int(version.split('.')[0]) < 2:
|
||||
return send_file(memory_zip,
|
||||
as_attachment=True,
|
||||
attachment_filename="Calibre-Web-debug-pack.zip")
|
||||
|
||||
+18
-2
@@ -39,8 +39,24 @@ def load_dependencies(optional=False):
|
||||
with open(req_path, 'r') as f:
|
||||
for line in f:
|
||||
if not line.startswith('#') and not line == '\n' and not line.startswith('git'):
|
||||
res = re.match(r'(.*?)([<=>\s]+)([\d\.]+),?\s?([<=>\s]+)?([\d\.]+)?', line.strip())
|
||||
res = re.match(r'(.*?)([<=>\s]+)([\d\.]+),?\s?([<=>\s]+)?([\d\.]+)?(?:\s?;\s?'
|
||||
r'(?:(python_version)\s?([<=>]+)\s?\'([\d\.]+)\'|'
|
||||
r'(sys_platform)\s?([\!=]+)\s?\'([\w]+)\'))?', line.strip())
|
||||
try:
|
||||
if res.group(7) and res.group(8):
|
||||
val = res.group(8).split(".")
|
||||
if not eval(str(sys.version_info[0]) + "." + "{:02d}".format(sys.version_info[1]) +
|
||||
res.group(7) + val[0] + "." + "{:02d}".format(int(val[1]))):
|
||||
continue
|
||||
elif res.group(10) and res.group(11):
|
||||
# only installed if platform is eqal, don't check if platform is not equal
|
||||
if res.group(10) == "==":
|
||||
if sys.platform != res.group(11):
|
||||
continue
|
||||
# installed if platform is not eqal, don't check if platform is equal
|
||||
elif res.group(10) == "!=":
|
||||
if sys.platform == res.group(11):
|
||||
continue
|
||||
if getattr(sys, 'frozen', False):
|
||||
dep_version = exe_deps[res.group(1).lower().replace('_', '-')]
|
||||
else:
|
||||
@@ -63,7 +79,7 @@ def dependency_check(optional=False):
|
||||
deps = load_dependencies(optional)
|
||||
for dep in deps:
|
||||
try:
|
||||
dep_version_int = [int(x) if x.isnumeric() else 0 for x in dep[0].split('.')]
|
||||
dep_version_int = [int(x) if x.isnumeric() else 0 for x in dep[0].split('.')[:3]]
|
||||
low_check = [int(x) for x in dep[3].split('.')]
|
||||
high_check = [int(x) for x in dep[5].split('.')]
|
||||
except AttributeError:
|
||||
|
||||
+726
-492
File diff suppressed because it is too large
Load Diff
+4
-5
@@ -28,17 +28,16 @@ log = logger.create()
|
||||
|
||||
def do_calibre_export(book_id, book_format):
|
||||
try:
|
||||
quotes = [3, 5, 7, 9]
|
||||
quotes = [4, 6]
|
||||
tmp_dir = get_temp_dir()
|
||||
calibredb_binarypath = get_calibre_binarypath("calibredb")
|
||||
temp_file_name = str(uuid4())
|
||||
my_env = os.environ.copy()
|
||||
if config.config_calibre_split:
|
||||
my_env['CALIBRE_OVERRIDE_DATABASE_PATH'] = os.path.join(config.config_calibre_dir, "metadata.db")
|
||||
library_path = config.config_calibre_split_dir
|
||||
else:
|
||||
library_path = config.config_calibre_dir
|
||||
opf_command = [calibredb_binarypath, 'export', '--dont-write-opf', '--with-library', library_path,
|
||||
library_path = config.get_book_path()
|
||||
opf_command = [calibredb_binarypath, 'export', '--dont-write-opf', '--dont-save-cover',
|
||||
'--with-library', library_path,
|
||||
'--to-dir', tmp_dir, '--formats', book_format, "--template", "{}".format(temp_file_name),
|
||||
str(book_id)]
|
||||
p = process_open(opf_command, quotes, my_env)
|
||||
|
||||
+9
-5
@@ -25,6 +25,7 @@ from . import config, logger
|
||||
from .helper import split_authors
|
||||
from .epub_helper import get_content_opf, default_ns
|
||||
from .constants import BookMeta
|
||||
from .string_helper import strip_whitespaces
|
||||
|
||||
log = logger.create()
|
||||
|
||||
@@ -55,7 +56,7 @@ def get_epub_layout(book, book_data):
|
||||
p = tree.xpath('/pkg:package/pkg:metadata', namespaces=default_ns)[0]
|
||||
|
||||
layout = p.xpath('pkg:meta[@property="rendition:layout"]/text()', namespaces=default_ns)
|
||||
except (etree.XMLSyntaxError, KeyError, IndexError, OSError) as e:
|
||||
except (etree.XMLSyntaxError, KeyError, IndexError, OSError, UnicodeDecodeError) as e:
|
||||
log.error("Could not parse epub metadata of book {} during kobo sync: {}".format(book.id, e))
|
||||
layout = []
|
||||
|
||||
@@ -65,7 +66,7 @@ def get_epub_layout(book, book_data):
|
||||
return layout[0]
|
||||
|
||||
|
||||
def get_epub_info(tmp_file_path, original_file_name, original_file_extension):
|
||||
def get_epub_info(tmp_file_path, original_file_name, original_file_extension, no_cover_processing):
|
||||
ns = {
|
||||
'n': 'urn:oasis:names:tc:opendocument:xmlns:container',
|
||||
'pkg': 'http://www.idpf.org/2007/opf',
|
||||
@@ -90,7 +91,7 @@ def get_epub_info(tmp_file_path, original_file_name, original_file_extension):
|
||||
elif s == 'date':
|
||||
epub_metadata[s] = tmp[0][:10]
|
||||
else:
|
||||
epub_metadata[s] = tmp[0].strip()
|
||||
epub_metadata[s] = strip_whitespaces(tmp[0])
|
||||
else:
|
||||
epub_metadata[s] = 'Unknown'
|
||||
|
||||
@@ -116,7 +117,10 @@ def get_epub_info(tmp_file_path, original_file_name, original_file_extension):
|
||||
epub_metadata = parse_epub_series(ns, tree, epub_metadata)
|
||||
|
||||
epub_zip = zipfile.ZipFile(tmp_file_path)
|
||||
cover_file = parse_epub_cover(ns, tree, epub_zip, cover_path, tmp_file_path)
|
||||
if not no_cover_processing:
|
||||
cover_file = parse_epub_cover(ns, tree, epub_zip, cover_path, tmp_file_path)
|
||||
else:
|
||||
cover_file = None
|
||||
|
||||
identifiers = []
|
||||
for node in p.xpath('dc:identifier', namespaces=ns):
|
||||
@@ -171,7 +175,7 @@ def parse_epub_cover(ns, tree, epub_zip, cover_path, tmp_file_path):
|
||||
for cs in cover_section:
|
||||
if cs.endswith('.xhtml') or cs.endswith('.html'):
|
||||
markup = epub_zip.read(os.path.join(cover_path, cs))
|
||||
markup_tree = etree.fromstring(markup)
|
||||
markup_tree = etree.fromstring(markup, parser=etree.XMLParser(resolve_entities=False, no_network=True))
|
||||
# no matter xhtml or html with no namespace
|
||||
img_src = markup_tree.xpath("//*[local-name() = 'img']/@src")
|
||||
# Alternative image source
|
||||
|
||||
+6
-2
@@ -53,16 +53,20 @@ def updateEpub(src, dest, filename, data, ):
|
||||
zf.writestr(filename, data)
|
||||
|
||||
|
||||
# Safe parser: disable entity resolution and network access to prevent XXE attacks
|
||||
_safe_parser = etree.XMLParser(resolve_entities=False, no_network=True)
|
||||
|
||||
|
||||
def get_content_opf(file_path, ns=None):
|
||||
if ns is None:
|
||||
ns = default_ns
|
||||
epubZip = zipfile.ZipFile(file_path)
|
||||
txt = epubZip.read('META-INF/container.xml')
|
||||
tree = etree.fromstring(txt)
|
||||
tree = etree.fromstring(txt, parser=_safe_parser)
|
||||
cf_name = tree.xpath('n:rootfiles/n:rootfile/@full-path', namespaces=ns)[0]
|
||||
cf = epubZip.read(cf_name)
|
||||
|
||||
return etree.fromstring(cf), cf_name
|
||||
return etree.fromstring(cf, parser=_safe_parser), cf_name
|
||||
|
||||
|
||||
def create_new_metadata_backup(book, custom_columns, export_language, translated_cover_name, lang_type=3):
|
||||
|
||||
+51
-4
@@ -18,38 +18,67 @@
|
||||
|
||||
import traceback
|
||||
|
||||
from flask import render_template
|
||||
from flask import render_template, request, flash, make_response
|
||||
from flask_limiter import RateLimitExceeded
|
||||
from flask_babel import gettext as _
|
||||
from werkzeug.exceptions import default_exceptions
|
||||
|
||||
from .cw_login import current_user
|
||||
try:
|
||||
from werkzeug.exceptions import FailedDependency
|
||||
except ImportError:
|
||||
from werkzeug.exceptions import UnprocessableEntity as FailedDependency
|
||||
|
||||
from . import config, app, logger, services
|
||||
|
||||
from .render_template import render_title_template
|
||||
from .web import render_login
|
||||
from .usermanagement import auth
|
||||
from cps.string_helper import strip_whitespaces
|
||||
|
||||
log = logger.create()
|
||||
|
||||
# custom error page
|
||||
|
||||
def error_http(error):
|
||||
headers = {'WWW-Authenticate': 'Basic realm="calibre-web"'} if error.code == 401 else {}
|
||||
return render_template('http_error.html',
|
||||
error_code="Error {0}".format(error.code),
|
||||
error_name=error.name,
|
||||
issue=False,
|
||||
goto_admin=False,
|
||||
unconfigured=not config.db_configured,
|
||||
instance=config.config_calibre_web_title
|
||||
), error.code
|
||||
), error.code, headers
|
||||
|
||||
|
||||
def internal_error(error):
|
||||
if (isinstance(error.original_exception, AttributeError) and
|
||||
error.original_exception.args[0] == "'NoneType' object has no attribute 'query'"
|
||||
and error.original_exception.name == "query"):
|
||||
return render_template('http_error.html',
|
||||
error_code="Database Error",
|
||||
error_name='The library used is invalid or has permission errors',
|
||||
issue=False,
|
||||
goto_admin=True,
|
||||
unconfigured=False,
|
||||
error_stack="",
|
||||
instance=config.config_calibre_web_title
|
||||
), 500
|
||||
log.error("500 Internal Server Error: %s", traceback.format_exc())
|
||||
error_stack = ""
|
||||
try:
|
||||
if current_user.is_authenticated and current_user.role_admin():
|
||||
error_stack = traceback.format_exc().split("\n")
|
||||
except Exception:
|
||||
pass
|
||||
return render_template('http_error.html',
|
||||
error_code="500 Internal Server Error",
|
||||
error_name='The server encountered an internal error and was unable to complete your '
|
||||
'request. There is an error in the application.',
|
||||
issue=True,
|
||||
goto_admin=False,
|
||||
unconfigured=False,
|
||||
error_stack=traceback.format_exc().split("\n"),
|
||||
error_stack=error_stack,
|
||||
instance=config.config_calibre_web_title
|
||||
), 500
|
||||
|
||||
@@ -70,3 +99,21 @@ def init_errorhandler():
|
||||
log.debug('LDAP server not accessible while trying to login to opds feed')
|
||||
return error_http(FailedDependency())
|
||||
|
||||
|
||||
@app.errorhandler(RateLimitExceeded)
|
||||
def handle_rate_limit(__):
|
||||
log.error("Rate limit exceeded {}".format(request.endpoint))
|
||||
if "register" in request.endpoint:
|
||||
flash(_(u"Please wait one minute to register next user"), category="error")
|
||||
return render_title_template('register.html', config=config, title=_("Register"), page="register")
|
||||
elif "login" in request.endpoint:
|
||||
form = request.form.to_dict()
|
||||
username = strip_whitespaces(form.get('username', "")).lower().replace("\n", "").replace("\r", "")
|
||||
flash(_("Please wait one minute before next login"), category="error")
|
||||
return render_login(username, form.get("password", ""))
|
||||
elif "opds" in request.endpoint:
|
||||
return auth.auth_error_callback(429)
|
||||
else:
|
||||
return make_response('', 429)
|
||||
|
||||
|
||||
|
||||
+4
-1
@@ -20,6 +20,9 @@ from lxml import etree
|
||||
|
||||
from .constants import BookMeta
|
||||
|
||||
# Safe parser: disable entity resolution and network access to prevent XXE attacks
|
||||
_safe_parser = etree.XMLParser(resolve_entities=False, no_network=True)
|
||||
|
||||
|
||||
def get_fb2_info(tmp_file_path, original_file_extension):
|
||||
|
||||
@@ -29,7 +32,7 @@ def get_fb2_info(tmp_file_path, original_file_extension):
|
||||
}
|
||||
|
||||
fb2_file = open(tmp_file_path, encoding="utf-8")
|
||||
tree = etree.fromstring(fb2_file.read().encode())
|
||||
tree = etree.fromstring(fb2_file.read().encode(), parser=_safe_parser)
|
||||
|
||||
authors = tree.xpath('/fb:FictionBook/fb:description/fb:title-info/fb:author', namespaces=ns)
|
||||
|
||||
|
||||
+22
-10
@@ -21,17 +21,27 @@ import os
|
||||
import shutil
|
||||
import zipfile
|
||||
import mimetypes
|
||||
import copy
|
||||
from io import BytesIO
|
||||
try:
|
||||
import magic
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
from . import logger
|
||||
|
||||
log = logger.create()
|
||||
|
||||
try:
|
||||
import magic
|
||||
error = None
|
||||
except ImportError as e:
|
||||
error = "Cannot import python-magic, checking uploaded file metadata will not work: {}".format(e)
|
||||
|
||||
|
||||
def get_mimetype(ext):
|
||||
# overwrite some mimetypes for proper file detection
|
||||
mimes = {".fb2": "text/xml",
|
||||
".cbz": "application/zip",
|
||||
".cbr": "application/x-rar"
|
||||
}
|
||||
return mimes.get(ext, mimetypes.types_map[ext])
|
||||
|
||||
|
||||
def get_temp_dir():
|
||||
tmp_dir = os.path.join(gettempdir(), 'calibre_web')
|
||||
@@ -46,12 +56,15 @@ def del_temp_dir():
|
||||
|
||||
|
||||
def validate_mime_type(file_buffer, allowed_extensions):
|
||||
if error:
|
||||
log.error(error)
|
||||
return False
|
||||
mime = magic.Magic(mime=True)
|
||||
allowed_mimetypes =list()
|
||||
allowed_mimetypes = list()
|
||||
for x in allowed_extensions:
|
||||
try:
|
||||
allowed_mimetypes.append(mimetypes.types_map["." + x])
|
||||
except KeyError as e:
|
||||
allowed_mimetypes.append(get_mimetype("." + x))
|
||||
except KeyError:
|
||||
log.error("Unkown mimetype for Extension: {}".format(x))
|
||||
tmp_mime_type = mime.from_buffer(file_buffer.read())
|
||||
file_buffer.seek(0)
|
||||
@@ -66,6 +79,5 @@ def validate_mime_type(file_buffer, allowed_extensions):
|
||||
return True
|
||||
except:
|
||||
file_buffer.seek(0)
|
||||
pass
|
||||
|
||||
log.error("Mimetype '{}' not found in allowed types".format(tmp_mime_type))
|
||||
return False
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from . import logger
|
||||
from .constants import CACHE_DIR
|
||||
from .constants import CACHE_DIRECTORY
|
||||
from os import makedirs, remove
|
||||
from os.path import isdir, isfile, join
|
||||
from shutil import rmtree
|
||||
@@ -25,7 +25,7 @@ from shutil import rmtree
|
||||
|
||||
class FileSystem:
|
||||
_instance = None
|
||||
_cache_dir = CACHE_DIR
|
||||
_cache_dir = CACHE_DIRECTORY
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
|
||||
+5
-5
@@ -29,11 +29,11 @@ from shutil import move, copyfile
|
||||
|
||||
from flask import Blueprint, flash, request, redirect, url_for, abort
|
||||
from flask_babel import gettext as _
|
||||
from flask_login import login_required
|
||||
|
||||
from . import logger, gdriveutils, config, ub, calibre_db, csrf
|
||||
from .admin import admin_required
|
||||
from .file_helper import get_temp_dir
|
||||
from .usermanagement import user_login_required
|
||||
|
||||
gdrive = Blueprint('gdrive', __name__, url_prefix='/gdrive')
|
||||
log = logger.create()
|
||||
@@ -49,7 +49,7 @@ gdrive_watch_callback_token = 'target=calibreweb-watch_files' # nosec
|
||||
|
||||
|
||||
@gdrive.route("/authenticate")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def authenticate_google_drive():
|
||||
try:
|
||||
@@ -76,7 +76,7 @@ def google_drive_callback():
|
||||
|
||||
|
||||
@gdrive.route("/watch/subscribe")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def watch_gdrive():
|
||||
if not config.config_google_drive_watch_changes_response:
|
||||
@@ -102,7 +102,7 @@ def watch_gdrive():
|
||||
|
||||
|
||||
@gdrive.route("/watch/revoke")
|
||||
@login_required
|
||||
@user_login_required
|
||||
@admin_required
|
||||
def revoke_watch_gdrive():
|
||||
last_watch_response = config.config_google_drive_watch_changes_response
|
||||
@@ -140,7 +140,7 @@ try:
|
||||
if response:
|
||||
dbpath = os.path.join(config.config_calibre_dir, "metadata.db").encode()
|
||||
if not response['deleted'] and response['file']['title'] == 'metadata.db' \
|
||||
and response['file']['md5Checksum'] != hashlib.md5(dbpath): # nosec
|
||||
and response['file']['md5Checksum'] != hashlib.md5(dbpath).hexdigest(): # nosec
|
||||
tmp_dir = get_temp_dir()
|
||||
|
||||
log.info('Database file updated')
|
||||
|
||||
+23
-1
@@ -16,7 +16,7 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
from datetime import datetime
|
||||
from gevent.pywsgi import WSGIHandler
|
||||
|
||||
|
||||
@@ -27,4 +27,26 @@ class MyWSGIHandler(WSGIHandler):
|
||||
env['RAW_URI'] = path
|
||||
return env
|
||||
|
||||
def format_request(self):
|
||||
now = datetime.now().replace(microsecond=0)
|
||||
length = self.response_length or '-'
|
||||
if self.time_finish:
|
||||
delta = '%.6f' % (self.time_finish - self.time_start)
|
||||
else:
|
||||
delta = '-'
|
||||
forwarded = self.environ.get('HTTP_X_FORWARDED_FOR', None)
|
||||
if forwarded:
|
||||
client_address = forwarded
|
||||
else:
|
||||
client_address = self.client_address[0] if isinstance(self.client_address, tuple) else self.client_address
|
||||
return '%s - - [%s] "%s" %s %s %s' % (
|
||||
client_address or '-',
|
||||
now,
|
||||
self.requestline or '',
|
||||
# Use the native string version of the status, saved so we don't have to
|
||||
# decode. But fallback to the encoded 'status' in case of subclasses
|
||||
# (Is that really necessary? At least there's no overhead.)
|
||||
(self._orig_status or self.status or '000').split()[0],
|
||||
length,
|
||||
delta)
|
||||
|
||||
|
||||
+132
-151
@@ -25,16 +25,16 @@ import re
|
||||
import regex
|
||||
import shutil
|
||||
import socket
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import requests
|
||||
import unidecode
|
||||
from uuid import uuid4
|
||||
|
||||
from flask import send_from_directory, make_response, abort, url_for, Response
|
||||
from flask import send_from_directory, make_response, abort, url_for, Response, request, after_this_request
|
||||
from flask_babel import gettext as _
|
||||
from flask_babel import lazy_gettext as N_
|
||||
from flask_babel import get_locale
|
||||
from flask_login import current_user
|
||||
from .cw_login import current_user
|
||||
from sqlalchemy.sql.expression import true, false, and_, or_, text, func
|
||||
from sqlalchemy.exc import InvalidRequestError, OperationalError
|
||||
from werkzeug.datastructures import Headers
|
||||
@@ -43,15 +43,16 @@ from markupsafe import escape
|
||||
from urllib.parse import quote
|
||||
|
||||
try:
|
||||
import advocate
|
||||
from advocate.exceptions import UnacceptableAddressException
|
||||
from . import cw_advocate
|
||||
from .cw_advocate.exceptions import UnacceptableAddressException
|
||||
use_advocate = True
|
||||
except ImportError:
|
||||
except ImportError as e:
|
||||
use_advocate = False
|
||||
advocate = requests
|
||||
UnacceptableAddressException = MissingSchema = BaseException
|
||||
|
||||
from . import calibre_db, cli_param
|
||||
from .string_helper import strip_whitespaces
|
||||
from .tasks.convert import TaskConvert
|
||||
from . import logger, config, db, ub, fs
|
||||
from . import gdriveutils as gd
|
||||
@@ -117,9 +118,11 @@ def convert_book_format(book_id, calibre_path, old_book_format, new_book_format,
|
||||
|
||||
# Texts are not lazy translated as they are supposed to get send out as is
|
||||
def send_test_mail(ereader_mail, user_name):
|
||||
WorkerThread.add(user_name, TaskEmail(_('Calibre-Web Test Email'), None, None,
|
||||
config.get_mail_settings(), ereader_mail, N_("Test Email"),
|
||||
_('This Email has been sent via Calibre-Web.')))
|
||||
for email in ereader_mail.split(','):
|
||||
email = strip_whitespaces(email)
|
||||
WorkerThread.add(user_name, TaskEmail(_('Calibre-Web Test Email'), None, None,
|
||||
config.get_mail_settings(), email, N_("Test Email"),
|
||||
_('This Email has been sent via Calibre-Web.')))
|
||||
return
|
||||
|
||||
|
||||
@@ -196,7 +199,7 @@ def check_send_to_ereader(entry):
|
||||
# Check if a reader is existing for any of the book formats, if not, return empty list, otherwise return
|
||||
# list with supported formats
|
||||
def check_read_formats(entry):
|
||||
extensions_reader = {'TXT', 'PDF', 'EPUB', 'CBZ', 'CBT', 'CBR', 'DJVU', 'DJV'}
|
||||
extensions_reader = {'TXT', 'PDF', 'EPUB', 'KEPUB', 'CBZ', 'CBT', 'CBR', 'DJVU', 'DJV'}
|
||||
book_formats = list()
|
||||
if len(entry.data):
|
||||
for ele in iter(entry.data):
|
||||
@@ -225,14 +228,16 @@ def send_mail(book_id, book_format, convert, ereader_mail, calibrepath, user_id)
|
||||
converted_file_name = entry.name + '.' + book_format.lower()
|
||||
link = '<a href="{}">{}</a>'.format(url_for('web.show_book', book_id=book_id), escape(book.title))
|
||||
email_text = N_("%(book)s send to eReader", book=link)
|
||||
WorkerThread.add(user_id, TaskEmail(_("Send to eReader"), book.path, converted_file_name,
|
||||
config.get_mail_settings(), ereader_mail,
|
||||
email_text, _('This Email has been sent via Calibre-Web.'), book.id))
|
||||
for email in ereader_mail.split(','):
|
||||
email = strip_whitespaces(email)
|
||||
WorkerThread.add(user_id, TaskEmail(_("Send to eReader"), book.path, converted_file_name,
|
||||
config.get_mail_settings(), email,
|
||||
email_text, _('This Email has been sent via Calibre-Web.'), book.id))
|
||||
return
|
||||
return _("The requested file could not be read. Maybe wrong permissions?")
|
||||
|
||||
|
||||
def get_valid_filename(value, replace_whitespace=True, chars=128):
|
||||
def get_valid_filename(value, replace_whitespace=True, chars=128, force_unidecode=False):
|
||||
"""
|
||||
Returns the given string converted to a string that can be used for a clean
|
||||
filename. Limits num characters to 128 max.
|
||||
@@ -240,7 +245,7 @@ def get_valid_filename(value, replace_whitespace=True, chars=128):
|
||||
if value[-1:] == '.':
|
||||
value = value[:-1]+'_'
|
||||
value = value.replace("/", "_").replace(":", "_").strip('\0')
|
||||
if config.config_unicode_filename:
|
||||
if config.config_unicode_filename or force_unidecode:
|
||||
value = (unidecode.unidecode(value))
|
||||
if replace_whitespace:
|
||||
# *+:\"/<>? are replaced by _
|
||||
@@ -248,7 +253,7 @@ def get_valid_filename(value, replace_whitespace=True, chars=128):
|
||||
# pipe has to be replaced with comma
|
||||
value = re.sub(r'[|]+', ',', value, flags=re.U)
|
||||
|
||||
value = value.encode('utf-8')[:chars].decode('utf-8', errors='ignore').strip()
|
||||
value = strip_whitespaces(value.encode('utf-8')[:chars].decode('utf-8', errors='ignore'))
|
||||
|
||||
if not value:
|
||||
raise ValueError("Filename cannot be empty")
|
||||
@@ -263,11 +268,11 @@ def split_authors(values):
|
||||
commas = author.count(',')
|
||||
if commas == 1:
|
||||
author_split = author.split(',')
|
||||
authors_list.append(author_split[1].strip() + ' ' + author_split[0].strip())
|
||||
authors_list.append(strip_whitespaces(author_split[1]) + ' ' + strip_whitespaces(author_split[0]))
|
||||
elif commas > 1:
|
||||
authors_list.extend([x.strip() for x in author.split(',')])
|
||||
authors_list.extend([strip_whitespaces(x) for x in author.split(',')])
|
||||
else:
|
||||
authors_list.append(author.strip())
|
||||
authors_list.append(strip_whitespaces(author))
|
||||
return authors_list
|
||||
|
||||
|
||||
@@ -302,18 +307,16 @@ def edit_book_read_status(book_id, read_status=None):
|
||||
if not config.config_read_column:
|
||||
book = ub.session.query(ub.ReadBook).filter(and_(ub.ReadBook.user_id == int(current_user.id),
|
||||
ub.ReadBook.book_id == book_id)).first()
|
||||
if book:
|
||||
if read_status is None:
|
||||
if book.read_status == ub.ReadBook.STATUS_FINISHED:
|
||||
book.read_status = ub.ReadBook.STATUS_UNREAD
|
||||
else:
|
||||
book.read_status = ub.ReadBook.STATUS_FINISHED
|
||||
else:
|
||||
book.read_status = ub.ReadBook.STATUS_FINISHED if read_status else ub.ReadBook.STATUS_UNREAD
|
||||
else:
|
||||
if not book:
|
||||
read_book = ub.ReadBook(user_id=current_user.id, book_id=book_id)
|
||||
read_book.read_status = ub.ReadBook.STATUS_FINISHED
|
||||
book = read_book
|
||||
if read_status is None:
|
||||
if book.read_status == ub.ReadBook.STATUS_FINISHED:
|
||||
book.read_status = ub.ReadBook.STATUS_UNREAD
|
||||
else:
|
||||
book.read_status = ub.ReadBook.STATUS_FINISHED
|
||||
else:
|
||||
book.read_status = ub.ReadBook.STATUS_FINISHED if read_status == True else ub.ReadBook.STATUS_UNREAD
|
||||
if not book.kobo_reading_state:
|
||||
kobo_reading_state = ub.KoboReadingState(user_id=current_user.id, book_id=book_id)
|
||||
kobo_reading_state.current_bookmark = ub.KoboBookmark()
|
||||
@@ -323,8 +326,8 @@ def edit_book_read_status(book_id, read_status=None):
|
||||
ub.session_commit("Book {} readbit toggled".format(book_id))
|
||||
else:
|
||||
try:
|
||||
calibre_db.update_title_sort(config)
|
||||
book = calibre_db.get_filtered_book(book_id)
|
||||
calibre_db.create_functions(config)
|
||||
book = calibre_db.get_filtered_book(book_id, True)
|
||||
book_read_status = getattr(book, 'custom_column_' + str(config.config_read_column))
|
||||
if len(book_read_status):
|
||||
if read_status is None:
|
||||
@@ -391,10 +394,16 @@ def delete_book_file(book, calibrepath, book_format=None):
|
||||
def rename_all_files_on_change(one_book, new_path, old_path, all_new_name, gdrive=False):
|
||||
for file_format in one_book.data:
|
||||
if not gdrive:
|
||||
if not os.path.exists(new_path):
|
||||
os.makedirs(new_path)
|
||||
shutil.move(os.path.join(old_path, file_format.name + '.' + file_format.format.lower()),
|
||||
os.path.join(new_path, all_new_name + '.' + file_format.format.lower()))
|
||||
try:
|
||||
if not os.path.exists(new_path):
|
||||
os.makedirs(new_path)
|
||||
shutil.move(os.path.join(old_path, file_format.name + '.' + file_format.format.lower()),
|
||||
os.path.join(new_path, all_new_name + '.' + file_format.format.lower()))
|
||||
except (PermissionError, FileNotFoundError) as ex:
|
||||
log.error("Moving book-id %s folder %s failed: %s", one_book.id, new_path, ex)
|
||||
return _("Moving book path of Book %(book_id)s to: '%(src)s' failed with error: %(error)s",
|
||||
book_id=one_book.id, src=new_path, error=str(ex))
|
||||
|
||||
else:
|
||||
g_file = gd.getFileFromEbooksFolder(old_path,
|
||||
file_format.name + '.' + file_format.format.lower())
|
||||
@@ -407,44 +416,13 @@ def rename_all_files_on_change(one_book, new_path, old_path, all_new_name, gdriv
|
||||
|
||||
# change name in Database
|
||||
file_format.name = all_new_name
|
||||
|
||||
|
||||
'''def rename_all_authors(first_author, renamed_author, calibre_path="", localbook=None, gdrive=False):
|
||||
# Create new_author_dir from parameter or from database
|
||||
# Create new title_dir from database and add id
|
||||
if first_author:
|
||||
new_authordir = get_valid_filename(first_author, chars=96)
|
||||
for r in renamed_author:
|
||||
new_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == r).first()
|
||||
old_author_dir = get_valid_filename(r, chars=96)
|
||||
new_author_rename_dir = get_valid_filename(new_author.name, chars=96)
|
||||
if gdrive:
|
||||
g_file = gd.getFileFromEbooksFolder(None, old_author_dir)
|
||||
if g_file:
|
||||
gd.moveGdriveFolderRemote(g_file, new_author_rename_dir)
|
||||
gd.updateDatabaseOnEdit(g_file['id'], new_author_rename_dir)
|
||||
else:
|
||||
if os.path.isdir(os.path.join(calibre_path, old_author_dir)):
|
||||
old_author_path = os.path.join(calibre_path, old_author_dir)
|
||||
new_author_path = os.path.join(calibre_path, new_author_rename_dir)
|
||||
try:
|
||||
shutil.move(os.path.normcase(old_author_path), os.path.normcase(new_author_path))
|
||||
except OSError as ex:
|
||||
log.error("Rename author from: %s to %s: %s", old_author_path, new_author_path, ex)
|
||||
log.debug(ex, exc_info=True)
|
||||
return _("Rename author from: '%(src)s' to '%(dest)s' failed with error: %(error)s",
|
||||
src=old_author_path, dest=new_author_path, error=str(ex))
|
||||
else:
|
||||
new_authordir = get_valid_filename(localbook.authors[0].name, chars=96)
|
||||
return new_authordir'''
|
||||
return False
|
||||
|
||||
|
||||
def rename_author_path(first_author, old_author_dir, renamed_author, calibre_path="", gdrive=False):
|
||||
# Create new_author_dir from parameter or from database
|
||||
# Create new title_dir from database and add id
|
||||
new_authordir = get_valid_filename(first_author, chars=96)
|
||||
# new_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == renamed_author).first()
|
||||
# old_author_dir = get_valid_filename(old_author_name, chars=96)
|
||||
new_author_rename_dir = get_valid_filename(renamed_author, chars=96)
|
||||
if gdrive:
|
||||
g_file = gd.getFileFromEbooksFolder(None, old_author_dir)
|
||||
@@ -455,12 +433,15 @@ def rename_author_path(first_author, old_author_dir, renamed_author, calibre_pat
|
||||
old_author_path = os.path.join(calibre_path, old_author_dir)
|
||||
new_author_path = os.path.join(calibre_path, new_author_rename_dir)
|
||||
try:
|
||||
shutil.move(old_author_path, new_author_path)
|
||||
except OSError as ex:
|
||||
log.error("Rename author from: %s to %s: %s", old_author_path, new_author_path, ex)
|
||||
log.debug(ex, exc_info=True)
|
||||
return _("Rename author from: '%(src)s' to '%(dest)s' failed with error: %(error)s",
|
||||
src=old_author_path, dest=new_author_path, error=str(ex))
|
||||
os.rename(old_author_path, new_author_path)
|
||||
except OSError:
|
||||
try:
|
||||
shutil.move(old_author_path, new_author_path)
|
||||
except OSError as ex:
|
||||
log.error("Rename author from: %s to %s: %s", old_author_path, new_author_path, ex)
|
||||
log.error_or_exception(ex)
|
||||
raise Exception(_("Rename author from: '%(src)s' to '%(dest)s' failed with error: %(error)s",
|
||||
src=old_author_path, dest=new_author_path, error=str(ex)))
|
||||
return new_authordir
|
||||
|
||||
# Moves files in file storage during author/title rename, or from temp dir to file storage
|
||||
@@ -490,17 +471,15 @@ def update_dir_structure_file(book_id, calibre_path, original_filepath, new_auth
|
||||
db_filename,
|
||||
original_filepath,
|
||||
path)
|
||||
# old_path = os.path.join(calibre_path, author_dir, new_title_dir).replace('\\', '/')
|
||||
new_path = os.path.join(calibre_path, new_author_dir, new_title_dir).replace('\\', '/')
|
||||
all_new_name = get_valid_filename(local_book.title, chars=42) + ' - ' \
|
||||
+ get_valid_filename(new_author, chars=42)
|
||||
# Book folder already moved, only files need to be renamed
|
||||
rename_all_files_on_change(local_book, new_path, new_path, all_new_name)
|
||||
if not error:
|
||||
new_path = os.path.join(calibre_path, new_author_dir, new_title_dir).replace('\\', '/')
|
||||
all_new_name = get_valid_filename(local_book.title, chars=42) + ' - ' \
|
||||
+ get_valid_filename(new_author, chars=42)
|
||||
# Book folder already moved, only files need to be renamed
|
||||
renameerror = rename_all_files_on_change(local_book, new_path, new_path, all_new_name)
|
||||
|
||||
if error:
|
||||
return error
|
||||
|
||||
# Rename all files from old names to new names
|
||||
if error or renameerror:
|
||||
return error or renameerror
|
||||
return False
|
||||
|
||||
|
||||
@@ -512,7 +491,7 @@ def upload_new_file_gdrive(book_id, first_author, title, title_dir, original_fil
|
||||
title_dir + " (" + str(book_id) + ")")
|
||||
book.path = gdrive_path.replace("\\", "/")
|
||||
gd.uploadFileToEbooksFolder(os.path.join(gdrive_path, file_name).replace("\\", "/"), original_filepath)
|
||||
return False # rename_files_on_change(first_author, renamed_author, local_book=book, gdrive=True)
|
||||
return False
|
||||
|
||||
|
||||
def update_dir_structure_gdrive(book_id, first_author):
|
||||
@@ -540,25 +519,27 @@ def update_dir_structure_gdrive(book_id, first_author):
|
||||
book.path = new_authordir + '/' + book.path.split('/')[1]
|
||||
gd.updateDatabaseOnEdit(g_file['id'], book.path)
|
||||
else:
|
||||
return _('File %(file)s not found on Google Drive', file=authordir) # file not found'''
|
||||
return _('File %(file)s not found on Google Drive', file=authordir) # file not found
|
||||
if titledir != new_titledir or authordir != new_authordir :
|
||||
all_new_name = get_valid_filename(book.title, chars=42) + ' - ' \
|
||||
+ get_valid_filename(new_authordir, chars=42)
|
||||
rename_all_files_on_change(book, book.path, book.path, all_new_name, gdrive=True) # todo: Move filenames on gdrive
|
||||
# change location in database to new author/title path
|
||||
# book.path = os.path.join(authordir, new_titledir).replace('\\', '/')
|
||||
return rename_all_files_on_change(book, book.path, book.path, all_new_name, gdrive=True) # todo: Move filenames on gdrive
|
||||
return False
|
||||
|
||||
|
||||
def move_files_on_change(calibre_path, new_author_dir, new_titledir, localbook, db_filename, original_filepath, path):
|
||||
new_path = os.path.join(calibre_path, new_author_dir, new_titledir)
|
||||
# new_name = get_valid_filename(localbook.title, chars=96) + ' - ' + new_author_dir
|
||||
try:
|
||||
if original_filepath:
|
||||
if not os.path.isdir(new_path):
|
||||
os.makedirs(new_path)
|
||||
shutil.move(original_filepath, os.path.join(new_path, db_filename))
|
||||
log.debug("Moving title: %s to %s/%s", original_filepath, new_path)
|
||||
try:
|
||||
shutil.move(original_filepath, os.path.join(new_path, db_filename))
|
||||
except OSError:
|
||||
log.error("Rename title from {} to {} failed with error, trying to "
|
||||
"move without metadata".format(path, new_path))
|
||||
shutil.move(original_filepath, os.path.join(new_path, db_filename), copy_function=shutil.copy)
|
||||
log.debug("Moving title: %s to %s", original_filepath, new_path)
|
||||
else:
|
||||
# Check new path is not valid path
|
||||
if not os.path.exists(new_path):
|
||||
@@ -578,33 +559,13 @@ def move_files_on_change(calibre_path, new_author_dir, new_titledir, localbook,
|
||||
log.error("Deleting authorpath for book %s failed: %s", localbook.id, ex)
|
||||
# change location in database to new author/title path
|
||||
localbook.path = os.path.join(new_author_dir, new_titledir).replace('\\', '/')
|
||||
except OSError as ex:
|
||||
except (OSError, FileNotFoundError) as ex:
|
||||
log.error_or_exception("Rename title from {} to {} failed with error: {}".format(path, new_path, ex))
|
||||
return _("Rename title from: '%(src)s' to '%(dest)s' failed with error: %(error)s",
|
||||
src=path, dest=new_path, error=str(ex))
|
||||
return False
|
||||
|
||||
|
||||
def rename_files_on_change(first_author,
|
||||
renamed_author,
|
||||
local_book,
|
||||
original_filepath="",
|
||||
path="",
|
||||
calibre_path="",
|
||||
gdrive=False):
|
||||
# Rename all files from old names to new names
|
||||
#try:
|
||||
#clean_author_database(renamed_author, calibre_path, gdrive=gdrive)
|
||||
#if first_author and first_author not in renamed_author:
|
||||
# clean_author_database([first_author], calibre_path, local_book, gdrive)
|
||||
#if not gdrive and not renamed_author and not original_filepath and len(os.listdir(os.path.dirname(path))) == 0:
|
||||
# shutil.rmtree(os.path.dirname(path))
|
||||
#except (OSError, FileNotFoundError) as ex:
|
||||
# log.error_or_exception("Error in rename file in path {}".format(ex))
|
||||
# return _("Error in rename file in path: {}".format(str(ex)))
|
||||
return False
|
||||
|
||||
|
||||
def delete_book_gdrive(book, book_format):
|
||||
error = None
|
||||
if book_format:
|
||||
@@ -684,23 +645,26 @@ def check_email(email):
|
||||
|
||||
|
||||
def check_username(username):
|
||||
username = username.strip()
|
||||
username = strip_whitespaces(username)
|
||||
if ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.lower()).scalar():
|
||||
log.error("This username is already taken")
|
||||
raise Exception(_("This username is already taken"))
|
||||
return username
|
||||
|
||||
|
||||
def valid_email(email):
|
||||
email = email.strip()
|
||||
# if email is not deleted
|
||||
if email:
|
||||
# Regex according to https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#validation
|
||||
if not re.search(r"^[\w.!#$%&'*+\\/=?^_`{|}~-]+@[\w](?:[\w-]{0,61}[\w])?(?:\.[\w](?:[\w-]{0,61}[\w])?)*$",
|
||||
email):
|
||||
log.error("Invalid Email address format")
|
||||
raise Exception(_("Invalid Email address format"))
|
||||
return email
|
||||
def valid_email(emails):
|
||||
valid_emails = []
|
||||
for email in emails.split(','):
|
||||
email = strip_whitespaces(email)
|
||||
# if email is not deleted
|
||||
if email:
|
||||
# Regex according to https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#validation
|
||||
if not re.search(r"^[\w.!#$%&'*+\\/=?^_`{|}~-]+@[\w](?:[\w-]{0,61}[\w])?(?:\.[\w](?:[\w-]{0,61}[\w])?)*$",
|
||||
email):
|
||||
log.error("Invalid Email address format for {}".format(email))
|
||||
raise Exception(_("Invalid Email address format"))
|
||||
valid_emails.append(email)
|
||||
return ",".join(valid_emails)
|
||||
|
||||
|
||||
def valid_password(check_password):
|
||||
@@ -810,24 +774,23 @@ def get_book_cover_internal(book, resolution=None):
|
||||
|
||||
def get_book_cover_thumbnail(book, resolution):
|
||||
if book and book.has_cover:
|
||||
return ub.session \
|
||||
.query(ub.Thumbnail) \
|
||||
.filter(ub.Thumbnail.type == THUMBNAIL_TYPE_COVER) \
|
||||
.filter(ub.Thumbnail.entity_id == book.id) \
|
||||
.filter(ub.Thumbnail.resolution == resolution) \
|
||||
.filter(or_(ub.Thumbnail.expiration.is_(None), ub.Thumbnail.expiration > datetime.utcnow())) \
|
||||
.first()
|
||||
return (ub.session
|
||||
.query(ub.Thumbnail)
|
||||
.filter(ub.Thumbnail.type == THUMBNAIL_TYPE_COVER)
|
||||
.filter(ub.Thumbnail.entity_id == book.id)
|
||||
.filter(ub.Thumbnail.resolution == resolution)
|
||||
.filter(or_(ub.Thumbnail.expiration.is_(None), ub.Thumbnail.expiration > datetime.now(timezone.utc)))
|
||||
.first())
|
||||
|
||||
|
||||
def get_series_thumbnail_on_failure(series_id, resolution):
|
||||
book = calibre_db.session \
|
||||
.query(db.Books) \
|
||||
.join(db.books_series_link) \
|
||||
.join(db.Series) \
|
||||
.filter(db.Series.id == series_id) \
|
||||
.filter(db.Books.has_cover == 1) \
|
||||
.first()
|
||||
|
||||
book = (calibre_db.session
|
||||
.query(db.Books)
|
||||
.join(db.books_series_link)
|
||||
.join(db.Series)
|
||||
.filter(db.Series.id == series_id)
|
||||
.filter(db.Books.has_cover == 1)
|
||||
.first())
|
||||
return get_book_cover_internal(book, resolution=resolution)
|
||||
|
||||
|
||||
@@ -849,13 +812,13 @@ def get_series_cover_internal(series_id, resolution=None):
|
||||
|
||||
|
||||
def get_series_thumbnail(series_id, resolution):
|
||||
return ub.session \
|
||||
.query(ub.Thumbnail) \
|
||||
.filter(ub.Thumbnail.type == THUMBNAIL_TYPE_SERIES) \
|
||||
.filter(ub.Thumbnail.entity_id == series_id) \
|
||||
.filter(ub.Thumbnail.resolution == resolution) \
|
||||
.filter(or_(ub.Thumbnail.expiration.is_(None), ub.Thumbnail.expiration > datetime.utcnow())) \
|
||||
.first()
|
||||
return (ub.session
|
||||
.query(ub.Thumbnail)
|
||||
.filter(ub.Thumbnail.type == THUMBNAIL_TYPE_SERIES)
|
||||
.filter(ub.Thumbnail.entity_id == series_id)
|
||||
.filter(ub.Thumbnail.resolution == resolution)
|
||||
.filter(or_(ub.Thumbnail.expiration.is_(None), ub.Thumbnail.expiration > datetime.now(timezone.utc)))
|
||||
.first())
|
||||
|
||||
|
||||
# saves book cover from url
|
||||
@@ -864,7 +827,7 @@ def save_cover_from_url(url, book_path):
|
||||
if cli_param.allow_localhost:
|
||||
img = requests.get(url, timeout=(10, 200), allow_redirects=False) # ToDo: Error Handling
|
||||
elif use_advocate:
|
||||
img = advocate.get(url, timeout=(10, 200), allow_redirects=False) # ToDo: Error Handling
|
||||
img = cw_advocate.get(url, timeout=(10, 200), allow_redirects=False) # ToDo: Error Handling
|
||||
else:
|
||||
log.error("python module advocate is not installed but is needed")
|
||||
return False, _("Python module 'advocate' is not installed but is needed for cover uploads")
|
||||
@@ -928,7 +891,7 @@ def save_cover(img, book_path):
|
||||
else:
|
||||
imgc = Image(blob=io.BytesIO(img.content))
|
||||
imgc.format = 'jpeg'
|
||||
imgc.transform_colorspace("rgb")
|
||||
imgc.transform_colorspace("srgb")
|
||||
img = imgc
|
||||
except (BlobError, MissingDelegateError):
|
||||
log.error("Invalid cover file content")
|
||||
@@ -993,11 +956,23 @@ def do_download_file(book, book_format, client, data, headers):
|
||||
else:
|
||||
download_name = book_name
|
||||
|
||||
# Clean up staged copies in /tmp/calibre_web after the response is sent
|
||||
# (kepubify / calibre-export branches) so the temp dir does not grow unbounded.
|
||||
if filename == get_temp_dir():
|
||||
_tmp_path = os.path.join(filename, download_name + "." + book_format)
|
||||
@after_this_request
|
||||
def _cleanup_staged_download(resp):
|
||||
try:
|
||||
os.remove(_tmp_path)
|
||||
except OSError as ex:
|
||||
log.warning('Failed to remove staged download %s: %s', _tmp_path, ex)
|
||||
return resp
|
||||
response = make_response(send_from_directory(filename, download_name + "." + book_format))
|
||||
# ToDo Check headers parameter
|
||||
for element in headers:
|
||||
response.headers[element[0]] = element[1]
|
||||
log.info('Downloading file: {}'.format(os.path.join(filename, book_name + "." + book_format)))
|
||||
log.info('Downloading file: \'%s\' by %s - %s', format(os.path.join(filename, book_name + "." + book_format)),
|
||||
current_user.name, request.headers.get('X-Forwarded-For', request.remote_addr))
|
||||
return response
|
||||
|
||||
|
||||
@@ -1127,11 +1102,17 @@ def get_download_link(book_id, book_format, client):
|
||||
file_name = book.title
|
||||
if len(book.authors) > 0:
|
||||
file_name = file_name + ' - ' + book.authors[0].name
|
||||
file_name = get_valid_filename(file_name, replace_whitespace=False)
|
||||
original_name = file_name
|
||||
file_name = get_valid_filename(file_name, replace_whitespace=False, force_unidecode=True)
|
||||
if client == "kindle":
|
||||
quoted_file_name = file_name
|
||||
else:
|
||||
native_name = get_valid_filename(original_name, replace_whitespace=False, force_unidecode=False)
|
||||
quoted_file_name = quote(native_name)
|
||||
headers = Headers()
|
||||
headers["Content-Type"] = mimetypes.types_map.get('.' + book_format, "application/octet-stream")
|
||||
headers["Content-Disposition"] = "attachment; filename=%s.%s; filename*=UTF-8''%s.%s" % (
|
||||
quote(file_name), book_format, quote(file_name), book_format)
|
||||
headers["Content-Disposition"] = ('attachment; filename="{}.{}"; filename*=UTF-8\'\'{}.{}').format(
|
||||
file_name, book_format, quoted_file_name, book_format)
|
||||
return do_download_file(book, book_format, client, data1, headers)
|
||||
else:
|
||||
log.error("Book id {} not found for downloading".format(book_id))
|
||||
|
||||
+16
-18
@@ -15,24 +15,17 @@
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
import sys
|
||||
|
||||
from .iso_language_names import LANGUAGE_NAMES as _LANGUAGE_NAMES
|
||||
from . import logger
|
||||
from .string_helper import strip_whitespaces
|
||||
|
||||
log = logger.create()
|
||||
|
||||
|
||||
try:
|
||||
from iso639 import languages, __version__
|
||||
get = languages.get
|
||||
except ImportError:
|
||||
from pycountry import languages as pyc_languages
|
||||
try:
|
||||
import pkg_resources
|
||||
__version__ = pkg_resources.get_distribution('pycountry').version + ' (PyCountry)'
|
||||
del pkg_resources
|
||||
except (ImportError, Exception):
|
||||
__version__ = "? (PyCountry)"
|
||||
|
||||
def _copy_fields(l):
|
||||
l.part1 = getattr(l, 'alpha_2', None)
|
||||
@@ -46,6 +39,11 @@ except ImportError:
|
||||
return _copy_fields(pyc_languages.get(alpha_2=part1))
|
||||
if name is not None:
|
||||
return _copy_fields(pyc_languages.get(name=name))
|
||||
except ImportError as ex:
|
||||
if sys.version_info >= (3, 12):
|
||||
print("Python 3.12 isn't compatible with iso-639. Please install pycountry.")
|
||||
from iso639 import languages
|
||||
get = languages.get
|
||||
|
||||
|
||||
def get_language_names(locale):
|
||||
@@ -69,20 +67,20 @@ def get_language_name(locale, lang_code):
|
||||
return name
|
||||
|
||||
|
||||
def get_language_codes(locale, language_names, remainder=None):
|
||||
language_names = set(x.strip().lower() for x in language_names if x)
|
||||
def get_language_code_from_name(locale, language_names, remainder=None):
|
||||
language_names = set(strip_whitespaces(x).lower() for x in language_names if x)
|
||||
lang = list()
|
||||
for k, v in get_language_names(locale).items():
|
||||
v = v.lower()
|
||||
if v in language_names:
|
||||
lang.append(k)
|
||||
language_names.remove(v)
|
||||
for key, val in get_language_names(locale).items():
|
||||
val = val.lower()
|
||||
if val in language_names:
|
||||
lang.append(key)
|
||||
language_names.remove(val)
|
||||
if remainder is not None and language_names:
|
||||
remainder.extend(language_names)
|
||||
return lang
|
||||
|
||||
|
||||
def get_valid_language_codes(locale, language_names, remainder=None):
|
||||
def get_valid_language_codes_from_code(locale, language_names, remainder=None):
|
||||
lang = list()
|
||||
if "" in language_names:
|
||||
language_names.remove("")
|
||||
@@ -103,6 +101,6 @@ def get_lang3(lang):
|
||||
ret_value = lang
|
||||
else:
|
||||
ret_value = ""
|
||||
except KeyError:
|
||||
except (KeyError, AttributeError):
|
||||
ret_value = lang
|
||||
return ret_value
|
||||
|
||||
@@ -12,6 +12,384 @@
|
||||
# map iso639 language codes to language names, translated
|
||||
|
||||
LANGUAGE_NAMES = {
|
||||
"ar": {
|
||||
"abk": "Abkhazian",
|
||||
"ace": "Achinese",
|
||||
"ach": "Acoli",
|
||||
"ada": "Adangme",
|
||||
"ady": "Adyghe",
|
||||
"aar": "Afar",
|
||||
"afh": "Afrihili",
|
||||
"afr": "الأفريكانس",
|
||||
"ain": "Ainu (Japan)",
|
||||
"aka": "Akan",
|
||||
"akk": "Akkadian",
|
||||
"sqi": "Albanian",
|
||||
"ale": "Aleut",
|
||||
"amh": "Amharic",
|
||||
"anp": "Angika",
|
||||
"ara": "العربية",
|
||||
"arg": "Aragonese",
|
||||
"arp": "Arapaho",
|
||||
"arw": "Arawak",
|
||||
"hye": "الأرمينية",
|
||||
"asm": "Assamese",
|
||||
"ast": "Asturian",
|
||||
"ava": "Avaric",
|
||||
"ave": "Avestan",
|
||||
"awa": "Awadhi",
|
||||
"aym": "Aymara",
|
||||
"aze": "الأذربيجانية",
|
||||
"ban": "البالية",
|
||||
"bal": "Baluchi",
|
||||
"bam": "Bambara",
|
||||
"bas": "Basa (Cameroon)",
|
||||
"bak": "Bashkir",
|
||||
"eus": "الباسك",
|
||||
"bej": "Beja",
|
||||
"bel": "بلاروسي",
|
||||
"bem": "Bemba (Zambia)",
|
||||
"ben": "البنغالية",
|
||||
"bit": "Berinomo",
|
||||
"bho": "Bhojpuri",
|
||||
"bik": "Bikol",
|
||||
"byn": "Bilin",
|
||||
"bin": "Bini",
|
||||
"bis": "Bislama",
|
||||
"zbl": "Blissymbols",
|
||||
"bos": "Bosnian",
|
||||
"bra": "Braj",
|
||||
"bre": "البريتون",
|
||||
"bug": "البجينيز",
|
||||
"bul": "البلغارية",
|
||||
"bua": "Buriat",
|
||||
"mya": "البورمية",
|
||||
"cad": "Caddo",
|
||||
"cat": "الكاتالانية",
|
||||
"ceb": "Cebuano",
|
||||
"chg": "Chagatai",
|
||||
"cha": "Chamorro",
|
||||
"che": "Chechen",
|
||||
"chr": "الشيروكى",
|
||||
"chy": "Cheyenne",
|
||||
"chb": "Chibcha",
|
||||
"zho": "الصينية",
|
||||
"chn": "Chinook jargon",
|
||||
"chp": "Chipewyan",
|
||||
"cho": "Choctaw",
|
||||
"cht": "Cholón",
|
||||
"chk": "Chuukese",
|
||||
"chv": "Chuvash",
|
||||
"cop": "القبطية",
|
||||
"cor": "Cornish",
|
||||
"cos": "Corsican",
|
||||
"cre": "Cree",
|
||||
"mus": "Creek",
|
||||
"hrv": "الكرواتية",
|
||||
"ces": "التشيكية",
|
||||
"dak": "Dakota",
|
||||
"dan": "الدنماركية",
|
||||
"dar": "Dargwa",
|
||||
"del": "Delaware",
|
||||
"div": "Dhivehi",
|
||||
"din": "Dinka",
|
||||
"doi": "Dogri (macrolanguage)",
|
||||
"dgr": "Dogrib",
|
||||
"dua": "Duala",
|
||||
"nld": "الهولندية",
|
||||
"dse": "Dutch Sign Language",
|
||||
"dyu": "Dyula",
|
||||
"dzo": "الزونخاية",
|
||||
"efi": "Efik",
|
||||
"egy": "Egyptian (Ancient)",
|
||||
"eka": "Ekajuk",
|
||||
"elx": "Elamite",
|
||||
"eng": "الإنجليزية",
|
||||
"enu": "Enu",
|
||||
"myv": "Erzya",
|
||||
"epo": "الإسبرانتو",
|
||||
"est": "الإستونية",
|
||||
"ewe": "Ewe",
|
||||
"ewo": "Ewondo",
|
||||
"fan": "Fang (Equatorial Guinea)",
|
||||
"fat": "Fanti",
|
||||
"fao": "Faroese",
|
||||
"fij": "Fijian",
|
||||
"fil": "Filipino",
|
||||
"fin": "الفنلندية",
|
||||
"fon": "Fon",
|
||||
"fra": "الفرنسية",
|
||||
"fur": "Friulian",
|
||||
"ful": "Fulah",
|
||||
"gaa": "Ga",
|
||||
"glg": "Galician",
|
||||
"lug": "Ganda",
|
||||
"gay": "Gayo",
|
||||
"gba": "Gbaya (Central African Republic)",
|
||||
"hmj": "Ge",
|
||||
"gez": "Geez",
|
||||
"kat": "Georgian",
|
||||
"deu": "الألمانية",
|
||||
"gil": "Gilbertese",
|
||||
"gon": "Gondi",
|
||||
"gor": "Gorontalo",
|
||||
"got": "القوطية",
|
||||
"grb": "Grebo",
|
||||
"grn": "Guarani",
|
||||
"guj": "الغوجاراتية",
|
||||
"gwi": "Gwichʼin",
|
||||
"hai": "Haida",
|
||||
"hau": "Hausa",
|
||||
"haw": "Hawaiian",
|
||||
"heb": "العبرية",
|
||||
"her": "Herero",
|
||||
"hil": "Hiligaynon",
|
||||
"hin": "الهندية",
|
||||
"hmo": "Hiri Motu",
|
||||
"hit": "Hittite",
|
||||
"hmn": "Hmong",
|
||||
"hun": "الهنغارية (المجرية)",
|
||||
"hup": "Hupa",
|
||||
"iba": "Iban",
|
||||
"isl": "الآيسلندية",
|
||||
"ido": "Ido",
|
||||
"ibo": "Igbo",
|
||||
"ilo": "Iloko",
|
||||
"ind": "الإندونيسية",
|
||||
"inh": "Ingush",
|
||||
"ina": "Interlingua (International Auxiliary Language Association)",
|
||||
"ile": "Interlingue",
|
||||
"iku": "Inuktitut",
|
||||
"ipk": "Inupiaq",
|
||||
"gle": "الأيرلندية",
|
||||
"ita": "الإيطالية",
|
||||
"jpn": "اليابانية",
|
||||
"jav": "الجاوية",
|
||||
"jrb": "Judeo-Arabic",
|
||||
"jpr": "Judeo-Persian",
|
||||
"kbd": "Kabardian",
|
||||
"kab": "Kabyle",
|
||||
"kac": "Kachin",
|
||||
"kal": "Kalaallisut",
|
||||
"xal": "Kalmyk",
|
||||
"kam": "Kamba (Kenya)",
|
||||
"kan": "الكانادا",
|
||||
"kau": "Kanuri",
|
||||
"kaa": "Kara-Kalpak",
|
||||
"krc": "Karachay-Balkar",
|
||||
"krl": "Karelian",
|
||||
"kas": "Kashmiri",
|
||||
"csb": "Kashubian",
|
||||
"kaw": "Kawi",
|
||||
"kaz": "Kazakh",
|
||||
"kha": "Khasi",
|
||||
"kho": "Khotanese",
|
||||
"kik": "Kikuyu",
|
||||
"kmb": "Kimbundu",
|
||||
"kin": "Kinyarwanda",
|
||||
"kir": "Kirghiz",
|
||||
"tlh": "Klingon",
|
||||
"kom": "Komi",
|
||||
"kon": "Kongo",
|
||||
"kok": "Konkani (macrolanguage)",
|
||||
"kor": "الكورية",
|
||||
"kos": "Kosraean",
|
||||
"kpe": "Kpelle",
|
||||
"kua": "Kuanyama",
|
||||
"kum": "Kumyk",
|
||||
"kur": "الكردية",
|
||||
"kru": "Kurukh",
|
||||
"kut": "Kutenai",
|
||||
"lad": "Ladino",
|
||||
"lah": "Lahnda",
|
||||
"lam": "Lamba",
|
||||
"lao": "اللاو",
|
||||
"lat": "Latin",
|
||||
"lav": "اللاتفية",
|
||||
"lez": "Lezghian",
|
||||
"lim": "Limburgan",
|
||||
"lin": "Lingala",
|
||||
"lit": "الليتوانية",
|
||||
"jbo": "Lojban",
|
||||
"loz": "Lozi",
|
||||
"lub": "Luba-Katanga",
|
||||
"lua": "Luba-Lulua",
|
||||
"lui": "Luiseno",
|
||||
"smj": "Lule Sami",
|
||||
"lun": "Lunda",
|
||||
"luo": "Luo (Kenya and Tanzania)",
|
||||
"lus": "Lushai",
|
||||
"ltz": "Luxembourgish",
|
||||
"mkd": "المقدونية",
|
||||
"mad": "Madurese",
|
||||
"mag": "Magahi",
|
||||
"mai": "Maithili",
|
||||
"mak": "Makasar",
|
||||
"mlg": "Malagasy",
|
||||
"msa": "Malay (macrolanguage)",
|
||||
"mal": "الماليالام",
|
||||
"mlt": "المالطية",
|
||||
"mnc": "Manchu",
|
||||
"mdr": "Mandar",
|
||||
"man": "Mandingo",
|
||||
"mni": "Manipuri",
|
||||
"glv": "Manx",
|
||||
"mri": "الموري",
|
||||
"arn": "Mapudungun",
|
||||
"mar": "Marathi",
|
||||
"chm": "Mari (Russia)",
|
||||
"mah": "Marshallese",
|
||||
"mwr": "Marwari",
|
||||
"mas": "Masai",
|
||||
"men": "Mende (Sierra Leone)",
|
||||
"mic": "Mi'kmaq",
|
||||
"min": "Minangkabau",
|
||||
"mwl": "Mirandese",
|
||||
"moh": "Mohawk",
|
||||
"mdf": "Moksha",
|
||||
"lol": "Mongo",
|
||||
"mon": "المغولية",
|
||||
"mos": "Mossi",
|
||||
"mul": "Multiple languages",
|
||||
"nqo": "N'Ko",
|
||||
"nau": "Nauru",
|
||||
"nav": "Navajo",
|
||||
"ndo": "Ndonga",
|
||||
"nap": "Neapolitan",
|
||||
"nia": "Nias",
|
||||
"niu": "Niuean",
|
||||
"zxx": "No linguistic content",
|
||||
"nog": "Nogai",
|
||||
"nor": "النرويجية",
|
||||
"nob": "Norwegian Bokmål",
|
||||
"nno": "Norwegian Nynorsk",
|
||||
"nym": "Nyamwezi",
|
||||
"nya": "Nyanja",
|
||||
"nyn": "Nyankole",
|
||||
"nyo": "Nyoro",
|
||||
"nzi": "Nzima",
|
||||
"oci": "Occitan (post 1500)",
|
||||
"oji": "Ojibwa",
|
||||
"orm": "Oromo",
|
||||
"osa": "Osage",
|
||||
"oss": "Ossetian",
|
||||
"pal": "Pahlavi",
|
||||
"pau": "Palauan",
|
||||
"pli": "Pali",
|
||||
"pam": "Pampanga",
|
||||
"pag": "Pangasinan",
|
||||
"pan": "Panjabi",
|
||||
"pap": "Papiamento",
|
||||
"fas": "الفارسي",
|
||||
"phn": "الفينيقية",
|
||||
"pon": "Pohnpeian",
|
||||
"pol": "البولندية",
|
||||
"por": "البرتغالية",
|
||||
"pus": "Pashto",
|
||||
"que": "Quechua",
|
||||
"raj": "Rajasthani",
|
||||
"rap": "Rapanui",
|
||||
"ron": "الرومانية",
|
||||
"roh": "Romansh",
|
||||
"rom": "Romany",
|
||||
"run": "Rundi",
|
||||
"rus": "الروسية",
|
||||
"smo": "Samoan",
|
||||
"sad": "Sandawe",
|
||||
"sag": "Sango",
|
||||
"san": "Sanskrit",
|
||||
"sat": "Santali",
|
||||
"srd": "Sardinian",
|
||||
"sas": "Sasak",
|
||||
"sco": "Scots",
|
||||
"sel": "Selkup",
|
||||
"srp": "الصربية",
|
||||
"srr": "Serer",
|
||||
"shn": "Shan",
|
||||
"sna": "Shona",
|
||||
"scn": "Sicilian",
|
||||
"sid": "Sidamo",
|
||||
"bla": "Siksika",
|
||||
"snd": "Sindhi",
|
||||
"sin": "السينهالا",
|
||||
"den": "Slave (Athapascan)",
|
||||
"slk": "السلوفاكية",
|
||||
"slv": "السلوفينية",
|
||||
"sog": "Sogdian",
|
||||
"som": "Somali",
|
||||
"snk": "Soninke",
|
||||
"spa": "الأسبانية",
|
||||
"srn": "Sranan Tongo",
|
||||
"suk": "Sukuma",
|
||||
"sux": "Sumerian",
|
||||
"sun": "السوندية",
|
||||
"sus": "Susu",
|
||||
"swa": "Swahili (macrolanguage)",
|
||||
"ssw": "Swati",
|
||||
"swe": "السويدية",
|
||||
"syr": "السريانية",
|
||||
"tgl": "التاغالوغية",
|
||||
"tah": "Tahitian",
|
||||
"tgk": "Tajik",
|
||||
"tmh": "Tamashek",
|
||||
"tam": "التاميلية",
|
||||
"tat": "Tatar",
|
||||
"tel": "التيلوغو",
|
||||
"ter": "Tereno",
|
||||
"tet": "Tetum",
|
||||
"tha": "التايلاندية",
|
||||
"bod": "التبتية",
|
||||
"tig": "Tigre",
|
||||
"tir": "Tigrinya",
|
||||
"tem": "Timne",
|
||||
"tiv": "Tiv",
|
||||
"tli": "Tlingit",
|
||||
"tpi": "Tok Pisin",
|
||||
"tkl": "Tokelau",
|
||||
"tog": "Tonga (Nyasa)",
|
||||
"ton": "Tonga (Tonga Islands)",
|
||||
"tsi": "Tsimshian",
|
||||
"tso": "Tsonga",
|
||||
"tsn": "Tswana",
|
||||
"tum": "Tumbuka",
|
||||
"tur": "التركية",
|
||||
"tuk": "Turkmen",
|
||||
"tvl": "Tuvalu",
|
||||
"tyv": "Tuvinian",
|
||||
"twi": "Twi",
|
||||
"udm": "Udmurt",
|
||||
"uga": "الأجاريتيكية",
|
||||
"uig": "الاغورية",
|
||||
"ukr": "Ukrainian",
|
||||
"umb": "Umbundu",
|
||||
"mis": "Uncoded languages",
|
||||
"und": "Undetermined",
|
||||
"urd": "الاردية",
|
||||
"uzb": "Uzbek",
|
||||
"vai": "الفاي",
|
||||
"ven": "Venda",
|
||||
"vie": "الفييتنامية",
|
||||
"vol": "Volapük",
|
||||
"vot": "Votic",
|
||||
"wln": "الوالون",
|
||||
"war": "Waray (Philippines)",
|
||||
"was": "Washo",
|
||||
"cym": "الويلزية",
|
||||
"wal": "Wolaytta",
|
||||
"wol": "Wolof",
|
||||
"xho": "الهاوسا",
|
||||
"sah": "Yakut",
|
||||
"yao": "Yao",
|
||||
"yap": "Yapese",
|
||||
"yid": "Yiddish",
|
||||
"yor": "Yoruba",
|
||||
"zap": "Zapotec",
|
||||
"zza": "Zaza",
|
||||
"zen": "Zenaga",
|
||||
"zha": "Zhuang",
|
||||
"zul": "الزولو",
|
||||
"zun": "Zuni"
|
||||
},
|
||||
"cs": {
|
||||
"aar": "afarština",
|
||||
"abk": "abchazajština",
|
||||
@@ -8138,6 +8516,384 @@ LANGUAGE_NAMES = {
|
||||
"zul": "Zulu",
|
||||
"zun": "Zuni"
|
||||
},
|
||||
"sl": {
|
||||
"abk": "abhazijski",
|
||||
"ace": "achinese",
|
||||
"ach": "Acoli",
|
||||
"ada": "Adangme",
|
||||
"ady": "Adyghe",
|
||||
"aar": "afarski",
|
||||
"afh": "Afrihili",
|
||||
"afr": "afrikanski",
|
||||
"ain": "Ainu (Japan)",
|
||||
"aka": "Akan",
|
||||
"akk": "akadski",
|
||||
"sqi": "albanščina",
|
||||
"ale": "aleutski",
|
||||
"amh": "amharski",
|
||||
"anp": "Angika",
|
||||
"ara": "arabski",
|
||||
"arg": "aragonski",
|
||||
"arp": "Arapaho",
|
||||
"arw": "araukanski",
|
||||
"hye": "armenščina",
|
||||
"asm": "asamski",
|
||||
"ast": "Asturian",
|
||||
"ava": "avarski",
|
||||
"ave": "avestijski jeziki",
|
||||
"awa": "Awadhi",
|
||||
"aym": "Aymara",
|
||||
"aze": "azerbajdžanski",
|
||||
"ban": "balijščina",
|
||||
"bal": "belučijski",
|
||||
"bam": "bambarski",
|
||||
"bas": "Basa (Cameroon)",
|
||||
"bak": "baškirski",
|
||||
"eus": "baskovščina",
|
||||
"bej": "Beja",
|
||||
"bel": "beloruščina",
|
||||
"bem": "Bemba (Zambia)",
|
||||
"ben": "bengalščina",
|
||||
"bit": "Berinomo",
|
||||
"bho": "Bhojpuri",
|
||||
"bik": "bikolščina",
|
||||
"byn": "Bilin",
|
||||
"bin": "Bini",
|
||||
"bis": "bislama",
|
||||
"zbl": "Blissymbols",
|
||||
"bos": "bošnjaščina",
|
||||
"bra": "Braj",
|
||||
"bre": "bretonščina",
|
||||
"bug": "buginščina",
|
||||
"bul": "bolgarščina",
|
||||
"bua": "burjatščina",
|
||||
"mya": "burmanščina",
|
||||
"cad": "kadajščina?",
|
||||
"cat": "katalonščina",
|
||||
"ceb": "cebuanščina",
|
||||
"chg": "Chagatai",
|
||||
"cha": "čamorščina",
|
||||
"che": "čečenščina",
|
||||
"chr": "čerokeščina",
|
||||
"chy": "čejenščina",
|
||||
"chb": "čibčevščina",
|
||||
"zho": "kitajščina",
|
||||
"chn": "Chinook jargon",
|
||||
"chp": "čipevščina",
|
||||
"cho": "Choctaw",
|
||||
"cht": "Cholón",
|
||||
"chk": "Chuukese",
|
||||
"chv": "čuvaščina",
|
||||
"cop": "koptščina",
|
||||
"cor": "kornijščina",
|
||||
"cos": "korzijščina",
|
||||
"cre": "krijščina",
|
||||
"mus": "Creek",
|
||||
"hrv": "hrvaščina",
|
||||
"ces": "češčina",
|
||||
"dak": "Dakota",
|
||||
"dan": "danski",
|
||||
"dar": "Dargwa",
|
||||
"del": "Delaware",
|
||||
"div": "Dhivehi",
|
||||
"din": "Dinka",
|
||||
"doi": "Dogri (macrolanguage)",
|
||||
"dgr": "Dogrib",
|
||||
"dua": "Duala",
|
||||
"nld": "nizozemščina",
|
||||
"dse": "Dutch Sign Language",
|
||||
"dyu": "Dyula",
|
||||
"dzo": "dzongkha",
|
||||
"efi": "Efik",
|
||||
"egy": "egipčanski",
|
||||
"eka": "Ekajuk",
|
||||
"elx": "elamščina",
|
||||
"eng": "angleščina",
|
||||
"enu": "Enu",
|
||||
"myv": "Erzya",
|
||||
"epo": "esperanto",
|
||||
"est": "estonščina",
|
||||
"ewe": "evenščina",
|
||||
"ewo": "Ewondo",
|
||||
"fan": "Fang (Equatorial Guinea)",
|
||||
"fat": "Fanti",
|
||||
"fao": "ferščina",
|
||||
"fij": "fidžijščina",
|
||||
"fil": "Filipino",
|
||||
"fin": "finščina",
|
||||
"fon": "Fon",
|
||||
"fra": "francoščina",
|
||||
"fur": "furlanščina",
|
||||
"ful": "fulščina",
|
||||
"gaa": "Ga",
|
||||
"glg": "Galician",
|
||||
"lug": "Ganda",
|
||||
"gay": "gajščina?",
|
||||
"gba": "Gbaya (Central African Republic)",
|
||||
"hmj": "Ge",
|
||||
"gez": "etiopščina?",
|
||||
"kat": "gruzinščina",
|
||||
"deu": "nemški",
|
||||
"gil": "gilbertščina",
|
||||
"gon": "Gondi",
|
||||
"gor": "Gorontalo",
|
||||
"got": "gotščina",
|
||||
"grb": "Grebo",
|
||||
"grn": "gvaranijščina",
|
||||
"guj": "gudžaratščina",
|
||||
"gwi": "Gwichʼin",
|
||||
"hai": "haidščina",
|
||||
"hau": "havščina",
|
||||
"haw": "havajščina",
|
||||
"heb": "hebrejščina",
|
||||
"her": "Herero",
|
||||
"hil": "hilingajnonščina",
|
||||
"hin": "hindijščina",
|
||||
"hmo": "hiri motu",
|
||||
"hit": "hetitščina",
|
||||
"hmn": "hmonščina; miaojščina",
|
||||
"hun": "madžarščina",
|
||||
"hup": "hupščina",
|
||||
"iba": "ibanščina",
|
||||
"isl": "islandščina",
|
||||
"ido": "Ido",
|
||||
"ibo": "Igbo",
|
||||
"ilo": "Iloko",
|
||||
"ind": "indonezijščina",
|
||||
"inh": "inguščina",
|
||||
"ina": "interlingva",
|
||||
"ile": "Interlingue",
|
||||
"iku": "inuktituščina",
|
||||
"ipk": "Inupiaq",
|
||||
"gle": "irščina",
|
||||
"ita": "italijanščina",
|
||||
"jpn": "japonščina",
|
||||
"jav": "javanščina",
|
||||
"jrb": "Judeo-Arabic",
|
||||
"jpr": "Judeo-Persian",
|
||||
"kbd": "kabardinščina",
|
||||
"kab": "Kabyle",
|
||||
"kac": "Kachin",
|
||||
"kal": "Kalaallisut",
|
||||
"xal": "Kalmyk",
|
||||
"kam": "Kamba (Kenya)",
|
||||
"kan": "kanareščina",
|
||||
"kau": "Kanuri",
|
||||
"kaa": "Kara-Kalpak",
|
||||
"krc": "Karachay-Balkar",
|
||||
"krl": "Karelian",
|
||||
"kas": "kašmirščina",
|
||||
"csb": "Kashubian",
|
||||
"kaw": "kavi",
|
||||
"kaz": "kazaščina",
|
||||
"kha": "Khasi",
|
||||
"kho": "Khotanese",
|
||||
"kik": "kikujščina",
|
||||
"kmb": "Kimbundu",
|
||||
"kin": "Kinyarwanda",
|
||||
"kir": "kirgiščina",
|
||||
"tlh": "Klingon",
|
||||
"kom": "komijščina",
|
||||
"kon": "Kongo",
|
||||
"kok": "Konkani (macrolanguage)",
|
||||
"kor": "korejščina",
|
||||
"kos": "Kosraean",
|
||||
"kpe": "Kpelle",
|
||||
"kua": "Kuanyama",
|
||||
"kum": "kumiščina",
|
||||
"kur": "kurdščina",
|
||||
"kru": "Kurukh",
|
||||
"kut": "kutenajščina",
|
||||
"lad": "ladinščina",
|
||||
"lah": "Lahnda",
|
||||
"lam": "Lamba",
|
||||
"lao": "laoščina",
|
||||
"lat": "latinščina",
|
||||
"lav": "latvijščina",
|
||||
"lez": "lezginščina",
|
||||
"lim": "Limburgan",
|
||||
"lin": "lingala",
|
||||
"lit": "litvanščina",
|
||||
"jbo": "Lojban",
|
||||
"loz": "Lozi",
|
||||
"lub": "Luba-Katanga",
|
||||
"lua": "lubalulujščina",
|
||||
"lui": "Luiseno",
|
||||
"smj": "Lule Sami",
|
||||
"lun": "Lunda",
|
||||
"luo": "Luo (Kenya and Tanzania)",
|
||||
"lus": "Lushai",
|
||||
"ltz": "Luxembourgish",
|
||||
"mkd": "makedonščina",
|
||||
"mad": "madurščina",
|
||||
"mag": "Magahi",
|
||||
"mai": "Maithili",
|
||||
"mak": "makasarščina",
|
||||
"mlg": "malgaščina",
|
||||
"msa": "Malay (macrolanguage)",
|
||||
"mal": "malajalščina",
|
||||
"mlt": "malteščina",
|
||||
"mnc": "Manchu",
|
||||
"mdr": "Mandar",
|
||||
"man": "Mandingo",
|
||||
"mni": "manipurščina",
|
||||
"glv": "manska gelščina",
|
||||
"mri": "maorščina",
|
||||
"arn": "Mapudungun",
|
||||
"mar": "maratščina",
|
||||
"chm": "Mari (Russia)",
|
||||
"mah": "Marshallese",
|
||||
"mwr": "Marwari",
|
||||
"mas": "masajščina",
|
||||
"men": "Mende (Sierra Leone)",
|
||||
"mic": "Mi'kmaq",
|
||||
"min": "Minangkabau",
|
||||
"mwl": "Mirandese",
|
||||
"moh": "mohoščina",
|
||||
"mdf": "Moksha",
|
||||
"lol": "Mongo",
|
||||
"mon": "mongolščina",
|
||||
"mos": "mosanščina",
|
||||
"mul": "Več jezikov",
|
||||
"nqo": "N'Ko",
|
||||
"nau": "Nauru",
|
||||
"nav": "navaščina",
|
||||
"ndo": "Ndonga",
|
||||
"nap": "napolitanščina",
|
||||
"nia": "niaščina",
|
||||
"niu": "niuejščina",
|
||||
"zxx": "No linguistic content",
|
||||
"nog": "Nogai",
|
||||
"nor": "norveščina",
|
||||
"nob": "Norwegian Bokmål",
|
||||
"nno": "norveščina; nynorsk",
|
||||
"nym": "Nyamwezi",
|
||||
"nya": "Nyanja",
|
||||
"nyn": "Nyankole",
|
||||
"nyo": "Nyoro",
|
||||
"nzi": "Nzima",
|
||||
"oci": "Occitan (post 1500)",
|
||||
"oji": "Ojibwa",
|
||||
"orm": "Oromo",
|
||||
"osa": "Osage",
|
||||
"oss": "Ossetian",
|
||||
"pal": "Pahlavi",
|
||||
"pau": "palavanščina",
|
||||
"pli": "Pali",
|
||||
"pam": "Pampanga",
|
||||
"pag": "pangasinanščina",
|
||||
"pan": "Panjabi",
|
||||
"pap": "papiamentu",
|
||||
"fas": "perzijščina",
|
||||
"phn": "feničanščina",
|
||||
"pon": "Pohnpeian",
|
||||
"pol": "poljščina",
|
||||
"por": "portugalđščina",
|
||||
"pus": "paštu",
|
||||
"que": "Quechua",
|
||||
"raj": "radžastanščina",
|
||||
"rap": "rapanujščina",
|
||||
"ron": "romunščina",
|
||||
"roh": "Romansh",
|
||||
"rom": "romščina",
|
||||
"run": "rundščina",
|
||||
"rus": "ruščina",
|
||||
"smo": "samoanščina",
|
||||
"sad": "Sandawe",
|
||||
"sag": "Sango",
|
||||
"san": "sanskrt",
|
||||
"sat": "santalščina",
|
||||
"srd": "sardinščina",
|
||||
"sas": "Sasak",
|
||||
"sco": "škotščina",
|
||||
"sel": "selkupščina",
|
||||
"srp": "srbščina",
|
||||
"srr": "Serer",
|
||||
"shn": "šanščina",
|
||||
"sna": "šonščina",
|
||||
"scn": "sicilijanščina",
|
||||
"sid": "Sidamo",
|
||||
"bla": "Siksika",
|
||||
"snd": "sindščina",
|
||||
"sin": "Sinhala",
|
||||
"den": "Slave (Athapascan)",
|
||||
"slk": "slovaščina",
|
||||
"slv": "slovenščina",
|
||||
"sog": "Sogdian",
|
||||
"som": "Somali",
|
||||
"snk": "Soninke",
|
||||
"spa": "španščina",
|
||||
"srn": "Sranan Tongo",
|
||||
"suk": "Sukuma",
|
||||
"sux": "sumerščina",
|
||||
"sun": "sundščina",
|
||||
"sus": "susuamijščina?",
|
||||
"swa": "Swahili (macrolanguage)",
|
||||
"ssw": "svazijščina?",
|
||||
"swe": "švedščina",
|
||||
"syr": "sirščina",
|
||||
"tgl": "tagaloščina",
|
||||
"tah": "tahitijščina",
|
||||
"tgk": "tadžiščina",
|
||||
"tmh": "Tamashek",
|
||||
"tam": "tamilščina",
|
||||
"tat": "tatarščina",
|
||||
"tel": "Telugu",
|
||||
"ter": "Tereno",
|
||||
"tet": "Tetum",
|
||||
"tha": "tajščina",
|
||||
"bod": "tibetanščina",
|
||||
"tig": "Tigre",
|
||||
"tir": "Tigrinya",
|
||||
"tem": "Timne",
|
||||
"tiv": "Tiv",
|
||||
"tli": "Tlingit",
|
||||
"tpi": "tok pisin",
|
||||
"tkl": "Tokelau",
|
||||
"tog": "Tonga (Nyasa)",
|
||||
"ton": "tonganščina",
|
||||
"tsi": "tsimšijščina",
|
||||
"tso": "Tsonga",
|
||||
"tsn": "Tswana",
|
||||
"tum": "Tumbuka",
|
||||
"tur": "turščina",
|
||||
"tuk": "turkmenščina",
|
||||
"tvl": "tuvalujščina",
|
||||
"tyv": "Tuvinian",
|
||||
"twi": "Twi",
|
||||
"udm": "Udmurt",
|
||||
"uga": "ugaritščina",
|
||||
"uig": "ujgurščina",
|
||||
"ukr": "ukrajinščina",
|
||||
"umb": "Umbundu",
|
||||
"mis": "Uncoded languages",
|
||||
"und": "nedoločen",
|
||||
"urd": "urdujščina",
|
||||
"uzb": "uzbeščina",
|
||||
"vai": "vajščina",
|
||||
"ven": "Venda",
|
||||
"vie": "vietnamščina",
|
||||
"vol": "Volapük",
|
||||
"vot": "votjaščina",
|
||||
"wln": "valonščina",
|
||||
"war": "Waray (Philippines)",
|
||||
"was": "Washo",
|
||||
"cym": "valižanščina",
|
||||
"wal": "Wolaytta",
|
||||
"wol": "Wolof",
|
||||
"xho": "koščina",
|
||||
"sah": "jakutščina",
|
||||
"yao": "jaojščina",
|
||||
"yap": "Yapese",
|
||||
"yid": "jidiš",
|
||||
"yor": "jorubščina",
|
||||
"zap": "Zapotec",
|
||||
"zza": "Zaza",
|
||||
"zen": "Zenaga",
|
||||
"zha": "Zhuang",
|
||||
"zul": "zulujščina",
|
||||
"zun": "Zuni"
|
||||
},
|
||||
"sv": {
|
||||
"aar": "Afar",
|
||||
"abk": "Abchaziska",
|
||||
|
||||
+26
-18
@@ -27,10 +27,10 @@ import datetime
|
||||
import mimetypes
|
||||
from uuid import uuid4
|
||||
|
||||
# from babel.dates import format_date
|
||||
from flask import Blueprint, request, url_for
|
||||
from flask import Blueprint, request, url_for, g
|
||||
from flask_babel import format_date
|
||||
from flask_login import current_user
|
||||
from .cw_login import current_user
|
||||
from .clean_html import clean_string as html_clean_string
|
||||
|
||||
from . import constants, logger
|
||||
|
||||
@@ -44,6 +44,8 @@ def url_for_other_page(page):
|
||||
args = request.view_args.copy()
|
||||
args['page'] = page
|
||||
for get, val in request.args.items():
|
||||
if get == "page":
|
||||
continue
|
||||
args[get] = val
|
||||
return url_for(request.endpoint, **args)
|
||||
|
||||
@@ -112,21 +114,12 @@ def yesno(value, yes, no):
|
||||
|
||||
@jinjia.app_template_filter('formatfloat')
|
||||
def formatfloat(value, decimals=1):
|
||||
value = 0 if not value else value
|
||||
return ('{0:.' + str(decimals) + 'f}').format(value).rstrip('0').rstrip('.')
|
||||
|
||||
|
||||
@jinjia.app_template_filter('formatseriesindex')
|
||||
def formatseriesindex_filter(series_index):
|
||||
if series_index:
|
||||
try:
|
||||
if int(series_index) - series_index == 0:
|
||||
return int(series_index)
|
||||
else:
|
||||
return series_index
|
||||
except (ValueError, TypeError):
|
||||
return series_index
|
||||
return 0
|
||||
if not value or (isinstance(value, str) and not value.is_numeric()):
|
||||
return value
|
||||
formated_value = ('{0:.' + str(decimals) + 'f}').format(value)
|
||||
if formated_value.endswith('.' + "0" * decimals):
|
||||
formated_value = formated_value.rstrip('0').rstrip('.')
|
||||
return formated_value
|
||||
|
||||
|
||||
@jinjia.app_template_filter('escapedlink')
|
||||
@@ -180,3 +173,18 @@ def get_cover_srcset(series):
|
||||
url = url_for('web.get_series_cover', series_id=series.id, resolution=shortname, c=cache_timestamp())
|
||||
srcset.append(f'{url} {resolution}x')
|
||||
return ', '.join(srcset)
|
||||
|
||||
|
||||
@jinjia.app_template_filter('music')
|
||||
def contains_music(book_formats):
|
||||
result = False
|
||||
for format in book_formats:
|
||||
if format.format.lower() in g.constants.EXTENSIONS_AUDIO:
|
||||
result = True
|
||||
return result
|
||||
|
||||
@jinjia.app_template_filter('clean_string')
|
||||
def clean_string(unsafe_text):
|
||||
return html_clean_string(unsafe_text)
|
||||
|
||||
|
||||
|
||||
+172
-95
@@ -18,13 +18,14 @@
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import base64
|
||||
import datetime
|
||||
from datetime import datetime, timezone
|
||||
import os
|
||||
import uuid
|
||||
import zipfile
|
||||
from time import gmtime, strftime
|
||||
import json
|
||||
from urllib.parse import unquote
|
||||
import requests
|
||||
|
||||
from flask import (
|
||||
Blueprint,
|
||||
@@ -36,19 +37,16 @@ from flask import (
|
||||
redirect,
|
||||
abort
|
||||
)
|
||||
from flask_login import current_user
|
||||
from .cw_login import current_user
|
||||
from werkzeug.datastructures import Headers
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.sql.expression import and_, or_
|
||||
from sqlalchemy.exc import StatementError
|
||||
from sqlalchemy.sql import select
|
||||
import requests
|
||||
|
||||
|
||||
from . import config, logger, kobo_auth, db, calibre_db, helper, shelf as shelf_lib, ub, csrf, kobo_sync_status
|
||||
from . import isoLanguages
|
||||
from . import isoLanguages, limiter
|
||||
from .epub import get_epub_layout
|
||||
from .constants import COVER_THUMBNAIL_SMALL
|
||||
from .constants import COVER_THUMBNAIL_SMALL, COVER_THUMBNAIL_MEDIUM, COVER_THUMBNAIL_LARGE, BASE_DIR
|
||||
from .helper import get_download_link
|
||||
from .services import SyncToken as SyncToken
|
||||
from .web import download_required
|
||||
@@ -107,24 +105,29 @@ def make_request_to_kobo_store(sync_token=None):
|
||||
return store_response
|
||||
|
||||
|
||||
def redirect_or_proxy_request():
|
||||
def redirect_or_proxy_request(auth=False):
|
||||
if config.config_kobo_proxy:
|
||||
if request.method == "GET":
|
||||
return redirect(get_store_url_for_current_request(), 307)
|
||||
else:
|
||||
# The Kobo device turns other request types into GET requests on redirects,
|
||||
# so we instead proxy to the Kobo store ourselves.
|
||||
store_response = make_request_to_kobo_store()
|
||||
try:
|
||||
if request.method == "GET":
|
||||
alfa = redirect(get_store_url_for_current_request(), 307)
|
||||
return alfa
|
||||
else:
|
||||
# The Kobo device turns other request types into GET requests on redirects,
|
||||
# so we instead proxy to the Kobo store ourselves.
|
||||
store_response = make_request_to_kobo_store()
|
||||
|
||||
response_headers = store_response.headers
|
||||
for header_key in CONNECTION_SPECIFIC_HEADERS:
|
||||
response_headers.pop(header_key, default=None)
|
||||
response_headers = store_response.headers
|
||||
for header_key in CONNECTION_SPECIFIC_HEADERS:
|
||||
response_headers.pop(header_key, default=None)
|
||||
|
||||
return make_response(
|
||||
store_response.content, store_response.status_code, response_headers.items()
|
||||
)
|
||||
else:
|
||||
return make_response(jsonify({}))
|
||||
return make_response(
|
||||
store_response.content, store_response.status_code, response_headers.items()
|
||||
)
|
||||
except Exception as e:
|
||||
log.error("Failed to receive or parse response from Kobo's endpoint: {}".format(e))
|
||||
if auth:
|
||||
return make_calibre_web_auth_response()
|
||||
return make_response(jsonify({}))
|
||||
|
||||
|
||||
def convert_to_kobo_timestamp_string(timestamp):
|
||||
@@ -132,12 +135,11 @@ def convert_to_kobo_timestamp_string(timestamp):
|
||||
return timestamp.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
except AttributeError as exc:
|
||||
log.debug("Timestamp not valid: {}".format(exc))
|
||||
return datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
@kobo.route("/v1/library/sync")
|
||||
@requires_kobo_auth
|
||||
# @download_required
|
||||
def HandleSyncRequest():
|
||||
if not current_user.role_download():
|
||||
log.info("Users need download permissions for syncing library to Kobo reader")
|
||||
@@ -151,15 +153,15 @@ def HandleSyncRequest():
|
||||
|
||||
# if no books synced don't respect sync_token
|
||||
if not ub.session.query(ub.KoboSyncedBooks).filter(ub.KoboSyncedBooks.user_id == current_user.id).count():
|
||||
sync_token.books_last_modified = datetime.datetime.min
|
||||
sync_token.books_last_created = datetime.datetime.min
|
||||
sync_token.reading_state_last_modified = datetime.datetime.min
|
||||
sync_token.books_last_modified = datetime.min
|
||||
sync_token.books_last_created = datetime.min
|
||||
sync_token.reading_state_last_modified = datetime.min
|
||||
|
||||
new_books_last_modified = sync_token.books_last_modified # needed for sync selected shelfs only
|
||||
new_books_last_created = sync_token.books_last_created # needed to distinguish between new and changed entitlement
|
||||
new_reading_state_last_modified = sync_token.reading_state_last_modified
|
||||
|
||||
new_archived_last_modified = datetime.datetime.min
|
||||
new_archived_last_modified = datetime.min
|
||||
sync_results = []
|
||||
|
||||
# We reload the book database so that the user gets a fresh view of the library
|
||||
@@ -324,7 +326,7 @@ def generate_sync_response(sync_token, sync_results, set_cont=False):
|
||||
sync_token.to_headers(extra_headers)
|
||||
|
||||
# log.debug("Kobo Sync Content: {}".format(sync_results))
|
||||
# jsonify decodes the unicode string different to what kobo expects
|
||||
# jsonify decodes the Unicode string different to what kobo expects
|
||||
response = make_response(json.dumps(sync_results), extra_headers)
|
||||
response.headers["Content-Type"] = "application/json; charset=utf-8"
|
||||
return response
|
||||
@@ -365,7 +367,7 @@ def get_download_url_for_book(book_id, book_format):
|
||||
)
|
||||
return url_for(
|
||||
"kobo.download_book",
|
||||
auth_token=kobo_auth.get_auth_token(),
|
||||
auth_token=get_auth_token(),
|
||||
book_id=book_id,
|
||||
book_format=book_format.lower(),
|
||||
_external=True,
|
||||
@@ -376,7 +378,7 @@ def create_book_entitlement(book, archived):
|
||||
book_uuid = str(book.uuid)
|
||||
return {
|
||||
"Accessibility": "Full",
|
||||
"ActivePeriod": {"From": convert_to_kobo_timestamp_string(datetime.datetime.utcnow())},
|
||||
"ActivePeriod": {"From": convert_to_kobo_timestamp_string(datetime.now(timezone.utc))},
|
||||
"Created": convert_to_kobo_timestamp_string(book.timestamp),
|
||||
"CrossRevisionId": book_uuid,
|
||||
"Id": book_uuid,
|
||||
@@ -424,7 +426,7 @@ def get_series(book):
|
||||
|
||||
|
||||
def get_seriesindex(book):
|
||||
return book.series_index or 1
|
||||
return book.series_index if isinstance(book.series_index, float) else 1
|
||||
|
||||
|
||||
def get_language(book):
|
||||
@@ -487,17 +489,20 @@ def get_metadata(book):
|
||||
|
||||
if get_series(book):
|
||||
name = get_series(book)
|
||||
metadata["Series"] = {
|
||||
"Name": get_series(book),
|
||||
"Number": get_seriesindex(book), # ToDo Check int() ?
|
||||
"NumberFloat": float(get_seriesindex(book)),
|
||||
# Get a deterministic id based on the series name.
|
||||
"Id": str(uuid.uuid3(uuid.NAMESPACE_DNS, name)),
|
||||
}
|
||||
|
||||
try:
|
||||
metadata["Series"] = {
|
||||
"Name": get_series(book),
|
||||
"Number": get_seriesindex(book), # ToDo Check int() ?
|
||||
"NumberFloat": float(get_seriesindex(book)),
|
||||
# Get a deterministic id based on the series name.
|
||||
"Id": str(uuid.uuid3(uuid.NAMESPACE_DNS, name)),
|
||||
}
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return metadata
|
||||
|
||||
|
||||
|
||||
@csrf.exempt
|
||||
@kobo.route("/v1/library/tags", methods=["POST", "DELETE"])
|
||||
@requires_kobo_auth
|
||||
@@ -726,7 +731,7 @@ def sync_shelves(sync_token, sync_results, only_kobo_shelves=False):
|
||||
ub.session_commit()
|
||||
|
||||
|
||||
# Creates a Kobo "Tag" object from a ub.Shelf object
|
||||
# Creates a Kobo "Tag" object from an ub.Shelf object
|
||||
def create_kobo_tag(shelf):
|
||||
tag = {
|
||||
"Created": convert_to_kobo_timestamp_string(shelf.created),
|
||||
@@ -796,7 +801,7 @@ def HandleStateRequest(book_uuid):
|
||||
if new_book_read_status == ub.ReadBook.STATUS_IN_PROGRESS \
|
||||
and new_book_read_status != book_read.read_status:
|
||||
book_read.times_started_reading += 1
|
||||
book_read.last_time_started_reading = datetime.datetime.utcnow()
|
||||
book_read.last_time_started_reading = datetime.now(timezone.utc)
|
||||
book_read.read_status = new_book_read_status
|
||||
update_results_response["StatusInfoResult"] = {"Result": "Success"}
|
||||
except (KeyError, TypeError, ValueError, StatementError):
|
||||
@@ -806,6 +811,8 @@ def HandleStateRequest(book_uuid):
|
||||
|
||||
ub.session.merge(kobo_reading_state)
|
||||
ub.session_commit()
|
||||
update_results_response["LastModified"] = convert_to_kobo_timestamp_string(kobo_reading_state.last_modified)
|
||||
update_results_response["PriorityTimestamp"] = convert_to_kobo_timestamp_string(kobo_reading_state.priority_timestamp)
|
||||
return jsonify({
|
||||
"RequestResult": "Success",
|
||||
"UpdateResults": [update_results_response],
|
||||
@@ -882,14 +889,21 @@ def get_statistics_response(statistics):
|
||||
return resp
|
||||
|
||||
|
||||
def _clean_progress(value):
|
||||
"""Return progress as int if it's a whole number, preserving Kobo device expectations."""
|
||||
if value is not None and value == int(value):
|
||||
return int(value)
|
||||
return value
|
||||
|
||||
|
||||
def get_current_bookmark_response(current_bookmark):
|
||||
resp = {
|
||||
"LastModified": convert_to_kobo_timestamp_string(current_bookmark.last_modified),
|
||||
}
|
||||
if current_bookmark.progress_percent:
|
||||
resp["ProgressPercent"] = current_bookmark.progress_percent
|
||||
if current_bookmark.content_source_progress_percent:
|
||||
resp["ContentSourceProgressPercent"] = current_bookmark.content_source_progress_percent
|
||||
if current_bookmark.progress_percent is not None:
|
||||
resp["ProgressPercent"] = _clean_progress(current_bookmark.progress_percent)
|
||||
if current_bookmark.content_source_progress_percent is not None:
|
||||
resp["ContentSourceProgressPercent"] = _clean_progress(current_bookmark.content_source_progress_percent)
|
||||
if current_bookmark.location_value:
|
||||
resp["Location"] = {
|
||||
"Value": current_bookmark.location_value,
|
||||
@@ -904,7 +918,12 @@ def get_current_bookmark_response(current_bookmark):
|
||||
@requires_kobo_auth
|
||||
def HandleCoverImageRequest(book_uuid, width, height, Quality, isGreyscale):
|
||||
try:
|
||||
resolution = None if int(height) > 1000 else COVER_THUMBNAIL_SMALL
|
||||
if int(height) > 1000:
|
||||
resolution = COVER_THUMBNAIL_LARGE
|
||||
elif int(height) > 500:
|
||||
resolution = COVER_THUMBNAIL_MEDIUM
|
||||
else:
|
||||
resolution = COVER_THUMBNAIL_SMALL
|
||||
except ValueError:
|
||||
log.error("Requested height %s of book %s is invalid" % (book_uuid, height))
|
||||
resolution = COVER_THUMBNAIL_SMALL
|
||||
@@ -949,8 +968,10 @@ def HandleBookDeletionRequest(book_uuid):
|
||||
|
||||
# TODO: Implement the following routes
|
||||
@csrf.exempt
|
||||
@kobo.route("/v1/library/<dummy>", methods=["DELETE", "GET"])
|
||||
@kobo.route("/v1/library/<dummy>", methods=["DELETE", "GET", "POST"])
|
||||
@kobo.route("/v1/library/<dummy>/preview", methods=["POST"])
|
||||
def HandleUnimplementedRequest(dummy=None):
|
||||
[limiter.limiter.clear(limit.limit, *limit.request_args) for limit in limiter.current_limits]
|
||||
log.debug("Unimplemented Library Request received: %s (request is forwarded to kobo if configured)",
|
||||
request.base_url)
|
||||
return redirect_or_proxy_request()
|
||||
@@ -965,6 +986,9 @@ def HandleUnimplementedRequest(dummy=None):
|
||||
@kobo.route("/v1/analytics/<dummy>", methods=["GET", "POST"])
|
||||
@kobo.route("/v1/assets", methods=["GET"])
|
||||
def HandleUserRequest(dummy=None):
|
||||
[limiter.limiter.clear(limit.limit, *limit.request_args) for limit in limiter.current_limits]
|
||||
log.error("Key: {}".format(limiter.current_limit.key))
|
||||
log.error("Remaining: {}".format(limiter.current_limit.remaining))
|
||||
log.debug("Unimplemented User Request received: %s (request is forwarded to kobo if configured)", request.base_url)
|
||||
return redirect_or_proxy_request()
|
||||
|
||||
@@ -972,6 +996,7 @@ def HandleUserRequest(dummy=None):
|
||||
@csrf.exempt
|
||||
@kobo.route("/v1/user/loyalty/benefits", methods=["GET"])
|
||||
def handle_benefits():
|
||||
[limiter.limiter.clear(limit.limit, *limit.request_args) for limit in limiter.current_limits]
|
||||
if config.config_kobo_proxy:
|
||||
return redirect_or_proxy_request()
|
||||
else:
|
||||
@@ -981,6 +1006,7 @@ def handle_benefits():
|
||||
@csrf.exempt
|
||||
@kobo.route("/v1/analytics/gettests", methods=["GET", "POST"])
|
||||
def handle_getests():
|
||||
[limiter.limiter.clear(limit.limit, *limit.request_args) for limit in limiter.current_limits]
|
||||
if config.config_kobo_proxy:
|
||||
return redirect_or_proxy_request()
|
||||
else:
|
||||
@@ -1002,9 +1028,12 @@ def handle_getests():
|
||||
@kobo.route("/v1/products/dailydeal", methods=["GET", "POST"])
|
||||
@kobo.route("/v1/products/deals", methods=["GET", "POST"])
|
||||
@kobo.route("/v1/products", methods=["GET", "POST"])
|
||||
@kobo.route("/v1/products/<path:dummy>", methods=["GET", "POST"])
|
||||
@kobo.route("/v1/products/<path:dummy>/", methods=["GET", "POST"])
|
||||
@kobo.route("/v1/affiliate", methods=["GET", "POST"])
|
||||
@kobo.route("/v1/deals", methods=["GET", "POST"])
|
||||
def HandleProductsRequest(dummy=None):
|
||||
[limiter.limiter.clear(limit.limit, *limit.request_args) for limit in limiter.current_limits]
|
||||
log.debug("Unimplemented Products Request received: %s (request is forwarded to kobo if configured)",
|
||||
request.base_url)
|
||||
return redirect_or_proxy_request()
|
||||
@@ -1030,13 +1059,16 @@ def make_calibre_web_auth_response():
|
||||
|
||||
|
||||
@csrf.exempt
|
||||
@kobo.route("/v1/auth/refresh", methods=["POST"])
|
||||
@kobo.route("/v1/auth/device", methods=["POST"])
|
||||
@requires_kobo_auth
|
||||
def HandleAuthRequest():
|
||||
log.error(limiter.current_limit)
|
||||
log.error(limiter.current_limit)
|
||||
log.debug('Kobo Auth request')
|
||||
if config.config_kobo_proxy:
|
||||
try:
|
||||
return redirect_or_proxy_request()
|
||||
return redirect_or_proxy_request(auth=True)
|
||||
except Exception:
|
||||
log.error("Failed to receive or parse response from Kobo's auth endpoint. Falling back to un-proxied mode.")
|
||||
return make_calibre_web_auth_response()
|
||||
@@ -1074,7 +1106,7 @@ def HandleInitRequest():
|
||||
kobo_resources["image_host"] = calibre_web_url
|
||||
kobo_resources["image_url_quality_template"] = unquote(calibre_web_url +
|
||||
url_for("kobo.HandleCoverImageRequest",
|
||||
auth_token=kobo_auth.get_auth_token(),
|
||||
auth_token=get_auth_token(),
|
||||
book_uuid="{ImageId}",
|
||||
width="{width}",
|
||||
height="{height}",
|
||||
@@ -1082,15 +1114,17 @@ def HandleInitRequest():
|
||||
isGreyscale='isGreyscale'))
|
||||
kobo_resources["image_url_template"] = unquote(calibre_web_url +
|
||||
url_for("kobo.HandleCoverImageRequest",
|
||||
auth_token=kobo_auth.get_auth_token(),
|
||||
auth_token=get_auth_token(),
|
||||
book_uuid="{ImageId}",
|
||||
width="{width}",
|
||||
height="{height}",
|
||||
isGreyscale='false'))
|
||||
kobo_resources["library_sync"] = calibre_web_url + url_for("kobo.HandleSyncRequest",
|
||||
auth_token=kobo_auth.get_auth_token())
|
||||
else:
|
||||
kobo_resources["image_host"] = url_for("web.index", _external=True).strip("/")
|
||||
kobo_resources["image_url_quality_template"] = unquote(url_for("kobo.HandleCoverImageRequest",
|
||||
auth_token=kobo_auth.get_auth_token(),
|
||||
auth_token=get_auth_token(),
|
||||
book_uuid="{ImageId}",
|
||||
width="{width}",
|
||||
height="{height}",
|
||||
@@ -1098,12 +1132,15 @@ def HandleInitRequest():
|
||||
isGreyscale='isGreyscale',
|
||||
_external=True))
|
||||
kobo_resources["image_url_template"] = unquote(url_for("kobo.HandleCoverImageRequest",
|
||||
auth_token=kobo_auth.get_auth_token(),
|
||||
auth_token=get_auth_token(),
|
||||
book_uuid="{ImageId}",
|
||||
width="{width}",
|
||||
height="{height}",
|
||||
isGreyscale='false',
|
||||
_external=True))
|
||||
kobo_resources["library_sync"] = url_for("kobo.HandleSyncRequest",
|
||||
auth_token=kobo_auth.get_auth_token(),
|
||||
_external=True)
|
||||
|
||||
response = make_response(jsonify({"Resources": kobo_resources}))
|
||||
response.headers["x-kobo-apitoken"] = "e30="
|
||||
@@ -1119,26 +1156,46 @@ def download_book(book_id, book_format):
|
||||
|
||||
|
||||
def NATIVE_KOBO_RESOURCES():
|
||||
kobo_file = os.path.join(BASE_DIR, "kobo_resources.txt")
|
||||
try:
|
||||
if os.path.isfile(kobo_file):
|
||||
with open(kobo_file, "r") as f:
|
||||
lines = f.read()
|
||||
return json.loads(lines)
|
||||
except Exception as e:
|
||||
log.error(e)
|
||||
return {
|
||||
"account_page": "https://secure.kobobooks.com/profile",
|
||||
"account_page": "https://www.kobo.com/account/settings",
|
||||
"account_page_rakuten": "https://my.rakuten.co.jp/",
|
||||
"add_device": "https://storeapi.kobo.com/v1/user/add-device",
|
||||
"add_entitlement": "https://storeapi.kobo.com/v1/library/{RevisionIds}",
|
||||
"affiliaterequest": "https://storeapi.kobo.com/v1/affiliate",
|
||||
"assets": "https://storeapi.kobo.com/v1/assets",
|
||||
"audiobook": "https://storeapi.kobo.com/v1/products/audiobooks/{ProductId}",
|
||||
"audiobook_detail_page": "https://www.kobo.com/{region}/{language}/audiobook/{slug}",
|
||||
"audiobook_landing_page": "https://www.kobo.com/{region}/{language}/audiobooks",
|
||||
"audiobook_preview": "https://storeapi.kobo.com/v1/products/audiobooks/{Id}/preview",
|
||||
"audiobook_purchase_withcredit": "https://storeapi.kobo.com/v1/store/audiobook/{Id}",
|
||||
"audiobook_subscription_orange_deal_inclusion_url": "https://authorize.kobo.com/inclusion",
|
||||
"authorproduct_recommendations": "https://storeapi.kobo.com/v1/products/books/authors/recommendations",
|
||||
"autocomplete": "https://storeapi.kobo.com/v1/products/autocomplete",
|
||||
"blackstone_header": {"key": "x-amz-request-payer", "value": "requester"},
|
||||
"blackstone_header": {
|
||||
"key": "x-amz-request-payer",
|
||||
"value": "requester"
|
||||
},
|
||||
"book": "https://storeapi.kobo.com/v1/products/books/{ProductId}",
|
||||
"book_detail_page": "https://store.kobobooks.com/{culture}/ebook/{slug}",
|
||||
"book_detail_page_rakuten": "https://books.rakuten.co.jp/rk/{crossrevisionid}",
|
||||
"book_landing_page": "https://store.kobobooks.com/ebooks",
|
||||
"book_detail_page": "https://www.kobo.com/{region}/{language}/ebook/{slug}",
|
||||
"book_detail_page_rakuten": "http://books.rakuten.co.jp/rk/{crossrevisionid}",
|
||||
"book_landing_page": "https://www.kobo.com/ebooks",
|
||||
"book_subscription": "https://storeapi.kobo.com/v1/products/books/subscriptions",
|
||||
"browse_history": "https://storeapi.kobo.com/v1/user/browsehistory",
|
||||
"categories": "https://storeapi.kobo.com/v1/categories",
|
||||
"categories_page": "https://store.kobobooks.com/ebooks/categories",
|
||||
"categories_page": "https://www.kobo.com/ebooks/categories",
|
||||
"category": "https://storeapi.kobo.com/v1/categories/{CategoryId}",
|
||||
"category_featured_lists": "https://storeapi.kobo.com/v1/categories/{CategoryId}/featured",
|
||||
"category_products": "https://storeapi.kobo.com/v1/categories/{CategoryId}/products",
|
||||
"checkout_borrowed_book": "https://storeapi.kobo.com/v1/library/borrow",
|
||||
"client_authd_referral": "https://authorize.kobo.com/api/AuthenticatedReferral/client/v1/getLink",
|
||||
"configuration_data": "https://storeapi.kobo.com/v1/configuration",
|
||||
"content_access_book": "https://storeapi.kobo.com/v1/products/books/{ProductId}/access",
|
||||
"customer_care_live_chat": "https://v2.zopim.com/widget/livechat.html?key=Y6gwUmnu4OATxN3Tli4Av9bYN319BTdO",
|
||||
@@ -1149,92 +1206,112 @@ def NATIVE_KOBO_RESOURCES():
|
||||
"delete_tag_items": "https://storeapi.kobo.com/v1/library/tags/{TagId}/items/delete",
|
||||
"device_auth": "https://storeapi.kobo.com/v1/auth/device",
|
||||
"device_refresh": "https://storeapi.kobo.com/v1/auth/refresh",
|
||||
"dictionary_host": "https://kbdownload1-a.akamaihd.net",
|
||||
"dictionary_host": "https://ereaderfiles.kobo.com",
|
||||
"discovery_host": "https://discovery.kobobooks.com",
|
||||
"ereaderdevices": "https://storeapi.kobo.com/v2/products/EReaderDeviceFeeds",
|
||||
"eula_page": "https://www.kobo.com/termsofuse?style=onestore",
|
||||
"exchange_auth": "https://storeapi.kobo.com/v1/auth/exchange",
|
||||
"external_book": "https://storeapi.kobo.com/v1/products/books/external/{Ids}",
|
||||
"facebook_sso_page":
|
||||
"https://authorize.kobo.com/signin/provider/Facebook/login?returnUrl=http://store.kobobooks.com/",
|
||||
"facebook_sso_page": "https://authorize.kobo.com/signin/provider/Facebook/login?returnUrl=http://kobo.com/",
|
||||
"featured_list": "https://storeapi.kobo.com/v1/products/featured/{FeaturedListId}",
|
||||
"featured_lists": "https://storeapi.kobo.com/v1/products/featured",
|
||||
"free_books_page": {
|
||||
"EN": "https://www.kobo.com/{region}/{language}/p/free-ebooks",
|
||||
"FR": "https://www.kobo.com/{region}/{language}/p/livres-gratuits",
|
||||
"IT": "https://www.kobo.com/{region}/{language}/p/libri-gratuiti",
|
||||
"NL": "https://www.kobo.com/{region}/{language}/"
|
||||
"List/bekijk-het-overzicht-van-gratis-ebooks/QpkkVWnUw8sxmgjSlCbJRg",
|
||||
"PT": "https://www.kobo.com/{region}/{language}/p/livros-gratis",
|
||||
"NL": "https://www.kobo.com/{region}/{language}/List/bekijk-het-overzicht-van-gratis-ebooks/QpkkVWnUw8sxmgjSlCbJRg",
|
||||
"PT": "https://www.kobo.com/{region}/{language}/p/livros-gratis"
|
||||
},
|
||||
"fte_feedback": "https://storeapi.kobo.com/v1/products/ftefeedback",
|
||||
"funnel_metrics": "https://storeapi.kobo.com/v1/funnelmetrics",
|
||||
"get_download_keys": "https://storeapi.kobo.com/v1/library/downloadkeys",
|
||||
"get_download_link": "https://storeapi.kobo.com/v1/library/downloadlink",
|
||||
"get_tests_request": "https://storeapi.kobo.com/v1/analytics/gettests",
|
||||
"giftcard_epd_redeem_url": "https://www.kobo.com/{storefront}/{language}/redeem-ereader",
|
||||
"giftcard_redeem_url": "https://www.kobo.com/{storefront}/{language}/redeem",
|
||||
"help_page": "https://www.kobo.com/help",
|
||||
"kobo_audiobooks_enabled": "False",
|
||||
"gpb_flow_enabled": "False",
|
||||
"help_page": "http://www.kobo.com/help",
|
||||
"image_host": "//cdn.kobo.com/book-images/",
|
||||
"image_url_quality_template": "https://cdn.kobo.com/book-images/{ImageId}/{Width}/{Height}/{Quality}/{IsGreyscale}/image.jpg",
|
||||
"image_url_template": "https://cdn.kobo.com/book-images/{ImageId}/{Width}/{Height}/false/image.jpg",
|
||||
"instapaper_enabled": "True",
|
||||
"instapaper_env_url": "https://www.instapaper.com/api/kobo",
|
||||
"instapaper_link_account_start": "https://authorize.kobo.com/{region}/{language}/linkinstapaper",
|
||||
"kobo_audiobooks_credit_redemption": "False",
|
||||
"kobo_audiobooks_enabled": "True",
|
||||
"kobo_audiobooks_orange_deal_enabled": "False",
|
||||
"kobo_audiobooks_subscriptions_enabled": "False",
|
||||
"kobo_nativeborrow_enabled": "True",
|
||||
"kobo_display_price": "True",
|
||||
"kobo_dropbox_link_account_enabled": "False",
|
||||
"kobo_google_tax": "False",
|
||||
"kobo_googledrive_link_account_enabled": "False",
|
||||
"kobo_nativeborrow_enabled": "False",
|
||||
"kobo_onedrive_link_account_enabled": "False",
|
||||
"kobo_onestorelibrary_enabled": "False",
|
||||
"kobo_privacyCentre_url": "https://www.kobo.com/privacy",
|
||||
"kobo_redeem_enabled": "True",
|
||||
"kobo_shelfie_enabled": "False",
|
||||
"kobo_subscriptions_enabled": "False",
|
||||
"kobo_superpoints_enabled": "False",
|
||||
"kobo_subscriptions_enabled": "True",
|
||||
"kobo_superpoints_enabled": "True",
|
||||
"kobo_wishlist_enabled": "True",
|
||||
"library_book": "https://storeapi.kobo.com/v1/user/library/books/{LibraryItemId}",
|
||||
"library_items": "https://storeapi.kobo.com/v1/user/library",
|
||||
"library_metadata": "https://storeapi.kobo.com/v1/library/{Ids}/metadata",
|
||||
"library_prices": "https://storeapi.kobo.com/v1/user/library/previews/prices",
|
||||
"library_stack": "https://storeapi.kobo.com/v1/user/library/stacks/{LibraryItemId}",
|
||||
"library_search": "https://storeapi.kobo.com/v1/library/search",
|
||||
"library_sync": "https://storeapi.kobo.com/v1/library/sync",
|
||||
"love_dashboard_page": "https://store.kobobooks.com/{culture}/kobosuperpoints",
|
||||
"love_points_redemption_page":
|
||||
"https://store.kobobooks.com/{culture}/KoboSuperPointsRedemption?productId={ProductId}",
|
||||
"magazine_landing_page": "https://store.kobobooks.com/emagazines",
|
||||
"love_dashboard_page": "https://www.kobo.com/{region}/{language}/kobosuperpoints",
|
||||
"love_points_redemption_page": "https://www.kobo.com/{region}/{language}/KoboSuperPointsRedemption?productId={ProductId}",
|
||||
"magazine_landing_page": "https://www.kobo.com/emagazines",
|
||||
"more_sign_in_options": "https://authorize.kobo.com/signin?returnUrl=http://kobo.com/#allProviders",
|
||||
"notebooks": "https://storeapi.kobo.com/api/internal/notebooks",
|
||||
"notifications_registration_issue": "https://storeapi.kobo.com/v1/notifications/registration",
|
||||
"oauth_host": "https://oauth.kobo.com",
|
||||
"overdrive_account": "https://auth.overdrive.com/account",
|
||||
"overdrive_library": "https://{libraryKey}.auth.overdrive.com/library",
|
||||
"overdrive_library_finder_host": "https://libraryfinder.api.overdrive.com",
|
||||
"overdrive_thunder_host": "https://thunder.api.overdrive.com",
|
||||
"password_retrieval_page": "https://www.kobobooks.com/passwordretrieval.html",
|
||||
"password_retrieval_page": "https://www.kobo.com/passwordretrieval.html",
|
||||
"personalizedrecommendations": "https://storeapi.kobo.com/v2/users/personalizedrecommendations",
|
||||
"pocket_link_account_start": "https://authorize.kobo.com/{region}/{language}/linkpocket",
|
||||
"post_analytics_event": "https://storeapi.kobo.com/v1/analytics/event",
|
||||
"ppx_purchasing_url": "https://purchasing.kobo.com",
|
||||
"privacy_page": "https://www.kobo.com/privacypolicy?style=onestore",
|
||||
"product_nextread": "https://storeapi.kobo.com/v1/products/{ProductIds}/nextread",
|
||||
"product_prices": "https://storeapi.kobo.com/v1/products/{ProductIds}/prices",
|
||||
"product_recommendations": "https://storeapi.kobo.com/v1/products/{ProductId}/recommendations",
|
||||
"product_reviews": "https://storeapi.kobo.com/v1/products/{ProductIds}/reviews",
|
||||
"products": "https://storeapi.kobo.com/v1/products",
|
||||
"provider_external_sign_in_page":
|
||||
"https://authorize.kobo.com/ExternalSignIn/{providerName}?returnUrl=http://store.kobobooks.com/",
|
||||
"purchase_buy": "https://www.kobo.com/checkout/createpurchase/",
|
||||
"purchase_buy_templated": "https://www.kobo.com/{culture}/checkout/createpurchase/{ProductId}",
|
||||
"productsv2": "https://storeapi.kobo.com/v2/products",
|
||||
"provider_external_sign_in_page": "https://authorize.kobo.com/ExternalSignIn/{providerName}?returnUrl=http://kobo.com/",
|
||||
"quickbuy_checkout": "https://storeapi.kobo.com/v1/store/quickbuy/{PurchaseId}/checkout",
|
||||
"quickbuy_create": "https://storeapi.kobo.com/v1/store/quickbuy/purchase",
|
||||
"rakuten_token_exchange": "https://storeapi.kobo.com/v1/auth/rakuten_token_exchange",
|
||||
"rating": "https://storeapi.kobo.com/v1/products/{ProductId}/rating/{Rating}",
|
||||
"reading_services_host": "https://readingservices.kobo.com",
|
||||
"reading_state": "https://storeapi.kobo.com/v1/library/{Ids}/state",
|
||||
"redeem_interstitial_page": "https://store.kobobooks.com",
|
||||
"registration_page": "https://authorize.kobo.com/signup?returnUrl=http://store.kobobooks.com/",
|
||||
"redeem_interstitial_page": "https://www.kobo.com",
|
||||
"registration_page": "https://authorize.kobo.com/signup?returnUrl=http://kobo.com/",
|
||||
"related_items": "https://storeapi.kobo.com/v1/products/{Id}/related",
|
||||
"remaining_book_series": "https://storeapi.kobo.com/v1/products/books/series/{SeriesId}",
|
||||
"rename_tag": "https://storeapi.kobo.com/v1/library/tags/{TagId}",
|
||||
"review": "https://storeapi.kobo.com/v1/products/reviews/{ReviewId}",
|
||||
"review_sentiment": "https://storeapi.kobo.com/v1/products/reviews/{ReviewId}/sentiment/{Sentiment}",
|
||||
"shelfie_recommendations": "https://storeapi.kobo.com/v1/user/recommendations/shelfie",
|
||||
"sign_in_page": "https://authorize.kobo.com/signin?returnUrl=http://store.kobobooks.com/",
|
||||
"sign_in_page": "https://authorize.kobo.com/signin?returnUrl=http://kobo.com/",
|
||||
"social_authorization_host": "https://social.kobobooks.com:8443",
|
||||
"social_host": "https://social.kobobooks.com",
|
||||
"stacks_host_productId": "https://store.kobobooks.com/collections/byproductid/",
|
||||
"store_home": "www.kobo.com/{region}/{language}",
|
||||
"store_host": "store.kobobooks.com",
|
||||
"store_newreleases": "https://store.kobobooks.com/{culture}/List/new-releases/961XUjtsU0qxkFItWOutGA",
|
||||
"store_search": "https://store.kobobooks.com/{culture}/Search?Query={query}",
|
||||
"store_top50": "https://store.kobobooks.com/{culture}/ebooks/Top",
|
||||
"store_host": "www.kobo.com",
|
||||
"store_newreleases": "https://www.kobo.com/{region}/{language}/List/new-releases/961XUjtsU0qxkFItWOutGA",
|
||||
"store_search": "https://www.kobo.com/{region}/{language}/Search?Query={query}",
|
||||
"store_top50": "https://www.kobo.com/{region}/{language}/ebooks/Top",
|
||||
"subs_landing_page": "https://www.kobo.com/{region}/{language}/plus",
|
||||
"subs_management_page": "https://www.kobo.com/{region}/{language}/account/subscriptions",
|
||||
"subs_plans_page": "https://www.kobo.com/{region}/{language}/plus/plans",
|
||||
"subs_purchase_buy_templated": "https://www.kobo.com/{region}/{language}/Checkoutoption/{ProductId}/{TierId}",
|
||||
"tag_items": "https://storeapi.kobo.com/v1/library/tags/{TagId}/Items",
|
||||
"tags": "https://storeapi.kobo.com/v1/library/tags",
|
||||
"taste_profile": "https://storeapi.kobo.com/v1/products/tasteprofile",
|
||||
"terms_of_sale_page": "https://authorize.kobo.com/{region}/{language}/terms/termsofsale",
|
||||
"update_accessibility_to_preview": "https://storeapi.kobo.com/v1/library/{EntitlementIds}/preview",
|
||||
"use_one_store": "False",
|
||||
"use_one_store": "True",
|
||||
"user_loyalty_benefits": "https://storeapi.kobo.com/v1/user/loyalty/benefits",
|
||||
"user_platform": "https://storeapi.kobo.com/v1/user/platform",
|
||||
"user_profile": "https://storeapi.kobo.com/v1/user/profile",
|
||||
@@ -1242,6 +1319,6 @@ def NATIVE_KOBO_RESOURCES():
|
||||
"user_recommendations": "https://storeapi.kobo.com/v1/user/recommendations",
|
||||
"user_reviews": "https://storeapi.kobo.com/v1/user/reviews",
|
||||
"user_wishlist": "https://storeapi.kobo.com/v1/user/wishlist",
|
||||
"userguide_host": "https://kbdownload1-a.akamaihd.net",
|
||||
"wishlist_page": "https://store.kobobooks.com/{region}/{language}/account/wishlist",
|
||||
"userguide_host": "https://ereaderfiles.kobo.com",
|
||||
"wishlist_page": "https://www.kobo.com/{region}/{language}/account/wishlist"
|
||||
}
|
||||
|
||||
+12
-14
@@ -22,7 +22,7 @@
|
||||
This module also includes research notes into the auth protocol used by Kobo devices.
|
||||
|
||||
Log-in:
|
||||
When first booting a Kobo device the user must sign into a Kobo (or affiliate) account.
|
||||
When first booting a Kobo device the user must log in to a Kobo (or affiliate) account.
|
||||
Upon successful sign-in, the user is redirected to
|
||||
https://auth.kobobooks.com/CrossDomainSignIn?id=<some id>
|
||||
which serves the following response:
|
||||
@@ -41,7 +41,7 @@ issue for a few years now https://www.mobileread.com/forums/showpost.php?p=34768
|
||||
will still grant access given the userkey.)
|
||||
|
||||
Official Kobo Store Api authorization:
|
||||
* For most of the endpoints we care about (sync, metadata, tags, etc), the userKey is
|
||||
* For most of the endpoints we care about (sync, metadata, tags, etc.), the userKey is
|
||||
passed in the x-kobo-userkey header, and is sufficient to authorize the API call.
|
||||
* Some endpoints (e.g: AnnotationService) instead make use of Bearer tokens pass through
|
||||
an authorization header. To get a BearerToken, the device makes a POST request to the
|
||||
@@ -65,12 +65,13 @@ from os import urandom
|
||||
from functools import wraps
|
||||
|
||||
from flask import g, Blueprint, abort, request
|
||||
from flask_login import login_user, current_user, login_required
|
||||
from .cw_login import login_user, current_user
|
||||
from flask_babel import gettext as _
|
||||
from flask_limiter import RateLimitExceeded
|
||||
|
||||
from . import logger, config, calibre_db, db, helper, ub, lm, limiter
|
||||
from .render_template import render_title_template
|
||||
from .usermanagement import user_login_required
|
||||
|
||||
|
||||
log = logger.create()
|
||||
|
||||
@@ -78,8 +79,10 @@ kobo_auth = Blueprint("kobo_auth", __name__, url_prefix="/kobo_auth")
|
||||
|
||||
|
||||
@kobo_auth.route("/generate_auth_token/<int:user_id>")
|
||||
@login_required
|
||||
@user_login_required
|
||||
def generate_auth_token(user_id):
|
||||
if current_user.id != user_id and not current_user.role_admin():
|
||||
abort(403)
|
||||
warning = False
|
||||
host_list = request.host.rsplit(':')
|
||||
if len(host_list) == 1:
|
||||
@@ -120,8 +123,10 @@ def generate_auth_token(user_id):
|
||||
|
||||
|
||||
@kobo_auth.route("/deleteauthtoken/<int:user_id>", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def delete_auth_token(user_id):
|
||||
if current_user.id != user_id and not current_user.role_admin():
|
||||
abort(403)
|
||||
# Invalidate any previously generated Kobo Auth token for this user
|
||||
ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.user_id == user_id)\
|
||||
.filter(ub.RemoteAuthToken.token_type==1).delete()
|
||||
@@ -152,13 +157,6 @@ def requires_kobo_auth(f):
|
||||
def inner(*args, **kwargs):
|
||||
auth_token = get_auth_token()
|
||||
if auth_token is not None:
|
||||
try:
|
||||
limiter.check()
|
||||
except RateLimitExceeded:
|
||||
return abort(429)
|
||||
except (ConnectionError, Exception) as e:
|
||||
log.error("Connection error to limiter backend: %s", e)
|
||||
return abort(429)
|
||||
user = (
|
||||
ub.session.query(ub.User)
|
||||
.join(ub.RemoteAuthToken)
|
||||
@@ -167,7 +165,7 @@ def requires_kobo_auth(f):
|
||||
)
|
||||
if user is not None:
|
||||
login_user(user)
|
||||
[limiter.limiter.storage.clear(k.key) for k in limiter.current_limits]
|
||||
[limiter.limiter.clear(limit.limit, *limit.request_args) for limit in limiter.current_limits]
|
||||
return f(*args, **kwargs)
|
||||
log.debug("Received Kobo request without a recognizable auth token.")
|
||||
return abort(401)
|
||||
|
||||
@@ -17,11 +17,11 @@
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
from flask_login import current_user
|
||||
from .cw_login import current_user
|
||||
from . import ub
|
||||
import datetime
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy.sql.expression import or_, and_, true
|
||||
from sqlalchemy import exc
|
||||
# from sqlalchemy import exc
|
||||
|
||||
|
||||
# Add the current book id to kobo_synced_books table for current user, if entry is already present,
|
||||
@@ -51,14 +51,16 @@ def remove_synced_book(book_id, all=False, session=None):
|
||||
ub.session_commit(_session=session)
|
||||
|
||||
|
||||
# If state == none, it will toggle the archive state of the passed book_id.
|
||||
# state = true archives it, state = false unarchives it
|
||||
def change_archived_books(book_id, state=None, message=None):
|
||||
archived_book = ub.session.query(ub.ArchivedBook).filter(and_(ub.ArchivedBook.user_id == int(current_user.id),
|
||||
ub.ArchivedBook.book_id == book_id)).first()
|
||||
if not archived_book:
|
||||
if not archived_book: # and (state == True or state == None):
|
||||
archived_book = ub.ArchivedBook(user_id=current_user.id, book_id=book_id)
|
||||
|
||||
archived_book.is_archived = state if state else not archived_book.is_archived
|
||||
archived_book.last_modified = datetime.datetime.utcnow() # toDo. Check utc timestamp
|
||||
archived_book.is_archived = state if state != None else not archived_book.is_archived
|
||||
archived_book.last_modified = datetime.now(timezone.utc) # toDo. Check utc timestamp
|
||||
|
||||
ub.session.merge(archived_book)
|
||||
ub.session_commit(message)
|
||||
|
||||
+5
-11
@@ -29,7 +29,7 @@ from .constants import CONFIG_DIR as _CONFIG_DIR
|
||||
ACCESS_FORMATTER_GEVENT = Formatter("%(message)s")
|
||||
ACCESS_FORMATTER_TORNADO = Formatter("[%(asctime)s] %(message)s")
|
||||
|
||||
FORMATTER = Formatter("[%(asctime)s] %(levelname)5s {%(name)s:%(lineno)d} %(message)s")
|
||||
FORMATTER = Formatter("[%(asctime)s] %(levelname)5s {%(filename)s:%(lineno)d} %(message)s")
|
||||
DEFAULT_LOG_LEVEL = logging.INFO
|
||||
DEFAULT_LOG_FILE = os.path.join(_CONFIG_DIR, "calibre-web.log")
|
||||
DEFAULT_ACCESS_LOG = os.path.join(_CONFIG_DIR, "access.log")
|
||||
@@ -42,18 +42,12 @@ logging.addLevelName(logging.CRITICAL, "CRIT")
|
||||
|
||||
class _Logger(logging.Logger):
|
||||
|
||||
def error_or_exception(self, message, stacklevel=2, *args, **kwargs):
|
||||
def error_or_exception(self, message, stacklevel=1, *args, **kwargs):
|
||||
is_debug = self.getEffectiveLevel() <= logging.DEBUG
|
||||
if sys.version_info > (3, 7):
|
||||
if is_debug:
|
||||
self.exception(message, stacklevel=stacklevel, *args, **kwargs)
|
||||
else:
|
||||
self.error(message, stacklevel=stacklevel, *args, **kwargs)
|
||||
if not is_debug:
|
||||
self.exception(message, stacklevel=stacklevel, *args, **kwargs)
|
||||
else:
|
||||
if is_debug:
|
||||
self.exception(message, stack_info=True, *args, **kwargs)
|
||||
else:
|
||||
self.error(message, *args, **kwargs)
|
||||
self.error(message, stacklevel=stacklevel, *args, **kwargs)
|
||||
|
||||
def debug_no_auth(self, message, *args, **kwargs):
|
||||
message = message.strip("\r\n")
|
||||
|
||||
+6
-4
@@ -20,18 +20,18 @@ import sys
|
||||
|
||||
from . import create_app, limiter
|
||||
from .jinjia import jinjia
|
||||
from .remotelogin import remotelogin
|
||||
from flask import request
|
||||
|
||||
|
||||
def request_username():
|
||||
return request.authorization.username
|
||||
return request.authorization.username if request.authorization else ""
|
||||
|
||||
|
||||
def main():
|
||||
app = create_app()
|
||||
|
||||
from .web import web
|
||||
from .basic import basic
|
||||
from .opds import opds
|
||||
from .admin import admi
|
||||
from .gdrive import gdrive
|
||||
@@ -42,6 +42,7 @@ def main():
|
||||
from .shelf import shelf
|
||||
from .tasks_status import tasks
|
||||
from .error_handler import init_errorhandler
|
||||
from .remotelogin import remotelogin
|
||||
try:
|
||||
from .kobo import kobo, get_kobo_activated
|
||||
from .kobo_auth import kobo_auth
|
||||
@@ -64,8 +65,9 @@ def main():
|
||||
app.register_blueprint(search)
|
||||
app.register_blueprint(tasks)
|
||||
app.register_blueprint(web)
|
||||
app.register_blueprint(opds)
|
||||
app.register_blueprint(basic)
|
||||
limiter.limit("3/minute", key_func=request_username)(opds)
|
||||
app.register_blueprint(opds)
|
||||
app.register_blueprint(jinjia)
|
||||
app.register_blueprint(about)
|
||||
app.register_blueprint(shelf)
|
||||
@@ -75,9 +77,9 @@ def main():
|
||||
app.register_blueprint(gdrive)
|
||||
app.register_blueprint(editbook)
|
||||
if kobo_available:
|
||||
limiter.limit("3/minute", key_func=get_remote_address)(kobo)
|
||||
app.register_blueprint(kobo)
|
||||
app.register_blueprint(kobo_auth)
|
||||
limiter.limit("3/minute", key_func=get_remote_address)(kobo)
|
||||
if oauth_available:
|
||||
app.register_blueprint(oauth)
|
||||
success = web_server.start()
|
||||
|
||||
@@ -38,14 +38,16 @@ class Amazon(Metadata):
|
||||
__name__ = "Amazon"
|
||||
__id__ = "amazon"
|
||||
headers = {'upgrade-insecure-requests': '1',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36',
|
||||
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
|
||||
'sec-gpc': '1',
|
||||
'sec-fetch-site': 'none',
|
||||
'sec-fetch-mode': 'navigate',
|
||||
'sec-fetch-user': '?1',
|
||||
'sec-fetch-dest': 'document',
|
||||
'accept-encoding': 'gzip, deflate, br',
|
||||
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:130.0) Gecko/20100101 Firefox/130.0',
|
||||
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/png,image/svg+xml,*/*;q=0.8',
|
||||
'Sec-Fetch-Site': 'same-origin',
|
||||
'Sec-Fetch-Mode': 'navigate',
|
||||
'Sec-Fetch-User': '?1',
|
||||
'Sec-Fetch-Dest': 'document',
|
||||
'Upgrade-Insecure-Requests': '1',
|
||||
'Alt-Used' : 'www.amazon.com',
|
||||
'Priority' : 'u=0, i',
|
||||
'accept-encoding': 'gzip, deflate, br, zstd',
|
||||
'accept-language': 'en-US,en;q=0.9'}
|
||||
session = requests.Session()
|
||||
session.headers=headers
|
||||
@@ -53,7 +55,6 @@ class Amazon(Metadata):
|
||||
def search(
|
||||
self, query: str, generic_cover: str = "", locale: str = "en"
|
||||
) -> Optional[List[MetaRecord]]:
|
||||
#timer=time()
|
||||
def inner(link, index) -> [dict, int]:
|
||||
with self.session as session:
|
||||
try:
|
||||
@@ -61,11 +62,11 @@ class Amazon(Metadata):
|
||||
r.raise_for_status()
|
||||
except Exception as ex:
|
||||
log.warning(ex)
|
||||
return None
|
||||
return []
|
||||
long_soup = BS(r.text, "lxml") #~4sec :/
|
||||
soup2 = long_soup.find("div", attrs={"cel_widget_id": "dpx-books-ppd_csm_instrumentation_wrapper"})
|
||||
soup2 = long_soup.find("div", attrs={"cel_widget_id": "dpx-ppd_csm_instrumentation_wrapper"})
|
||||
if soup2 is None:
|
||||
return None
|
||||
return []
|
||||
try:
|
||||
match = MetaRecord(
|
||||
title = "",
|
||||
@@ -88,7 +89,7 @@ class Amazon(Metadata):
|
||||
soup2.find("div", attrs={"data-feature-name": "bookDescription"}).stripped_strings)\
|
||||
.replace("\xa0"," ")[:-9].strip().strip("\n")
|
||||
except (AttributeError, TypeError):
|
||||
return None # if there is no description it is not a book and therefore should be ignored
|
||||
return [] # if there is no description it is not a book and therefore should be ignored
|
||||
try:
|
||||
match.title = soup2.find("span", attrs={"id": "productTitle"}).text
|
||||
except (AttributeError, TypeError):
|
||||
@@ -107,13 +108,13 @@ class Amazon(Metadata):
|
||||
except (AttributeError, ValueError):
|
||||
match.rating = 0
|
||||
try:
|
||||
match.cover = soup2.find("img", attrs={"class": "a-dynamic-image frontImage"})["src"]
|
||||
match.cover = soup2.find("img", attrs={"class": "a-dynamic-image"})["src"]
|
||||
except (AttributeError, TypeError):
|
||||
match.cover = ""
|
||||
return match, index
|
||||
except Exception as e:
|
||||
log.error_or_exception(e)
|
||||
return None
|
||||
return []
|
||||
|
||||
val = list()
|
||||
if self.active:
|
||||
@@ -133,7 +134,7 @@ class Amazon(Metadata):
|
||||
links_list = [next(filter(lambda i: "digital-text" in i["href"], x.findAll("a")))["href"] for x in
|
||||
soup.findAll("div", attrs={"data-component-type": "s-search-result"})]
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
|
||||
fut = {executor.submit(inner, link, index) for index, link in enumerate(links_list[:5])}
|
||||
val = list(map(lambda x : x.result() ,concurrent.futures.as_completed(fut)))
|
||||
fut = {executor.submit(inner, link, index) for index, link in enumerate(links_list[:3])}
|
||||
val = list(map(lambda x : x.result(), concurrent.futures.as_completed(fut)))
|
||||
result = list(filter(lambda x: x, val))
|
||||
return [x[0] for x in sorted(result, key=itemgetter(1))] #sort by amazons listing order for best relevance
|
||||
|
||||
@@ -57,7 +57,7 @@ class ComicVine(Metadata):
|
||||
result.raise_for_status()
|
||||
except Exception as e:
|
||||
log.warning(e)
|
||||
return None
|
||||
return []
|
||||
for result in result.json()["results"]:
|
||||
match = self._parse_search_result(
|
||||
result=result, generic_cover=generic_cover, locale=locale
|
||||
|
||||
@@ -155,7 +155,7 @@ class Douban(Metadata):
|
||||
r.raise_for_status()
|
||||
except Exception as e:
|
||||
log.warning(e)
|
||||
return None
|
||||
return []
|
||||
|
||||
match = MetaRecord(
|
||||
id=id,
|
||||
|
||||
@@ -23,7 +23,7 @@ from datetime import datetime
|
||||
|
||||
import requests
|
||||
|
||||
from cps import logger
|
||||
from cps import logger, config
|
||||
from cps.isoLanguages import get_lang3, get_language_name
|
||||
from cps.services.Metadata import MetaRecord, MetaSourceInfo, Metadata
|
||||
|
||||
@@ -31,13 +31,14 @@ log = logger.create()
|
||||
|
||||
|
||||
class Google(Metadata):
|
||||
__name__ = "Google"
|
||||
__name__ = "Google Books"
|
||||
__id__ = "google"
|
||||
DESCRIPTION = "Google Books"
|
||||
META_URL = "https://books.google.com/"
|
||||
BOOK_URL = "https://books.google.com/books?id="
|
||||
SEARCH_URL = "https://www.googleapis.com/books/v1/volumes?q="
|
||||
ISBN_TYPE = "ISBN_13"
|
||||
API_KEY = "&key=" + config.config_googlebooks_api_key
|
||||
|
||||
def search(
|
||||
self, query: str, generic_cover: str = "", locale: str = "en"
|
||||
@@ -50,11 +51,11 @@ class Google(Metadata):
|
||||
tokens = [quote(t.encode("utf-8")) for t in title_tokens]
|
||||
query = "+".join(tokens)
|
||||
try:
|
||||
results = requests.get(Google.SEARCH_URL + query)
|
||||
results = requests.get(Google.SEARCH_URL + query + Google.API_KEY)
|
||||
results.raise_for_status()
|
||||
except Exception as e:
|
||||
log.warning(e)
|
||||
return None
|
||||
return []
|
||||
for result in results.json().get("items", []):
|
||||
val.append(
|
||||
self._parse_search_result(
|
||||
|
||||
@@ -137,7 +137,7 @@ class LubimyCzytac(Metadata):
|
||||
|
||||
def _prepare_query(self, title: str) -> str:
|
||||
query = ""
|
||||
characters_to_remove = "\?()\/"
|
||||
characters_to_remove = r"\?()\/"
|
||||
pattern = "[" + characters_to_remove + "]"
|
||||
title = re.sub(pattern, "", title)
|
||||
title = title.replace("_", " ")
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ class OAuthBackend(SQLAlchemyBackend):
|
||||
Stores and retrieves OAuth tokens using a relational database through
|
||||
the `SQLAlchemy`_ ORM.
|
||||
|
||||
.. _SQLAlchemy: https://www.sqlalchemy.org/
|
||||
_SQLAlchemy: https://www.sqlalchemy.org/
|
||||
"""
|
||||
def __init__(self, model, session, provider_id,
|
||||
user=None, user_id=None, user_required=None, anon_user=None,
|
||||
|
||||
+12
-3
@@ -30,8 +30,9 @@ from flask_dance.consumer import oauth_authorized, oauth_error
|
||||
from flask_dance.contrib.github import make_github_blueprint, github
|
||||
from flask_dance.contrib.google import make_google_blueprint, google
|
||||
from oauthlib.oauth2 import TokenExpiredError, InvalidGrantError
|
||||
from flask_login import login_user, current_user, login_required
|
||||
from .cw_login import login_user, current_user
|
||||
from sqlalchemy.orm.exc import NoResultFound
|
||||
from .usermanagement import user_login_required
|
||||
|
||||
from . import constants, logger, config, app, ub
|
||||
|
||||
@@ -133,6 +134,14 @@ def bind_oauth_or_register(provider_id, provider_user_id, redirect_url, provider
|
||||
oauth_entry = query.first()
|
||||
# already bind with user, just login
|
||||
if oauth_entry.user:
|
||||
# If a user is already logged in and it's a different account, reject the link
|
||||
# to prevent account takeover via shared OAuth identities
|
||||
if current_user and current_user.is_authenticated and oauth_entry.user_id != current_user.id:
|
||||
flash(_("This %(oauth)s account is already linked to a different user",
|
||||
oauth=provider_name), category="error")
|
||||
log.warning("User %s tried to link OAuth account already bound to user %s",
|
||||
current_user.id, oauth_entry.user_id)
|
||||
return redirect(url_for('web.profile'))
|
||||
login_user(oauth_entry.user)
|
||||
log.debug("You are now logged in as: '%s'", oauth_entry.user.name)
|
||||
flash(_("Success! You are now logged in as: %(nickname)s", nickname=oauth_entry.user.name),
|
||||
@@ -340,7 +349,7 @@ def github_login():
|
||||
|
||||
|
||||
@oauth.route('/unlink/github', methods=["GET"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def github_login_unlink():
|
||||
return unlink_oauth(oauthblueprints[0]['id'])
|
||||
|
||||
@@ -364,6 +373,6 @@ def google_login():
|
||||
|
||||
|
||||
@oauth.route('/unlink/google', methods=["GET"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def google_login_unlink():
|
||||
return unlink_oauth(oauthblueprints[1]['id'])
|
||||
|
||||
+76
-57
@@ -21,18 +21,18 @@
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import datetime
|
||||
import json
|
||||
from urllib.parse import unquote_plus
|
||||
|
||||
from flask import Blueprint, request, render_template, make_response, abort, Response, g
|
||||
from flask_login import current_user
|
||||
from flask import Blueprint, request, render_template, make_response, abort, g, jsonify
|
||||
from flask_babel import get_locale
|
||||
from flask_babel import gettext as _
|
||||
|
||||
|
||||
from sqlalchemy.sql.expression import func, text, or_, and_, true
|
||||
from sqlalchemy.exc import InvalidRequestError, OperationalError
|
||||
|
||||
from . import logger, config, db, calibre_db, ub, isoLanguages, constants
|
||||
from .usermanagement import requires_basic_auth_if_no_ano
|
||||
from .usermanagement import requires_basic_auth_if_no_ano, auth
|
||||
from .helper import get_download_link, get_book_cover
|
||||
from .pagination import Pagination
|
||||
from .web import render_read_books
|
||||
@@ -87,50 +87,53 @@ def feed_letter_books(book_id):
|
||||
letter,
|
||||
[db.Books.sort],
|
||||
True, config.config_read_column)
|
||||
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/new")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_new():
|
||||
if not current_user.check_visibility(constants.SIDEBAR_RECENT):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_RECENT):
|
||||
abort(404)
|
||||
off = request.args.get("offset") or 0
|
||||
entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,
|
||||
db.Books, True, [db.Books.timestamp.desc()],
|
||||
True, config.config_read_column)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/discover")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_discover():
|
||||
if not current_user.check_visibility(constants.SIDEBAR_RANDOM):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_RANDOM):
|
||||
abort(404)
|
||||
query = calibre_db.generate_linked_query(config.config_read_column, db.Books)
|
||||
entries = query.filter(calibre_db.common_filters()).order_by(func.random()).limit(config.config_books_per_page)
|
||||
pagination = Pagination(1, config.config_books_per_page, int(config.config_books_per_page))
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/rated")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_best_rated():
|
||||
if not current_user.check_visibility(constants.SIDEBAR_BEST_RATED):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_BEST_RATED):
|
||||
abort(404)
|
||||
off = request.args.get("offset") or 0
|
||||
entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,
|
||||
db.Books, db.Books.ratings.any(db.Ratings.rating > 9),
|
||||
[db.Books.timestamp.desc()],
|
||||
True, config.config_read_column)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/hot")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_hot():
|
||||
if not current_user.check_visibility(constants.SIDEBAR_HOT):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_HOT):
|
||||
abort(404)
|
||||
off = request.args.get("offset") or 0
|
||||
all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id)).order_by(
|
||||
@@ -148,13 +151,14 @@ def feed_hot():
|
||||
num_books = entries.__len__()
|
||||
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1),
|
||||
config.config_books_per_page, num_books)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/author")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_authorindex():
|
||||
if not current_user.check_visibility(constants.SIDEBAR_AUTHOR):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_AUTHOR):
|
||||
abort(404)
|
||||
return render_element_index(db.Authors.sort, db.books_authors_link, 'opds.feed_letter_author')
|
||||
|
||||
@@ -162,7 +166,7 @@ def feed_authorindex():
|
||||
@opds.route("/opds/author/letter/<book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_letter_author(book_id):
|
||||
if not current_user.check_visibility(constants.SIDEBAR_AUTHOR):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_AUTHOR):
|
||||
abort(404)
|
||||
off = request.args.get("offset") or 0
|
||||
letter = true() if book_id == "00" else func.upper(db.Authors.sort).startswith(book_id)
|
||||
@@ -173,7 +177,8 @@ def feed_letter_author(book_id):
|
||||
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
|
||||
entries.count())
|
||||
entries = entries.limit(config.config_books_per_page).offset(off).all()
|
||||
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_author', pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_author', pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/author/<int:book_id>")
|
||||
@@ -185,7 +190,7 @@ def feed_author(book_id):
|
||||
@opds.route("/opds/publisher")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_publisherindex():
|
||||
if not current_user.check_visibility(constants.SIDEBAR_PUBLISHER):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_PUBLISHER):
|
||||
abort(404)
|
||||
off = request.args.get("offset") or 0
|
||||
entries = calibre_db.session.query(db.Publishers)\
|
||||
@@ -196,7 +201,8 @@ def feed_publisherindex():
|
||||
.limit(config.config_books_per_page).offset(off)
|
||||
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
|
||||
len(calibre_db.session.query(db.Publishers).all()))
|
||||
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_publisher', pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_publisher', pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/publisher/<int:book_id>")
|
||||
@@ -208,7 +214,7 @@ def feed_publisher(book_id):
|
||||
@opds.route("/opds/category")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_categoryindex():
|
||||
if not current_user.check_visibility(constants.SIDEBAR_CATEGORY):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_CATEGORY):
|
||||
abort(404)
|
||||
return render_element_index(db.Tags.name, db.books_tags_link, 'opds.feed_letter_category')
|
||||
|
||||
@@ -216,7 +222,7 @@ def feed_categoryindex():
|
||||
@opds.route("/opds/category/letter/<book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_letter_category(book_id):
|
||||
if not current_user.check_visibility(constants.SIDEBAR_CATEGORY):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_CATEGORY):
|
||||
abort(404)
|
||||
off = request.args.get("offset") or 0
|
||||
letter = true() if book_id == "00" else func.upper(db.Tags.name).startswith(book_id)
|
||||
@@ -229,7 +235,8 @@ def feed_letter_category(book_id):
|
||||
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
|
||||
entries.count())
|
||||
entries = entries.offset(off).limit(config.config_books_per_page).all()
|
||||
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_category', pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_category', pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/category/<int:book_id>")
|
||||
@@ -241,7 +248,7 @@ def feed_category(book_id):
|
||||
@opds.route("/opds/series")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_seriesindex():
|
||||
if not current_user.check_visibility(constants.SIDEBAR_SERIES):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_SERIES):
|
||||
abort(404)
|
||||
return render_element_index(db.Series.sort, db.books_series_link, 'opds.feed_letter_series')
|
||||
|
||||
@@ -249,7 +256,7 @@ def feed_seriesindex():
|
||||
@opds.route("/opds/series/letter/<book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_letter_series(book_id):
|
||||
if not current_user.check_visibility(constants.SIDEBAR_SERIES):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_SERIES):
|
||||
abort(404)
|
||||
off = request.args.get("offset") or 0
|
||||
letter = true() if book_id == "00" else func.upper(db.Series.sort).startswith(book_id)
|
||||
@@ -262,7 +269,8 @@ def feed_letter_series(book_id):
|
||||
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
|
||||
entries.count())
|
||||
entries = entries.offset(off).limit(config.config_books_per_page).all()
|
||||
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_series', pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_series', pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/series/<int:book_id>")
|
||||
@@ -274,13 +282,14 @@ def feed_series(book_id):
|
||||
db.Books.series.any(db.Series.id == book_id),
|
||||
[db.Books.series_index],
|
||||
True, config.config_read_column)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/ratings")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_ratingindex():
|
||||
if not current_user.check_visibility(constants.SIDEBAR_RATING):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_RATING):
|
||||
abort(404)
|
||||
off = request.args.get("offset") or 0
|
||||
entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'),
|
||||
@@ -296,7 +305,8 @@ def feed_ratingindex():
|
||||
element = list()
|
||||
for entry in entries:
|
||||
element.append(FeedObject(entry[0].id, _("{} Stars").format(entry.name)))
|
||||
return render_xml_template('feed.xml', listelements=element, folder='opds.feed_ratings', pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', listelements=element, folder='opds.feed_ratings', pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/ratings/<book_id>")
|
||||
@@ -308,7 +318,7 @@ def feed_ratings(book_id):
|
||||
@opds.route("/opds/formats")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_formatindex():
|
||||
if not current_user.check_visibility(constants.SIDEBAR_FORMAT):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_FORMAT):
|
||||
abort(404)
|
||||
off = request.args.get("offset") or 0
|
||||
entries = calibre_db.session.query(db.Data).join(db.Books)\
|
||||
@@ -320,7 +330,8 @@ def feed_formatindex():
|
||||
element = list()
|
||||
for entry in entries:
|
||||
element.append(FeedObject(entry.format, entry.format))
|
||||
return render_xml_template('feed.xml', listelements=element, folder='opds.feed_format', pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', listelements=element, folder='opds.feed_format', pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/formats/<book_id>")
|
||||
@@ -332,25 +343,27 @@ def feed_format(book_id):
|
||||
db.Books.data.any(db.Data.format == book_id.upper()),
|
||||
[db.Books.timestamp.desc()],
|
||||
True, config.config_read_column)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/language")
|
||||
@opds.route("/opds/language/")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_languagesindex():
|
||||
if not current_user.check_visibility(constants.SIDEBAR_LANGUAGE):
|
||||
if not auth.current_user().check_visibility(constants.SIDEBAR_LANGUAGE):
|
||||
abort(404)
|
||||
off = request.args.get("offset") or 0
|
||||
if current_user.filter_language() == "all":
|
||||
if auth.current_user().filter_language() == "all":
|
||||
languages = calibre_db.speaking_language()
|
||||
else:
|
||||
languages = calibre_db.session.query(db.Languages).filter(
|
||||
db.Languages.lang_code == current_user.filter_language()).all()
|
||||
db.Languages.lang_code == auth.current_user().filter_language()).all()
|
||||
languages[0].name = isoLanguages.get_language_name(get_locale(), languages[0].lang_code)
|
||||
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
|
||||
len(languages))
|
||||
return render_xml_template('feed.xml', listelements=languages, folder='opds.feed_languages', pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', listelements=languages, folder='opds.feed_languages', pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/language/<int:book_id>")
|
||||
@@ -362,34 +375,36 @@ def feed_languages(book_id):
|
||||
db.Books.languages.any(db.Languages.id == book_id),
|
||||
[db.Books.timestamp.desc()],
|
||||
True, config.config_read_column)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/shelfindex")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_shelfindex():
|
||||
if not (current_user.is_authenticated or g.allow_anonymous):
|
||||
if not (auth.current_user().is_authenticated or g.allow_anonymous):
|
||||
abort(404)
|
||||
off = request.args.get("offset") or 0
|
||||
shelf = ub.session.query(ub.Shelf).filter(
|
||||
or_(ub.Shelf.is_public == 1, ub.Shelf.user_id == current_user.id)).order_by(ub.Shelf.name).all()
|
||||
or_(ub.Shelf.is_public == 1, ub.Shelf.user_id == auth.current_user().id)).order_by(ub.Shelf.name).all()
|
||||
number = len(shelf)
|
||||
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
|
||||
number)
|
||||
return render_xml_template('feed.xml', listelements=shelf, folder='opds.feed_shelf', pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', listelements=shelf, folder='opds.feed_shelf', pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/shelf/<int:book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_shelf(book_id):
|
||||
if not (current_user.is_authenticated or g.allow_anonymous):
|
||||
if not (auth.current_user().is_authenticated or g.allow_anonymous):
|
||||
abort(404)
|
||||
off = request.args.get("offset") or 0
|
||||
if current_user.is_anonymous:
|
||||
if auth.current_user().is_anonymous:
|
||||
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.is_public == 1,
|
||||
ub.Shelf.id == book_id).first()
|
||||
else:
|
||||
shelf = ub.session.query(ub.Shelf).filter(or_(and_(ub.Shelf.user_id == int(current_user.id),
|
||||
shelf = ub.session.query(ub.Shelf).filter(or_(and_(ub.Shelf.user_id == int(auth.current_user().id),
|
||||
ub.Shelf.id == book_id),
|
||||
and_(ub.Shelf.is_public == 1,
|
||||
ub.Shelf.id == book_id))).first()
|
||||
@@ -416,18 +431,16 @@ def feed_shelf(book_id):
|
||||
except (OperationalError, InvalidRequestError) as e:
|
||||
ub.session.rollback()
|
||||
log.error_or_exception("Settings Database error: {}".format(e))
|
||||
return render_xml_template('feed.xml', entries=result, pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', entries=result, pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/download/<book_id>/<book_format>/")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def opds_download_link(book_id, book_format):
|
||||
if not current_user.role_download():
|
||||
return abort(403)
|
||||
if "Kobo" in request.headers.get('User-Agent'):
|
||||
client = "kobo"
|
||||
else:
|
||||
client = ""
|
||||
if not auth.current_user().role_download():
|
||||
return abort(401)
|
||||
client = "kobo" if "Kobo" in request.headers.get('User-Agent') else ""
|
||||
return get_download_link(book_id, book_format.lower(), client)
|
||||
|
||||
|
||||
@@ -453,7 +466,7 @@ def get_database_stats():
|
||||
stat['authors'] = calibre_db.session.query(db.Authors).count()
|
||||
stat['categories'] = calibre_db.session.query(db.Tags).count()
|
||||
stat['series'] = calibre_db.session.query(db.Series).count()
|
||||
return Response(json.dumps(stat), mimetype="application/json")
|
||||
return make_response(jsonify(stat))
|
||||
|
||||
|
||||
@opds.route("/opds/thumb_240_240/<book_id>")
|
||||
@@ -468,21 +481,23 @@ def feed_get_cover(book_id):
|
||||
@opds.route("/opds/readbooks")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_read_books():
|
||||
if not (current_user.check_visibility(constants.SIDEBAR_READ_AND_UNREAD) and not current_user.is_anonymous):
|
||||
if not (auth.current_user().check_visibility(constants.SIDEBAR_READ_AND_UNREAD) and not auth.current_user().is_anonymous):
|
||||
return abort(403)
|
||||
off = request.args.get("offset") or 0
|
||||
result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, True, True)
|
||||
return render_xml_template('feed.xml', entries=result, pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', entries=result, pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
@opds.route("/opds/unreadbooks")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_unread_books():
|
||||
if not (current_user.check_visibility(constants.SIDEBAR_READ_AND_UNREAD) and not current_user.is_anonymous):
|
||||
if not (auth.current_user().check_visibility(constants.SIDEBAR_READ_AND_UNREAD) and not auth.current_user().is_anonymous):
|
||||
return abort(403)
|
||||
off = request.args.get("offset") or 0
|
||||
result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, False, True)
|
||||
return render_xml_template('feed.xml', entries=result, pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', entries=result, pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
class FeedObject:
|
||||
@@ -504,7 +519,8 @@ def feed_search(term):
|
||||
entries, __, ___ = calibre_db.get_search_results(term, config=config)
|
||||
entries_count = len(entries) if len(entries) > 0 else 1
|
||||
pagination = Pagination(1, entries_count, entries_count)
|
||||
return render_xml_template('feed.xml', searchterm=term, entries=entries, pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', searchterm=term, entries=entries, pagination=pagination, cc=cc)
|
||||
else:
|
||||
return render_xml_template('feed.xml', searchterm="")
|
||||
|
||||
@@ -526,7 +542,8 @@ def render_xml_dataset(data_table, book_id):
|
||||
getattr(db.Books, data_table.__tablename__).any(data_table.id == book_id),
|
||||
[db.Books.timestamp.desc()],
|
||||
True, config.config_read_column)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination, cc=cc)
|
||||
|
||||
|
||||
def render_element_index(database_column, linked_table, folder):
|
||||
@@ -547,7 +564,9 @@ def render_element_index(database_column, linked_table, folder):
|
||||
elements.append({'id': entry.id, 'name': entry.id})
|
||||
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
|
||||
len(entries) + 1)
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
return render_xml_template('feed.xml',
|
||||
letterelements=elements,
|
||||
folder=folder,
|
||||
pagination=pagination)
|
||||
pagination=pagination,
|
||||
cc=cc)
|
||||
|
||||
Executable → Regular
+1
-1
@@ -29,7 +29,7 @@
|
||||
|
||||
from urllib.parse import urlparse, urljoin
|
||||
|
||||
from flask import request, url_for, redirect, current_app
|
||||
from flask import request, url_for, current_app
|
||||
|
||||
|
||||
def is_safe_url(target):
|
||||
|
||||
+3
-2
@@ -25,12 +25,13 @@ from datetime import datetime
|
||||
from functools import wraps
|
||||
|
||||
from flask import Blueprint, request, make_response, abort, url_for, flash, redirect
|
||||
from flask_login import login_required, current_user, login_user
|
||||
from .cw_login import login_user, current_user
|
||||
from flask_babel import gettext as _
|
||||
from sqlalchemy.sql.expression import true
|
||||
|
||||
from . import config, logger, ub
|
||||
from .render_template import render_title_template
|
||||
from .usermanagement import user_login_required
|
||||
|
||||
|
||||
remotelogin = Blueprint('remotelogin', __name__)
|
||||
@@ -65,7 +66,7 @@ def remote_login():
|
||||
|
||||
@remotelogin.route('/verify/<token>')
|
||||
@remote_login_required
|
||||
@login_required
|
||||
@user_login_required
|
||||
def verify_token(token):
|
||||
auth_token = ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.auth_token == token).first()
|
||||
|
||||
|
||||
+12
-13
@@ -19,14 +19,13 @@
|
||||
from flask import render_template, g, abort, request
|
||||
from flask_babel import gettext as _
|
||||
from werkzeug.local import LocalProxy
|
||||
from flask_login import current_user
|
||||
from .cw_login import current_user
|
||||
from sqlalchemy.sql.expression import or_
|
||||
|
||||
from . import config, constants, logger, ub
|
||||
from .ub import User
|
||||
|
||||
|
||||
|
||||
log = logger.create()
|
||||
|
||||
def get_sidebar_config(kwargs=None):
|
||||
@@ -48,7 +47,7 @@ def get_sidebar_config(kwargs=None):
|
||||
if current_user.role_admin():
|
||||
sidebar.append({"glyph": "glyphicon-download", "text": _('Downloaded Books'), "link": 'web.download_list',
|
||||
"id": "download", "visibility": constants.SIDEBAR_DOWNLOAD, 'public': (not current_user.is_anonymous),
|
||||
"page": "download", "show_text": _('Show Downloaded Books'),
|
||||
"page": "download", "show_text": _('Show Downloaded Books'), "no_param":True,
|
||||
"config_show": content})
|
||||
else:
|
||||
sidebar.append({"glyph": "glyphicon-download", "text": _('Downloaded Books'), "link": 'web.books_list',
|
||||
@@ -70,37 +69,37 @@ def get_sidebar_config(kwargs=None):
|
||||
"visibility": constants.SIDEBAR_RANDOM, 'public': True, "page": "discover",
|
||||
"show_text": _('Show Random Books'), "config_show": True})
|
||||
sidebar.append({"glyph": "glyphicon-inbox", "text": _('Categories'), "link": 'web.category_list', "id": "cat",
|
||||
"visibility": constants.SIDEBAR_CATEGORY, 'public': True, "page": "category",
|
||||
"visibility": constants.SIDEBAR_CATEGORY, 'public': True, "page": "category", "no_param":True,
|
||||
"show_text": _('Show Category Section'), "config_show": True})
|
||||
sidebar.append({"glyph": "glyphicon-bookmark", "text": _('Series'), "link": 'web.series_list', "id": "serie",
|
||||
"visibility": constants.SIDEBAR_SERIES, 'public': True, "page": "series",
|
||||
"visibility": constants.SIDEBAR_SERIES, 'public': True, "page": "series", "no_param":True,
|
||||
"show_text": _('Show Series Section'), "config_show": True})
|
||||
sidebar.append({"glyph": "glyphicon-user", "text": _('Authors'), "link": 'web.author_list', "id": "author",
|
||||
"visibility": constants.SIDEBAR_AUTHOR, 'public': True, "page": "author",
|
||||
"visibility": constants.SIDEBAR_AUTHOR, 'public': True, "page": "author", "no_param":True,
|
||||
"show_text": _('Show Author Section'), "config_show": True})
|
||||
sidebar.append(
|
||||
{"glyph": "glyphicon-text-size", "text": _('Publishers'), "link": 'web.publisher_list', "id": "publisher",
|
||||
"visibility": constants.SIDEBAR_PUBLISHER, 'public': True, "page": "publisher",
|
||||
"visibility": constants.SIDEBAR_PUBLISHER, 'public': True, "page": "publisher", "no_param":True,
|
||||
"show_text": _('Show Publisher Section'), "config_show":True})
|
||||
sidebar.append({"glyph": "glyphicon-flag", "text": _('Languages'), "link": 'web.language_overview', "id": "lang",
|
||||
"visibility": constants.SIDEBAR_LANGUAGE, 'public': (current_user.filter_language() == 'all'),
|
||||
"page": "language",
|
||||
"page": "language", "no_param":True,
|
||||
"show_text": _('Show Language Section'), "config_show": True})
|
||||
sidebar.append({"glyph": "glyphicon-star-empty", "text": _('Ratings'), "link": 'web.ratings_list', "id": "rate",
|
||||
"visibility": constants.SIDEBAR_RATING, 'public': True,
|
||||
"visibility": constants.SIDEBAR_RATING, 'public': True, "no_param":True,
|
||||
"page": "rating", "show_text": _('Show Ratings Section'), "config_show": True})
|
||||
sidebar.append({"glyph": "glyphicon-file", "text": _('File formats'), "link": 'web.formats_list', "id": "format",
|
||||
"visibility": constants.SIDEBAR_FORMAT, 'public': True,
|
||||
"visibility": constants.SIDEBAR_FORMAT, 'public': True, "no_param":True,
|
||||
"page": "format", "show_text": _('Show File Formats Section'), "config_show": True})
|
||||
sidebar.append(
|
||||
{"glyph": "glyphicon-trash", "text": _('Archived Books'), "link": 'web.books_list', "id": "archived",
|
||||
{"glyph": "glyphicon-folder-open", "text": _('Archived Books'), "link": 'web.books_list', "id": "archived",
|
||||
"visibility": constants.SIDEBAR_ARCHIVED, 'public': (not current_user.is_anonymous), "page": "archived",
|
||||
"show_text": _('Show Archived Books'), "config_show": content})
|
||||
if not simple:
|
||||
sidebar.append(
|
||||
{"glyph": "glyphicon-th-list", "text": _('Books List'), "link": 'web.books_table', "id": "list",
|
||||
"visibility": constants.SIDEBAR_LIST, 'public': (not current_user.is_anonymous), "page": "list",
|
||||
"show_text": _('Show Books List'), "config_show": content})
|
||||
"visibility": constants.SIDEBAR_LIST, 'public': (not current_user.is_anonymous),
|
||||
"show_text": _('Show Books List'), "config_show": content, "no_param":True})
|
||||
g.shelves_access = ub.session.query(ub.Shelf).filter(
|
||||
or_(ub.Shelf.is_public == 1, ub.Shelf.user_id == current_user.id)).order_by(ub.Shelf.name).all()
|
||||
|
||||
|
||||
+4
-2
@@ -41,9 +41,9 @@ class ReverseProxied(object):
|
||||
"""Wrap the application in this middleware and configure the
|
||||
front-end server to add these headers, to let you quietly bind
|
||||
this to a URL other than / and to an HTTP scheme that is
|
||||
different than what is used locally.
|
||||
different from what is used locally.
|
||||
|
||||
Code courtesy of: http://flask.pocoo.org/snippets/35/
|
||||
Code courtesy of: https://flask.pocoo.org/snippets/35/
|
||||
|
||||
In nginx:
|
||||
location /myprefix {
|
||||
@@ -61,11 +61,13 @@ class ReverseProxied(object):
|
||||
|
||||
def __call__(self, environ, start_response):
|
||||
self.proxied = False
|
||||
self.script_name = "/"
|
||||
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
|
||||
if script_name:
|
||||
self.proxied = True
|
||||
environ['SCRIPT_NAME'] = script_name
|
||||
path_info = environ.get('PATH_INFO', '')
|
||||
self.script_name = script_name
|
||||
if path_info and path_info.startswith(script_name):
|
||||
environ['PATH_INFO'] = path_info[len(script_name):]
|
||||
|
||||
|
||||
+3
-3
@@ -21,7 +21,7 @@ import datetime
|
||||
from . import config, constants
|
||||
from .services.background_scheduler import BackgroundScheduler, CronTrigger, use_APScheduler
|
||||
from .tasks.database import TaskReconnectDatabase
|
||||
from .tasks.tempFolder import TaskDeleteTempFolder
|
||||
from .tasks.clean import TaskClean
|
||||
from .tasks.thumbnail import TaskGenerateCoverThumbnails, TaskGenerateSeriesThumbnails, TaskClearCoverThumbnailCache
|
||||
from .services.worker import WorkerThread
|
||||
from .tasks.metadata_backup import TaskBackupMetadata
|
||||
@@ -33,7 +33,7 @@ def get_scheduled_tasks(reconnect=True):
|
||||
tasks.append([lambda: TaskReconnectDatabase(), 'reconnect', False])
|
||||
|
||||
# Delete temp folder
|
||||
tasks.append([lambda: TaskDeleteTempFolder(), 'delete temp', True])
|
||||
tasks.append([lambda: TaskClean(), 'delete temp', True])
|
||||
|
||||
# Generate metadata.opf file for each changed book
|
||||
if config.schedule_metadata_backup:
|
||||
@@ -94,7 +94,7 @@ def register_startup_tasks():
|
||||
if constants.APP_MODE in ['development', 'test'] and not should_task_be_running(start, duration):
|
||||
scheduler.schedule_tasks_immediately(tasks=get_scheduled_tasks(False))
|
||||
else:
|
||||
scheduler.schedule_tasks_immediately(tasks=[[lambda: TaskDeleteTempFolder(), 'delete temp', True]])
|
||||
scheduler.schedule_tasks_immediately(tasks=[[lambda: TaskClean(), 'delete temp', True]])
|
||||
|
||||
|
||||
def should_task_be_running(start, duration):
|
||||
|
||||
+65
-24
@@ -19,17 +19,19 @@ from datetime import datetime
|
||||
|
||||
from flask import Blueprint, request, redirect, url_for, flash
|
||||
from flask import session as flask_session
|
||||
from flask_login import current_user
|
||||
from .cw_login import current_user
|
||||
from flask_babel import format_date
|
||||
from flask_babel import gettext as _
|
||||
from sqlalchemy.sql.expression import func, not_, and_, or_, text, true
|
||||
from sqlalchemy.sql.functions import coalesce
|
||||
|
||||
from . import logger, db, calibre_db, config, ub
|
||||
from .string_helper import strip_whitespaces
|
||||
from .usermanagement import login_required_if_no_ano
|
||||
from .render_template import render_title_template
|
||||
from .pagination import Pagination
|
||||
|
||||
|
||||
search = Blueprint('search', __name__)
|
||||
|
||||
log = logger.create()
|
||||
@@ -80,16 +82,27 @@ def adv_search_custom_columns(cc, term, q):
|
||||
if custom_end:
|
||||
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
|
||||
func.datetime(db.cc_classes[c.id].value) <= func.datetime(custom_end)))
|
||||
elif c.datatype in ["int", "float"]:
|
||||
custom_low = term.get('custom_column_' + str(c.id) + '_low')
|
||||
custom_high = term.get('custom_column_' + str(c.id) + '_high')
|
||||
if custom_low:
|
||||
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
|
||||
db.cc_classes[c.id].value >= custom_low))
|
||||
if custom_high:
|
||||
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
|
||||
db.cc_classes[c.id].value <= custom_high))
|
||||
else:
|
||||
custom_query = term.get('custom_column_' + str(c.id))
|
||||
if custom_query != '' and custom_query is not None:
|
||||
if c.datatype == 'bool':
|
||||
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
|
||||
db.cc_classes[c.id].value == (custom_query == "True")))
|
||||
elif c.datatype == 'int' or c.datatype == 'float':
|
||||
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
|
||||
db.cc_classes[c.id].value == custom_query))
|
||||
elif c.datatype == 'rating':
|
||||
if c.datatype == 'bool':
|
||||
if custom_query != "Any":
|
||||
if custom_query == "":
|
||||
q = q.filter(~getattr(db.Books, 'custom_column_' + str(c.id)).
|
||||
any(db.cc_classes[c.id].value >= 0))
|
||||
else:
|
||||
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
|
||||
db.cc_classes[c.id].value == bool(custom_query == "True")))
|
||||
elif custom_query != '' and custom_query is not None:
|
||||
if c.datatype == 'rating':
|
||||
q = q.filter(getattr(db.Books, 'custom_column_' + str(c.id)).any(
|
||||
db.cc_classes[c.id].value == int(float(custom_query) * 2)))
|
||||
else:
|
||||
@@ -128,10 +141,10 @@ def adv_search_read_status(read_status):
|
||||
db_filter = coalesce(ub.ReadBook.read_status, 0) != ub.ReadBook.STATUS_FINISHED
|
||||
else:
|
||||
try:
|
||||
if read_status == "True":
|
||||
db_filter = db.cc_classes[config.config_read_column].value == True
|
||||
if read_status == "":
|
||||
db_filter = coalesce(db.cc_classes[config.config_read_column].value, 2) == 2
|
||||
else:
|
||||
db_filter = coalesce(db.cc_classes[config.config_read_column].value, False) != True
|
||||
db_filter = db.cc_classes[config.config_read_column].value == bool(read_status == "True")
|
||||
except (KeyError, AttributeError, IndexError):
|
||||
log.error("Custom Column No.{} does not exist in calibre database".format(config.config_read_column))
|
||||
flash(_("Custom Column No.%(column)d does not exist in calibre database",
|
||||
@@ -164,11 +177,24 @@ def adv_search_serie(q, include_series_inputs, exclude_series_inputs):
|
||||
q = q.filter(not_(db.Books.series.any(db.Series.id == serie)))
|
||||
return q
|
||||
|
||||
|
||||
def adv_search_shelf(q, include_shelf_inputs, exclude_shelf_inputs):
|
||||
q = q.outerjoin(ub.BookShelf, db.Books.id == ub.BookShelf.book_id)\
|
||||
.filter(or_(ub.BookShelf.shelf == None, ub.BookShelf.shelf.notin_(exclude_shelf_inputs)))
|
||||
if len(include_shelf_inputs) > 0:
|
||||
q = q.filter(ub.BookShelf.shelf.in_(include_shelf_inputs))
|
||||
if len(include_shelf_inputs):
|
||||
in_shelf = (
|
||||
calibre_db.session.query(ub.BookShelf.id)
|
||||
.filter(ub.BookShelf.book_id == db.Books.id)
|
||||
.filter(ub.BookShelf.shelf.in_(include_shelf_inputs))
|
||||
.exists()
|
||||
)
|
||||
q = q.filter(in_shelf)
|
||||
if len(exclude_shelf_inputs):
|
||||
ex_shelf = (
|
||||
calibre_db.session.query(ub.BookShelf.id)
|
||||
.filter(ub.BookShelf.book_id == db.Books.id)
|
||||
.filter(ub.BookShelf.shelf.in_(exclude_shelf_inputs))
|
||||
.exists()
|
||||
)
|
||||
q = q.filter(~ex_shelf)
|
||||
return q
|
||||
|
||||
def extend_search_term(searchterm,
|
||||
@@ -231,7 +257,7 @@ def render_adv_search_results(term, offset=None, order=None, limit=None):
|
||||
pagination = None
|
||||
|
||||
cc = calibre_db.get_cc_columns(config, filter_config_custom_read=True)
|
||||
calibre_db.session.connection().connection.connection.create_function("lower", 1, db.lcase)
|
||||
calibre_db.create_functions()
|
||||
query = calibre_db.generate_linked_query(config.config_read_column, db.Books)
|
||||
q = query.outerjoin(db.books_series_link, db.Books.id == db.books_series_link.c.book)\
|
||||
.outerjoin(db.Series)\
|
||||
@@ -244,21 +270,21 @@ def render_adv_search_results(term, offset=None, order=None, limit=None):
|
||||
tags['include_' + element] = term.get('include_' + element)
|
||||
tags['exclude_' + element] = term.get('exclude_' + element)
|
||||
|
||||
author_name = term.get("author_name")
|
||||
book_title = term.get("book_title")
|
||||
author_name = term.get("authors")
|
||||
book_title = term.get("title")
|
||||
publisher = term.get("publisher")
|
||||
pub_start = term.get("publishstart")
|
||||
pub_end = term.get("publishend")
|
||||
rating_low = term.get("ratinghigh")
|
||||
rating_high = term.get("ratinglow")
|
||||
description = term.get("comment")
|
||||
description = term.get("comments")
|
||||
read_status = term.get("read_status")
|
||||
if author_name:
|
||||
author_name = author_name.strip().lower().replace(',', '|')
|
||||
author_name = strip_whitespaces(author_name).lower().replace(',', '|')
|
||||
if book_title:
|
||||
book_title = book_title.strip().lower()
|
||||
book_title = strip_whitespaces(book_title).lower()
|
||||
if publisher:
|
||||
publisher = publisher.strip().lower()
|
||||
publisher = strip_whitespaces(publisher).lower()
|
||||
|
||||
search_term = []
|
||||
cc_present = False
|
||||
@@ -274,10 +300,23 @@ def render_adv_search_results(term, offset=None, order=None, limit=None):
|
||||
cc_present = True
|
||||
if column_end:
|
||||
search_term.extend(["{} <= {}".format(c.name,
|
||||
format_date(datetime.strptime(column_end, "%Y-%m-%d").date(),
|
||||
format_date(datetime.strptime(column_end, "%Y-%m-%d").date(),
|
||||
format='medium')
|
||||
)])
|
||||
cc_present = True
|
||||
if c.datatype in ["int", "float"]:
|
||||
column_low = term.get('custom_column_' + str(c.id) + '_low')
|
||||
column_high = term.get('custom_column_' + str(c.id) + '_high')
|
||||
if column_low:
|
||||
search_term.extend(["{} >= {}".format(c.name, column_low)])
|
||||
cc_present = True
|
||||
if column_high:
|
||||
search_term.extend(["{} <= {}".format(c.name,column_high)])
|
||||
cc_present = True
|
||||
elif c.datatype == "bool":
|
||||
if term.get('custom_column_' + str(c.id)) != "Any":
|
||||
search_term.extend([("{}: {}".format(c.name, term.get('custom_column_' + str(c.id))))])
|
||||
cc_present = True
|
||||
elif term.get('custom_column_' + str(c.id)):
|
||||
search_term.extend([("{}: {}".format(c.name, term.get('custom_column_' + str(c.id))))])
|
||||
cc_present = True
|
||||
@@ -314,10 +353,12 @@ def render_adv_search_results(term, offset=None, order=None, limit=None):
|
||||
q = adv_search_ratings(q, rating_high, rating_low)
|
||||
|
||||
if description:
|
||||
pass
|
||||
q = q.filter(db.Books.comments.any(func.lower(db.Comments.text).ilike("%" + description + "%")))
|
||||
|
||||
# search custom columns
|
||||
try:
|
||||
pass
|
||||
q = adv_search_custom_columns(cc, term, q)
|
||||
except AttributeError as ex:
|
||||
log.debug_or_exception(ex)
|
||||
|
||||
+11
-15
@@ -23,17 +23,16 @@ import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
from flask import Blueprint, Response, request, url_for
|
||||
from flask_login import current_user
|
||||
from flask_login import login_required
|
||||
from flask import Blueprint, request, url_for, make_response, jsonify
|
||||
from .cw_login import current_user
|
||||
from flask_babel import get_locale
|
||||
from sqlalchemy.exc import InvalidRequestError, OperationalError
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
|
||||
from cps.services.Metadata import Metadata
|
||||
from . import constants, logger, ub, web_server
|
||||
from .usermanagement import user_login_required
|
||||
|
||||
# current_milli_time = lambda: int(round(time() * 1000))
|
||||
|
||||
meta = Blueprint("metadata", __name__)
|
||||
|
||||
@@ -81,7 +80,7 @@ cl = list_classes(new_list)
|
||||
|
||||
|
||||
@meta.route("/metadata/provider")
|
||||
@login_required
|
||||
@user_login_required
|
||||
def metadata_provider():
|
||||
active = current_user.view_settings.get("metadata", {})
|
||||
provider = list()
|
||||
@@ -90,12 +89,12 @@ def metadata_provider():
|
||||
provider.append(
|
||||
{"name": c.__name__, "active": ac, "initial": ac, "id": c.__id__}
|
||||
)
|
||||
return Response(json.dumps(provider), mimetype="application/json")
|
||||
return make_response(jsonify(provider))
|
||||
|
||||
|
||||
@meta.route("/metadata/provider", methods=["POST"])
|
||||
@meta.route("/metadata/provider/<prov_name>", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def metadata_change_active_provider(prov_name):
|
||||
new_state = request.get_json()
|
||||
active = current_user.view_settings.get("metadata", {})
|
||||
@@ -115,14 +114,12 @@ def metadata_change_active_provider(prov_name):
|
||||
provider = next((c for c in cl if c.__id__ == prov_name), None)
|
||||
if provider is not None:
|
||||
data = provider.search(new_state.get("query", ""))
|
||||
return Response(
|
||||
json.dumps([asdict(x) for x in data]), mimetype="application/json"
|
||||
)
|
||||
return make_response(jsonify([asdict(x) for x in data]))
|
||||
return ""
|
||||
|
||||
|
||||
@meta.route("/metadata/search", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def metadata_search():
|
||||
query = request.form.to_dict().get("query")
|
||||
data = list()
|
||||
@@ -130,7 +127,7 @@ def metadata_search():
|
||||
locale = get_locale()
|
||||
if query:
|
||||
static_cover = url_for("static", filename="generic_cover.jpg")
|
||||
# start = current_milli_time()
|
||||
# ret = cl[0].search(query, static_cover, locale)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
|
||||
meta = {
|
||||
executor.submit(c.search, query, static_cover, locale): c
|
||||
@@ -138,6 +135,5 @@ def metadata_search():
|
||||
if active.get(c.__id__, True)
|
||||
}
|
||||
for future in concurrent.futures.as_completed(meta):
|
||||
data.extend([asdict(x) for x in future.result() if x])
|
||||
# log.info({'Time elapsed {}'.format(current_milli_time()-start)})
|
||||
return Response(json.dumps(data), mimetype="application/json")
|
||||
data.extend([asdict(x) for x in (future.result() or []) if x])
|
||||
return make_response(jsonify(data))
|
||||
|
||||
+15
-2
@@ -21,7 +21,6 @@ import os
|
||||
import errno
|
||||
import signal
|
||||
import socket
|
||||
import asyncio
|
||||
|
||||
try:
|
||||
from gevent.pywsgi import WSGIServer
|
||||
@@ -42,7 +41,7 @@ except ImportError:
|
||||
VERSION = 'Tornado ' + _version
|
||||
_GEVENT = False
|
||||
|
||||
from . import logger
|
||||
from . import logger, constants
|
||||
|
||||
|
||||
log = logger.create()
|
||||
@@ -217,6 +216,13 @@ class WebServer(object):
|
||||
try:
|
||||
sock, output = self._make_gevent_listener()
|
||||
log.info('Starting Gevent server on %s', output)
|
||||
try:
|
||||
# Also print to stdout so interactive terminals show a clear success message
|
||||
if constants.APP_MODE not in ['development', 'test']:
|
||||
print(f"Calibre-Web: server started on {output}")
|
||||
except Exception:
|
||||
print(f"Calibre-Web: error {output}")
|
||||
pass
|
||||
self.wsgiserver = WSGIServer(sock, self.app, log=self.access_logger, handler_class=MyWSGIHandler,
|
||||
error_log=log,
|
||||
spawn=Pool(), **ssl_args)
|
||||
@@ -267,6 +273,13 @@ class WebServer(object):
|
||||
output = _readable_listen_address(self.listen_address, self.listen_port)
|
||||
http_server.listen(self.listen_port, self.listen_address)
|
||||
log.info('Starting Tornado server on %s', output)
|
||||
# Also print to stdout so interactive terminals show a clear success message
|
||||
try:
|
||||
if constants.APP_MODE not in ['development', 'test']:
|
||||
print(f"Calibre-Web: server started on {output}")
|
||||
except Exception:
|
||||
print(f"Calibre-Web: error {output}")
|
||||
pass
|
||||
|
||||
self.wsgiserver = IOLoop.current()
|
||||
self.wsgiserver.start()
|
||||
|
||||
@@ -42,6 +42,7 @@ class BackgroundScheduler:
|
||||
if cls._instance is None:
|
||||
cls._instance = super(BackgroundScheduler, cls).__new__(cls)
|
||||
cls.log = logger.create()
|
||||
logger.logging.getLogger('tzlocal').setLevel(logger.logging.WARNING)
|
||||
cls.scheduler = BScheduler()
|
||||
cls.scheduler.start()
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ def send_messsage(token, msg):
|
||||
if creds and creds.expired and creds.refresh_token:
|
||||
creds.refresh(Request())
|
||||
service = build('gmail', 'v1', credentials=creds)
|
||||
message_as_bytes = msg.as_bytes() # the message should converted from string to bytes.
|
||||
message_as_bytes = msg.as_bytes() # the message should be converted from string to bytes.
|
||||
message_as_base64 = base64.urlsafe_b64encode(message_as_bytes) # encode in base64 (printable letters coding)
|
||||
raw = message_as_base64.decode() # convert to something JSON serializable
|
||||
body = {'raw': raw}
|
||||
|
||||
@@ -22,7 +22,7 @@ import requests
|
||||
|
||||
from goodreads.client import GoodreadsClient
|
||||
from goodreads.request import GoodreadsRequest
|
||||
import xmltodict
|
||||
from lxml import etree
|
||||
|
||||
try:
|
||||
import Levenshtein
|
||||
@@ -33,6 +33,39 @@ from .. import logger
|
||||
from ..clean_html import clean_string
|
||||
|
||||
|
||||
|
||||
|
||||
def etree_to_dict(t):
|
||||
"""
|
||||
Convert lxml ElementTree to a nested dict (similar to xmltodict).
|
||||
"""
|
||||
d = {t.tag: {} if t.attrib else None}
|
||||
children = list(t)
|
||||
|
||||
if children:
|
||||
dd = {}
|
||||
for dc in map(etree_to_dict, children):
|
||||
for k, v in dc.items():
|
||||
if k in dd:
|
||||
if not isinstance(dd[k], list):
|
||||
dd[k] = [dd[k]]
|
||||
dd[k].append(v)
|
||||
else:
|
||||
dd[k] = v
|
||||
d = {t.tag: dd}
|
||||
|
||||
if t.attrib:
|
||||
d[t.tag].update(('@' + k, v) for k, v in t.attrib.items())
|
||||
|
||||
text = (t.text or '').strip()
|
||||
if text:
|
||||
if children or t.attrib:
|
||||
d[t.tag]['#text'] = text
|
||||
else:
|
||||
d[t.tag] = text
|
||||
|
||||
return d
|
||||
|
||||
class my_GoodreadsClient(GoodreadsClient):
|
||||
|
||||
def request(self, *args, **kwargs):
|
||||
@@ -59,7 +92,9 @@ class my_GoodreadsRequest(GoodreadsRequest):
|
||||
if resp.status_code != 200:
|
||||
raise GoodreadsRequestException(resp.reason, self.path)
|
||||
if self.req_format == 'xml':
|
||||
data_dict = xmltodict.parse(resp.content)
|
||||
root = etree.fromstring(resp.content, parser=etree.XMLParser(resolve_entities=False, no_network=True))
|
||||
data_dict = etree_to_dict(root)
|
||||
|
||||
return data_dict['GoodreadsResponse']
|
||||
else:
|
||||
raise Exception("Invalid format")
|
||||
@@ -117,7 +152,7 @@ def get_author_info(author_name):
|
||||
|
||||
|
||||
def get_other_books(author_info, library_books=None):
|
||||
# Get all identifiers (ISBN, Goodreads, etc) and filter author's books by that list so we show fewer duplicates
|
||||
# Get all identifiers (ISBN, Goodreads, etc.) and filter author's books by that list so we show fewer duplicates
|
||||
# Note: Not all images will be shown, even though they're available on Goodreads.com.
|
||||
# See https://www.goodreads.com/topic/show/18213769-goodreads-book-images
|
||||
|
||||
|
||||
@@ -31,6 +31,16 @@ except ImportError:
|
||||
log = logger.create()
|
||||
|
||||
|
||||
def _escape_ldap_filter(s):
|
||||
"""Escape special characters for safe use in LDAP filter strings (RFC 4515)."""
|
||||
s = s.replace('\\', '\\5c')
|
||||
s = s.replace('*', '\\2a')
|
||||
s = s.replace('(', '\\28')
|
||||
s = s.replace(')', '\\29')
|
||||
s = s.replace('\x00', '\\00')
|
||||
return s
|
||||
|
||||
|
||||
class LDAPLogger(object):
|
||||
|
||||
@staticmethod
|
||||
@@ -148,9 +158,11 @@ def bind_user(username, password):
|
||||
|
||||
:returns: True if login succeeded, False if login failed, None if server unavailable.
|
||||
'''
|
||||
# Escape LDAP special characters to prevent LDAP injection in search filters
|
||||
safe_username = _escape_ldap_filter(username)
|
||||
try:
|
||||
if _ldap.get_object_details(username):
|
||||
result = _ldap.bind_user(username, password)
|
||||
if _ldap.get_object_details(safe_username):
|
||||
result = _ldap.bind_user(safe_username, password)
|
||||
log.debug("LDAP login '%s': %r", username, result)
|
||||
return result is not None, None
|
||||
return None, None # User not found
|
||||
|
||||
@@ -199,7 +199,7 @@ class CalibreTask:
|
||||
self.run(*args)
|
||||
except Exception as ex:
|
||||
self._handleError(str(ex))
|
||||
log.error_or_exception(ex)
|
||||
log.exception(ex)
|
||||
|
||||
self.end_time = datetime.now()
|
||||
|
||||
|
||||
+97
-40
@@ -21,17 +21,17 @@
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from flask import Blueprint, flash, redirect, request, url_for, abort
|
||||
from flask_babel import gettext as _
|
||||
from flask_login import current_user, login_required
|
||||
from .cw_login import current_user
|
||||
from sqlalchemy.exc import InvalidRequestError, OperationalError
|
||||
from sqlalchemy.sql.expression import func, true
|
||||
|
||||
from . import calibre_db, config, db, logger, ub
|
||||
from .render_template import render_title_template
|
||||
from .usermanagement import login_required_if_no_ano
|
||||
from .usermanagement import login_required_if_no_ano, user_login_required
|
||||
|
||||
log = logger.create()
|
||||
|
||||
@@ -39,7 +39,7 @@ shelf = Blueprint('shelf', __name__)
|
||||
|
||||
|
||||
@shelf.route("/shelf/add/<int:shelf_id>/<int:book_id>", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def add_to_shelf(shelf_id, book_id):
|
||||
xhr = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
|
||||
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
|
||||
@@ -80,7 +80,7 @@ def add_to_shelf(shelf_id, book_id):
|
||||
return "%s is a invalid Book Id. Could not be added to Shelf" % book_id, 400
|
||||
|
||||
shelf.books.append(ub.BookShelf(shelf=shelf.id, book_id=book_id, order=maxOrder + 1))
|
||||
shelf.last_modified = datetime.utcnow()
|
||||
shelf.last_modified = datetime.now(timezone.utc)
|
||||
try:
|
||||
ub.session.merge(shelf)
|
||||
ub.session.commit()
|
||||
@@ -102,8 +102,54 @@ def add_to_shelf(shelf_id, book_id):
|
||||
return "", 204
|
||||
|
||||
|
||||
@shelf.route("/shelf/massremove/<int:shelf_id>", methods=["POST"])
|
||||
@user_login_required
|
||||
def search_from_shelf(shelf_id):
|
||||
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
|
||||
if shelf is None:
|
||||
log.error("Invalid shelf specified: {}".format(shelf_id))
|
||||
flash(_("Invalid shelf specified"), category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
|
||||
if not check_shelf_edit_permissions(shelf):
|
||||
log.warning("You are not allowed to remove a book from the shelf".format(shelf.name))
|
||||
flash(_("You are not allowed to remove a book from the shelf"), category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
|
||||
if current_user.id in ub.searched_ids and ub.searched_ids[current_user.id]:
|
||||
books_from_shelf = list()
|
||||
books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).all()
|
||||
if books_in_shelf:
|
||||
book_ids = [book_id.book_id for book_id in books_in_shelf]
|
||||
for searchid in ub.searched_ids[current_user.id]:
|
||||
if searchid in book_ids:
|
||||
books_from_shelf.append(searchid)
|
||||
else:
|
||||
log.error("No Books are part of {}".format(shelf.name))
|
||||
flash(_("No Books are part of the shelf: %(name)s", name=shelf.name), category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
|
||||
# maxOrder = ub.session.query(func.max(ub.BookShelf.order)).filter(ub.BookShelf.shelf == shelf_id).first()[0] or 0
|
||||
|
||||
for book in books_from_shelf:
|
||||
ub.session.delete(ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).filter(
|
||||
ub.BookShelf.book_id == book).first())
|
||||
shelf.last_modified = datetime.now(timezone.utc)
|
||||
try:
|
||||
ub.session.commit()
|
||||
flash(_("Books have been removed from shelf: %(sname)s", sname=shelf.name), category="success")
|
||||
except (OperationalError, InvalidRequestError) as e:
|
||||
ub.session.rollback()
|
||||
log.error_or_exception("Settings Database error: {}".format(e))
|
||||
flash(_("Oops! Database Error: %(error)s.", error=e.orig), category="error")
|
||||
else:
|
||||
log.error("Could not remove books from shelf: {}".format(shelf.name))
|
||||
flash(_("Could not remove books from shelf: %(sname)s", sname=shelf.name), category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
|
||||
|
||||
@shelf.route("/shelf/massadd/<int:shelf_id>", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def search_to_shelf(shelf_id):
|
||||
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
|
||||
if shelf is None:
|
||||
@@ -120,9 +166,7 @@ def search_to_shelf(shelf_id):
|
||||
books_for_shelf = list()
|
||||
books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).all()
|
||||
if books_in_shelf:
|
||||
book_ids = list()
|
||||
for book_id in books_in_shelf:
|
||||
book_ids.append(book_id.book_id)
|
||||
book_ids = [book_id.book_id for book_id in books_in_shelf]
|
||||
for searchid in ub.searched_ids[current_user.id]:
|
||||
if searchid not in book_ids:
|
||||
books_for_shelf.append(searchid)
|
||||
@@ -139,7 +183,7 @@ def search_to_shelf(shelf_id):
|
||||
for book in books_for_shelf:
|
||||
maxOrder += 1
|
||||
shelf.books.append(ub.BookShelf(shelf=shelf.id, book_id=book, order=maxOrder))
|
||||
shelf.last_modified = datetime.utcnow()
|
||||
shelf.last_modified = datetime.now(timezone.utc)
|
||||
try:
|
||||
ub.session.merge(shelf)
|
||||
ub.session.commit()
|
||||
@@ -155,7 +199,7 @@ def search_to_shelf(shelf_id):
|
||||
|
||||
|
||||
@shelf.route("/shelf/remove/<int:shelf_id>/<int:book_id>", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def remove_from_shelf(shelf_id, book_id):
|
||||
xhr = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
|
||||
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
|
||||
@@ -185,7 +229,7 @@ def remove_from_shelf(shelf_id, book_id):
|
||||
|
||||
try:
|
||||
ub.session.delete(book_shelf)
|
||||
shelf.last_modified = datetime.utcnow()
|
||||
shelf.last_modified = datetime.now(timezone.utc)
|
||||
ub.session.commit()
|
||||
except (OperationalError, InvalidRequestError) as e:
|
||||
ub.session.rollback()
|
||||
@@ -212,14 +256,14 @@ def remove_from_shelf(shelf_id, book_id):
|
||||
|
||||
|
||||
@shelf.route("/shelf/create", methods=["GET", "POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def create_shelf():
|
||||
shelf = ub.Shelf()
|
||||
return create_edit_shelf(shelf, page_title=_("Create a Shelf"), page="shelfcreate")
|
||||
|
||||
|
||||
@shelf.route("/shelf/edit/<int:shelf_id>", methods=["GET", "POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def edit_shelf(shelf_id):
|
||||
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
|
||||
if not check_shelf_edit_permissions(shelf):
|
||||
@@ -229,7 +273,7 @@ def edit_shelf(shelf_id):
|
||||
|
||||
|
||||
@shelf.route("/shelf/delete/<int:shelf_id>", methods=["POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def delete_shelf(shelf_id):
|
||||
cur_shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
|
||||
try:
|
||||
@@ -250,7 +294,7 @@ def show_simpleshelf(shelf_id):
|
||||
return render_show_shelf(2, shelf_id, 1, None)
|
||||
|
||||
|
||||
@shelf.route("/shelf/<int:shelf_id>", defaults={"sort_param": "order", 'page': 1})
|
||||
@shelf.route("/shelf/<int:shelf_id>", defaults={"sort_param": "stored", 'page': 1})
|
||||
@shelf.route("/shelf/<int:shelf_id>/<sort_param>", defaults={'page': 1})
|
||||
@shelf.route("/shelf/<int:shelf_id>/<sort_param>/<int:page>")
|
||||
@login_required_if_no_ano
|
||||
@@ -259,11 +303,14 @@ def show_shelf(shelf_id, sort_param, page):
|
||||
|
||||
|
||||
@shelf.route("/shelf/order/<int:shelf_id>", methods=["GET", "POST"])
|
||||
@login_required
|
||||
@user_login_required
|
||||
def order_shelf(shelf_id):
|
||||
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
|
||||
if shelf and check_shelf_view_permissions(shelf):
|
||||
if request.method == "POST":
|
||||
if not check_shelf_edit_permissions(shelf):
|
||||
flash(_("Sorry you are not allowed to edit this shelf"), category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
to_save = request.form.to_dict()
|
||||
books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).order_by(
|
||||
ub.BookShelf.order.asc()).all()
|
||||
@@ -271,7 +318,7 @@ def order_shelf(shelf_id):
|
||||
for book in books_in_shelf:
|
||||
setattr(book, 'order', to_save[str(book.book_id)])
|
||||
counter += 1
|
||||
# if order different from before -> shelf.last_modified = datetime.utcnow()
|
||||
# if order different from before -> shelf.last_modified = datetime.now(timezone.utc)
|
||||
try:
|
||||
ub.session.commit()
|
||||
except (OperationalError, InvalidRequestError) as e:
|
||||
@@ -418,29 +465,37 @@ def change_shelf_order(shelf_id, order):
|
||||
|
||||
def render_show_shelf(shelf_type, shelf_id, page_no, sort_param):
|
||||
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
|
||||
|
||||
status = current_user.get_view_property("shelf", 'man')
|
||||
# check user is allowed to access shelf
|
||||
if shelf and check_shelf_view_permissions(shelf):
|
||||
if shelf_type == 1:
|
||||
# order = [ub.BookShelf.order.asc()]
|
||||
if sort_param == 'pubnew':
|
||||
change_shelf_order(shelf_id, [db.Books.pubdate.desc()])
|
||||
if sort_param == 'pubold':
|
||||
change_shelf_order(shelf_id, [db.Books.pubdate])
|
||||
if sort_param == 'abc':
|
||||
change_shelf_order(shelf_id, [db.Books.sort])
|
||||
if sort_param == 'zyx':
|
||||
change_shelf_order(shelf_id, [db.Books.sort.desc()])
|
||||
if sort_param == 'new':
|
||||
change_shelf_order(shelf_id, [db.Books.timestamp.desc()])
|
||||
if sort_param == 'old':
|
||||
change_shelf_order(shelf_id, [db.Books.timestamp])
|
||||
if sort_param == 'authaz':
|
||||
change_shelf_order(shelf_id, [db.Books.author_sort.asc(), db.Series.name, db.Books.series_index])
|
||||
if sort_param == 'authza':
|
||||
change_shelf_order(shelf_id, [db.Books.author_sort.desc(),
|
||||
db.Series.name.desc(),
|
||||
db.Books.series_index.desc()])
|
||||
if status != 'on':
|
||||
if sort_param == 'stored':
|
||||
sort_param = current_user.get_view_property("shelf", 'stored')
|
||||
else:
|
||||
current_user.set_view_property("shelf", 'stored', sort_param)
|
||||
if sort_param == 'pubnew':
|
||||
change_shelf_order(shelf_id, [db.Books.pubdate.desc()])
|
||||
if sort_param == 'pubold':
|
||||
change_shelf_order(shelf_id, [db.Books.pubdate])
|
||||
if sort_param == 'shelfnew':
|
||||
change_shelf_order(shelf_id, [ub.BookShelf.date_added.desc()])
|
||||
if sort_param == 'shelfold':
|
||||
change_shelf_order(shelf_id, [ub.BookShelf.date_added])
|
||||
if sort_param == 'abc':
|
||||
change_shelf_order(shelf_id, [db.Books.sort])
|
||||
if sort_param == 'zyx':
|
||||
change_shelf_order(shelf_id, [db.Books.sort.desc()])
|
||||
if sort_param == 'new':
|
||||
change_shelf_order(shelf_id, [db.Books.timestamp.desc()])
|
||||
if sort_param == 'old':
|
||||
change_shelf_order(shelf_id, [db.Books.timestamp])
|
||||
if sort_param == 'authaz':
|
||||
change_shelf_order(shelf_id, [db.Books.author_sort.asc(), db.Series.name, db.Books.series_index])
|
||||
if sort_param == 'authza':
|
||||
change_shelf_order(shelf_id, [db.Books.author_sort.desc(),
|
||||
db.Series.name.desc(),
|
||||
db.Books.series_index.desc()])
|
||||
page = "shelf.html"
|
||||
pagesize = 0
|
||||
else:
|
||||
@@ -453,7 +508,7 @@ def render_show_shelf(shelf_type, shelf_id, page_no, sort_param):
|
||||
[ub.BookShelf.order.asc()],
|
||||
True, config.config_read_column,
|
||||
ub.BookShelf, ub.BookShelf.book_id == db.Books.id)
|
||||
# delete chelf entries where book is not existent anymore, can happen if book is deleted outside calibre-web
|
||||
# delete shelf entries where book is not existent anymore, can happen if book is deleted outside calibre-web
|
||||
wrong_entries = calibre_db.session.query(ub.BookShelf) \
|
||||
.join(db.Books, ub.BookShelf.book_id == db.Books.id, isouter=True) \
|
||||
.filter(db.Books.id == None).all()
|
||||
@@ -472,7 +527,9 @@ def render_show_shelf(shelf_type, shelf_id, page_no, sort_param):
|
||||
pagination=pagination,
|
||||
title=_("Shelf: '%(name)s'", name=shelf.name),
|
||||
shelf=shelf,
|
||||
page="shelf")
|
||||
page="shelf",
|
||||
status=status,
|
||||
order=sort_param)
|
||||
else:
|
||||
flash(_("Error opening shelf. Shelf does not exist or is not accessible"), category="error")
|
||||
return redirect(url_for("web.index"))
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
body {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
nav {
|
||||
height: 75px;
|
||||
padding: 5px 20px;
|
||||
width: 100%;
|
||||
display: table;
|
||||
box-sizing: border-box;
|
||||
border-bottom: 1px solid black;
|
||||
}
|
||||
|
||||
nav > * {
|
||||
display: inline-block;
|
||||
display: table-cell;
|
||||
vertical-align: middle;
|
||||
float: none;
|
||||
text-align: center;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
nav > *:first-child {
|
||||
text-align: left;
|
||||
width: 1%;
|
||||
}
|
||||
|
||||
.theme{
|
||||
text-align: center;
|
||||
margin: 10px;
|
||||
}
|
||||
nav > *:last-child {
|
||||
text-align: right;
|
||||
width: 1%;
|
||||
}
|
||||
|
||||
nav > a {
|
||||
color: black;
|
||||
margin: 0 20px;
|
||||
}
|
||||
|
||||
.search {
|
||||
margin: auto auto;
|
||||
}
|
||||
|
||||
form > input {
|
||||
width: 18ch;
|
||||
padding-left: 4px;
|
||||
}
|
||||
|
||||
form > * {
|
||||
height: 50px;
|
||||
background-color: white;
|
||||
border-radius: 0;
|
||||
border: 1px solid #ccc;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
display: inline-block;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
form > span {
|
||||
margin-left: -5px;
|
||||
}
|
||||
|
||||
button {
|
||||
border: none;
|
||||
padding: 0 10px;
|
||||
margin: 0;
|
||||
width: 160px;
|
||||
height: 100%;
|
||||
background-color: white;
|
||||
}
|
||||
|
||||
.body {
|
||||
padding: 5px 20px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: black;
|
||||
}
|
||||
|
||||
img {
|
||||
width: 150px;
|
||||
height: 250px;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.listing {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
margin-right: 20px;
|
||||
}
|
||||
|
||||
.pagination {
|
||||
padding: 10px 0;
|
||||
height: 20px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.pagination > div {
|
||||
float: left;
|
||||
}
|
||||
|
||||
.pagination > div:last-child {
|
||||
float: right;
|
||||
}
|
||||
+99
-53
@@ -2018,7 +2018,7 @@ body > div.container-fluid > div > div.col-sm-10 > div.pagination > .page-previo
|
||||
display: none
|
||||
}
|
||||
|
||||
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container > div.col-xs-12, body.catlist > div.container-fluid > div > div.col-sm-10 > div.container > div.col-xs-12, body.langlist > div.container-fluid > div > div.col-sm-10 > div.container > div.col-sm-6, body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container > div.col-sm-6 {
|
||||
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container1 > div.col-xs-12, body.downloadlist > div.container-fluid > div > div.col-sm-10 > div.container1 > div.col-xs-12, body.catlist > div.container-fluid > div > div.col-sm-10 > div.container1 > div.col-xs-12, body.langlist > div.container-fluid > div > div.col-sm-10 > div.container1 > div.col-sm-6, body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container1 > div.col-sm-6 {
|
||||
width: 100%
|
||||
}
|
||||
|
||||
@@ -2042,7 +2042,7 @@ body.serieslist > div.container-fluid > div > div.col-sm-10:before {
|
||||
}
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container1 {
|
||||
width: calc(80% - 30px);
|
||||
margin: 120px 0 30px 20%;
|
||||
border-top: 2px solid rgba(0, 0, 0, .3);
|
||||
@@ -2051,19 +2051,19 @@ body > div.container-fluid > div > div.col-sm-10 > div.container {
|
||||
max-width: calc(80% - 30px)
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container > div {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div {
|
||||
padding: 0
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row {
|
||||
padding: 4px 0
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row:nth-of-type(even) {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row:nth-of-type(even) {
|
||||
background: hsla(0, 0%, 100%, .02)
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row > .col-xs-6 {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row > .col-xs-6 {
|
||||
width: calc(91.666% - 30px);
|
||||
overflow: hidden;
|
||||
-o-text-overflow: ellipsis;
|
||||
@@ -2072,7 +2072,7 @@ body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row >
|
||||
padding-left: 60px
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row > .col-xs-6 > a {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row > .col-xs-6 > a {
|
||||
-o-text-overflow: ellipsis;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
@@ -2082,7 +2082,7 @@ body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row >
|
||||
}
|
||||
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container1 {
|
||||
width: calc(80% - 30px);
|
||||
margin: 120px 0 30px 20%;
|
||||
border-top: 2px solid rgba(0, 0, 0, .3);
|
||||
@@ -2091,19 +2091,19 @@ body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container
|
||||
max-width: calc(80% - 30px)
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container > div {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container1 > div {
|
||||
padding: 0
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container > div > .row {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container1 > div > .row {
|
||||
padding: 4px 0
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container > div > .row:nth-of-type(even) {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container1 > div > .row:nth-of-type(even) {
|
||||
background: hsla(0, 0%, 100%, .02)
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container > div > .row > .col-xs-6 {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container1 > div > .row > .col-xs-6 {
|
||||
width: calc(91.666% - 30px);
|
||||
overflow: hidden;
|
||||
-o-text-overflow: ellipsis;
|
||||
@@ -2112,7 +2112,7 @@ body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container
|
||||
padding-left: 60px
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container > div > .row > .col-xs-6 > a {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.discover > div.container1 > div > .row > .col-xs-6 > a {
|
||||
-o-text-overflow: ellipsis;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
@@ -2146,7 +2146,6 @@ body.catlist > div.container-fluid > div.row-fluid > div.col-sm-10:before {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
body.authorlist > div.container-fluid > div.row-fluid > div.col-sm-10:before, body.langlist > div.container-fluid > div > div.col-sm-10:before {
|
||||
font-family: 'Glyphicons Halflings', serif;
|
||||
font-style: normal;
|
||||
@@ -2172,10 +2171,12 @@ body.authorlist > div.container-fluid > div.row-fluid > div.col-sm-10:before {
|
||||
}
|
||||
|
||||
body.langlist > div.container-fluid > div > div.col-sm-10:before {
|
||||
content: "\e034"
|
||||
content: "\e034";
|
||||
top: 240px;
|
||||
}
|
||||
|
||||
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container:before, body.catlist > div.container-fluid > div > div.col-sm-10 > div.container:before, body.langlist > div.container-fluid > div > div.col-sm-10 > div.container:before, body.me > div.container-fluid > div > div.col-sm-10 > div.discover:before, body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
|
||||
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.downloadlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.catlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.langlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.me > div.container-fluid > div > div.col-sm-10 > div.discover:before, body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
top: 60px;
|
||||
font-size: 24px;
|
||||
color: #eee;
|
||||
@@ -2186,63 +2187,104 @@ body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container:befo
|
||||
font-weight: 400
|
||||
}
|
||||
|
||||
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
content: "Authors";
|
||||
top: 115px;
|
||||
display: table;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 992px) {
|
||||
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
top: 60px;
|
||||
}
|
||||
}
|
||||
|
||||
body.catlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
@media screen and (max-width: 992px) {
|
||||
body.downloadlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
top: 60px;
|
||||
}
|
||||
}
|
||||
|
||||
body.downloadlist > div.container-fluid > div.row-fluid > div.col-sm-10:before {
|
||||
font-family: Glyphicons Halflings, serif;
|
||||
content: "\E026";
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 1;
|
||||
font-size: 6vw;
|
||||
position: fixed;
|
||||
left: 240px;
|
||||
top: 240px;
|
||||
width: calc(20% - 55px);
|
||||
text-align: center
|
||||
}
|
||||
|
||||
|
||||
@media screen and (max-width: 992px) {
|
||||
body.downloadlist > div.container-fluid > div.row-fluid > div.col-sm-10:before {
|
||||
top: 180px;
|
||||
}
|
||||
}
|
||||
|
||||
body.downloadlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
content: "Downloads";
|
||||
top: 115px;
|
||||
display: table;
|
||||
}
|
||||
|
||||
|
||||
body.catlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
content: "Categories";
|
||||
top: 115px;
|
||||
display: table;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 992px) {
|
||||
body.catlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.catlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
top: 60px;
|
||||
}
|
||||
}
|
||||
|
||||
body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
content: "Series";
|
||||
top: 115px;
|
||||
display: table;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 992px) {
|
||||
body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
top: 60px;
|
||||
}
|
||||
}
|
||||
|
||||
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
content: "File formats";
|
||||
top: 115px;
|
||||
display: table;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 992px) {
|
||||
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
top: 60px;
|
||||
}
|
||||
}
|
||||
|
||||
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
content: "File formats";
|
||||
top: 115px;
|
||||
display: table;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 992px) {
|
||||
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
top: 60px;
|
||||
}
|
||||
}
|
||||
|
||||
body.langlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
content: "Languages"
|
||||
body.langlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
content: "Languages";
|
||||
top: 115px;
|
||||
display: table;
|
||||
}
|
||||
|
||||
body.advsearch > div.container-fluid > div > div.col-sm-10 > div.col-md-10.col-lg-6 {
|
||||
@@ -3268,6 +3310,10 @@ div.btn-group[role=group][aria-label="Download, send to Kindle, reading"] > div.
|
||||
left: auto !important
|
||||
}
|
||||
|
||||
ul.dropdown-menu.offscreen {
|
||||
margin: 2px -160px 0
|
||||
}
|
||||
|
||||
div.btn-group[role=group][aria-label="Download, send to Kindle, reading"] .dropdown-menu.offscreen {
|
||||
position: fixed;
|
||||
top: 120px;
|
||||
@@ -4333,6 +4379,7 @@ body.advanced_search > div.container-fluid > div.row-fluid > div.col-sm-10 > div
|
||||
|
||||
.navbar-right > li > ul.dropdown-menu.offscreen {
|
||||
right: -10px
|
||||
|
||||
}
|
||||
|
||||
.login .plexBack, body.login > div.container-fluid > div.row-fluid > div.col-sm-2, body.login > div.navbar.navbar-default.navbar-static-top > div > form {
|
||||
@@ -6416,7 +6463,7 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
|
||||
display: none !important
|
||||
}
|
||||
|
||||
.shelforder > .container-fluid > .row-fluid > .col-sm-10 > div.col-sm-6.col-lg-6.col-xs-6 > h2:before, body.advsearch > div.container-fluid > div > div.col-sm-10:before, body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container:before, body.catlist > div.container-fluid > div > div.col-sm-10 > div.container:before, body.langlist > div.container-fluid > div > div.col-sm-10 > div.container:before, body.login .navbar > .container-fluid > .navbar-header > button.navbar-toggle, body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
.shelforder > .container-fluid > .row-fluid > .col-sm-10 > div.col-sm-6.col-lg-6.col-xs-6 > h2:before, body.advsearch > div.container-fluid > div > div.col-sm-10:before, body.authorlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.catlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.langlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.downloadlist > div.container-fluid > div > div.col-sm-10 > div.container1:before, body.login .navbar > .container-fluid > .navbar-header > button.navbar-toggle, body.serieslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
display: none
|
||||
}
|
||||
|
||||
@@ -6522,7 +6569,7 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
|
||||
background-size: 30px
|
||||
}
|
||||
|
||||
body.advanced_search > div.container-fluid > div > div.col-sm-10 > div.col-sm-8:before, body.author:not(.authorlist) .undefined-img:before, body.authorlist > div.container-fluid > div.row-fluid > div.col-sm-10:before, body.catlist > div.container-fluid > div.row-fluid > div.col-sm-10:before, body.langlist > div.container-fluid > div > div.col-sm-10:before, body.ratingslist > div.container-fluid > div > div.col-sm-10:before, body.serieslist > div.container-fluid > div > div.col-sm-10:before, body.shelforder > div.container-fluid > div.row-fluid > div.col-sm-10:before {
|
||||
body.advanced_search > div.container-fluid > div > div.col-sm-10 > div.col-sm-8:before, body.author:not(.authorlist) .undefined-img:before, body.authorlist > div.container-fluid > div.row-fluid > div.col-sm-10:before, body.catlist > div.container-fluid > div.row-fluid > div.col-sm-10:before, body.downloadlist > div.container-fluid > div.row-fluid > div.col-sm-10:before, body.langlist > div.container-fluid > div > div.col-sm-10:before, body.ratingslist > div.container-fluid > div > div.col-sm-10:before, body.serieslist > div.container-fluid > div > div.col-sm-10:before, body.shelforder > div.container-fluid > div.row-fluid > div.col-sm-10:before {
|
||||
position: fixed;
|
||||
top: 62px;
|
||||
right: 23px;
|
||||
@@ -6542,7 +6589,7 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
|
||||
border-top: 1px solid hsla(0, 0%, 78%, .15)
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container1 {
|
||||
left: 0;
|
||||
width: auto;
|
||||
margin: 0 !important;
|
||||
@@ -6669,7 +6716,7 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
|
||||
margin-bottom: 5px
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row {
|
||||
padding: 0
|
||||
}
|
||||
|
||||
@@ -7148,12 +7195,11 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
|
||||
}
|
||||
|
||||
body.editbook > div.container-fluid > div.row-fluid > div.col-sm-10 > div.col-sm-3, body.upload > div.container-fluid > div.row-fluid > div.col-sm-10 > div.col-sm-3 {
|
||||
max-width: 130px;
|
||||
width: 130px;
|
||||
height: 180px;
|
||||
margin: 0;
|
||||
position: relative;
|
||||
max-width: unset;
|
||||
width: 100%;
|
||||
height: unset;
|
||||
padding: 15px;
|
||||
position: absolute
|
||||
}
|
||||
|
||||
body.editbook > div.container-fluid > div.row-fluid > div.col-sm-10 > form > div.col-sm-9, body.upload > div.container-fluid > div.row-fluid > div.col-sm-10 > form > div.col-sm-9 {
|
||||
@@ -7162,10 +7208,6 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
|
||||
width: 100%
|
||||
}
|
||||
|
||||
body.editbook > div.container-fluid > div.row-fluid > div.col-sm-10 > form > div.col-sm-9 > .form-group:nth-child(1), body.editbook > div.container-fluid > div.row-fluid > div.col-sm-10 > form > div.col-sm-9 > .form-group:nth-child(2), body.upload > div.container-fluid > div.row-fluid > div.col-sm-10 > form > div.col-sm-9 > .form-group:nth-child(1), body.upload > div.container-fluid > div.row-fluid > div.col-sm-10 > form > div.col-sm-9 > .form-group:nth-child(2) {
|
||||
padding-left: 120px
|
||||
}
|
||||
|
||||
#deleteButton, body.editbook > div.container-fluid > div.row-fluid > div.col-sm-10 > div.col-sm-3 > div.text-center > #delete, body.upload > div.container-fluid > div.row-fluid > div.col-sm-10 > div.col-sm-3 > div.text-center > #delete {
|
||||
top: 48px;
|
||||
height: 42px
|
||||
@@ -7441,11 +7483,11 @@ body.edituser.admin > div.container-fluid > div.row-fluid > div.col-sm-10 > div.
|
||||
text-decoration: none
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row:nth-of-type(even) {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row:nth-of-type(even) {
|
||||
background: 0 0
|
||||
}
|
||||
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container > div > .row {
|
||||
body > div.container-fluid > div > div.col-sm-10 > div.container1 > div > .row {
|
||||
border-bottom: 1px solid hsla(0, 0%, 78%, .15)
|
||||
}
|
||||
|
||||
@@ -7600,7 +7642,7 @@ body.formatslist > div.container-fluid > div > div.col-sm-10:before {
|
||||
}
|
||||
}
|
||||
|
||||
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
content: "Publishers";
|
||||
top: 115px;
|
||||
font-size: 24px;
|
||||
@@ -7608,17 +7650,18 @@ body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container:b
|
||||
line-height: 1;
|
||||
padding-left: 15px;
|
||||
position: absolute;
|
||||
display: table;
|
||||
font-family: Open Sans Bold, Helvetica Neue, Helvetica, Arial, sans-serif;
|
||||
font-weight: 400
|
||||
}
|
||||
|
||||
@media screen and (max-width: 992px) {
|
||||
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
top: 60px;
|
||||
}
|
||||
}
|
||||
|
||||
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
content: "Ratings";
|
||||
top: 115px;
|
||||
font-size: 24px;
|
||||
@@ -7626,23 +7669,24 @@ body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container:bef
|
||||
line-height: 1;
|
||||
padding-left: 15px;
|
||||
position: absolute;
|
||||
display: table;
|
||||
font-family: Open Sans Bold, Helvetica Neue, Helvetica, Arial, sans-serif;
|
||||
font-weight: 400
|
||||
}
|
||||
|
||||
@media screen and (max-width: 992px) {
|
||||
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
top: 60px;
|
||||
}
|
||||
}
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.ratingslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
content: "File formats";
|
||||
top: 115px;
|
||||
font-size: 24px;
|
||||
@@ -7655,18 +7699,18 @@ body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container:bef
|
||||
}
|
||||
|
||||
@media screen and (max-width: 992px) {
|
||||
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
top: 60px;
|
||||
}
|
||||
}
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.formatslist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container > div.col-sm-6 {
|
||||
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container1 > div.col-sm-6 {
|
||||
width: 100%
|
||||
}
|
||||
|
||||
@@ -7705,7 +7749,7 @@ body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container >
|
||||
color: hsla(0, 0%, 100%, .7)
|
||||
}
|
||||
|
||||
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container:before {
|
||||
body.publisherlist > div.container-fluid > div > div.col-sm-10 > div.container1:before {
|
||||
display: none !important
|
||||
}
|
||||
}
|
||||
@@ -7951,3 +7995,5 @@ div.comments[data-readmore] {
|
||||
transition: height 300ms;
|
||||
overflow: hidden
|
||||
}
|
||||
|
||||
.dropdown-menu > .offscreen
|
||||
|
||||
@@ -26,3 +26,14 @@ body.serieslist.grid-view div.container-fluid > div > div.col-sm-10::before {
|
||||
input.datepicker {color: transparent}
|
||||
input.datepicker:focus {color: transparent}
|
||||
input.datepicker:focus + input {color: #555}
|
||||
|
||||
.col-sm-3.col-lg-2.col-xs-6.book.session {
|
||||
margin-left: 0;
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 767px) {
|
||||
.row-fluid > .col-sm-2 {
|
||||
visibility: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,12 @@
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.amberTheme {
|
||||
background: #e8bf5e;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.blackTheme {
|
||||
background: #000;
|
||||
color: #fff
|
||||
color: #fff;
|
||||
}
|
||||
Vendored
-1
@@ -157,7 +157,6 @@ fieldset[disabled] .twitter-typeahead .tt-input {
|
||||
list-style: none;
|
||||
font-size: 14px;
|
||||
background-color: #ffffff;
|
||||
border: 1px solid #cccccc;
|
||||
border: 1px solid rgba(0, 0, 0, 0.15);
|
||||
border-radius: 4px;
|
||||
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
|
||||
|
||||
Vendored
+15
@@ -1894,6 +1894,8 @@
|
||||
width:100%;
|
||||
height:100%;
|
||||
margin:0;
|
||||
top:0;
|
||||
left:0;
|
||||
}
|
||||
|
||||
.annotationEditorLayer :is(.freeTextEditor, .inkEditor, .stampEditor) > .resizers{
|
||||
@@ -2646,6 +2648,10 @@
|
||||
}
|
||||
}
|
||||
|
||||
.pdfViewer.copyAll{
|
||||
cursor:wait;
|
||||
}
|
||||
|
||||
.pdfViewer .canvasWrapper{
|
||||
overflow:hidden;
|
||||
width:100%;
|
||||
@@ -3010,6 +3016,15 @@ body{
|
||||
scrollbar-color:var(--scrollbar-color) var(--scrollbar-bg-color);
|
||||
}
|
||||
|
||||
body.wait::before{
|
||||
content:"";
|
||||
position:fixed;
|
||||
width:100%;
|
||||
height:100%;
|
||||
z-index:100000;
|
||||
cursor:wait;
|
||||
}
|
||||
|
||||
.hidden,
|
||||
[hidden]{
|
||||
display:none !important;
|
||||
|
||||
+170
-78
@@ -1,11 +1,10 @@
|
||||
@font-face {
|
||||
font-family: 'fontello';
|
||||
src: url('fonts/fontello.eot?60518104');
|
||||
src:
|
||||
url('fonts/fontello.eot?60518104#iefix') format('embedded-opentype'),
|
||||
url('fonts/fontello.woff?60518104') format('woff'),
|
||||
url('fonts/fontello.ttf?60518104') format('truetype'),
|
||||
url('fonts/fontello.svg?60518104#fontello') format('svg');
|
||||
font-family: "fontello";
|
||||
src: url("fonts/fontello.eot?60518104");
|
||||
src: url("fonts/fontello.eot?60518104#iefix") format("embedded-opentype"),
|
||||
url("fonts/fontello.woff?60518104") format("woff"),
|
||||
url("fonts/fontello.ttf?60518104") format("truetype"),
|
||||
url("fonts/fontello.svg?60518104#fontello") format("svg");
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
}
|
||||
@@ -16,7 +15,7 @@ body {
|
||||
}
|
||||
|
||||
.myselect {
|
||||
overflow: visible !important;
|
||||
overflow: visible !important;
|
||||
}
|
||||
|
||||
#main {
|
||||
@@ -48,7 +47,7 @@ body {
|
||||
-webkit-transition: opacity 0.5s;
|
||||
-moz-transition: opacity 0.5s;
|
||||
transition: opacity 0.5s;
|
||||
z-index: 10;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
#titlebar:hover {
|
||||
@@ -77,7 +76,6 @@ body {
|
||||
}
|
||||
|
||||
#panels a {
|
||||
visibility: hidden;
|
||||
width: 18px;
|
||||
height: 20px;
|
||||
overflow: hidden;
|
||||
@@ -94,14 +92,18 @@ body {
|
||||
box-shadow: inset 0 0 6px rgba(155, 155, 155, 0.8);
|
||||
}
|
||||
|
||||
#book-title { font-weight: 600; }
|
||||
#title-seperator { display: none; }
|
||||
#book-title {
|
||||
font-weight: 600;
|
||||
}
|
||||
#title-seperator {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#viewer {
|
||||
width: 80%;
|
||||
height: 80%;
|
||||
margin: 0 auto;
|
||||
z-index: 2;
|
||||
z-index: 0;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -137,6 +139,7 @@ body {
|
||||
user-select: none;
|
||||
padding-top: 160px;
|
||||
padding-bottom: 160px;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.arrow:hover {
|
||||
@@ -201,10 +204,16 @@ body {
|
||||
max-width: 80%;
|
||||
}
|
||||
|
||||
#title-controls { float: right; }
|
||||
#title-controls {
|
||||
float: right;
|
||||
}
|
||||
|
||||
#panels a::before { visibility: visible; }
|
||||
#panels a:hover { color: #aaa; }
|
||||
#panels a::before {
|
||||
visibility: visible;
|
||||
}
|
||||
#panels a:hover {
|
||||
color: #aaa;
|
||||
}
|
||||
|
||||
.list_item.currentChapter > a,
|
||||
.list_item a:hover {
|
||||
@@ -238,8 +247,12 @@ body {
|
||||
margin-top: -1px;
|
||||
}
|
||||
|
||||
input::-webkit-input-placeholder { color: #454545; }
|
||||
input:-moz-placeholder { color: #454545; }
|
||||
input::-webkit-input-placeholder {
|
||||
color: #454545;
|
||||
}
|
||||
input:-moz-placeholder {
|
||||
color: #454545;
|
||||
}
|
||||
|
||||
#divider {
|
||||
position: absolute;
|
||||
@@ -379,14 +392,14 @@ input:-moz-placeholder { color: #454545; }
|
||||
}
|
||||
|
||||
.toc_toggle::before {
|
||||
content: '▸';
|
||||
content: "▸";
|
||||
color: #fff;
|
||||
margin-right: -4px;
|
||||
}
|
||||
|
||||
.currentChapter > .toc_toggle::before,
|
||||
.openChapter > .toc_toggle::before {
|
||||
content: '▾';
|
||||
content: "▾";
|
||||
}
|
||||
|
||||
.view {
|
||||
@@ -500,24 +513,36 @@ input:-moz-placeholder { color: #454545; }
|
||||
list-style-type: none;
|
||||
}
|
||||
|
||||
#settingsPanel .xsmall { font-size: x-small; }
|
||||
#settingsPanel .small { font-size: small; }
|
||||
#settingsPanel .medium { font-size: medium; }
|
||||
#settingsPanel .large { font-size: large; }
|
||||
#settingsPanel .xlarge { font-size: x-large; }
|
||||
#settingsPanel .xsmall {
|
||||
font-size: x-small;
|
||||
}
|
||||
#settingsPanel .small {
|
||||
font-size: small;
|
||||
}
|
||||
#settingsPanel .medium {
|
||||
font-size: medium;
|
||||
}
|
||||
#settingsPanel .large {
|
||||
font-size: large;
|
||||
}
|
||||
#settingsPanel .xlarge {
|
||||
font-size: x-large;
|
||||
}
|
||||
|
||||
.highlight { background-color: yellow; }
|
||||
.highlight {
|
||||
background-color: yellow;
|
||||
}
|
||||
|
||||
.modal {
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
width: 630px;
|
||||
height: auto;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 97vw;
|
||||
height: 90dvh;
|
||||
max-width: 630px;
|
||||
z-index: 2000;
|
||||
visibility: hidden;
|
||||
margin-left: -320px;
|
||||
margin-top: -160px;
|
||||
}
|
||||
|
||||
.overlay {
|
||||
@@ -540,7 +565,7 @@ input:-moz-placeholder { color: #454545; }
|
||||
}
|
||||
|
||||
.md-show ~ .overlay {
|
||||
opacity: 1;
|
||||
/* opacity: 1; */
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
@@ -551,11 +576,11 @@ input:-moz-placeholder { color: #454545; }
|
||||
position: relative;
|
||||
border-radius: 3px;
|
||||
margin: 0 auto;
|
||||
height: 320px;
|
||||
/* height: 320px; */
|
||||
}
|
||||
|
||||
.md-content > div {
|
||||
padding: 15px 40px 30px;
|
||||
padding: 10px 20px;
|
||||
margin: 0;
|
||||
font-weight: 300;
|
||||
font-size: 14px;
|
||||
@@ -582,6 +607,7 @@ input:-moz-placeholder { color: #454545; }
|
||||
color: white;
|
||||
}
|
||||
|
||||
.md-content .themes button.lightTheme,
|
||||
.md-content .themes button.whiteTheme {
|
||||
background-color: white;
|
||||
color: black;
|
||||
@@ -592,6 +618,11 @@ input:-moz-placeholder { color: #454545; }
|
||||
color: black;
|
||||
}
|
||||
|
||||
.md-content .themes button.amberTheme {
|
||||
background-color: #e8bf5e;
|
||||
color: black;
|
||||
}
|
||||
|
||||
.md-content .themes button.blackTheme {
|
||||
background-color: black;
|
||||
color: white;
|
||||
@@ -639,31 +670,47 @@ input:-moz-placeholder { color: #454545; }
|
||||
|
||||
@media only screen and (max-width: 900px) {
|
||||
#viewer {
|
||||
width: 60%;
|
||||
margin-left: 20%;
|
||||
width: 100%;
|
||||
height: calc(100dvh - 99px);
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
#viewer iframe {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
#prev {
|
||||
left: 20px;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
#next {
|
||||
right: 20px;
|
||||
z-index: 10;
|
||||
}
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 550px) {
|
||||
#viewer {
|
||||
width: 80%;
|
||||
margin-left: 10%;
|
||||
width: 100%;
|
||||
height: calc(100dvh - 99px);
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
#viewer iframe {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
#prev {
|
||||
left: 0;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
#next {
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.arrow {
|
||||
@@ -713,11 +760,7 @@ input:-moz-placeholder { color: #454545; }
|
||||
}
|
||||
}
|
||||
|
||||
@media only screen
|
||||
and (min-device-width: 768px)
|
||||
and (max-device-width: 1024px)
|
||||
and (orientation: landscape)
|
||||
/* and (-webkit-min-device-pixel-ratio: 2)*/ {
|
||||
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) /* and (-webkit-min-device-pixel-ratio: 2) */ {
|
||||
#viewer {
|
||||
width: 80%;
|
||||
margin-left: 10%;
|
||||
@@ -740,47 +783,52 @@ input:-moz-placeholder { color: #454545; }
|
||||
/* For iPhone 6\6s portrait layouts only */
|
||||
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation: portrait) {
|
||||
#viewer {
|
||||
width: 300px;
|
||||
height: 480px;
|
||||
width: 100%;
|
||||
height: calc(100dvh - 99px);
|
||||
}
|
||||
|
||||
#viewer iframe {
|
||||
width: 300px;
|
||||
height: 480px;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
/* For iPhone 6\6s landscape layouts only */
|
||||
@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation: landscape) {
|
||||
#viewer {
|
||||
width: 450px;
|
||||
height: 300px;
|
||||
width: 100%;
|
||||
height: calc(100dvh - 99px);
|
||||
}
|
||||
|
||||
#viewer iframe {
|
||||
width: 450px;
|
||||
height: 300px;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
/* For iPhone portrait layouts only */
|
||||
@media only screen and (max-device-width: 374px) and (orientation: portrait) {
|
||||
#viewer {
|
||||
width: 256px;
|
||||
height: 432px;
|
||||
width: 100%;
|
||||
height: calc(100dvh - 99px);
|
||||
}
|
||||
|
||||
#viewer iframe {
|
||||
width: 256px;
|
||||
height: 432px;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
/* For iPhone landscape layouts only */
|
||||
@media only screen and (max-device-width: 374px) and (orientation: landscape) {
|
||||
#viewer {
|
||||
width: 100%;
|
||||
height: calc(100dvh - 99px);
|
||||
}
|
||||
|
||||
#viewer iframe {
|
||||
width: 256px;
|
||||
height: 124px;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -804,25 +852,69 @@ input:-moz-placeholder { color: #454545; }
|
||||
font-size: 112%;
|
||||
}
|
||||
|
||||
.icon-search::before { content: '\e807'; } /* '' */
|
||||
.icon-resize-full-1::before { content: '\e804'; } /* '' */
|
||||
.icon-cancel-circled2::before { content: '\e80f'; } /* '' */
|
||||
.icon-link::before { content: '\e80d'; } /* '' */
|
||||
.icon-bookmark::before { content: '\e805'; } /* '' */
|
||||
.icon-bookmark-empty::before { content: '\e806'; } /* '' */
|
||||
.icon-download-cloud::before { content: '\e811'; } /* '' */
|
||||
.icon-edit::before { content: '\e814'; } /* '' */
|
||||
.icon-menu::before { content: '\e802'; } /* '' */
|
||||
.icon-cog::before { content: '\e813'; } /* '' */
|
||||
.icon-resize-full::before { content: '\e812'; } /* '' */
|
||||
.icon-cancel-circled::before { content: '\e80e'; } /* '' */
|
||||
.icon-up-dir::before { content: '\e80c'; } /* '' */
|
||||
.icon-right-dir::before { content: '\e80b'; } /* '' */
|
||||
.icon-angle-right::before { content: '\e809'; } /* '' */
|
||||
.icon-angle-down::before { content: '\e80a'; } /* '' */
|
||||
.icon-right::before { content: '\e815'; } /* '' */
|
||||
.icon-list-1::before { content: '\e803'; } /* '' */
|
||||
.icon-list-numbered::before { content: '\e801'; } /* '' */
|
||||
.icon-columns::before { content: '\e810'; } /* '' */
|
||||
.icon-list::before { content: '\e800'; } /* '' */
|
||||
.icon-resize-small::before { content: '\e808'; } /* '' */
|
||||
.icon-search::before {
|
||||
content: "\e807";
|
||||
} /* '' */
|
||||
.icon-resize-full-1::before {
|
||||
content: "\e804";
|
||||
} /* '' */
|
||||
.icon-cancel-circled2::before {
|
||||
content: "\e80f";
|
||||
} /* '' */
|
||||
.icon-link::before {
|
||||
content: "\e80d";
|
||||
} /* '' */
|
||||
.icon-bookmark::before {
|
||||
content: "\e805";
|
||||
} /* '' */
|
||||
.icon-bookmark-empty::before {
|
||||
content: "\e806";
|
||||
} /* '' */
|
||||
.icon-download-cloud::before {
|
||||
content: "\e811";
|
||||
} /* '' */
|
||||
.icon-edit::before {
|
||||
content: "\e814";
|
||||
} /* '' */
|
||||
.icon-menu::before {
|
||||
content: "\e802";
|
||||
} /* '' */
|
||||
.icon-cog::before {
|
||||
content: "\e813";
|
||||
} /* '' */
|
||||
.icon-resize-full::before {
|
||||
content: "\e812";
|
||||
} /* '' */
|
||||
.icon-cancel-circled::before {
|
||||
content: "\e80e";
|
||||
} /* '' */
|
||||
.icon-up-dir::before {
|
||||
content: "\e80c";
|
||||
} /* '' */
|
||||
.icon-right-dir::before {
|
||||
content: "\e80b";
|
||||
} /* '' */
|
||||
.icon-angle-right::before {
|
||||
content: "\e809";
|
||||
} /* '' */
|
||||
.icon-angle-down::before {
|
||||
content: "\e80a";
|
||||
} /* '' */
|
||||
.icon-right::before {
|
||||
content: "\e815";
|
||||
} /* '' */
|
||||
.icon-list-1::before {
|
||||
content: "\e803";
|
||||
} /* '' */
|
||||
.icon-list-numbered::before {
|
||||
content: "\e801";
|
||||
} /* '' */
|
||||
.icon-columns::before {
|
||||
content: "\e810";
|
||||
} /* '' */
|
||||
.icon-list::before {
|
||||
content: "\e800";
|
||||
} /* '' */
|
||||
.icon-resize-small::before {
|
||||
content: "\e808";
|
||||
} /* '' */
|
||||
|
||||
+73
-21
@@ -1,29 +1,81 @@
|
||||
.fontSizeWrapper {
|
||||
position: relative;
|
||||
position: relative;
|
||||
}
|
||||
.slider {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
transform: translate(0,-50%);
|
||||
width: 90%;
|
||||
height: 60px;
|
||||
background: transparent;
|
||||
border-radius: 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
box-shadow: 0px 15px 40px #7E6D5766;
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
transform: translate(0, -50%);
|
||||
width: 90%;
|
||||
height: 60px;
|
||||
background: transparent;
|
||||
border-radius: 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
box-shadow: 0px 15px 40px #7e6d5766;
|
||||
}
|
||||
.slider label {
|
||||
font-size: 20px;
|
||||
font-weight: 400;
|
||||
font-family: Open Sans;
|
||||
padding-right: 10px;
|
||||
color: white;
|
||||
font-size: 20px;
|
||||
font-weight: 400;
|
||||
font-family: Open Sans;
|
||||
padding-right: 10px;
|
||||
color: white;
|
||||
}
|
||||
.slider input[type="range"] {
|
||||
width: 80%;
|
||||
height: 5px;
|
||||
background: black;
|
||||
border: none;
|
||||
outline: none;
|
||||
width: 80%;
|
||||
height: 5px;
|
||||
background: black;
|
||||
border: none;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.item {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
font-family: Open Sans;
|
||||
padding-right: 10px;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.item ~ button {
|
||||
display: inline-block;
|
||||
border: none;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
margin-top: 5%;
|
||||
margin-right: 1%;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
#main,
|
||||
#viewer,
|
||||
#sidebar,
|
||||
#tocView {
|
||||
touch-action: pan-y;
|
||||
}
|
||||
|
||||
.read-footer {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0 12px;
|
||||
}
|
||||
.read-footer #pages-count {
|
||||
font-size: 12px;
|
||||
|
||||
position: absolute;
|
||||
left: 12px;
|
||||
bottom: 2px;
|
||||
}
|
||||
|
||||
#back-button {
|
||||
width: 50px !important;
|
||||
right: 50px;
|
||||
// position: absolute;
|
||||
}
|
||||
|
||||
#progress {
|
||||
right: 4rem;
|
||||
bottom: 2px;
|
||||
width: fit-content;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
#add-to-shelves.dropdown-menu, #remove-from-shelves.dropdown-menu {
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.tooltip.bottom .tooltip-inner {
|
||||
font-size: 13px;
|
||||
@@ -429,6 +433,9 @@ div.log {
|
||||
padding: 0.5em;
|
||||
}
|
||||
|
||||
.badge-sm{
|
||||
font-size: 70%;
|
||||
}
|
||||
#detailcover { cursor:zoom-in; }
|
||||
#detailcover:-webkit-full-screen { cursor:zoom-out; border: 0; }
|
||||
#detailcover:-moz-full-screen { cursor:zoom-out; border: 0; }
|
||||
@@ -438,3 +445,43 @@ div.log {
|
||||
.error-list {
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
body > div.container-fluid > div.row-fluid > div.col-sm-10 {
|
||||
max-height: calc(100vh - 111px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
body > div.container-fluid > div.row-fluid > div.col-sm-2 {
|
||||
max-height: calc(100vh - 111px);
|
||||
overflow-y: auto;
|
||||
/* hide scrollbar in IE, Edge */
|
||||
-ms-overflow-style: none;
|
||||
|
||||
/* hide scrollbar in Firefox */
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
/* hide scrollbar in WebKit browsers (Chrome, Safari, Opera) */
|
||||
body > div.container-fluid > div.row-fluid > div.col-sm-2::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.scrollable-col {
|
||||
/* keep vertical scrolling */
|
||||
overflow-y: auto;
|
||||
|
||||
/* hide scrollbar in IE, Edge */
|
||||
-ms-overflow-style: none;
|
||||
|
||||
/* hide scrollbar in Firefox */
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
/* hide scrollbar in WebKit browsers (Chrome, Safari, Opera) */
|
||||
.scrollable-col::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
body > div.container-fluid {
|
||||
padding-right: 0px;
|
||||
}
|
||||
|
||||
Executable → Regular
@@ -3,9 +3,9 @@
|
||||
*/
|
||||
/* global Bloodhound, language, Modernizr, tinymce, getPath */
|
||||
|
||||
if ($("#description").length) {
|
||||
if ($("#comments").length && typeof tinymce !== "undefined") {
|
||||
tinymce.init({
|
||||
selector: "#description",
|
||||
selector: "#comments",
|
||||
plugins: 'code',
|
||||
branding: false,
|
||||
menubar: "edit view format",
|
||||
@@ -93,7 +93,7 @@ var authors = new Bloodhound({
|
||||
},
|
||||
});
|
||||
|
||||
$(".form-group #bookAuthor").typeahead(
|
||||
$(".form-group #authors").typeahead(
|
||||
{
|
||||
highlight: true,
|
||||
minLength: 1,
|
||||
@@ -243,13 +243,13 @@ $("#search").on("change input.typeahead:selected", function(event) {
|
||||
});
|
||||
});
|
||||
|
||||
$("#btn-upload-format").on("change", function () {
|
||||
/*$("#btn-upload-format").on("change", function () {
|
||||
var filename = $(this).val();
|
||||
if (filename.substring(3, 11) === "fakepath") {
|
||||
filename = filename.substring(12);
|
||||
} // Remove c:\fake at beginning from localhost chrome
|
||||
$("#upload-format").text(filename);
|
||||
});
|
||||
});*/
|
||||
|
||||
$("#btn-upload-cover").on("change", function () {
|
||||
var filename = $(this).val();
|
||||
@@ -261,8 +261,8 @@ $("#btn-upload-cover").on("change", function () {
|
||||
|
||||
$("#xchange").click(function () {
|
||||
this.blur();
|
||||
var title = $("#book_title").val();
|
||||
$("#book_title").val($("#bookAuthor").val());
|
||||
$("#bookAuthor").val(title);
|
||||
var title = $("#title").val();
|
||||
$("#title").val($("#authors").val());
|
||||
$("#authors").val(title);
|
||||
});
|
||||
|
||||
|
||||
@@ -38,12 +38,12 @@ $(function () {
|
||||
}
|
||||
|
||||
function populateForm (book) {
|
||||
tinymce.get("description").setContent(book.description);
|
||||
tinymce.get("comments").setContent(book.description);
|
||||
var uniqueTags = getUniqueValues('tags', book)
|
||||
var uniqueLanguages = getUniqueValues('languages', book)
|
||||
var ampSeparatedAuthors = (book.authors || []).join(" & ");
|
||||
$("#bookAuthor").val(ampSeparatedAuthors);
|
||||
$("#book_title").val(book.title);
|
||||
$("#authors").val(ampSeparatedAuthors);
|
||||
$("#title").val(book.title);
|
||||
$("#tags").val(uniqueTags.join(", "));
|
||||
$("#languages").val(uniqueLanguages.join(", "));
|
||||
$("#rating").data("rating").setValue(Math.round(book.rating));
|
||||
@@ -103,11 +103,11 @@ $(function () {
|
||||
});
|
||||
}
|
||||
else {
|
||||
$("#meta-info").html("<p class=\"text-danger\">" + msg.no_result + "!</p>" + $("#meta-info")[0].innerHTML)
|
||||
$("#meta-info").html("<p class=\"text-danger\">" + msg.no_result + "</p>" + $("#meta-info")[0].innerHTML)
|
||||
}
|
||||
},
|
||||
error: function error() {
|
||||
$("#meta-info").html("<p class=\"text-danger\">" + msg.search_error + "!</p>" + $("#meta-info")[0].innerHTML);
|
||||
$("#meta-info").html("<p class=\"text-danger\">" + msg.search_error + "</p>" + $("#meta-info")[0].innerHTML);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -172,7 +172,7 @@ $(function () {
|
||||
|
||||
$("#get_meta").click(function () {
|
||||
populate_provider();
|
||||
var bookTitle = $("#book_title").val();
|
||||
var bookTitle = $("#title").val();
|
||||
$("#keyword").val(bookTitle);
|
||||
keyword = bookTitle;
|
||||
doSearch(bookTitle);
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
!function(a){a.fn.datepicker.dates.ar={days:["الأحد","الاثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت","الأحد"],daysShort:["أحد","اثنين","ثلاثاء","أربعاء","خميس","جمعة","سبت","أحد"],daysMin:["ح","ن","ث","ع","خ","ج","س","ح"],months:["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليو","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر"],monthsShort:["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليو","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر"],today:"هذا اليوم",rtl:!0}}(jQuery);
|
||||
+1
@@ -0,0 +1 @@
|
||||
!function(a){a.fn.datepicker.dates.sl={days:["Nedelja","Ponedeljek","Torek","Sreda","Četrtek","Petek","Sobota"],daysShort:["Ned","Pon","Tor","Sre","Čet","Pet","Sob"],daysMin:["Ne","Po","To","Sr","Če","Pe","So"],months:["Januar","Februar","Marec","April","Maj","Junij","Julij","Avgust","September","Oktober","November","December"],monthsShort:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Avg","Sep","Okt","Nov","Dec"],today:"Danes",weekStart:1}}(jQuery);
|
||||
+5655
-328
File diff suppressed because it is too large
Load Diff
+5641
-253
File diff suppressed because one or more lines are too long
+2
File diff suppressed because one or more lines are too long
+3
File diff suppressed because one or more lines are too long
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -183,7 +183,7 @@ try {
|
||||
];
|
||||
$.each(sequences, function(ignore, sequence) {
|
||||
for (j = 0; j < word.length - 2; j += 1) {
|
||||
// iterate the word trough a sliding window of size 3:
|
||||
// iterate the word through a sliding window of size 3:
|
||||
if (
|
||||
sequence.indexOf(
|
||||
word.toLowerCase().substring(j, j + 3)
|
||||
|
||||
+447
-291
File diff suppressed because it is too large
Load Diff
+70
-32
@@ -49,7 +49,7 @@ function elementSorter(a, b) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Generic control/related handler to show/hide fields based on a checkbox' value
|
||||
// Generic control/related handler to show/hide fields based on a 'checkbox' value
|
||||
// e.g.
|
||||
// <input type="checkbox" data-control="stuff-to-show">
|
||||
// <div data-related="stuff-to-show">...</div>
|
||||
@@ -63,7 +63,7 @@ $(document).on("change", "input[type=\"checkbox\"][data-control]", function () {
|
||||
});
|
||||
});
|
||||
|
||||
// Generic control/related handler to show/hide fields based on a select' value
|
||||
// Generic control/related handler to show/hide fields based on a 'select' value
|
||||
$(document).on("change", "select[data-control]", function() {
|
||||
var $this = $(this);
|
||||
var name = $this.data("control");
|
||||
@@ -79,7 +79,7 @@ $(document).on("change", "select[data-control]", function() {
|
||||
}
|
||||
});
|
||||
|
||||
// Generic control/related handler to show/hide fields based on a select' value
|
||||
// Generic control/related handler to show/hide fields based on a 'select' value
|
||||
// this one is made to show all values if select value is not 0
|
||||
$(document).on("change", "select[data-controlall]", function() {
|
||||
var $this = $(this);
|
||||
@@ -130,8 +130,13 @@ $(".container-fluid").bind('drop', function (e) {
|
||||
}
|
||||
});
|
||||
if (dt.files.length) {
|
||||
$("#btn-upload")[0].files = dt.files;
|
||||
$("#form-upload").submit();
|
||||
if($("#btn-upload-format").length) {
|
||||
$("#btn-upload-format")[0].files = dt.files;
|
||||
$("#form-upload-format").submit();
|
||||
} else {
|
||||
$("#btn-upload")[0].files = dt.files;
|
||||
$("#form-upload").submit();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -140,12 +145,25 @@ $("#btn-upload").change(function() {
|
||||
$("#form-upload").submit();
|
||||
});
|
||||
|
||||
$("#btn-upload-format").change(function() {
|
||||
$("#form-upload-format").submit();
|
||||
});
|
||||
|
||||
|
||||
$("#form-upload").uploadprogress({
|
||||
redirect_url: getPath() + "/", //"{{ url_for('web.index')}}",
|
||||
uploadedMsg: $("#form-upload").data("message"), //"{{_('Upload done, processing, please wait...')}}",
|
||||
modalTitle: $("#form-upload").data("title"), //"{{_('Uploading...')}}",
|
||||
modalFooter: $("#form-upload").data("footer"), //"{{_('Close')}}",
|
||||
modalTitleFailed: $("#form-upload").data("failed") //"{{_('Error')}}"
|
||||
redirect_url: getPath() + "/",
|
||||
uploadedMsg: $("#form-upload").data("message"),
|
||||
modalTitle: $("#form-upload").data("title"),
|
||||
modalFooter: $("#form-upload").data("footer"),
|
||||
modalTitleFailed: $("#form-upload").data("failed")
|
||||
});
|
||||
|
||||
$("#form-upload-format").uploadprogress({
|
||||
redirect_url: getPath() + "/",
|
||||
uploadedMsg: $("#form-upload-format").data("message"),
|
||||
modalTitle: $("#form-upload-format").data("title"),
|
||||
modalFooter: $("#form-upload-format").data("footer"),
|
||||
modalTitleFailed: $("#form-upload-format").data("failed")
|
||||
});
|
||||
|
||||
$(document).ready(function() {
|
||||
@@ -160,15 +178,21 @@ $(document).ready(function() {
|
||||
|
||||
$(".session").click(function() {
|
||||
window.sessionStorage.setItem("back", window.location.pathname);
|
||||
window.sessionStorage.setItem("search", window.location.search);
|
||||
});
|
||||
|
||||
$("#back").click(function() {
|
||||
var loc = sessionStorage.getItem("back");
|
||||
var param = sessionStorage.getItem("search");
|
||||
if (!loc) {
|
||||
loc = $(this).data("back");
|
||||
}
|
||||
sessionStorage.removeItem("back");
|
||||
window.location.href = loc;
|
||||
sessionStorage.removeItem("search");
|
||||
if (param === null) {
|
||||
param = "";
|
||||
}
|
||||
window.location.href = loc + param;
|
||||
|
||||
});
|
||||
|
||||
@@ -205,10 +229,12 @@ $("#delete_confirm").click(function(event) {
|
||||
postButton(event, getPath() + "/delete/" + deleteId + "/" + bookFormat);
|
||||
} else {
|
||||
if (ajaxResponse) {
|
||||
path = getPath() + "/ajax/delete/" + deleteId;
|
||||
$.ajax({
|
||||
method:"post",
|
||||
url: path,
|
||||
url: getPath() + "/ajax/deletebook",
|
||||
method: "post",
|
||||
contentType: "application/json; charset=utf-8",
|
||||
dataType: "json",
|
||||
data: JSON.stringify({"bookid": [deleteId]}),
|
||||
timeout: 900,
|
||||
success:function(data) {
|
||||
data.forEach(function(item) {
|
||||
@@ -384,17 +410,17 @@ $(function() {
|
||||
});
|
||||
|
||||
// fix for infinite scroll on CaliBlur Theme (#981)
|
||||
if ($("body").hasClass("blur")) {
|
||||
$(".col-sm-10").bind("scroll", function () {
|
||||
if (
|
||||
$(this).scrollTop() + $(this).innerHeight() >=
|
||||
$(this)[0].scrollHeight
|
||||
) {
|
||||
$loadMore.infiniteScroll("loadNextPage");
|
||||
window.history.replaceState({}, null, $loadMore.infiniteScroll("getAbsolutePath"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$(".col-sm-10").bind("scroll", function () {
|
||||
if (
|
||||
$(this).scrollTop() + $(this).innerHeight() >=
|
||||
$(this)[0].scrollHeight
|
||||
) {
|
||||
$loadMore.infiniteScroll("loadNextPage");
|
||||
window.history.replaceState({}, null, $loadMore.infiniteScroll("getAbsolutePath"));
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
$("#restart").click(function() {
|
||||
@@ -598,6 +624,7 @@ $(function() {
|
||||
});
|
||||
|
||||
$("#toggle_order_shelf").click(function() {
|
||||
$("#toggle_order_shelf").toggleClass("dummy");
|
||||
$("#new").toggleClass("disabled");
|
||||
$("#old").toggleClass("disabled");
|
||||
$("#asc").toggleClass("disabled");
|
||||
@@ -606,9 +633,20 @@ $(function() {
|
||||
$("#auth_za").toggleClass("disabled");
|
||||
$("#pub_new").toggleClass("disabled");
|
||||
$("#pub_old").toggleClass("disabled");
|
||||
$("#shelf_new").toggleClass("disabled");
|
||||
$("#shelf_old").toggleClass("disabled");
|
||||
var alternative_text = $("#toggle_order_shelf").data('alt-text');
|
||||
var status = $("#toggle_order_shelf").hasClass("dummy") ? "on" : "off";
|
||||
$("#toggle_order_shelf").data('alt-text', $("#toggle_order_shelf").html());
|
||||
$("#toggle_order_shelf").html(alternative_text);
|
||||
|
||||
$.ajax({
|
||||
method:"post",
|
||||
contentType: "application/json; charset=utf-8",
|
||||
dataType: "json",
|
||||
url: getPath() + "/ajax/view",
|
||||
data: "{\"shelf\": {\"man\": \"" + status + "\"}}",
|
||||
});
|
||||
});
|
||||
|
||||
$("#btndeluser").click(function() {
|
||||
@@ -690,20 +728,20 @@ $(function() {
|
||||
url: getPath() + "/ajax/simulatedbchange",
|
||||
data: {config_calibre_dir: $("#config_calibre_dir").val(), csrf_token: $("input[name='csrf_token']").val()},
|
||||
success: function success(data) {
|
||||
if ( data.change ) {
|
||||
if ( data.valid ) {
|
||||
if ( !data.valid ) {
|
||||
$("#InvalidDialog").modal('show');
|
||||
}
|
||||
else{
|
||||
if ( data.change ) {
|
||||
confirmDialog(
|
||||
"db_submit",
|
||||
"GeneralChangeModal",
|
||||
0,
|
||||
changeDbSettings
|
||||
);
|
||||
}
|
||||
else {
|
||||
$("#InvalidDialog").modal('show');
|
||||
}
|
||||
} else {
|
||||
} else {
|
||||
changeDbSettings();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user