Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0e0422010 | ||
|
|
01ab75a158 | ||
|
|
d9c10b830a | ||
|
|
35f6f4c727 | ||
|
|
3b216bfa07 | ||
|
|
e8e2f789e5 | ||
|
|
bbef41290f | ||
|
|
81b85445d8 | ||
|
|
35209ede67 | ||
|
|
0c0313f375 | ||
|
|
6bf0753978 | ||
|
|
a02f621f08 | ||
|
|
de1bc3f9af | ||
|
|
01090169a7 | ||
|
|
b564a97cdf | ||
|
|
a118fffc99 | ||
|
|
5b59aab81a | ||
|
|
7d3d0c661e | ||
|
|
f6f20ebc77 | ||
|
|
58cb54c76f | ||
|
|
3fc326fa48 | ||
|
|
a50aff67a2 | ||
|
|
3c1f5fd37f | ||
|
|
8ae066c387 | ||
|
|
0feb62c142 | ||
|
|
96b1e8960b | ||
|
|
df67079573 | ||
|
|
e3dbf7a88d | ||
|
|
8dd0585919 | ||
|
|
c830a5936e | ||
|
|
405f3c181f | ||
|
|
6d839d5cc7 | ||
|
|
bbadfa2251 | ||
|
|
7b8b2f93a0 | ||
|
|
c1030dfd13 | ||
|
|
a90177afa0 | ||
|
|
c095ee3c14 | ||
|
|
ae1f515446 | ||
|
|
0548fbb685 | ||
|
|
f22e4d996c | ||
|
|
3e0d8763c3 | ||
|
|
47f5e2ffb4 | ||
|
|
f39dc100b4 | ||
|
|
573c9f9fb4 | ||
|
|
785726deee | ||
|
|
4edd1914b4 | ||
|
|
222929e741 | ||
|
|
70b67077cc | ||
|
|
ec73558b03 | ||
|
|
bdedec90dd | ||
|
|
d45085215f | ||
|
|
b85627da5c | ||
|
|
592288cb22 | ||
|
|
2e3a3ee460 | ||
|
|
b7927a0df1 | ||
|
|
021298374e | ||
|
|
92f65882b2 | ||
|
|
f0399d04b7 | ||
|
|
9b57fa25de | ||
|
|
afbe77de3d | ||
|
|
d26d357151 | ||
|
|
4db9691cfc | ||
|
|
45c433caab | ||
|
|
25422b3411 | ||
|
|
a184f4e71a | ||
|
|
4569188008 | ||
|
|
9d9acb058d | ||
|
|
7d67168a4a | ||
|
|
09751d8b87 | ||
|
|
fd5ab0ef53 | ||
|
|
3bf173d958 | ||
|
|
98d630d453 | ||
|
|
eb2e816bfd | ||
|
|
bd01e840ca | ||
|
|
91a21ababe | ||
|
|
f4096b136e | ||
|
|
7598dfe952 | ||
|
|
5ed3b1cf53 | ||
|
|
7640ac1b3b | ||
|
|
66874f8163 | ||
|
|
3f91313303 | ||
|
|
8438b2a07b | ||
|
|
67e3721530 | ||
|
|
2252d661c0 | ||
|
|
87e526642c | ||
|
|
7f9da94a18 | ||
|
|
ec7c2db971 | ||
|
|
fcd2b68359 | ||
|
|
a1d372630d | ||
|
|
fc859afb92 | ||
|
|
2e0d0a2429 | ||
|
|
d084a06e63 | ||
|
|
e880238cb9 | ||
|
|
f58c5bee1c | ||
|
|
cbb9edac19 | ||
|
|
1b8bd27b3c | ||
|
|
6cb713d62c | ||
|
|
642af2f973 | ||
|
|
9273843062 | ||
|
|
2989586c6d | ||
|
|
5ede079401 | ||
|
|
7ad419dc8c | ||
|
|
bcdc976414 | ||
|
|
6aad9378b8 | ||
|
|
6f5390ead5 | ||
|
|
d624b67e93 | ||
|
|
01cc97c1b2 | ||
|
|
7c016265d2 | ||
|
|
974549b1af | ||
|
|
add502d236 | ||
|
|
294c594cbb | ||
|
|
60aa016734 | ||
|
|
27e8fbd248 | ||
|
|
d856c4d78e | ||
|
|
25b09a532f | ||
|
|
c1f4ca36b6 | ||
|
|
58379159fb | ||
|
|
17470b3b56 | ||
|
|
42cc13d1e2 | ||
|
|
ecc5cb167e | ||
|
|
d72210c6ae | ||
|
|
61deda1076 | ||
|
|
1e0ff0f9c2 | ||
|
|
00bf1f5ec9 | ||
|
|
2b6f5b1565 | ||
|
|
e5abc5f281 | ||
|
|
95371d0d7f | ||
|
|
c7df8a1a34 | ||
|
|
b414d91964 | ||
|
|
82164fc8e7 | ||
|
|
a5415e00d5 | ||
|
|
434029270b | ||
|
|
b3b85bf692 | ||
|
|
a36c6da3ae | ||
|
|
9e72c3b40d | ||
|
|
a0cebfbfb1 | ||
|
|
64e833f5d6 | ||
|
|
4da64ceb23 | ||
|
|
99ec99b539 | ||
|
|
3077b854d7 | ||
|
|
a8317d900b | ||
|
|
668bf3a15e | ||
|
|
481e52b503 | ||
|
|
bbb65ec804 | ||
|
|
4b7b646692 | ||
|
|
65cfb1ccbc | ||
|
|
9e9d7b3642 | ||
|
|
1294672809 | ||
|
|
857584a929 | ||
|
|
75c68d92ec | ||
|
|
b4772d9b66 | ||
|
|
382cd9458f | ||
|
|
be7ac7e163 | ||
|
|
27f71d910b | ||
|
|
9f260128cf | ||
|
|
cdd38350fe | ||
|
|
aefed40a2f | ||
|
|
88278672d8 | ||
|
|
bd0071354c | ||
|
|
c6bf62a6eb | ||
|
|
95544ef885 | ||
|
|
fe4db16a7e | ||
|
|
9b127a9f97 | ||
|
|
9e4aeac16d | ||
|
|
9653308300 | ||
|
|
7671a1d5c8 | ||
|
|
bd6b5ac873 | ||
|
|
00dc60da79 | ||
|
|
708861bcd5 | ||
|
|
24a2c0a5cf | ||
|
|
1e1d3a7c81 | ||
|
|
2ebddcfee3 | ||
|
|
4517f5b0cb | ||
|
|
666015e867 | ||
|
|
9d5e9b28ae | ||
|
|
6f1e78b9a3 | ||
|
|
d5aa345da6 | ||
|
|
e060c62742 | ||
|
|
5695268d1b | ||
|
|
cea10d3945 | ||
|
|
fe21d15194 | ||
|
|
369d5059c3 | ||
|
|
56a9c62421 | ||
|
|
50d703e2d8 | ||
|
|
5aefc893de | ||
|
|
6e5d9d7657 | ||
|
|
1be7dfcdca | ||
|
|
e58eb8dac1 | ||
|
|
d02eb842c7 | ||
|
|
f3efef1f60 | ||
|
|
659481c83b | ||
|
|
bad4c01474 | ||
|
|
cd53d57516 | ||
|
|
ac54899415 | ||
|
|
abe46e1862 | ||
|
|
3be47d6e57 | ||
|
|
25f608d109 | ||
|
|
aca5324914 | ||
|
|
d8f9e2feb2 | ||
|
|
ed26d34961 | ||
|
|
50919d4721 | ||
|
|
5edde53fed | ||
|
|
1c15e10ac0 | ||
|
|
52be2ad4a2 | ||
|
|
43fdef5e53 | ||
|
|
b699796236 | ||
|
|
b82d03c12c | ||
|
|
b8eb557761 | ||
|
|
ba40c6693e | ||
|
|
e064a3ec2b | ||
|
|
f6561456f7 | ||
|
|
deb91996a8 | ||
|
|
cd1fe6dde0 | ||
|
|
3f6a466ca7 | ||
|
|
50f4fe6546 | ||
|
|
861277460d | ||
|
|
83babf88fc | ||
|
|
58735caff3 | ||
|
|
844eb6c379 | ||
|
|
1b8410e786 | ||
|
|
fed9eff7b8 | ||
|
|
bf5de95fdc | ||
|
|
2e25e797dd | ||
|
|
c1ac68e2ae | ||
|
|
623a92ebec | ||
|
|
2edcd16119 | ||
|
|
af202bd6d1 | ||
|
|
d5a332a84e | ||
|
|
d6884164a5 | ||
|
|
707556a36d | ||
|
|
356a4f588e | ||
|
|
241b31458d | ||
|
|
efb04ddd8f | ||
|
|
781ca7a3f3 | ||
|
|
6f6d8df431 | ||
|
|
9ebde57fc3 | ||
|
|
8dc1e9bfa4 | ||
|
|
e3db2796c9 | ||
|
|
42ef049b63 | ||
|
|
8930426f2a | ||
|
|
ceffa3a108 | ||
|
|
c0a06eec46 | ||
|
|
86ef1d47e8 | ||
|
|
b835aa660a | ||
|
|
4d92d7da3a | ||
|
|
d1e6a85803 | ||
|
|
d8bad7394a | ||
|
|
f5062d1354 | ||
|
|
1d79d9ded2 | ||
|
|
10e212fcde | ||
|
|
1fa267ce1b | ||
|
|
abcf9a1808 | ||
|
|
d4cfad6363 | ||
|
|
3a24561ca2 | ||
|
|
5c19a8aacc | ||
|
|
3946ef8f0d | ||
|
|
6a2868c68d | ||
|
|
7ae3255ea9 | ||
|
|
91e6d94c83 | ||
|
|
e615073893 | ||
|
|
32e27712f0 | ||
|
|
ff39fac50f | ||
|
|
80d3ba42b4 | ||
|
|
d25cfb7499 | ||
|
|
24ad15be11 | ||
|
|
a35c635987 | ||
|
|
aa9fdd2ada | ||
|
|
afa585eb65 | ||
|
|
03acb77162 | ||
|
|
28ca39ca13 | ||
|
|
b05c17b8bb | ||
|
|
3839af65c4 | ||
|
|
275e073c42 | ||
|
|
c4876010e9 | ||
|
|
bce69b2dfc | ||
|
|
fb97e39d9f | ||
|
|
913690df78 | ||
|
|
e68a3f18fa | ||
|
|
1534827ad7 | ||
|
|
b36422bc05 | ||
|
|
1e2335dea0 | ||
|
|
e052590270 | ||
|
|
41ca85268f | ||
|
|
0e9709f304 | ||
|
|
ceec1051d5 | ||
|
|
81ccc11c9c | ||
|
|
702e96ddd6 | ||
|
|
53603f79bd | ||
|
|
250cafe814 | ||
|
|
16633ef1d3 | ||
|
|
f0a5225524 | ||
|
|
a32b36bf81 | ||
|
|
302679719d | ||
|
|
a63baa1758 | ||
|
|
752192a057 | ||
|
|
e245a147d9 | ||
|
|
0ec2bcd897 | ||
|
|
19c75d6790 | ||
|
|
0654156dd6 | ||
|
|
e4b0434733 | ||
|
|
b32721c293 | ||
|
|
c5e39a7523 | ||
|
|
0db837c0ce | ||
|
|
53dae32897 | ||
|
|
018f3ca250 | ||
|
|
a1a8a0cf29 | ||
|
|
f9c3e751f6 | ||
|
|
c7b057ec51 | ||
|
|
85ea762054 | ||
|
|
56cd62ed90 | ||
|
|
9a8c342e61 | ||
|
|
3b81ea37f4 | ||
|
|
3c8bfc31e4 | ||
|
|
59881367fe | ||
|
|
c8ebaee0f7 | ||
|
|
d5d0ad50fa | ||
|
|
6ef792d65d | ||
|
|
20fa9f5523 | ||
|
|
616cc2018a | ||
|
|
e69b1adccd | ||
|
|
280efad939 | ||
|
|
15ec6bec95 | ||
|
|
aae81c3d24 | ||
|
|
259ac94b93 | ||
|
|
a27314464a | ||
|
|
87f07003f4 | ||
|
|
1bf065fd04 | ||
|
|
f8de7e75cc | ||
|
|
7d586b3745 | ||
|
|
a56e071a19 | ||
|
|
480aecb16c | ||
|
|
ec7803fa76 | ||
|
|
91938fd18a | ||
|
|
aa2d3d2b36 | ||
|
|
d5e9cdc5b7 | ||
|
|
305e75c0ae | ||
|
|
0d247fef6a | ||
|
|
94da61c57e | ||
|
|
430ccd9ab1 | ||
|
|
47d94d9bd6 | ||
|
|
a6d1f6039d | ||
|
|
31234a4b98 | ||
|
|
476275ea53 | ||
|
|
792d4a65bc | ||
|
|
0e2dca5f4d | ||
|
|
557296b7be | ||
|
|
2236191263 | ||
|
|
1138c86868 | ||
|
|
08500c66a8 | ||
|
|
67836006c5 | ||
|
|
fa03a9ee25 | ||
|
|
bf4564e365 | ||
|
|
6a96664381 | ||
|
|
e6e3032f02 | ||
|
|
6d424f0a30 | ||
|
|
a6f0375db3 | ||
|
|
1833e8fdb4 | ||
|
|
70151c2e11 | ||
|
|
ab69962e8a | ||
|
|
075fe994af | ||
|
|
1aca1b9fdd | ||
|
|
9fea5a55f4 | ||
|
|
1a0bf45c34 | ||
|
|
67874e07b6 | ||
|
|
ced0bcfe33 | ||
|
|
8c0aa79f78 | ||
|
|
93e8c5be32 | ||
|
|
d9f86aecd2 | ||
|
|
e9552fedef | ||
|
|
84e1c6e809 | ||
|
|
aadd6fd7e0 | ||
|
|
59987ed359 | ||
|
|
a79600c81f | ||
|
|
e8a4c3c6b9 | ||
|
|
62fce26651 | ||
|
|
25add6511f | ||
|
|
b2a28cd39a | ||
|
|
6de3aebf3a | ||
|
|
1b7e422772 | ||
|
|
b0f48b7f00 | ||
|
|
94b07d05c1 | ||
|
|
4392fec7f5 | ||
|
|
c1d0ec076b | ||
|
|
a47d6cd937 | ||
|
|
dcdb5e2a9e | ||
|
|
240325dc18 | ||
|
|
e599d2ec05 | ||
|
|
c62a417cbf | ||
|
|
98fc1ee0a7 | ||
|
|
78d0fd811b | ||
|
|
54d06e580d | ||
|
|
a62fca1e55 | ||
|
|
7b1d23eba4 | ||
|
|
2502c279fc | ||
|
|
878fc8c2fd | ||
|
|
64902eebcb | ||
|
|
e520f6afc4 | ||
|
|
0cc1ae9324 | ||
|
|
1b2124aa35 | ||
|
|
bd4fde9e63 | ||
|
|
c85cfa90a4 | ||
|
|
a0449b50c8 | ||
|
|
010c0bfc7d | ||
|
|
394b063b8c | ||
|
|
251780bed6 | ||
|
|
decc2a9c79 | ||
|
|
b62d84424e | ||
|
|
e15324d2cd | ||
|
|
20b84a9459 | ||
|
|
109198a374 | ||
|
|
dafc68f049 | ||
|
|
3e5c944365 | ||
|
|
d95838309e | ||
|
|
4745fc0db1 | ||
|
|
b3648187ff | ||
|
|
b35483edf8 | ||
|
|
f29088e854 | ||
|
|
b009dfe4ee | ||
|
|
eba94f430c | ||
|
|
06347b7e3c | ||
|
|
6bc426b21d | ||
|
|
e0fac8d2c0 | ||
|
|
4a849aab7f | ||
|
|
ad2d0c84e4 | ||
|
|
6bf360fbfb | ||
|
|
380292a8aa | ||
|
|
f9949da745 | ||
|
|
b0cc52e0aa | ||
|
|
9ef705650b | ||
|
|
c6dadbe75e | ||
|
|
0a65c05083 | ||
|
|
21026340ad | ||
|
|
eb2273247f | ||
|
|
02fc698f1c | ||
|
|
8dc11e89bd | ||
|
|
12c3264000 | ||
|
|
b34672ed19 | ||
|
|
541c8c4b93 | ||
|
|
b97373bf37 | ||
|
|
c0b561cb5a | ||
|
|
bd3ccfd0a9 | ||
|
|
5470acd3af | ||
|
|
64696fe973 | ||
|
|
f2cd93dc54 | ||
|
|
ed2fa4cdd8 | ||
|
|
c2c4636961 | ||
|
|
03cca1d1c0 | ||
|
|
354b075885 | ||
|
|
de7f039b99 | ||
|
|
c2e530af17 | ||
|
|
19797d5d23 | ||
|
|
144c2b5fc7 | ||
|
|
577b525508 | ||
|
|
7da40d1c2e | ||
|
|
4e3a5ca33b | ||
|
|
97e4707f72 | ||
|
|
541dd6b579 | ||
|
|
450ee43677 | ||
|
|
e57229e670 | ||
|
|
c0b2e886d2 | ||
|
|
bb4749c65b | ||
|
|
1ef2a96465 | ||
|
|
5aa37c68a2 | ||
|
|
6e5a1a1f4d | ||
|
|
b624ce16c3 | ||
|
|
3be5b5f919 | ||
|
|
04ac5b69ac | ||
|
|
9cc14ac5c7 | ||
|
|
755eb1405b | ||
|
|
0138294b36 | ||
|
|
c0a4addf30 | ||
|
|
39bbee0eeb | ||
|
|
39dda3f534 | ||
|
|
1cb8dbe795 | ||
|
|
85f1ca6101 | ||
|
|
e13820bbf0 | ||
|
|
3973362457 | ||
|
|
2f3f13afb9 | ||
|
|
b38877e193 | ||
|
|
0e1dbb5377 | ||
|
|
f07cc8b103 | ||
|
|
67775bc797 | ||
|
|
05933a5f0c | ||
|
|
e15ebd5aac | ||
|
|
d32b2ca524 | ||
|
|
d0a895628e | ||
|
|
90f2b3fb21 | ||
|
|
0f95800dde | ||
|
|
ff99cd2456 | ||
|
|
04971f8672 | ||
|
|
b6177b27f4 | ||
|
|
ae97e87506 | ||
|
|
df91ca500f | ||
|
|
2d73f541c0 | ||
|
|
7561eabe52 | ||
|
|
067fb1b0b7 | ||
|
|
78071841cc | ||
|
|
fac232229e | ||
|
|
a43021e87c | ||
|
|
eb599373ee | ||
|
|
7b529b5f9e | ||
|
|
1a0de3b3cf | ||
|
|
947154dc9c | ||
|
|
8acd1f1fe4 | ||
|
|
665210e506 | ||
|
|
91b9370a21 | ||
|
|
ca0aa600b4 | ||
|
|
1c42c4c969 | ||
|
|
389f0ae452 | ||
|
|
6e406311c3 | ||
|
|
00a24756f4 | ||
|
|
9025f312cc | ||
|
|
d5e453edd3 | ||
|
|
26cc64bdd6 | ||
|
|
87884c1af2 | ||
|
|
c0623a949c | ||
|
|
42a23ea23c | ||
|
|
710c31d1ca | ||
|
|
f637ba4dad | ||
|
|
80d2c60cef | ||
|
|
b17d71e4c3 | ||
|
|
3c5bd3a605 | ||
|
|
7cc8d1e693 | ||
|
|
99520d54a5 | ||
|
|
e10a8c078b | ||
|
|
7a196fed7c | ||
|
|
c418c7e725 | ||
|
|
e35748deff | ||
|
|
b57efbe31c | ||
|
|
8f91437701 | ||
|
|
a7eb547ca4 | ||
|
|
0ceb12f74f | ||
|
|
4960624de7 | ||
|
|
2c92f24d89 | ||
|
|
0b7c679dba | ||
|
|
aab3cdc58a | ||
|
|
3c63f5b204 | ||
|
|
0b97bbf827 | ||
|
|
970dbb0c59 | ||
|
|
d21d3c2ceb | ||
|
|
0f6493b8ce | ||
|
|
f26beec1d3 | ||
|
|
c4225e29ed | ||
|
|
9243326cd3 | ||
|
|
86beb8023a | ||
|
|
f4e134742b | ||
|
|
2b17bf4114 | ||
|
|
c4f0fc8f7b | ||
|
|
3d6c836e7d | ||
|
|
c279055af4 | ||
|
|
657cba042a | ||
|
|
7a58e48cae | ||
|
|
670eab62bf | ||
|
|
fc85586809 | ||
|
|
837fc4988d | ||
|
|
4664b47851 | ||
|
|
9864d932e0 | ||
|
|
436f60caa9 | ||
|
|
e9530eda9d | ||
|
|
f4ddac16f9 | ||
|
|
33bdc07f55 | ||
|
|
130a4ed2d3 | ||
|
|
59ebc1af8a | ||
|
|
82e15d2e98 | ||
|
|
9c842f1895 | ||
|
|
8cc849488b | ||
|
|
fcaa232967 | ||
|
|
d3f8153b90 | ||
|
|
99ecf22790 | ||
|
|
b1b7ee65b4 | ||
|
|
6889456662 | ||
|
|
081553dc9f | ||
|
|
5d8d796807 | ||
|
|
f3d88fc746 | ||
|
|
d87ccae6c9 | ||
|
|
2760a7816d | ||
|
|
8f5c649d0f | ||
|
|
fcf9e7a1ef | ||
|
|
2be7b6480a | ||
|
|
f5ded86c02 | ||
|
|
8abfaf0ffd | ||
|
|
b070ba142f | ||
|
|
bd7c6828bf | ||
|
|
d0671ec58c | ||
|
|
1e40ffd1cc | ||
|
|
da2c3e9ed7 | ||
|
|
f62d6abb69 | ||
|
|
12ad7a6322 | ||
|
|
b75247ea3a | ||
|
|
9a963bbe79 | ||
|
|
994bc8b0e4 | ||
|
|
2451605033 | ||
|
|
10942527f3 | ||
|
|
4909ed5ccd | ||
|
|
5cf5df68dc | ||
|
|
dd32cc99ea | ||
|
|
79092dc8eb | ||
|
|
6229e4610a | ||
|
|
bfe36d3f4a | ||
|
|
d42bf44fad | ||
|
|
33e352819c | ||
|
|
53ee0aaee1 | ||
|
|
42707a19bd | ||
|
|
0888706790 | ||
|
|
16453a05f8 | ||
|
|
2fbb7466d3 | ||
|
|
f29f94f45f | ||
|
|
cd973868fc | ||
|
|
3c35f02cac | ||
|
|
22c93e2389 | ||
|
|
8c751eb532 | ||
|
|
4df443e007 | ||
|
|
f52fa41439 | ||
|
|
f77d72fd86 | ||
|
|
9b80c84794 | ||
|
|
725fc658f8 | ||
|
|
24bbf226a1 | ||
|
|
e4e27662f5 | ||
|
|
83474da7b5 | ||
|
|
9146e5f287 | ||
|
|
ff4502c63a | ||
|
|
9711bd8fe1 | ||
|
|
05139e53be | ||
|
|
870b2642a9 | ||
|
|
d31b26ae7d | ||
|
|
5511925ba2 | ||
|
|
f96b20717d | ||
|
|
940c9c45d7 | ||
|
|
87d6008dfc | ||
|
|
b9c0c8d2dc | ||
|
|
81c30d5fd5 | ||
|
|
0aa33d88a5 | ||
|
|
e64a504bb1 | ||
|
|
bc876a159e | ||
|
|
4aa1a838ed | ||
|
|
095a51edd0 | ||
|
|
a3a11bdf3f | ||
|
|
70b503f3d4 | ||
|
|
bbf609b880 | ||
|
|
0992bafe30 | ||
|
|
c810c5275a | ||
|
|
3c1b06872d | ||
|
|
cefdd2f66c | ||
|
|
5dac13b1da | ||
|
|
6014b04b2a | ||
|
|
8aebf48193 | ||
|
|
fbb905957b | ||
|
|
e0ce135838 | ||
|
|
60497c60c1 | ||
|
|
251a77c8b4 | ||
|
|
2b7c1345ee | ||
|
|
69b7d94774 | ||
|
|
7b7494b8a4 | ||
|
|
8fe762709b | ||
|
|
a3f17deb17 | ||
|
|
9390dcdd43 | ||
|
|
e6fb460071 | ||
|
|
6137fdeb33 | ||
|
|
4a4d02ea6a | ||
|
|
be26e5f152 | ||
|
|
127bfba135 | ||
|
|
7efae3c125 | ||
|
|
1e5af21000 | ||
|
|
33a0a4c173 | ||
|
|
eeb7974e05 | ||
|
|
f45ea1a31c | ||
|
|
a866dbaa80 | ||
|
|
62447d6b89 | ||
|
|
93f0724b83 | ||
|
|
724762843d | ||
|
|
ff16afbf0b | ||
|
|
9d7ef25062 | ||
|
|
88078d65e9 | ||
|
|
b07a97c17e | ||
|
|
41e7d65e2a | ||
|
|
7fa5865cf6 | ||
|
|
e0b8fe3b1a | ||
|
|
4a11dd1e16 | ||
|
|
34a474101f | ||
|
|
e6799e7a04 | ||
|
|
0f83f9992c | ||
|
|
d2ad78eb40 | ||
|
|
0b32738f4e | ||
|
|
a9cedb3fca | ||
|
|
51f9cd4bb4 | ||
|
|
a1668e2411 | ||
|
|
9418045a2c | ||
|
|
a7da6d210a | ||
|
|
59a41dc844 | ||
|
|
e09f2c9beb | ||
|
|
4bc3c8d9ac | ||
|
|
9acea8adf4 | ||
|
|
e5f754ed0e | ||
|
|
263a8f9048 | ||
|
|
6f9e52792a | ||
|
|
4a9b01e93b | ||
|
|
b7de23e895 | ||
|
|
f358f78da8 | ||
|
|
b8ab66369e | ||
|
|
54a78d5565 | ||
|
|
b4324cd685 | ||
|
|
ca212c8737 | ||
|
|
6fe4ed3e24 | ||
|
|
a659f2e49d | ||
|
|
760fbbb357 | ||
|
|
56388145b5 | ||
|
|
cd60db417c | ||
|
|
5cce01215f | ||
|
|
bc8bdfe385 | ||
|
|
4578af7a6d | ||
|
|
9e1cdd8f57 | ||
|
|
682c3b834f | ||
|
|
e269bab186 | ||
|
|
33a89c5d89 | ||
|
|
139047b22b | ||
|
|
9b50114852 | ||
|
|
b100d198e8 | ||
|
|
7849f2fb4b | ||
|
|
b35ecddde3 | ||
|
|
bde7921016 | ||
|
|
ee28e3346b | ||
|
|
d33b0587cb | ||
|
|
7e0ed537b7 | ||
|
|
1e351eb01d | ||
|
|
1a83bddf8c | ||
|
|
2a63c35743 | ||
|
|
27dcbcd7e1 | ||
|
|
0cf4c7b7b7 | ||
|
|
623372387d | ||
|
|
abf0f4d699 | ||
|
|
2bea447de5 | ||
|
|
f6538b6110 | ||
|
|
2d3ae71a3d | ||
|
|
9a20faf640 | ||
|
|
123493ee59 | ||
|
|
2d498dd138 | ||
|
|
376214e2d2 | ||
|
|
62da469fd1 | ||
|
|
d64009e23e | ||
|
|
fd8b642d64 | ||
|
|
d5ed5cd665 | ||
|
|
fa95d064ff | ||
|
|
1905e0ee6f | ||
|
|
96b18faea1 | ||
|
|
0d7f2e157a | ||
|
|
2d66936d8b | ||
|
|
b637a63e71 | ||
|
|
1ae778d81e | ||
|
|
f4412ee96b | ||
|
|
9130aceb5a | ||
|
|
b8336c03c3 | ||
|
|
76c3ade394 | ||
|
|
d9b22fd513 | ||
|
|
88ea998f8b | ||
|
|
8b605aeaa8 | ||
|
|
db91577485 | ||
|
|
5d9404863d | ||
|
|
d3986ca14a | ||
|
|
2508c1abb2 | ||
|
|
983e3b2274 | ||
|
|
72a02e087c | ||
|
|
352b4a0b73 | ||
|
|
d957b2d20f | ||
|
|
dcab8af8ab | ||
|
|
e1987c34d9 | ||
|
|
a80a8aab1c | ||
|
|
d6fbcdb09d | ||
|
|
d39b28b011 | ||
|
|
8f36128fe3 | ||
|
|
986d4c99bd | ||
|
|
f677dcb1f4 | ||
|
|
1a9b220ec2 | ||
|
|
d15d252af7 | ||
|
|
5e3618716d | ||
|
|
f13522559d | ||
|
|
777c2726d3 | ||
|
|
c25afdc203 | ||
|
|
c25f6d7c38 | ||
|
|
388e46ee81 | ||
|
|
242866948f | ||
|
|
15bb0ce990 | ||
|
|
a82911ea5d | ||
|
|
9a8f20317b | ||
|
|
b605a0f622 | ||
|
|
046a074c3a | ||
|
|
7c96fac95c | ||
|
|
a3ef53102d | ||
|
|
68513b775b | ||
|
|
a79dcc93f6 | ||
|
|
7aabfc573b | ||
|
|
22dde5d18e | ||
|
|
56505457eb | ||
|
|
5930c6d5fb | ||
|
|
6b162a4e49 | ||
|
|
c3b9888b31 | ||
|
|
cb8dfdde4c | ||
|
|
ff5d333fc8 | ||
|
|
8eb4b6288a | ||
|
|
f18836be90 | ||
|
|
3372070a58 | ||
|
|
f99e2ebd13 | ||
|
|
4feb26eefb | ||
|
|
2da7cd2064 | ||
|
|
9d7daf7afd | ||
|
|
cb1ebc1cd0 | ||
|
|
6ad56a0859 | ||
|
|
8515781564 | ||
|
|
7e2bfbd255 | ||
|
|
e2325f7ba4 | ||
|
|
9afdab8c52 | ||
|
|
f620d4a9ca | ||
|
|
fb1e763bbe | ||
|
|
ecea7e7493 | ||
|
|
560ade00b4 | ||
|
|
81ea24ad54 | ||
|
|
747b25046a | ||
|
|
b9536812f4 | ||
|
|
eed2f0a430 | ||
|
|
31fe8cd263 | ||
|
|
a3fadbaa1a | ||
|
|
e2be655d74 | ||
|
|
2cd653c773 | ||
|
|
6538aff02f | ||
|
|
c1e3dec9be | ||
|
|
42c13ae135 | ||
|
|
9bd51c650b | ||
|
|
ba1c1c87c4 | ||
|
|
ceefba2743 | ||
|
|
70da46b05e | ||
|
|
32b7b39223 | ||
|
|
2343c79126 | ||
|
|
09a5a69f86 | ||
|
|
4081895a78 | ||
|
|
a522566a0c | ||
|
|
013c4e9c35 | ||
|
|
067f289050 | ||
|
|
06511b92aa | ||
|
|
32f4c9eabf | ||
|
|
14bc345883 | ||
|
|
d76b4fd7ea | ||
|
|
83cdd7e9fb | ||
|
|
50441bae62 | ||
|
|
5b0766a9b0 | ||
|
|
d979fe8e5f | ||
|
|
f2c52fd278 | ||
|
|
87d60308f2 | ||
|
|
64ebc56c87 | ||
|
|
58d485cbb5 | ||
|
|
e99dd3310c | ||
|
|
400f6e02a5 | ||
|
|
700b0609df | ||
|
|
bc52f90ed4 | ||
|
|
0771546dad | ||
|
|
95a1a71a66 | ||
|
|
b9b8e3f632 | ||
|
|
1e03a2ae40 | ||
|
|
25da6aeeca | ||
|
|
00b422807b | ||
|
|
130701a7bb | ||
|
|
ff88e68904 | ||
|
|
55fcf23d2b | ||
|
|
1b0b4c4cc5 | ||
|
|
cd57731593 | ||
|
|
37a80b935d | ||
|
|
4d61aec153 | ||
|
|
1adf25d50b | ||
|
|
ae33aee3f6 | ||
|
|
2c99e71626 | ||
|
|
e7f7775efa | ||
|
|
8b60a19577 | ||
|
|
5701e08db9 | ||
|
|
72a2fc49f8 | ||
|
|
d2617322c6 | ||
|
|
fa82745f64 | ||
|
|
19b2a334e4 | ||
|
|
627c2adf08 | ||
|
|
e3e137ca50 | ||
|
|
0978be580f | ||
|
|
5792838333 | ||
|
|
f9995583a5 | ||
|
|
4cc68bd139 | ||
|
|
d2510ad1bc | ||
|
|
4d81d3613c | ||
|
|
7d28963a32 | ||
|
|
b2594468b4 | ||
|
|
754b9832e9 | ||
|
|
097ac879ea | ||
|
|
bc0416cbb4 | ||
|
|
2814617e4b | ||
|
|
da9dfd166d | ||
|
|
1be07a42df | ||
|
|
1d83a6a898 | ||
|
|
2ff286b672 | ||
|
|
e8620a0986 | ||
|
|
7fb18bbdc7 | ||
|
|
5b67b687d3 | ||
|
|
9adcfa99f4 | ||
|
|
e723aaa5f6 | ||
|
|
d128b037a5 | ||
|
|
99fda00442 | ||
|
|
f574f8faf0 | ||
|
|
cedfa90d76 | ||
|
|
f1e6f6e505 | ||
|
|
b4f95cced7 | ||
|
|
e16c0caebb | ||
|
|
52489a484a | ||
|
|
e1d5c2c578 | ||
|
|
49f49632ad | ||
|
|
6dadc6fb1e | ||
|
|
a58a2f5fe4 | ||
|
|
c33c6bbff0 | ||
|
|
093f90d4c1 | ||
|
|
20ffa325d3 | ||
|
|
5027304801 | ||
|
|
85d5afd6d9 | ||
|
|
df295e92ee | ||
|
|
2e67bd2407 | ||
|
|
9aa01ee8cf | ||
|
|
6b993ad329 | ||
|
|
d70ded0993 | ||
|
|
3dacdcc8bb | ||
|
|
bb03026589 | ||
|
|
2f69e3141e | ||
|
|
1f4564da76 | ||
|
|
3b8e5ddfb3 | ||
|
|
edc293f96a | ||
|
|
3fa4149bb0 | ||
|
|
4b68a6ff23 | ||
|
|
28116c49dc | ||
|
|
6e6f144b7a | ||
|
|
e3f4f24c3e | ||
|
|
eb37e3a52b | ||
|
|
95d540630e | ||
|
|
23d66a0d68 | ||
|
|
0d64692c84 | ||
|
|
1cb640e51e | ||
|
|
2d98285545 | ||
|
|
376001100a | ||
|
|
e2954249f8 | ||
|
|
cc0b0196f4 | ||
|
|
6dfa171b4e | ||
|
|
b140073988 | ||
|
|
c22bc857b0 | ||
|
|
497fbdcdfc | ||
|
|
861f1b2ca3 | ||
|
|
6108ef4c89 | ||
|
|
a9c0bcb4a2 | ||
|
|
8f9de05768 | ||
|
|
e61e94f0fa | ||
|
|
85aac02593 | ||
|
|
9a678c41fe | ||
|
|
7c8f6ce62f | ||
|
|
9a896ea81e | ||
|
|
422c1893c0 | ||
|
|
f1cb5276d7 | ||
|
|
bed1b24340 | ||
|
|
da909ff084 | ||
|
|
8f743b70a4 | ||
|
|
a761017116 | ||
|
|
f06cc25a99 | ||
|
|
eff8480d5c | ||
|
|
eec303de49 | ||
|
|
07a936c5e8 | ||
|
|
a6002a2c6c | ||
|
|
7ba014ba49 | ||
|
|
165c649f31 | ||
|
|
4cf71dd336 | ||
|
|
c0a401216b | ||
|
|
2d712a3841 | ||
|
|
a2b5b4dd17 | ||
|
|
0480edce2a | ||
|
|
4eded82102 | ||
|
|
ec4ff83465 | ||
|
|
8745b8b051 | ||
|
|
4e28c3cadb | ||
|
|
76c724c783 | ||
|
|
032cb59388 | ||
|
|
e29247774c | ||
|
|
18d16f9a8b | ||
|
|
d137735be1 | ||
|
|
65929c02bc | ||
|
|
22466d6b98 | ||
|
|
23fe79c618 | ||
|
|
b202ca5619 | ||
|
|
7929711fea | ||
|
|
49a028a599 | ||
|
|
670cbcd336 | ||
|
|
449d31e8a1 | ||
|
|
fe82583813 | ||
|
|
1450a21d00 | ||
|
|
ae15544aed | ||
|
|
4b7a37cf7d | ||
|
|
cb7727900c | ||
|
|
e012726cd4 | ||
|
|
f49688fdb9 | ||
|
|
e32b017431 | ||
|
|
393869e538 | ||
|
|
d3bde0408f | ||
|
|
34d3225984 | ||
|
|
eaed53e25b | ||
|
|
feacbe8ebd | ||
|
|
bdf6052388 | ||
|
|
ec0a0190e7 | ||
|
|
99d653eece | ||
|
|
f825c5ae83 | ||
|
|
173484c30e | ||
|
|
884270093b | ||
|
|
62e7ab8c2b | ||
|
|
ded480207b | ||
|
|
ef49e2b5b3 | ||
|
|
b0a055a870 | ||
|
|
9b9e29a3b6 | ||
|
|
1a9a436cbe | ||
|
|
62dd29d2f3 | ||
|
|
d406d91856 | ||
|
|
98494c610a | ||
|
|
649a553fa4 | ||
|
|
e17a06d7bd | ||
|
|
4b14cc6a74 | ||
|
|
65560ab65e | ||
|
|
b65095fd0f | ||
|
|
28733179d2 | ||
|
|
960d23ca50 | ||
|
|
057f70ea9c | ||
|
|
3e378bd665 | ||
|
|
c120138f26 | ||
|
|
31b20362ec | ||
|
|
e7eb5b6ea6 | ||
|
|
fe91ed815e | ||
|
|
9e5cad0dc8 | ||
|
|
36cbc42363 | ||
|
|
4cb82ea9bd | ||
|
|
572ac4a17b | ||
|
|
6c552f6b43 | ||
|
|
9723129436 | ||
|
|
dc5191f8ba | ||
|
|
d79726899f | ||
|
|
8ab5710098 | ||
|
|
61d628d596 | ||
|
|
078fc25845 | ||
|
|
67eb4b317a | ||
|
|
6322919bc7 | ||
|
|
b81b8a1dea | ||
|
|
f3a3797850 | ||
|
|
5ec1283bb1 | ||
|
|
8634b0c6f0 | ||
|
|
d89830af61 | ||
|
|
ef1736b571 | ||
|
|
d951ee4b83 | ||
|
|
04081f62c4 | ||
|
|
0f28dc5e55 | ||
|
|
508f49df18 | ||
|
|
bec280c6b1 | ||
|
|
6a8ae9c0c4 | ||
|
|
ac22483f98 | ||
|
|
59d56d5c83 | ||
|
|
cdaad2fb4a | ||
|
|
843279bacb | ||
|
|
a000de0270 | ||
|
|
bf41b04cfa | ||
|
|
9ce2e8ea53 | ||
|
|
f066926fc9 | ||
|
|
4c38b0ab10 | ||
|
|
cf35c9dcef | ||
|
|
45ff9394f2 | ||
|
|
414043ded1 | ||
|
|
2533c9c14e | ||
|
|
f10f0dada6 | ||
|
|
282859bc1b | ||
|
|
a3ae97a5a3 | ||
|
|
ed8275a20b | ||
|
|
f2add3f788 | ||
|
|
ad144922fb | ||
|
|
b9c0f2a3d3 | ||
|
|
0cc07362b8 | ||
|
|
4ee5dcaff3 | ||
|
|
4d44746a88 | ||
|
|
1535bdbcd8 | ||
|
|
ecb160b28d | ||
|
|
7e9941def0 | ||
|
|
f9c6fb30bf | ||
|
|
94ad93ebd7 | ||
|
|
0e1ec5034e | ||
|
|
76b0505bd9 | ||
|
|
b309c1fc91 | ||
|
|
b9a802a19c | ||
|
|
a882ad3e65 | ||
|
|
969105b205 | ||
|
|
28bfb06c67 | ||
|
|
704dcb3e58 | ||
|
|
a7e723d8d4 | ||
|
|
4c6f5096be | ||
|
|
1a1d105fae | ||
|
|
42a0639bb5 | ||
|
|
e27b08203d | ||
|
|
1ca4583896 | ||
|
|
25fc6f1937 | ||
|
|
0ccc3f7252 | ||
|
|
66acd1821d | ||
|
|
93a0217d5f | ||
|
|
711a697570 | ||
|
|
f8139f3198 | ||
|
|
df01022f49 | ||
|
|
450411a732 | ||
|
|
f80c67828b | ||
|
|
d1889a5e06 | ||
|
|
12263ff02f | ||
|
|
76f914cbc2 | ||
|
|
c1f5252b3f | ||
|
|
20c6f79a44 | ||
|
|
ee6f1405d4 | ||
|
|
ee3541d74e | ||
|
|
e048388213 | ||
|
|
3ff3431b17 | ||
|
|
8608ff11f7 | ||
|
|
7e0d9fbace | ||
|
|
c6c9cfea22 | ||
|
|
a758976c69 | ||
|
|
a14192b7e0 | ||
|
|
601464083b | ||
|
|
ccca5d4d1c | ||
|
|
ba10657829 | ||
|
|
6315655f93 | ||
|
|
533cb23b73 | ||
|
|
0b95424a0d | ||
|
|
852f252d13 | ||
|
|
080042882f | ||
|
|
dde5b08c47 | ||
|
|
88d2c60ee8 | ||
|
|
eeff5a5d43 | ||
|
|
67dd4a72b0 | ||
|
|
a0b8cc21cc | ||
|
|
329a7a03a5 | ||
|
|
d0a3503d74 | ||
|
|
59b78f9984 | ||
|
|
bf75f16169 | ||
|
|
2f833dc457 | ||
|
|
22344a3971 | ||
|
|
8dde6ba60f | ||
|
|
d44f283a05 | ||
|
|
c18d5786dd | ||
|
|
f26ccfe16c | ||
|
|
1c681ee378 | ||
|
|
4c1ae44bbe | ||
|
|
94b5ec91cc | ||
|
|
6bfbf3ee41 | ||
|
|
fc24fa337e | ||
|
|
7b4306b1d6 | ||
|
|
4516cc0d65 | ||
|
|
308784c601 | ||
|
|
9145c9a52c | ||
|
|
4038cb5b85 | ||
|
|
628658972c | ||
|
|
db0fe9a755 | ||
|
|
fdf10e3d2e | ||
|
|
ded3e06a9b | ||
|
|
0dd0605a1f | ||
|
|
827b0c6e50 | ||
|
|
d1b533848d | ||
|
|
13ae28edab | ||
|
|
82253219e8 | ||
|
|
94592b74a6 | ||
|
|
eef2112e1e | ||
|
|
b83d56eff2 | ||
|
|
4c539b6db4 | ||
|
|
2ad329e64c | ||
|
|
4de89ec6ce | ||
|
|
fc885c8fa2 | ||
|
|
ef2c98ba39 | ||
|
|
41d922867e | ||
|
|
89223760e6 | ||
|
|
9a8a1f75ca | ||
|
|
52e8e7e4b0 | ||
|
|
93f65484de | ||
|
|
7d08cde8b8 | ||
|
|
d3c2bf7dd4 | ||
|
|
54cf3652b0 | ||
|
|
5607d2086d | ||
|
|
27ed918896 | ||
|
|
9b2df9cfd9 | ||
|
|
5dd08e438c | ||
|
|
2f8c8c3a28 | ||
|
|
dde7cf18f7 | ||
|
|
48aadbf716 | ||
|
|
5514af60e5 | ||
|
|
e8449eb02f | ||
|
|
9ea21a7ecb | ||
|
|
fec86c2862 | ||
|
|
11e5d4c5b7 | ||
|
|
b852fb0e26 | ||
|
|
0fc18bf3b1 | ||
|
|
d4be584782 | ||
|
|
2120d72901 | ||
|
|
6f9c08f906 | ||
|
|
70c666c380 | ||
|
|
46197d82b5 | ||
|
|
e4eab17595 | ||
|
|
cf10244f20 | ||
|
|
570684d308 | ||
|
|
244db8d894 | ||
|
|
96d6018ecc | ||
|
|
73ad6dd0c4 | ||
|
|
d0e15da352 | ||
|
|
b1b293a3ec | ||
|
|
5f0660a4e5 | ||
|
|
ec3a3a73ef | ||
|
|
087c4c5929 | ||
|
|
e0ee2e0801 | ||
|
|
c79a9e9858 | ||
|
|
b3fdce36af | ||
|
|
b7535b9526 | ||
|
|
0cf1cc5587 | ||
|
|
098dab889a | ||
|
|
cc856c7cd1 | ||
|
|
a20a155d39 | ||
|
|
1a458fe39f | ||
|
|
051ffdda35 | ||
|
|
a48418364c | ||
|
|
b75497231e | ||
|
|
5cceeb6ef2 | ||
|
|
29b94c5615 | ||
|
|
81fc1eccd3 | ||
|
|
22fae51c9d | ||
|
|
4332f7a640 | ||
|
|
d0e603e62d | ||
|
|
38c28f4358 | ||
|
|
742799b4ac | ||
|
|
5405dc5141 | ||
|
|
013793f989 | ||
|
|
2468cf63cc | ||
|
|
8e9b5d7e50 | ||
|
|
a33515d907 | ||
|
|
a276a33081 | ||
|
|
e325c3dbf6 | ||
|
|
b3fef625a8 | ||
|
|
13994a5f96 | ||
|
|
e8ac62cdd8 | ||
|
|
1bc7134ec2 | ||
|
|
273572f44c | ||
|
|
ac37483d47 | ||
|
|
0cc2b49296 | ||
|
|
44d5adc16f | ||
|
|
f749fc641b | ||
|
|
87c76c09e2 | ||
|
|
e787f9dd9f | ||
|
|
ec7d5b17ab | ||
|
|
47641eee59 | ||
|
|
42abe28cc1 | ||
|
|
b48afa38ac | ||
|
|
f7269d8df2 | ||
|
|
ce0fab8d2f | ||
|
|
33472567de | ||
|
|
f5e12328dc | ||
|
|
486c0f2937 | ||
|
|
e69c4cd1dc | ||
|
|
e0d3ccd8d1 | ||
|
|
16a3deec2c | ||
|
|
92db00692a | ||
|
|
fe88010a72 | ||
|
|
99ae4be2c2 | ||
|
|
a9085752c1 | ||
|
|
e1fbc9255c | ||
|
|
f33e25ac40 | ||
|
|
51365ab006 | ||
|
|
d61b7e48d7 | ||
|
|
f590b24f85 | ||
|
|
308fd55483 | ||
|
|
fefb44e612 | ||
|
|
dd3b562f1a | ||
|
|
30c9aa3df9 | ||
|
|
688184e255 | ||
|
|
75fb7c2e95 | ||
|
|
264b4b669e | ||
|
|
51f12c51ad | ||
|
|
03d134697c | ||
|
|
e706e1a68d | ||
|
|
ff3f42db95 | ||
|
|
e8aedeac36 | ||
|
|
2bf6b263ed | ||
|
|
bf166b757a | ||
|
|
b4165335a7 | ||
|
|
2a1bf2fa71 | ||
|
|
718d50a037 | ||
|
|
41960ada4a | ||
|
|
0a02caad04 | ||
|
|
ff75bdba9e | ||
|
|
189243a9b0 | ||
|
|
34e339c506 | ||
|
|
a437c603c6 | ||
|
|
4e940f7fa0 | ||
|
|
69fde7dead | ||
|
|
4368c182a0 | ||
|
|
48f4b12c0e | ||
|
|
6a6c1b6b21 | ||
|
|
51808d2ad4 | ||
|
|
0735fb1e92 | ||
|
|
850a85915b | ||
|
|
148f1109c6 | ||
|
|
fcbeeca305 | ||
|
|
fb16429867 | ||
|
|
e1439b529b | ||
|
|
db38d7ee78 | ||
|
|
0adcd1b3d9 | ||
|
|
36a984ce3c | ||
|
|
fcefd8031a | ||
|
|
64bebaa1d1 | ||
|
|
0138ff9e16 | ||
|
|
9bc085a23e | ||
|
|
1ce432b136 | ||
|
|
e0fbfa44a4 | ||
|
|
0a92d79ec0 | ||
|
|
b95f6563cc | ||
|
|
547bbecef1 | ||
|
|
700cb3b553 | ||
|
|
8646f8f23a | ||
|
|
99cc69c67d | ||
|
|
2c5d76908a | ||
|
|
832b34fc54 | ||
|
|
000b85ff81 | ||
|
|
bb317d54f2 | ||
|
|
d6f41d8dc0 | ||
|
|
6dff5ed679 | ||
|
|
fb8b6310d5 | ||
|
|
02aaf17ac5 | ||
|
|
b160a8de0b | ||
|
|
e3246fd751 | ||
|
|
91b1775f50 | ||
|
|
fb18ab1ca5 | ||
|
|
01ff55c84e | ||
|
|
523aab2e9e | ||
|
|
9a7d9da654 | ||
|
|
e9446556a1 | ||
|
|
806a5f209f | ||
|
|
c864b368b0 | ||
|
|
27eb09fb19 | ||
|
|
bea7223a0a | ||
|
|
0297823bda | ||
|
|
d1bce5c2d9 | ||
|
|
46c0ae3ccc | ||
|
|
ce6b689147 | ||
|
|
2d92818613 | ||
|
|
487878819e | ||
|
|
6682b1ced1 | ||
|
|
bc89b0658a | ||
|
|
d9dde36c74 | ||
|
|
44284ea5fb | ||
|
|
9f0c0b34af | ||
|
|
87ec44aed5 | ||
|
|
898e6b4f80 | ||
|
|
dea2600913 | ||
|
|
dc46ad16ae | ||
|
|
456550a943 | ||
|
|
7b789b3701 | ||
|
|
0480d493cf | ||
|
|
b4d7733e0a | ||
|
|
8b8fe7a0ae | ||
|
|
85ffc90f66 | ||
|
|
fa38798066 | ||
|
|
d657330584 | ||
|
|
36cb79de62 | ||
|
|
063ee5e855 | ||
|
|
7393b69757 | ||
|
|
8bd1903d98 | ||
|
|
d8bf540db2 | ||
|
|
e29f17ac46 | ||
|
|
1770f3fd0d | ||
|
|
4239f2ed71 | ||
|
|
3939ec28ba | ||
|
|
742ec2b38d | ||
|
|
9296d35517 | ||
|
|
06c15a792e | ||
|
|
95ca1e6a9d | ||
|
|
1df82110d1 | ||
|
|
24c743d23d | ||
|
|
f1b1ebe29e | ||
|
|
6384cdc74d | ||
|
|
d093fbb069 | ||
|
|
f9b4505843 | ||
|
|
ca2bcc647d | ||
|
|
b90048d72e | ||
|
|
a5fe08e84c | ||
|
|
2874cf531c | ||
|
|
ea7058e896 | ||
|
|
38bb10d36b | ||
|
|
58943bb156 | ||
|
|
2d66da3cb9 | ||
|
|
b7efbf9040 | ||
|
|
5222e157cb | ||
|
|
1e3a948977 | ||
|
|
20cc5107da | ||
|
|
a6a4d5f09b | ||
|
|
028c53287d | ||
|
|
24a9bea137 | ||
|
|
ef1a2d1730 | ||
|
|
6abff36e07 | ||
|
|
902685a197 | ||
|
|
c04b146486 | ||
|
|
7bb5afa585 | ||
|
|
06fde4fcd0 | ||
|
|
195845ab0c | ||
|
|
81a329f1e7 | ||
|
|
cd6272a1c9 | ||
|
|
53be752787 | ||
|
|
42ac06c114 | ||
|
|
9e159ed5ab | ||
|
|
2c42972230 | ||
|
|
f926e58891 | ||
|
|
a784c6bd52 | ||
|
|
05d78f5cb5 | ||
|
|
4ef7615d88 | ||
|
|
77c2783a3e | ||
|
|
ce4f1258b5 | ||
|
|
3fbaba6693 | ||
|
|
a8b36aed92 | ||
|
|
4749eccfa5 | ||
|
|
5b1dfc123f | ||
|
|
41a3623fcc | ||
|
|
296ac203d4 | ||
|
|
0c9436ca82 | ||
|
|
70c9dd1b95 | ||
|
|
80753b1115 | ||
|
|
a194216568 | ||
|
|
8bee424cc0 | ||
|
|
25ab3cabfe | ||
|
|
587174b771 | ||
|
|
3e1c34efe6 | ||
|
|
5864637f1c | ||
|
|
ec6b346ca1 | ||
|
|
e99f5bcced | ||
|
|
b89309ab82 | ||
|
|
2d230ec96a | ||
|
|
4550333f1e | ||
|
|
3ba610eb64 | ||
|
|
2436c6a118 | ||
|
|
4de80b26c1 | ||
|
|
bab14a1fbf | ||
|
|
0c27ff11b9 | ||
|
|
734e2ffbb2 | ||
|
|
da42c51af2 | ||
|
|
7cb6801241 | ||
|
|
f6c04b9b84 | ||
|
|
4eacb21259 | ||
|
|
6d1a3ccdcc | ||
|
|
c870f6e87d | ||
|
|
6d907094d7 | ||
|
|
6643f0d1e0 | ||
|
|
20b07e0752 | ||
|
|
092423adc7 | ||
|
|
a50ca1a85f | ||
|
|
02199c8c1d | ||
|
|
c166c92685 | ||
|
|
f243515261 | ||
|
|
98181fe21c | ||
|
|
a26ce8d8b5 | ||
|
|
de0e27c512 | ||
|
|
09e7d76c6f | ||
|
|
d597e05fa9 | ||
|
|
98dc991339 | ||
|
|
1d40434d2b | ||
|
|
46b87dc7eb | ||
|
|
fe7c56d269 | ||
|
|
5ba4801a79 | ||
|
|
ad564e25ca | ||
|
|
404be948d4 | ||
|
|
8cbc345f36 | ||
|
|
89927fd7e9 | ||
|
|
6b4a024234 | ||
|
|
18794831e0 | ||
|
|
3fb851304f | ||
|
|
d267338837 | ||
|
|
8e1641dac9 | ||
|
|
57d37ffba8 | ||
|
|
82afa81220 | ||
|
|
d730eb8d31 | ||
|
|
5a219b580f | ||
|
|
fb83bfb363 | ||
|
|
df7d3d18b6 | ||
|
|
a0535aa3db | ||
|
|
202b6121ab | ||
|
|
4e8b814ec2 | ||
|
|
6becca17bf | ||
|
|
c8b64d4162 | ||
|
|
0854303710 | ||
|
|
cba3e62e71 | ||
|
|
dcba720e97 | ||
|
|
6c614c06f6 | ||
|
|
9a812f11e7 | ||
|
|
917132fe26 | ||
|
|
187ca5dc8f | ||
|
|
7d795771d3 | ||
|
|
e51bc4ea78 | ||
|
|
2dc3235d4f | ||
|
|
040bb4a5a8 | ||
|
|
fc4436f091 | ||
|
|
5dbdef25d3 | ||
|
|
b9f3ac2eea | ||
|
|
9fc0c3b3de | ||
|
|
4f81184da0 | ||
|
|
8223561844 | ||
|
|
32a6beae65 | ||
|
|
146068c936 | ||
|
|
3b8c5ef21a | ||
|
|
e60ef8fc97 | ||
|
|
24d755b123 | ||
|
|
7c89f0b5b9 | ||
|
|
134a10f56c | ||
|
|
3a70c86f49 | ||
|
|
ac431bbc4a | ||
|
|
371097eb4d | ||
|
|
6346059698 | ||
|
|
372c284ad4 | ||
|
|
264ccdbf6d | ||
|
|
b95150ff11 | ||
|
|
81fc04f24d | ||
|
|
3d4ebddb04 | ||
|
|
de299e0d6a | ||
|
|
29cb8bfec4 | ||
|
|
b7f3e00fbf | ||
|
|
27a18d60a7 | ||
|
|
de8f6d3e8d | ||
|
|
6893635251 | ||
|
|
94a38a3b47 | ||
|
|
7d99e21d0d | ||
|
|
df3eb40e3c | ||
|
|
ba6b5f8fd1 | ||
|
|
8f518993a4 | ||
|
|
dac48a2610 | ||
|
|
7c0d10da79 | ||
|
|
d77b52af96 | ||
|
|
29f6463ed9 | ||
|
|
ed0bdbf31d | ||
|
|
b152d3e06d | ||
|
|
16cd57fe55 | ||
|
|
3f578122a3 | ||
|
|
51a27322be | ||
|
|
050feed5dc | ||
|
|
e3ddc16657 | ||
|
|
33cdf20cd5 | ||
|
|
317e59df4b | ||
|
|
a9a6f5b97e | ||
|
|
8b1444ebc2 | ||
|
|
509071949a | ||
|
|
697d857549 | ||
|
|
2ea45b1fdc | ||
|
|
726595e117 | ||
|
|
1666e32aaf | ||
|
|
6a69bbe4b5 | ||
|
|
7a608b4fb0 | ||
|
|
814ad87a42 | ||
|
|
3e4b5e23fa | ||
|
|
ab24ed8088 | ||
|
|
50ba2e329a | ||
|
|
c1e2a98f46 | ||
|
|
e04aa80fd6 | ||
|
|
482e977af4 | ||
|
|
2535bbbcf1 | ||
|
|
6698773d81 | ||
|
|
aefaf47f4c | ||
|
|
9b49125776 | ||
|
|
b33a2ac90d | ||
|
|
f67953c447 | ||
|
|
981632f599 | ||
|
|
a6c453d826 | ||
|
|
4087e685f4 | ||
|
|
5255085de1 | ||
|
|
9247ded710 | ||
|
|
0bb0cbaef0 | ||
|
|
0f7d272e13 | ||
|
|
00dafe3121 | ||
|
|
e44494aad0 | ||
|
|
4ab3dc2599 | ||
|
|
acfad7a982 | ||
|
|
b29b5b7ac1 | ||
|
|
7803ffb995 | ||
|
|
fc79cdfaa2 | ||
|
|
f9dbc6bc78 | ||
|
|
dc7aaae235 | ||
|
|
9804a98af8 | ||
|
|
647e954e8a | ||
|
|
004d9118bc | ||
|
|
594c8aad91 | ||
|
|
542a0008c9 | ||
|
|
24f7918aa4 | ||
|
|
2eec329bdf | ||
|
|
0411d4a8c9 | ||
|
|
a986faea56 | ||
|
|
ad71d0a03f | ||
|
|
0955c6d6fb | ||
|
|
d30b44ee0f | ||
|
|
a6f4db0f25 | ||
|
|
4547c328bc | ||
|
|
5027aeb3a0 | ||
|
|
c0239a659c | ||
|
|
e404da4192 | ||
|
|
69fa7d0091 | ||
|
|
e1d6aec682 | ||
|
|
155795a18e | ||
|
|
8c4052e884 | ||
|
|
3c63e2b7e4 | ||
|
|
9b119fa724 | ||
|
|
a17c1c063e | ||
|
|
6728f5da2d | ||
|
|
16adeae5c3 | ||
|
|
485eba94cc | ||
|
|
5a074348ac | ||
|
|
cd9bb56db5 | ||
|
|
8150f934fd | ||
|
|
4c8f3f7bae | ||
|
|
ab5f176f58 | ||
|
|
b294ac00ed | ||
|
|
165cbad67b | ||
|
|
b30da58eb9 | ||
|
|
b0fb6b858d | ||
|
|
53ce22ef5e | ||
|
|
8e7a52f44e | ||
|
|
05a35be019 | ||
|
|
4406220f70 | ||
|
|
51a6cff411 | ||
|
|
8f4253adbd | ||
|
|
3e404101bd | ||
|
|
65105d9dbe | ||
|
|
3a4d351a57 | ||
|
|
ce66c752c4 | ||
|
|
4e42a179fa | ||
|
|
973f555544 | ||
|
|
1d7e52c198 | ||
|
|
1b42dd1043 | ||
|
|
77e0022252 | ||
|
|
56964a890b | ||
|
|
cef41661dd | ||
|
|
68ca0b86da | ||
|
|
79a9ef4859 | ||
|
|
2798dd5916 | ||
|
|
8143c16c14 | ||
|
|
42435ab34a | ||
|
|
434fb2e7cb | ||
|
|
bce70bf17c | ||
|
|
cde44178c4 | ||
|
|
661ed17d23 | ||
|
|
c659f28334 | ||
|
|
218e35e3aa | ||
|
|
cabad83418 | ||
|
|
24ae7350f5 | ||
|
|
c60277f4d3 | ||
|
|
6a07cfba65 | ||
|
|
87c415830f | ||
|
|
c78c63e1d5 | ||
|
|
56ee8c56ba | ||
|
|
48495f0d66 | ||
|
|
8ad84a7ceb | ||
|
|
32e818af6a | ||
|
|
d9adb4fc94 | ||
|
|
513ac6cfb4 | ||
|
|
1da4efec86 | ||
|
|
1c630eb604 | ||
|
|
1c18a788f4 | ||
|
|
5887f0fe6b | ||
|
|
b782489a8c | ||
|
|
01381488f4 | ||
|
|
6555d5869f | ||
|
|
54c4f40188 | ||
|
|
62e8bee2a8 | ||
|
|
9ec3ddd492 | ||
|
|
d81dbb13e4 | ||
|
|
c238367b64 | ||
|
|
cdcb8a50d1 | ||
|
|
520c695401 | ||
|
|
b831b9d6b2 | ||
|
|
bbe91f439a | ||
|
|
b586a32843 | ||
|
|
288944db2c | ||
|
|
f2c07d8f81 | ||
|
|
d6a9746824 | ||
|
|
f84274f1c5 | ||
|
|
2118d920f5 | ||
|
|
207004beff | ||
|
|
27d084ce39 | ||
|
|
f705889c23 | ||
|
|
7098d08888 | ||
|
|
eabc6e23be | ||
|
|
b6d7207ec3 | ||
|
|
c33623efee | ||
|
|
2215bf3d7f | ||
|
|
86fe970651 | ||
|
|
3dc372c573 | ||
|
|
efcee0a7b7 | ||
|
|
39b6b100f9 | ||
|
|
9351ff032f | ||
|
|
f0760c07d8 | ||
|
|
77b0954c70 | ||
|
|
af7dbbf1e4 | ||
|
|
b661c2fa92 | ||
|
|
e308a74dc2 | ||
|
|
040d7d9ae3 | ||
|
|
f9b1e84704 | ||
|
|
eede894e72 | ||
|
|
55c0bb6d34 | ||
|
|
2b55b9b250 | ||
|
|
22add37b64 | ||
|
|
8a9695d48e | ||
|
|
e0faad1e59 | ||
|
|
fffa2d5a1b | ||
|
|
0926ae530c | ||
|
|
0b709f7dfb | ||
|
|
b5da2c4199 | ||
|
|
9ede01f130 | ||
|
|
c61463447f | ||
|
|
55b54de6a0 | ||
|
|
5357867103 | ||
|
|
222797e631 | ||
|
|
92841b46d7 | ||
|
|
6fe60d5c5e | ||
|
|
4c2323fcc9 | ||
|
|
fda0ab1e86 | ||
|
|
54079b36ae | ||
|
|
f8a99c60d8 | ||
|
|
2f27a7b0ce | ||
|
|
8af178c19c | ||
|
|
78f9ee86b1 | ||
|
|
ab5873984e | ||
|
|
62ea8b8913 | ||
|
|
a4416c202d | ||
|
|
1f5edffccf | ||
|
|
651260022c | ||
|
|
2e4344f7ea | ||
|
|
3cb7e77b60 | ||
|
|
f782dc1857 | ||
|
|
7179f133bb | ||
|
|
88f31ddad1 | ||
|
|
a7ab7fcf06 | ||
|
|
6f61e80c97 | ||
|
|
d1afdb4aac | ||
|
|
1112dc82c9 | ||
|
|
e47b0c6433 | ||
|
|
94ae9937f0 | ||
|
|
fadd085b57 | ||
|
|
5167ee520e | ||
|
|
f758a1cc64 | ||
|
|
2145be6db2 | ||
|
|
c740fe9124 | ||
|
|
a371e40c66 | ||
|
|
ccc6184342 | ||
|
|
c8c2d6659c | ||
|
|
1413f26c85 | ||
|
|
c7d7a7597c | ||
|
|
fbb7663a2f | ||
|
|
c93dd32179 | ||
|
|
7165826011 | ||
|
|
ada727a570 | ||
|
|
01b0f9534c | ||
|
|
0735283d45 | ||
|
|
3764c33a3a | ||
|
|
9fc02f67c2 | ||
|
|
0c40e40dc3 | ||
|
|
e31df16309 | ||
|
|
d7ea5bb9d7 | ||
|
|
6cda5fee0d | ||
|
|
1fb45d769f | ||
|
|
ca5e285c5a | ||
|
|
fb0eebfc52 | ||
|
|
dd90fb003e | ||
|
|
61cd044255 | ||
|
|
879d02081a | ||
|
|
051bc53aa2 | ||
|
|
a7fdbad8b4 | ||
|
|
5515772903 | ||
|
|
ff900fd9c0 | ||
|
|
eec4be7a29 | ||
|
|
6a821b8a75 | ||
|
|
1385ecb383 | ||
|
|
74418f3139 | ||
|
|
72def4b97b | ||
|
|
564c3b4778 | ||
|
|
c9eff4a70c | ||
|
|
879f63d1c1 | ||
|
|
3fb458dd19 | ||
|
|
d9a73b4fa3 | ||
|
|
23b3bfd967 | ||
|
|
f543d7f486 | ||
|
|
6a058d2c52 | ||
|
|
c73698e8fd | ||
|
|
38a255e069 | ||
|
|
ff41775dbb | ||
|
|
7e530618b7 | ||
|
|
d04a78afe6 | ||
|
|
f566237be0 | ||
|
|
87fa4a57b5 | ||
|
|
a65ad9483c | ||
|
|
4cbdccd39e | ||
|
|
9356148e2d | ||
|
|
4be55285d8 | ||
|
|
2caee35884 | ||
|
|
3eae2e9c2c | ||
|
|
e9fb5d9f25 | ||
|
|
6261981656 | ||
|
|
82ca3f31f9 | ||
|
|
97f3aa8325 | ||
|
|
7c503b4a31 | ||
|
|
9f8cab99e3 | ||
|
|
5f25b81004 | ||
|
|
73bbffccaa | ||
|
|
43ad7d6e29 | ||
|
|
2c27d631b4 | ||
|
|
eb31b4b00b | ||
|
|
f59d9d5aa8 | ||
|
|
746b7b1262 | ||
|
|
2d67d55b73 | ||
|
|
5f228fbb40 | ||
|
|
12576393cf | ||
|
|
7f43a2e104 | ||
|
|
00f17bb697 | ||
|
|
cf00b4eebf | ||
|
|
be5c67fddd | ||
|
|
fc4dc36c65 | ||
|
|
97a0dccdec | ||
|
|
9f64a96502 | ||
|
|
b9c3a3fcea | ||
|
|
6d43e0422a | ||
|
|
0d7e58ce79 | ||
|
|
3e008ef29b | ||
|
|
5c6be5d6d0 | ||
|
|
2bd4eff56f | ||
|
|
38f3c2d5b9 | ||
|
|
c6542fdec6 | ||
|
|
26a7d9ef30 | ||
|
|
847dbfc021 | ||
|
|
929f32335f | ||
|
|
61a8eccf18 | ||
|
|
d01a0c6617 | ||
|
|
d168e3bfdb | ||
|
|
99c6247baf | ||
|
|
a334ef28e7 | ||
|
|
63634961d4 | ||
|
|
d82289e303 | ||
|
|
a836df9a5a | ||
|
|
8bfcdffeb6 | ||
|
|
e411c0fded | ||
|
|
4708347c16 | ||
|
|
be64961de5 | ||
|
|
405a3909b0 | ||
|
|
e734bb120a | ||
|
|
006e596c72 | ||
|
|
499a66dfb0 | ||
|
|
11c8b47c39 | ||
|
|
00a29f3d88 | ||
|
|
e5b9da5201 | ||
|
|
ad44e58c7a | ||
|
|
572b5427c7 | ||
|
|
32af660f86 | ||
|
|
cc8a431532 | ||
|
|
5c7aeb2f2c | ||
|
|
e254565901 | ||
|
|
3d0beba261 | ||
|
|
147947662c | ||
|
|
f40fc5aa75 | ||
|
|
9b74d51f21 | ||
|
|
d45b1b8ea5 | ||
|
|
4437d7376d | ||
|
|
304db0d20e | ||
|
|
26949970d8 | ||
|
|
8e4539cf8e | ||
|
|
546ed65e1d | ||
|
|
14b6202eec | ||
|
|
50973ffb72 | ||
|
|
9a5ab97d78 | ||
|
|
6190e64956 | ||
|
|
79286c9384 | ||
|
|
c4e3f3670f | ||
|
|
b89ab9ff10 | ||
|
|
97d12b94f6 | ||
|
|
e4d801bbaf | ||
|
|
a02f949d23 | ||
|
|
b4e0d039ef | ||
|
|
bb0d5c5538 | ||
|
|
f5b335e8e9 | ||
|
|
67bd5d41aa | ||
|
|
1879dcb24a | ||
|
|
6662a58cb0 | ||
|
|
4fecce0a0d | ||
|
|
f70c839014 | ||
|
|
0c80f5c63a | ||
|
|
3b03aa30a6 | ||
|
|
9b3b2acb49 | ||
|
|
406d1c76c9 | ||
|
|
bfd0e87a17 | ||
|
|
2de4bfdcf2 | ||
|
|
f1a65a2aeb | ||
|
|
05da2ae3c7 | ||
|
|
4ae9d4a749 | ||
|
|
2253708da7 | ||
|
|
51e591bd25 | ||
|
|
2a5f2ff7b3 | ||
|
|
1c9ff6421d | ||
|
|
dc93222579 | ||
|
|
8143bc7873 | ||
|
|
772f978b45 | ||
|
|
0f1db18eae | ||
|
|
6940bb9b88 | ||
|
|
07649d04a3 | ||
|
|
39a3f70084 | ||
|
|
8e8486497f | ||
|
|
e5593d9a7f | ||
|
|
3f2a9c8bae | ||
|
|
7c69589c5b | ||
|
|
149e9b4bd4 | ||
|
|
a360b1759a | ||
|
|
765b817384 | ||
|
|
baf83b2f5a | ||
|
|
9c1b3f136f | ||
|
|
a66873a9e2 | ||
|
|
4a33278596 | ||
|
|
6d2270d931 | ||
|
|
1db1c2e7df | ||
|
|
da3fcb9a72 | ||
|
|
9144a7ceb9 | ||
|
|
feb6a71f95 | ||
|
|
1561a4abdf | ||
|
|
f483ca3214 | ||
|
|
0224d45961 | ||
|
|
0be17ed157 | ||
|
|
f0de822ce7 | ||
|
|
fb23db57b4 | ||
|
|
fda977b155 | ||
|
|
68a36597ab | ||
|
|
de58d0a4d8 | ||
|
|
54a006a420 | ||
|
|
246d7673a9 | ||
|
|
eef4787b79 | ||
|
|
1de3929988 | ||
|
|
cc3088c52f | ||
|
|
0facb8fffa | ||
|
|
1a7052b287 | ||
|
|
38307ececb | ||
|
|
e92497b34e | ||
|
|
3d5d95904a | ||
|
|
a0be02e687 | ||
|
|
37007dafee | ||
|
|
4230226716 | ||
|
|
1dc6f44828 | ||
|
|
c1ef1bcd19 | ||
|
|
1fc4bc5204 | ||
|
|
f5235b1d4c | ||
|
|
d6ee8f75e9 | ||
|
|
a00d93a2d9 | ||
|
|
561d40f8ff | ||
|
|
36229076f7 | ||
|
|
7f34073955 | ||
|
|
b75b91606c | ||
|
|
80582573f5 | ||
|
|
3683e4e7eb | ||
|
|
8ababf9f77 | ||
|
|
5971194678 | ||
|
|
d48cdcc789 | ||
|
|
d763168dec | ||
|
|
7ccc40cf5b | ||
|
|
aafb267787 | ||
|
|
82e4f11334 | ||
|
|
2e37c14d94 | ||
|
|
91f0908059 | ||
|
|
8d284b151d | ||
|
|
30954cc27f | ||
|
|
4b76b8400d | ||
|
|
1abbcfa3c6 | ||
|
|
9b4ca22254 | ||
|
|
c6d3613e57 | ||
|
|
e0229c917c |
+1
-1
@@ -1,4 +1,4 @@
|
||||
updater.py ident export-subst
|
||||
constants.py ident export-subst
|
||||
/test export-ignore
|
||||
cps/static/css/libs/* linguist-vendored
|
||||
cps/static/js/libs/* linguist-vendored
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
name: Bug/Problem report
|
||||
about: Create a report to help us improve Calibre-Web
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
<!-- Please have a look at our [Contributing Guidelines](https://github.com/janeczku/calibre-web/blob/master/CONTRIBUTING.md) -->
|
||||
|
||||
**Describe the bug/problem**
|
||||
A clear and concise description of what the bug is. If you are asking for support, please check our [Wiki](https://github.com/janeczku/calibre-web/wiki) if your question is already answered there.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Logfile**
|
||||
Add content of calibre-web.log file or the relevant error, try to reproduce your problem with "debug" log-level to get more output.
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Environment (please complete the following information):**
|
||||
- OS: [e.g. Windows 10/Raspberry Pi OS]
|
||||
- Python version: [e.g. python2.7]
|
||||
- Calibre-Web version: [e.g. 0.6.8 or 087c4c59 (git rev-parse --short HEAD)]:
|
||||
- Docker container: [None/LinuxServer]:
|
||||
- Special Hardware: [e.g. Rasperry Pi Zero]
|
||||
- Browser: [e.g. Chrome 83.0.4103.97, Safari 13.3.7, Firefox 68.0.1 ESR]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here. [e.g. access via reverse proxy, database background sync, special database location]
|
||||
@@ -0,0 +1 @@
|
||||
blank_issues_enabled: false
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for Calibre-Web
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
<!-- Please have a look at our [Contributing Guidelines](https://github.com/janeczku/calibre-web/blob/master/CONTRIBUTING.md) -->
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
+8
-5
@@ -6,26 +6,29 @@ __pycache__/
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
.python-version
|
||||
env/
|
||||
venv/
|
||||
eggs/
|
||||
dist/
|
||||
executable/
|
||||
build/
|
||||
vendor/
|
||||
.eggs/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
.pylint.d
|
||||
|
||||
# calibre-web
|
||||
*.db
|
||||
*.log
|
||||
config.ini
|
||||
cps/static/[0-9]*
|
||||
|
||||
.idea/
|
||||
*.bak
|
||||
*.log.*
|
||||
tags
|
||||
|
||||
settings.yaml
|
||||
gdrive_credentials
|
||||
|
||||
vendor
|
||||
client_secrets.json
|
||||
gmail.json
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
## How to contribute to Calibre-Web
|
||||
|
||||
First of all, we would like to thank you for reading this text. We are happy you are willing to contribute to Calibre-Web.
|
||||
|
||||
### **General**
|
||||
|
||||
**Communication language** is English. Google translated texts are not as bad as you might think, they are usually understandable, so don't worry if you generate your post that way.
|
||||
|
||||
**Calibre-Web** is not **Calibre**. If you are having a question regarding Calibre please post this at their [repository](https://github.com/kovidgoyal/calibre).
|
||||
|
||||
**Docker-Containers** of Calibre-Web are maintained by different persons than the people who drive Calibre-Web. If we come to the conclusion during our analysis that the problem is related to Docker, we might ask you to open a new issue at the repository of the Docker Container.
|
||||
|
||||
If you are having **Basic Installation Problems** with python or its dependencies, please consider using your favorite search engine to find a solution. In case you can't find a solution, we are happy to help you.
|
||||
|
||||
We can offer only very limited support regarding configuration of **Reverse-Proxy Installations**, **OPDS-Reader** or other programs in combination with Calibre-Web.
|
||||
|
||||
### **Translation**
|
||||
|
||||
Some of the user languages in Calibre-Web having missing translations. We are happy to add the missing texts if you translate them. Create a Pull Request, create an issue with the .po file attached, or write an email to "ozzie.fernandez.isaacs@googlemail.com" with attached translation file. To display all book languages in your native language an additional file is used (iso_language_names.py). The content of this file is auto-generated with the corresponding translations of Calibre, please do not edit this file on your own.
|
||||
|
||||
### **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).
|
||||
|
||||
### **Reporting a bug**
|
||||
|
||||
Do not open up a GitHub issue if the bug is a **security vulnerability** in Calibre-Web. Instead, please write an email to "ozzie.fernandez.isaacs@googlemail.com".
|
||||
|
||||
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?assignees=&labels=&template=bug_report.md&title=). 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.
|
||||
|
||||
### **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.
|
||||
|
||||
### **Contributing code to Calibre-Web**
|
||||
|
||||
Open a new GitHub pull request with the patch. Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.
|
||||
|
||||
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.
|
||||
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
-3
@@ -1,3 +1 @@
|
||||
include cps/static/*
|
||||
include cps/templates/*
|
||||
include cps/translations/*
|
||||
graft src/calibreweb
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# About
|
||||
|
||||
Calibre-Web is a web app providing a clean interface for browsing, reading and downloading eBooks using an existing [Calibre](https://calibre-ebook.com) database.
|
||||
|
||||
[](https://github.com/janeczku/calibre-web/blob/master/LICENSE)
|
||||
[]()
|
||||
[](https://github.com/janeczku/calibre-web/releases)
|
||||
[](https://pypi.org/project/calibreweb/)
|
||||
[](https://pypi.org/project/calibreweb/)
|
||||
[](https://discord.gg/h2VsJ2NEfB)
|
||||
|
||||
*This software is a fork of [library](https://github.com/mutschler/calibreserver) and licensed under the GPL v3 License.*
|
||||
|
||||

|
||||
|
||||
## Features
|
||||
|
||||
- Bootstrap 3 HTML5 interface
|
||||
- full graphical setup
|
||||
- User management with fine-grained per-user permissions
|
||||
- Admin interface
|
||||
- User Interface in brazilian, czech, dutch, english, finnish, french, german, greek, hungarian, italian, japanese, khmer, korean, polish, russian, simplified and traditional chinese, spanish, swedish, turkish, ukrainian
|
||||
- OPDS feed for eBook reader apps
|
||||
- Filter and search by titles, authors, tags, series and language
|
||||
- Create a custom book collection (shelves)
|
||||
- Support for editing eBook metadata and deleting eBooks from Calibre library
|
||||
- Support for converting eBooks through Calibre binaries
|
||||
- Restrict eBook download to logged-in users
|
||||
- Support for public user registration
|
||||
- Send eBooks to Kindle devices with the click of a button
|
||||
- Sync your Kobo devices through Calibre-Web with your Calibre library
|
||||
- Support for reading eBooks directly in the browser (.txt, .epub, .pdf, .cbr, .cbt, .cbz, .djvu)
|
||||
- Upload new books in many formats, including audio formats (.mp3, .m4a, .m4b)
|
||||
- Support for Calibre Custom Columns
|
||||
- Ability to hide content based on categories and Custom Column content per user
|
||||
- Self-update capability
|
||||
- "Magic Link" login to make it easy to log on eReaders
|
||||
- Login via LDAP, google/github oauth and via proxy authentication
|
||||
|
||||
## Installation
|
||||
|
||||
#### Installation via pip (recommended)
|
||||
1. Install calibre web via pip with the command `pip install calibreweb` (Depending on your OS and or distro the command could also be `pip3`).
|
||||
2. Optional features can also be installed via pip, please refer to [this page](https://github.com/janeczku/calibre-web/wiki/Dependencies-in-Calibre-Web-Linux-Windows) for details
|
||||
3. Calibre-Web can be started afterwards by typing `cps` or `python3 -m cps`
|
||||
|
||||
#### Manual installation
|
||||
1. Install dependencies by running `pip3 install --target vendor -r requirements.txt` (python3.x). Alternativly set up a python virtual environment.
|
||||
2. Execute the command: `python3 cps.py` (or `nohup python3 cps.py` - recommended if you want to exit the terminal window)
|
||||
|
||||
Issues with Ubuntu:
|
||||
Please note that running the above install command can fail on some versions of Ubuntu, saying `"can't combine user with prefix"`. This is a [known bug](https://github.com/pypa/pip/issues/3826) and can be remedied by using the command `pip install --system --target vendor -r requirements.txt` instead.
|
||||
|
||||
## Quick start
|
||||
|
||||
Point your browser to `http://localhost:8083` or `http://localhost:8083/opds` for the OPDS catalog
|
||||
Set `Location of Calibre database` to the path of the folder where your Calibre library (metadata.db) lives, push "submit" button\
|
||||
Optionally a Google Drive can be used to host the calibre library [-> Using Google Drive integration](https://github.com/janeczku/calibre-web/wiki/Configuration#using-google-drive-integration)
|
||||
Go to Login page
|
||||
|
||||
#### Default admin login:
|
||||
*Username:* admin\
|
||||
*Password:* admin123
|
||||
|
||||
|
||||
## Requirements
|
||||
|
||||
python 3.5+
|
||||
|
||||
Optionally, to enable on-the-fly conversion from one ebook format to another when using the send-to-kindle feature, or during editing of ebooks metadata:
|
||||
|
||||
[Download and install](https://calibre-ebook.com/download) the Calibre desktop program for your platform and enter the folder including program name (normally /opt/calibre/ebook-convert, or C:\Program Files\calibre\ebook-convert.exe) in the field "calibre's converter tool" on the setup page.
|
||||
|
||||
[Download](https://github.com/pgaskin/kepubify/releases/latest) Kepubify tool for your platform and place the binary starting with `kepubify` in Linux: `\opt\kepubify` Windows: `C:\Program Files\kepubify`.
|
||||
|
||||
## Docker Images
|
||||
|
||||
A pre-built Docker image is available in these Docker Hub repository (maintained by the LinuxServer team):
|
||||
|
||||
#### **LinuxServer - x64, armhf, aarch64**
|
||||
+ Docker Hub - [https://hub.docker.com/r/linuxserver/calibre-web](https://hub.docker.com/r/linuxserver/calibre-web)
|
||||
+ Github - [https://github.com/linuxserver/docker-calibre-web](https://github.com/linuxserver/docker-calibre-web)
|
||||
+ Github - (Optional Calibre layer) - [https://github.com/linuxserver/docker-calibre-web/tree/calibre](https://github.com/linuxserver/docker-calibre-web/tree/calibre)
|
||||
|
||||
This image has the option to pull in an extra docker manifest layer to include the Calibre `ebook-convert` binary. Just include the environmental variable `DOCKER_MODS=linuxserver/calibre-web:calibre` in your docker run/docker compose file. **(x64 only)**
|
||||
|
||||
If you do not need this functionality then this can be omitted, keeping the image as lightweight as possible.
|
||||
|
||||
Both the Calibre-Web and Calibre-Mod images are rebuilt automatically on new releases of Calibre-Web and Calibre respectively, and on updates to any included base image packages on a weekly basis if required.
|
||||
+ The "path to convertertool" should be set to `/usr/bin/ebook-convert`
|
||||
+ The "path to unrar" should be set to `/usr/bin/unrar`
|
||||
|
||||
# Contact
|
||||
|
||||
Just reach us out on [Discord](https://discord.gg/h2VsJ2NEfB)
|
||||
|
||||
For further information, How To's and FAQ please check the [Wiki](https://github.com/janeczku/calibre-web/wiki)
|
||||
|
||||
# Contributing to Calibre-Web
|
||||
|
||||
Please have a look at our [Contributing Guidelines](https://github.com/janeczku/calibre-web/blob/master/CONTRIBUTING.md)
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
# Security Policy
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Please report security issues to ozzie.fernandez.isaacs@googlemail.com
|
||||
|
||||
## Supported Versions
|
||||
|
||||
To receive fixes for security vulnerabilities it is required to always upgrade to the latest version of Calibre-Web. See https://github.com/janeczku/calibre-web/releases/latest for the latest release.
|
||||
|
||||
## 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 ||
|
||||
| V 0.6.15 | Fix for "javascript:" script links in identifier. Thanks to @scara31 ||
|
||||
| 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 ||
|
||||
| V 0.6.16 | Localhost can no longer be used to upload covers. Thanks to @scara31 ||
|
||||
| V 0.6.16 | Another case where public shelfs could be created without permission is prevented. Thanks to @ibarrionuevo ||
|
||||
|
||||
|
||||
## Staement regarding Log4j (CVE-2021-44228 and related)
|
||||
|
||||
Calibre-web is not affected by bugs related to Log4j. Calibre-Web is a python program, therefore not using Java, and not using the Java logging feature log4j.
|
||||
@@ -1,21 +1,82 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2012-2019 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 sys
|
||||
import os
|
||||
|
||||
|
||||
base_path = os.path.dirname(os.path.abspath(__file__))
|
||||
# Insert local directories into path
|
||||
sys.path.append(base_path)
|
||||
sys.path.append(os.path.join(base_path, 'cps'))
|
||||
sys.path.append(os.path.join(base_path, 'vendor'))
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vendor'))
|
||||
|
||||
|
||||
from cps import create_app
|
||||
from cps import web_server
|
||||
from cps.opds import opds
|
||||
from cps.web import web
|
||||
from cps.jinjia import jinjia
|
||||
from cps.about import about
|
||||
from cps.shelf import shelf
|
||||
from cps.admin import admi
|
||||
from cps.gdrive import gdrive
|
||||
from cps.editbooks import editbook
|
||||
from cps.remotelogin import remotelogin
|
||||
from cps.search_metadata import meta
|
||||
from cps.error_handler import init_errorhandler
|
||||
|
||||
try:
|
||||
from cps.kobo import kobo, get_kobo_activated
|
||||
from cps.kobo_auth import kobo_auth
|
||||
kobo_available = get_kobo_activated()
|
||||
except (ImportError, AttributeError): # Catch also error for not installed flask-WTF (missing csrf decorator)
|
||||
kobo_available = False
|
||||
|
||||
try:
|
||||
from cps.oauth_bb import oauth
|
||||
oauth_available = True
|
||||
except ImportError:
|
||||
oauth_available = False
|
||||
|
||||
|
||||
def main():
|
||||
app = create_app()
|
||||
|
||||
init_errorhandler()
|
||||
|
||||
app.register_blueprint(web)
|
||||
app.register_blueprint(opds)
|
||||
app.register_blueprint(jinjia)
|
||||
app.register_blueprint(about)
|
||||
app.register_blueprint(shelf)
|
||||
app.register_blueprint(admi)
|
||||
app.register_blueprint(remotelogin)
|
||||
app.register_blueprint(meta)
|
||||
app.register_blueprint(gdrive)
|
||||
app.register_blueprint(editbook)
|
||||
if kobo_available:
|
||||
app.register_blueprint(kobo)
|
||||
app.register_blueprint(kobo_auth)
|
||||
if oauth_available:
|
||||
app.register_blueprint(oauth)
|
||||
success = web_server.start()
|
||||
sys.exit(0 if success else 1)
|
||||
|
||||
from cps.server import Server
|
||||
|
||||
if __name__ == '__main__':
|
||||
Server.startServer()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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, GammaC0de, vuolter
|
||||
#
|
||||
# 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_login import LoginManager
|
||||
from flask import session
|
||||
|
||||
|
||||
class MyLoginManager(LoginManager):
|
||||
def _session_protection_failed(self):
|
||||
sess = session._get_current_object()
|
||||
ident = self._session_identifier_generator()
|
||||
if(sess and not (len(sess) == 1 and sess.get('csrf_token', None))) and ident != sess.get('_id', None):
|
||||
return super(). _session_protection_failed()
|
||||
return False
|
||||
Executable → Regular
+188
-1
@@ -1,2 +1,189 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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
|
||||
#
|
||||
# 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/>.
|
||||
__package__ = "cps"
|
||||
|
||||
import sys
|
||||
import os
|
||||
import mimetypes
|
||||
|
||||
from babel import Locale as LC
|
||||
from babel import negotiate_locale
|
||||
from babel.core import UnknownLocaleError
|
||||
from flask import Flask, request, g
|
||||
from .MyLoginManager import MyLoginManager
|
||||
from flask_babel import Babel
|
||||
from flask_principal import Principal
|
||||
|
||||
from . import config_sql, logger, cache_buster, cli, ub, db
|
||||
from .reverseproxy import ReverseProxied
|
||||
from .server import WebServer
|
||||
from .dep_check import dependency_check
|
||||
|
||||
try:
|
||||
import lxml
|
||||
lxml_present = True
|
||||
except ImportError:
|
||||
lxml_present = False
|
||||
|
||||
try:
|
||||
from flask_wtf.csrf import CSRFProtect
|
||||
wtf_present = True
|
||||
except ImportError:
|
||||
wtf_present = False
|
||||
|
||||
mimetypes.init()
|
||||
mimetypes.add_type('application/xhtml+xml', '.xhtml')
|
||||
mimetypes.add_type('application/epub+zip', '.epub')
|
||||
mimetypes.add_type('application/fb2+zip', '.fb2')
|
||||
mimetypes.add_type('application/x-mobipocket-ebook', '.mobi')
|
||||
mimetypes.add_type('application/x-mobipocket-ebook', '.prc')
|
||||
mimetypes.add_type('application/vnd.amazon.ebook', '.azw')
|
||||
mimetypes.add_type('application/x-mobi8-ebook', '.azw3')
|
||||
mimetypes.add_type('application/x-cbr', '.cbr')
|
||||
mimetypes.add_type('application/x-cbz', '.cbz')
|
||||
mimetypes.add_type('application/x-cbt', '.cbt')
|
||||
mimetypes.add_type('image/vnd.djvu', '.djvu')
|
||||
mimetypes.add_type('application/mpeg', '.mpeg')
|
||||
mimetypes.add_type('application/mpeg', '.mp3')
|
||||
mimetypes.add_type('application/mp4', '.m4a')
|
||||
mimetypes.add_type('application/mp4', '.m4b')
|
||||
mimetypes.add_type('application/ogg', '.ogg')
|
||||
mimetypes.add_type('application/ogg', '.oga')
|
||||
mimetypes.add_type('text/css', '.css')
|
||||
mimetypes.add_type('text/javascript; charset=UTF-8', '.js')
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
|
||||
lm = MyLoginManager()
|
||||
lm.login_view = 'web.login'
|
||||
lm.anonymous_user = ub.Anonymous
|
||||
lm.session_protection = 'strong'
|
||||
|
||||
if wtf_present:
|
||||
csrf = CSRFProtect()
|
||||
csrf.init_app(app)
|
||||
else:
|
||||
csrf = None
|
||||
|
||||
ub.init_db(cli.settingspath)
|
||||
# pylint: disable=no-member
|
||||
config = config_sql.load_configuration(ub.session)
|
||||
|
||||
web_server = WebServer()
|
||||
|
||||
babel = Babel()
|
||||
_BABEL_TRANSLATIONS = set()
|
||||
|
||||
log = logger.create()
|
||||
|
||||
|
||||
from . import services
|
||||
|
||||
db.CalibreDB.update_config(config)
|
||||
db.CalibreDB.setup_db(config.config_calibre_dir, cli.settingspath)
|
||||
|
||||
|
||||
calibre_db = db.CalibreDB()
|
||||
|
||||
def create_app():
|
||||
if sys.version_info < (3, 0):
|
||||
log.info(
|
||||
'*** Python2 is EOL since end of 2019, this version of Calibre-Web is no longer supporting Python2, please update your installation to Python3 ***')
|
||||
print(
|
||||
'*** Python2 is EOL since end of 2019, this version of Calibre-Web is no longer supporting Python2, please update your installation to Python3 ***')
|
||||
web_server.stop(True)
|
||||
sys.exit(5)
|
||||
if not lxml_present:
|
||||
log.info('*** "lxml" is needed for calibre-web to run. Please install it using pip: "pip install lxml" ***')
|
||||
print('*** "lxml" is needed for calibre-web to run. Please install it using pip: "pip install lxml" ***')
|
||||
web_server.stop(True)
|
||||
sys.exit(6)
|
||||
if not wtf_present:
|
||||
log.info('*** "flask-WTF" is needed for calibre-web to run. Please install it using pip: "pip install flask-WTF" ***')
|
||||
print('*** "flask-WTF" is needed for calibre-web to run. Please install it using pip: "pip install flask-WTF" ***')
|
||||
web_server.stop(True)
|
||||
sys.exit(7)
|
||||
for res in dependency_check() + dependency_check(True):
|
||||
log.info('*** "{}" version does not fit the requirements. Should: {}, Found: {}, please consider installing required version ***'
|
||||
.format(res['name'],
|
||||
res['target'],
|
||||
res['found']))
|
||||
app.wsgi_app = ReverseProxied(app.wsgi_app)
|
||||
|
||||
if os.environ.get('FLASK_DEBUG'):
|
||||
cache_buster.init_cache_busting(app)
|
||||
log.info('Starting Calibre Web...')
|
||||
|
||||
Principal(app)
|
||||
lm.init_app(app)
|
||||
app.secret_key = os.getenv('SECRET_KEY', config_sql.get_flask_session_key(ub.session))
|
||||
|
||||
web_server.init_app(app, config)
|
||||
|
||||
babel.init_app(app)
|
||||
_BABEL_TRANSLATIONS.update(str(item) for item in babel.list_translations())
|
||||
_BABEL_TRANSLATIONS.add('en')
|
||||
|
||||
if services.ldap:
|
||||
services.ldap.init_app(app, config)
|
||||
if services.goodreads_support:
|
||||
services.goodreads_support.connect(config.config_goodreads_api_key,
|
||||
config.config_goodreads_api_secret,
|
||||
config.config_use_goodreads)
|
||||
|
||||
return app
|
||||
|
||||
@babel.localeselector
|
||||
def get_locale():
|
||||
# if a user is logged in, use the locale from the user settings
|
||||
user = getattr(g, 'user', None)
|
||||
if user is not None and hasattr(user, "locale"):
|
||||
if user.name != 'Guest': # if the account is the guest account bypass the config lang settings
|
||||
return user.locale
|
||||
|
||||
preferred = list()
|
||||
if request.accept_languages:
|
||||
for x in request.accept_languages.values():
|
||||
try:
|
||||
preferred.append(str(LC.parse(x.replace('-', '_'))))
|
||||
except (UnknownLocaleError, ValueError) as e:
|
||||
log.debug('Could not parse locale "%s": %s', x, e)
|
||||
|
||||
return negotiate_locale(preferred or ['en'], _BABEL_TRANSLATIONS)
|
||||
|
||||
|
||||
@babel.timezoneselector
|
||||
def get_timezone():
|
||||
user = getattr(g, 'user', None)
|
||||
return user.timezone if user else None
|
||||
|
||||
|
||||
from .updater import Updater
|
||||
updater_thread = Updater()
|
||||
updater_thread.start()
|
||||
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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
|
||||
#
|
||||
# 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 sys
|
||||
import platform
|
||||
import sqlite3
|
||||
from collections import OrderedDict
|
||||
|
||||
import babel, pytz, requests, sqlalchemy
|
||||
import werkzeug, flask, flask_login, flask_principal, jinja2
|
||||
from flask_babel import gettext as _
|
||||
try:
|
||||
from flask_wtf import __version__ as flaskwtf_version
|
||||
except ImportError:
|
||||
flaskwtf_version = _(u'not installed')
|
||||
|
||||
from . import db, calibre_db, converter, uploader, server, isoLanguages, constants, gdriveutils, dep_check
|
||||
from .render_template import render_title_template
|
||||
|
||||
try:
|
||||
from flask_login import __version__ as flask_loginVersion
|
||||
except ImportError:
|
||||
from flask_login.__about__ import __version__ as flask_loginVersion
|
||||
try:
|
||||
# pylint: disable=unused-import
|
||||
import unidecode
|
||||
# _() necessary to make babel aware of string for translation
|
||||
unidecode_version = _(u'installed')
|
||||
except ImportError:
|
||||
unidecode_version = _(u'not installed')
|
||||
|
||||
try:
|
||||
from flask_dance import __version__ as flask_danceVersion
|
||||
except ImportError:
|
||||
flask_danceVersion = None
|
||||
|
||||
try:
|
||||
from greenlet import __version__ as greenlet_Version
|
||||
except ImportError:
|
||||
greenlet_Version = None
|
||||
|
||||
try:
|
||||
from scholarly import scholarly
|
||||
scholarly_version = _(u'installed')
|
||||
except ImportError:
|
||||
scholarly_version = _(u'not installed')
|
||||
|
||||
from . import services
|
||||
|
||||
about = flask.Blueprint('about', __name__)
|
||||
|
||||
ret = dict()
|
||||
req = dep_check.load_dependencys(False)
|
||||
opt = dep_check.load_dependencys(True)
|
||||
for i in (req + opt):
|
||||
ret[i[1]] = i[0]
|
||||
|
||||
if constants.NIGHTLY_VERSION[0] == "$Format:%H$":
|
||||
calibre_web_version = constants.STABLE_VERSION['version']
|
||||
else:
|
||||
calibre_web_version = (constants.STABLE_VERSION['version'] + ' - '
|
||||
+ constants.NIGHTLY_VERSION[0].replace('%','%%') + ' - '
|
||||
+ constants.NIGHTLY_VERSION[1].replace('%','%%'))
|
||||
if getattr(sys, 'frozen', False):
|
||||
calibre_web_version += " - Exe-Version"
|
||||
elif constants.HOME_CONFIG:
|
||||
calibre_web_version += " - pyPi"
|
||||
|
||||
if not ret:
|
||||
_VERSIONS = OrderedDict(
|
||||
Platform = '{0[0]} {0[2]} {0[3]} {0[4]} {0[5]}'.format(platform.uname()),
|
||||
Python=sys.version,
|
||||
Calibre_Web=calibre_web_version,
|
||||
WebServer=server.VERSION,
|
||||
Flask=flask.__version__,
|
||||
Flask_Login=flask_loginVersion,
|
||||
Flask_Principal=flask_principal.__version__,
|
||||
Flask_WTF=flaskwtf_version,
|
||||
Werkzeug=werkzeug.__version__,
|
||||
Babel=babel.__version__,
|
||||
Jinja2=jinja2.__version__,
|
||||
Requests=requests.__version__,
|
||||
SqlAlchemy=sqlalchemy.__version__,
|
||||
pySqlite=sqlite3.version,
|
||||
SQLite=sqlite3.sqlite_version,
|
||||
iso639=isoLanguages.__version__,
|
||||
pytz=pytz.__version__,
|
||||
Unidecode=unidecode_version,
|
||||
Scholarly=scholarly_version,
|
||||
Flask_SimpleLDAP=u'installed' if bool(services.ldap) else None,
|
||||
python_LDAP=services.ldapVersion if bool(services.ldapVersion) else None,
|
||||
Goodreads=u'installed' if bool(services.goodreads_support) else None,
|
||||
jsonschema=services.SyncToken.__version__ if bool(services.SyncToken) else None,
|
||||
flask_dance=flask_danceVersion,
|
||||
greenlet=greenlet_Version
|
||||
)
|
||||
_VERSIONS.update(gdriveutils.get_versions())
|
||||
_VERSIONS.update(uploader.get_versions(True))
|
||||
else:
|
||||
_VERSIONS = OrderedDict(
|
||||
Platform = '{0[0]} {0[2]} {0[3]} {0[4]} {0[5]}'.format(platform.uname()),
|
||||
Python = sys.version,
|
||||
Calibre_Web=calibre_web_version,
|
||||
Werkzeug = werkzeug.__version__,
|
||||
Jinja2=jinja2.__version__,
|
||||
pySqlite = sqlite3.version,
|
||||
SQLite = sqlite3.sqlite_version,
|
||||
)
|
||||
_VERSIONS.update(ret)
|
||||
_VERSIONS.update(uploader.get_versions(False))
|
||||
|
||||
def collect_stats():
|
||||
_VERSIONS['ebook converter'] = _(converter.get_calibre_version())
|
||||
_VERSIONS['unrar'] = _(converter.get_unrar_version())
|
||||
_VERSIONS['kepubify'] = _(converter.get_kepubify_version())
|
||||
return _VERSIONS
|
||||
|
||||
@about.route("/stats")
|
||||
@flask_login.login_required
|
||||
def stats():
|
||||
counter = calibre_db.session.query(db.Books).count()
|
||||
authors = calibre_db.session.query(db.Authors).count()
|
||||
categorys = calibre_db.session.query(db.Tags).count()
|
||||
series = calibre_db.session.query(db.Series).count()
|
||||
return render_title_template('stats.html', bookcounter=counter, authorcounter=authors, versions=collect_stats(),
|
||||
categorycounter=categorys, seriecounter=series, title=_(u"Statistics"), page="stat")
|
||||
+1884
File diff suppressed because it is too large
Load Diff
@@ -1,217 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2016-2019 lemmsh cervinko Kennyl matthazinski 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 logging
|
||||
import uploader
|
||||
import os
|
||||
from flask_babel import gettext as _
|
||||
import comic
|
||||
|
||||
try:
|
||||
from lxml.etree import LXML_VERSION as lxmlversion
|
||||
except ImportError:
|
||||
lxmlversion = None
|
||||
|
||||
__author__ = 'lemmsh'
|
||||
|
||||
logger = logging.getLogger("book_formats")
|
||||
|
||||
try:
|
||||
from wand.image import Image
|
||||
from wand import version as ImageVersion
|
||||
from wand.exceptions import PolicyError
|
||||
use_generic_pdf_cover = False
|
||||
except (ImportError, RuntimeError) as e:
|
||||
logger.warning('cannot import Image, generating pdf covers for pdf uploads will not work: %s', e)
|
||||
use_generic_pdf_cover = True
|
||||
try:
|
||||
from PyPDF2 import PdfFileReader
|
||||
from PyPDF2 import __version__ as PyPdfVersion
|
||||
use_pdf_meta = True
|
||||
except ImportError as e:
|
||||
logger.warning('cannot import PyPDF2, extracting pdf metadata will not work: %s', e)
|
||||
use_pdf_meta = False
|
||||
|
||||
try:
|
||||
import epub
|
||||
use_epub_meta = True
|
||||
except ImportError as e:
|
||||
logger.warning('cannot import epub, extracting epub metadata will not work: %s', e)
|
||||
use_epub_meta = False
|
||||
|
||||
try:
|
||||
import fb2
|
||||
use_fb2_meta = True
|
||||
except ImportError as e:
|
||||
logger.warning('cannot import fb2, extracting fb2 metadata will not work: %s', e)
|
||||
use_fb2_meta = False
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
from PIL import __version__ as PILversion
|
||||
use_PIL = True
|
||||
except ImportError:
|
||||
use_PIL = False
|
||||
|
||||
|
||||
def process(tmp_file_path, original_file_name, original_file_extension):
|
||||
meta = None
|
||||
try:
|
||||
if ".PDF" == original_file_extension.upper():
|
||||
meta = pdf_meta(tmp_file_path, original_file_name, original_file_extension)
|
||||
if ".EPUB" == original_file_extension.upper() and use_epub_meta is True:
|
||||
meta = epub.get_epub_info(tmp_file_path, original_file_name, original_file_extension)
|
||||
if ".FB2" == original_file_extension.upper() and use_fb2_meta is True:
|
||||
meta = fb2.get_fb2_info(tmp_file_path, original_file_extension)
|
||||
if original_file_extension.upper() in ['.CBZ', '.CBT']:
|
||||
meta = comic.get_comic_info(tmp_file_path, original_file_name, original_file_extension)
|
||||
|
||||
except Exception as ex:
|
||||
logger.warning('cannot parse metadata, using default: %s', ex)
|
||||
|
||||
if meta and meta.title.strip() and meta.author.strip():
|
||||
return meta
|
||||
else:
|
||||
return default_meta(tmp_file_path, original_file_name, original_file_extension)
|
||||
|
||||
|
||||
def default_meta(tmp_file_path, original_file_name, original_file_extension):
|
||||
return uploader.BookMeta(
|
||||
file_path=tmp_file_path,
|
||||
extension=original_file_extension,
|
||||
title=original_file_name,
|
||||
author=u"Unknown",
|
||||
cover=None,
|
||||
description="",
|
||||
tags="",
|
||||
series="",
|
||||
series_id="",
|
||||
languages="")
|
||||
|
||||
|
||||
def pdf_meta(tmp_file_path, original_file_name, original_file_extension):
|
||||
|
||||
if use_pdf_meta:
|
||||
pdf = PdfFileReader(open(tmp_file_path, 'rb'), strict=False)
|
||||
doc_info = pdf.getDocumentInfo()
|
||||
else:
|
||||
doc_info = None
|
||||
|
||||
if doc_info is not None:
|
||||
author = doc_info.author if doc_info.author else u"Unknown"
|
||||
title = doc_info.title if doc_info.title else original_file_name
|
||||
subject = doc_info.subject
|
||||
else:
|
||||
author = u"Unknown"
|
||||
title = original_file_name
|
||||
subject = ""
|
||||
return uploader.BookMeta(
|
||||
file_path=tmp_file_path,
|
||||
extension=original_file_extension,
|
||||
title=title,
|
||||
author=author,
|
||||
cover=pdf_preview(tmp_file_path, original_file_name),
|
||||
description=subject,
|
||||
tags="",
|
||||
series="",
|
||||
series_id="",
|
||||
languages="")
|
||||
|
||||
|
||||
def pdf_preview(tmp_file_path, tmp_dir):
|
||||
if use_generic_pdf_cover:
|
||||
return None
|
||||
else:
|
||||
if use_PIL:
|
||||
try:
|
||||
input1 = PdfFileReader(open(tmp_file_path, 'rb'), strict=False)
|
||||
page0 = input1.getPage(0)
|
||||
xObject = page0['/Resources']['/XObject'].getObject()
|
||||
|
||||
for obj in xObject:
|
||||
if xObject[obj]['/Subtype'] == '/Image':
|
||||
size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
|
||||
data = xObject[obj]._data # xObject[obj].getData()
|
||||
if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
|
||||
mode = "RGB"
|
||||
else:
|
||||
mode = "P"
|
||||
if '/Filter' in xObject[obj]:
|
||||
if xObject[obj]['/Filter'] == '/FlateDecode':
|
||||
img = Image.frombytes(mode, size, data)
|
||||
cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.png"
|
||||
img.save(filename=os.path.join(tmp_dir, cover_file_name))
|
||||
return cover_file_name
|
||||
# img.save(obj[1:] + ".png")
|
||||
elif xObject[obj]['/Filter'] == '/DCTDecode':
|
||||
cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.jpg"
|
||||
img = open(cover_file_name, "wb")
|
||||
img.write(data)
|
||||
img.close()
|
||||
return cover_file_name
|
||||
elif xObject[obj]['/Filter'] == '/JPXDecode':
|
||||
cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.jp2"
|
||||
img = open(cover_file_name, "wb")
|
||||
img.write(data)
|
||||
img.close()
|
||||
return cover_file_name
|
||||
else:
|
||||
img = Image.frombytes(mode, size, data)
|
||||
cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.png"
|
||||
img.save(filename=os.path.join(tmp_dir, cover_file_name))
|
||||
return cover_file_name
|
||||
except Exception as ex:
|
||||
print(ex)
|
||||
try:
|
||||
cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.jpg"
|
||||
with Image(filename=tmp_file_path + "[0]", resolution=150) as img:
|
||||
img.compression_quality = 88
|
||||
img.save(filename=os.path.join(tmp_dir, cover_file_name))
|
||||
return cover_file_name
|
||||
except PolicyError as ex:
|
||||
logger.warning('Pdf extraction forbidden by Imagemagick policy: %s', ex)
|
||||
return None
|
||||
except Exception as ex:
|
||||
logger.warning('Cannot extract cover image, using default: %s', ex)
|
||||
return None
|
||||
|
||||
def get_versions():
|
||||
if not use_generic_pdf_cover:
|
||||
IVersion = ImageVersion.MAGICK_VERSION
|
||||
WVersion = ImageVersion.VERSION
|
||||
else:
|
||||
IVersion = _(u'not installed')
|
||||
WVersion = _(u'not installed')
|
||||
if use_pdf_meta:
|
||||
PVersion='v'+PyPdfVersion
|
||||
else:
|
||||
PVersion=_(u'not installed')
|
||||
if lxmlversion:
|
||||
XVersion = 'v'+'.'.join(map(str, lxmlversion))
|
||||
else:
|
||||
XVersion = _(u'not installed')
|
||||
if use_PIL:
|
||||
PILVersion = 'v' + PILversion
|
||||
else:
|
||||
PILVersion = _(u'not installed')
|
||||
return {'Image Magick': IVersion,
|
||||
'PyPdf': PVersion,
|
||||
'lxml':XVersion,
|
||||
'Wand': WVersion,
|
||||
'Pillow': PILVersion}
|
||||
+12
-4
@@ -1,3 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2016-2019 jkrehm andy29485 OzzieIsaacs
|
||||
#
|
||||
@@ -17,8 +19,13 @@
|
||||
# Inspired by https://github.com/ChrisTM/Flask-CacheBust
|
||||
# Uses query strings so CSS font files are found without having to resort to absolute URLs
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import hashlib
|
||||
|
||||
from . import logger
|
||||
|
||||
|
||||
log = logger.create()
|
||||
|
||||
|
||||
def init_cache_busting(app):
|
||||
@@ -34,20 +41,20 @@ def init_cache_busting(app):
|
||||
|
||||
hash_table = {} # map of file hashes
|
||||
|
||||
app.logger.debug('Computing cache-busting values...')
|
||||
log.debug('Computing cache-busting values...')
|
||||
# compute file hashes
|
||||
for dirpath, __, filenames in os.walk(static_folder):
|
||||
for filename in filenames:
|
||||
# compute version component
|
||||
rooted_filename = os.path.join(dirpath, filename)
|
||||
with open(rooted_filename, 'rb') as f:
|
||||
file_hash = hashlib.md5(f.read()).hexdigest()[:7]
|
||||
file_hash = hashlib.md5(f.read()).hexdigest()[:7] # nosec
|
||||
|
||||
# save version to tables
|
||||
file_path = rooted_filename.replace(static_folder, "")
|
||||
file_path = file_path.replace("\\", "/") # Convert Windows path to web path
|
||||
hash_table[file_path] = file_hash
|
||||
app.logger.debug('Finished computing cache-busting values')
|
||||
log.debug('Finished computing cache-busting values')
|
||||
|
||||
def bust_filename(filename):
|
||||
return hash_table.get(filename, "")
|
||||
@@ -56,6 +63,7 @@ def init_cache_busting(app):
|
||||
return filename.split("?", 1)[0]
|
||||
|
||||
@app.url_defaults
|
||||
# pylint: disable=unused-variable
|
||||
def reverse_to_cache_busted_url(endpoint, values):
|
||||
"""
|
||||
Make `url_for` produce busted filenames when using the 'static' endpoint.
|
||||
|
||||
+61
-22
@@ -1,7 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2018 OzzieIsaacs
|
||||
#
|
||||
@@ -18,52 +16,93 @@
|
||||
# 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 argparse
|
||||
import os
|
||||
import sys
|
||||
import os
|
||||
import argparse
|
||||
import socket
|
||||
|
||||
from .constants import CONFIG_DIR as _CONFIG_DIR
|
||||
from .constants import STABLE_VERSION as _STABLE_VERSION
|
||||
from .constants import NIGHTLY_VERSION as _NIGHTLY_VERSION
|
||||
|
||||
|
||||
def version_info():
|
||||
if _NIGHTLY_VERSION[1].startswith('$Format'):
|
||||
return "Calibre-Web version: %s - unkown git-clone" % _STABLE_VERSION['version']
|
||||
return "Calibre-Web version: %s -%s" % (_STABLE_VERSION['version'], _NIGHTLY_VERSION[1])
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser(description='Calibre Web is a web app'
|
||||
' providing a interface for browsing, reading and downloading eBooks\n', prog='cps.py')
|
||||
' providing a interface for browsing, reading and downloading eBooks\n', prog='cps.py')
|
||||
parser.add_argument('-p', metavar='path', help='path and name to settings db, e.g. /opt/cw.db')
|
||||
parser.add_argument('-g', metavar='path', help='path and name to gdrive db, e.g. /opt/gd.db')
|
||||
parser.add_argument('-c', metavar='path', help='path and name to SSL certfile, e.g. /opt/test.cert, works only in combination with keyfile')
|
||||
parser.add_argument('-k', metavar='path', help='path and name to SSL keyfile, e.g. /opt/test.key, works only in combination with certfile')
|
||||
parser.add_argument('-c', metavar='path',
|
||||
help='path and name to SSL certfile, e.g. /opt/test.cert, works only in combination with keyfile')
|
||||
parser.add_argument('-k', metavar='path',
|
||||
help='path and name to SSL keyfile, e.g. /opt/test.key, works only in combination with certfile')
|
||||
parser.add_argument('-v', '--version', action='version', help='Shows version number and exits Calibre-web',
|
||||
version=version_info())
|
||||
parser.add_argument('-i', metavar='ip-address', help='Server IP-Address to listen')
|
||||
parser.add_argument('-s', metavar='user:pass', help='Sets specific username to new password')
|
||||
parser.add_argument('-f', action='store_true', help='Flag is depreciated and will be removed in next version')
|
||||
parser.add_argument('-l', action='store_true', help='Allow loading covers from localhost')
|
||||
args = parser.parse_args()
|
||||
|
||||
generalPath = os.path.normpath(os.getenv("CALIBRE_DBPATH",
|
||||
os.path.dirname(os.path.realpath(__file__)) + os.sep + ".." + os.sep))
|
||||
if args.p:
|
||||
settingspath = args.p
|
||||
else:
|
||||
settingspath = os.path.join(generalPath, "app.db")
|
||||
|
||||
if args.g:
|
||||
gdpath = args.g
|
||||
else:
|
||||
gdpath = os.path.join(generalPath, "gdrive.db")
|
||||
settingspath = args.p or os.path.join(_CONFIG_DIR, "app.db")
|
||||
gdpath = args.g or os.path.join(_CONFIG_DIR, "gdrive.db")
|
||||
|
||||
# handle and check parameter for ssl encryption
|
||||
certfilepath = None
|
||||
keyfilepath = None
|
||||
if args.c:
|
||||
if os.path.isfile(args.c):
|
||||
certfilepath = args.c
|
||||
else:
|
||||
print("Certfilepath is invalid. Exiting...")
|
||||
print("Certfile path is invalid. Exiting...")
|
||||
sys.exit(1)
|
||||
|
||||
if args.c is "":
|
||||
if args.c == "":
|
||||
certfilepath = ""
|
||||
|
||||
if args.k:
|
||||
if os.path.isfile(args.k):
|
||||
keyfilepath = args.k
|
||||
else:
|
||||
print("Keyfilepath is invalid. Exiting...")
|
||||
print("Keyfile path is invalid. Exiting...")
|
||||
sys.exit(1)
|
||||
|
||||
if (args.k and not args.c) or (not args.k and args.c):
|
||||
print("Certfile and Keyfile have to be used together. Exiting...")
|
||||
sys.exit(1)
|
||||
|
||||
if args.k is "":
|
||||
if args.k == "":
|
||||
keyfilepath = ""
|
||||
|
||||
# load covers from localhost
|
||||
allow_localhost = args.l or None
|
||||
# handle and check ip address argument
|
||||
ip_address = args.i or None
|
||||
if ip_address:
|
||||
try:
|
||||
# try to parse the given ip address with socket
|
||||
if hasattr(socket, 'inet_pton'):
|
||||
if ':' in ip_address:
|
||||
socket.inet_pton(socket.AF_INET6, ip_address)
|
||||
else:
|
||||
socket.inet_pton(socket.AF_INET, ip_address)
|
||||
else:
|
||||
# on windows python < 3.4, inet_pton is not available
|
||||
# inet_atom only handles IPv4 addresses
|
||||
socket.inet_aton(ip_address)
|
||||
except socket.error as err:
|
||||
print(ip_address, ':', err)
|
||||
sys.exit(1)
|
||||
|
||||
# handle and check user password argument
|
||||
user_credentials = args.s or None
|
||||
if user_credentials and ":" not in user_credentials:
|
||||
print("No valid 'username:password' format")
|
||||
sys.exit(3)
|
||||
|
||||
if args.f:
|
||||
print("Warning: -f flag is depreciated and will be removed in next version")
|
||||
|
||||
Executable → Regular
+113
-65
@@ -1,4 +1,3 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
@@ -18,65 +17,117 @@
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os
|
||||
import uploader
|
||||
import logging
|
||||
from iso639 import languages as isoLanguages
|
||||
|
||||
from . import logger, isoLanguages
|
||||
from .constants import BookMeta
|
||||
|
||||
|
||||
logger = logging.getLogger("book_formats")
|
||||
log = logger.create()
|
||||
|
||||
|
||||
try:
|
||||
from wand.image import Image
|
||||
use_IM = True
|
||||
except (ImportError, RuntimeError) as e:
|
||||
use_IM = False
|
||||
|
||||
|
||||
try:
|
||||
from comicapi.comicarchive import ComicArchive, MetaDataStyle
|
||||
use_comic_meta = True
|
||||
except ImportError as e:
|
||||
logger.warning('cannot import comicapi, extracting comic metadata will not work: %s', e)
|
||||
try:
|
||||
from comicapi import __version__ as comic_version
|
||||
except ImportError:
|
||||
comic_version = ''
|
||||
except (ImportError, LookupError) as e:
|
||||
log.debug('Cannot import comicapi, extracting comic metadata will not work: %s', e)
|
||||
import zipfile
|
||||
import tarfile
|
||||
try:
|
||||
import rarfile
|
||||
use_rarfile = True
|
||||
except (ImportError, SyntaxError) as e:
|
||||
log.debug('Cannot import rarfile, extracting cover files from rar files will not work: %s', e)
|
||||
use_rarfile = False
|
||||
use_comic_meta = False
|
||||
|
||||
NO_JPEG_EXTENSIONS = ['.png', '.webp', '.bmp']
|
||||
COVER_EXTENSIONS = ['.png', '.webp', '.bmp', '.jpg', '.jpeg']
|
||||
|
||||
def extractCover(tmp_file_name, original_file_extension):
|
||||
if use_comic_meta:
|
||||
archive = ComicArchive(tmp_file_name)
|
||||
cover_data = None
|
||||
ext = os.path.splitext(archive.getPageName(0))
|
||||
if len(ext) > 1:
|
||||
extension = ext[1].lower()
|
||||
if extension == '.jpg' or extension == '.jpeg':
|
||||
cover_data = archive.getPage(0)
|
||||
def _cover_processing(tmp_file_name, img, extension):
|
||||
tmp_cover_name = os.path.join(os.path.dirname(tmp_file_name), 'cover.jpg')
|
||||
if extension in NO_JPEG_EXTENSIONS:
|
||||
if use_IM:
|
||||
with Image(blob=img) as imgc:
|
||||
imgc.format = 'jpeg'
|
||||
imgc.transform_colorspace('rgb')
|
||||
imgc.save(filename=tmp_cover_name)
|
||||
return tmp_cover_name
|
||||
else:
|
||||
return None
|
||||
if img:
|
||||
with open(tmp_cover_name, 'wb') as f:
|
||||
f.write(img)
|
||||
return tmp_cover_name
|
||||
else:
|
||||
if original_file_extension.upper() == '.CBZ':
|
||||
cf = zipfile.ZipFile(tmp_file_name)
|
||||
for name in cf.namelist():
|
||||
ext = os.path.splitext(name)
|
||||
if len(ext) > 1:
|
||||
extension = ext[1].lower()
|
||||
if extension == '.jpg':
|
||||
cover_data = cf.read(name)
|
||||
break
|
||||
elif original_file_extension.upper() == '.CBT':
|
||||
cf = tarfile.TarFile(tmp_file_name)
|
||||
return None
|
||||
|
||||
|
||||
def _extract_Cover_from_archive(original_file_extension, tmp_file_name, rarExecutable):
|
||||
cover_data = extension = None
|
||||
if original_file_extension.upper() == '.CBZ':
|
||||
cf = zipfile.ZipFile(tmp_file_name)
|
||||
for name in cf.namelist():
|
||||
ext = os.path.splitext(name)
|
||||
if len(ext) > 1:
|
||||
extension = ext[1].lower()
|
||||
if extension in COVER_EXTENSIONS:
|
||||
cover_data = cf.read(name)
|
||||
break
|
||||
elif original_file_extension.upper() == '.CBT':
|
||||
cf = tarfile.TarFile(tmp_file_name)
|
||||
for name in cf.getnames():
|
||||
ext = os.path.splitext(name)
|
||||
if len(ext) > 1:
|
||||
extension = ext[1].lower()
|
||||
if extension in COVER_EXTENSIONS:
|
||||
cover_data = cf.extractfile(name).read()
|
||||
break
|
||||
elif original_file_extension.upper() == '.CBR' and use_rarfile:
|
||||
try:
|
||||
rarfile.UNRAR_TOOL = rarExecutable
|
||||
cf = rarfile.RarFile(tmp_file_name)
|
||||
for name in cf.getnames():
|
||||
ext = os.path.splitext(name)
|
||||
if len(ext) > 1:
|
||||
extension = ext[1].lower()
|
||||
if extension == '.jpg':
|
||||
cover_data = cf.extractfile(name).read()
|
||||
if extension in COVER_EXTENSIONS:
|
||||
cover_data = cf.read(name)
|
||||
break
|
||||
prefix = os.path.dirname(tmp_file_name)
|
||||
if cover_data:
|
||||
tmp_cover_name = prefix + '/cover' + extension
|
||||
image = open(tmp_cover_name, 'wb')
|
||||
image.write(cover_data)
|
||||
image.close()
|
||||
else:
|
||||
tmp_cover_name = None
|
||||
return tmp_cover_name
|
||||
except Exception as ex:
|
||||
log.debug('Rarfile failed with error: %s', ex)
|
||||
return cover_data, extension
|
||||
|
||||
|
||||
def get_comic_info(tmp_file_path, original_file_name, original_file_extension):
|
||||
def _extractCover(tmp_file_name, original_file_extension, rarExecutable):
|
||||
cover_data = extension = None
|
||||
if use_comic_meta:
|
||||
archive = ComicArchive(tmp_file_path)
|
||||
archive = ComicArchive(tmp_file_name, rar_exe_path=rarExecutable)
|
||||
for index, name in enumerate(archive.getPageNameList()):
|
||||
ext = os.path.splitext(name)
|
||||
if len(ext) > 1:
|
||||
extension = ext[1].lower()
|
||||
if extension in COVER_EXTENSIONS:
|
||||
cover_data = archive.getPage(index)
|
||||
break
|
||||
else:
|
||||
cover_data, extension = _extract_Cover_from_archive(original_file_extension, tmp_file_name, rarExecutable)
|
||||
return _cover_processing(tmp_file_name, cover_data, extension)
|
||||
|
||||
|
||||
def get_comic_info(tmp_file_path, original_file_name, original_file_extension, rarExecutable):
|
||||
if use_comic_meta:
|
||||
archive = ComicArchive(tmp_file_path, rar_exe_path=rarExecutable)
|
||||
if archive.seemsToBeAComicArchive():
|
||||
if archive.hasMetadata(MetaDataStyle.CIX):
|
||||
style = MetaDataStyle.CIX
|
||||
@@ -85,38 +136,35 @@ def get_comic_info(tmp_file_path, original_file_name, original_file_extension):
|
||||
else:
|
||||
style = None
|
||||
|
||||
if style is not None:
|
||||
loadedMetadata = archive.readMetadata(style)
|
||||
# if style is not None:
|
||||
loadedMetadata = archive.readMetadata(style)
|
||||
|
||||
lang = loadedMetadata.language
|
||||
if len(lang) == 2:
|
||||
loadedMetadata.language = isoLanguages.get(part1=lang).name
|
||||
elif len(lang) == 3:
|
||||
loadedMetadata.language = isoLanguages.get(part3=lang).name
|
||||
else:
|
||||
loadedMetadata.language = ""
|
||||
lang = loadedMetadata.language or ""
|
||||
loadedMetadata.language = isoLanguages.get_lang3(lang)
|
||||
|
||||
return uploader.BookMeta(
|
||||
return BookMeta(
|
||||
file_path=tmp_file_path,
|
||||
extension=original_file_extension,
|
||||
title=loadedMetadata.title or original_file_name,
|
||||
author=" & ".join([credit["person"] for credit in loadedMetadata.credits if credit["role"] == "Writer"]) or u"Unknown",
|
||||
cover=extractCover(tmp_file_path, original_file_extension),
|
||||
author=" & ".join([credit["person"]
|
||||
for credit in loadedMetadata.credits if credit["role"] == "Writer"]) or u'Unknown',
|
||||
cover=_extractCover(tmp_file_path, original_file_extension, rarExecutable),
|
||||
description=loadedMetadata.comments or "",
|
||||
tags="",
|
||||
series=loadedMetadata.series or "",
|
||||
series_id=loadedMetadata.issue or "",
|
||||
languages=loadedMetadata.language)
|
||||
else:
|
||||
languages=loadedMetadata.language,
|
||||
publisher="")
|
||||
|
||||
return uploader.BookMeta(
|
||||
file_path=tmp_file_path,
|
||||
extension=original_file_extension,
|
||||
title=original_file_name,
|
||||
author=u"Unknown",
|
||||
cover=extractCover(tmp_file_path, original_file_extension),
|
||||
description="",
|
||||
tags="",
|
||||
series="",
|
||||
series_id="",
|
||||
languages="")
|
||||
return BookMeta(
|
||||
file_path=tmp_file_path,
|
||||
extension=original_file_extension,
|
||||
title=original_file_name,
|
||||
author=u'Unknown',
|
||||
cover=_extractCover(tmp_file_path, original_file_extension, rarExecutable),
|
||||
description="",
|
||||
tags="",
|
||||
series="",
|
||||
series_id="",
|
||||
languages="",
|
||||
publisher="")
|
||||
|
||||
@@ -0,0 +1,457 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2019 OzzieIsaacs, pwr
|
||||
#
|
||||
# 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 os
|
||||
import sys
|
||||
import json
|
||||
|
||||
from sqlalchemy import Column, String, Integer, SmallInteger, Boolean, BLOB, JSON
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlalchemy.sql.expression import text
|
||||
try:
|
||||
# Compatibility with sqlalchemy 2.0
|
||||
from sqlalchemy.orm import declarative_base
|
||||
except ImportError:
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
from . import constants, cli, logger
|
||||
|
||||
|
||||
log = logger.create()
|
||||
_Base = declarative_base()
|
||||
|
||||
class _Flask_Settings(_Base):
|
||||
__tablename__ = 'flask_settings'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
flask_session_key = Column(BLOB, default=b"")
|
||||
|
||||
def __init__(self, key):
|
||||
self.flask_session_key = key
|
||||
|
||||
|
||||
# Baseclass for representing settings in app.db with email server settings and Calibre database settings
|
||||
# (application settings)
|
||||
class _Settings(_Base):
|
||||
__tablename__ = 'settings'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
mail_server = Column(String, default=constants.DEFAULT_MAIL_SERVER)
|
||||
mail_port = Column(Integer, default=25)
|
||||
mail_use_ssl = Column(SmallInteger, default=0)
|
||||
mail_login = Column(String, default='mail@example.com')
|
||||
mail_password = Column(String, default='mypassword')
|
||||
mail_from = Column(String, default='automailer <mail@example.com>')
|
||||
mail_size = Column(Integer, default=25*1024*1024)
|
||||
mail_server_type = Column(SmallInteger, default=0)
|
||||
mail_gmail_token = Column(JSON, default={})
|
||||
|
||||
config_calibre_dir = Column(String)
|
||||
config_port = Column(Integer, default=constants.DEFAULT_PORT)
|
||||
config_external_port = Column(Integer, default=constants.DEFAULT_PORT)
|
||||
config_certfile = Column(String)
|
||||
config_keyfile = Column(String)
|
||||
config_trustedhosts = Column(String,default='')
|
||||
config_calibre_web_title = Column(String, default=u'Calibre-Web')
|
||||
config_books_per_page = Column(Integer, default=60)
|
||||
config_random_books = Column(Integer, default=4)
|
||||
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|Einen|Dem|Des|Einem|Eines)\s+')
|
||||
config_mature_content_tags = Column(String, default='')
|
||||
config_theme = Column(Integer, default=0)
|
||||
|
||||
config_log_level = Column(SmallInteger, default=logger.DEFAULT_LOG_LEVEL)
|
||||
config_logfile = Column(String)
|
||||
config_access_log = Column(SmallInteger, default=0)
|
||||
config_access_logfile = Column(String)
|
||||
|
||||
config_uploading = Column(SmallInteger, default=0)
|
||||
config_anonbrowse = Column(SmallInteger, default=0)
|
||||
config_public_reg = Column(SmallInteger, default=0)
|
||||
config_remote_login = Column(Boolean, default=False)
|
||||
config_kobo_sync = Column(Boolean, default=False)
|
||||
|
||||
config_default_role = Column(SmallInteger, default=0)
|
||||
config_default_show = Column(SmallInteger, default=constants.ADMIN_USER_SIDEBAR)
|
||||
config_default_language = Column(String(3), default="all")
|
||||
config_default_locale = Column(String(2), default="en")
|
||||
config_columns_to_ignore = Column(String)
|
||||
|
||||
config_denied_tags = Column(String, default="")
|
||||
config_allowed_tags = Column(String, default="")
|
||||
config_restricted_column = Column(SmallInteger, default=0)
|
||||
config_denied_column_value = Column(String, default="")
|
||||
config_allowed_column_value = Column(String, default="")
|
||||
|
||||
config_use_google_drive = Column(Boolean, default=False)
|
||||
config_google_drive_folder = Column(String)
|
||||
config_google_drive_watch_changes_response = Column(JSON, default={})
|
||||
|
||||
config_use_goodreads = Column(Boolean, default=False)
|
||||
config_goodreads_api_key = Column(String)
|
||||
config_goodreads_api_secret = Column(String)
|
||||
config_register_email = Column(Boolean, default=False)
|
||||
config_login_type = Column(Integer, default=0)
|
||||
|
||||
config_kobo_proxy = Column(Boolean, default=False)
|
||||
|
||||
config_ldap_provider_url = Column(String, default='example.org')
|
||||
config_ldap_port = Column(SmallInteger, default=389)
|
||||
config_ldap_authentication = Column(SmallInteger, default=constants.LDAP_AUTH_SIMPLE)
|
||||
config_ldap_serv_username = Column(String, default='cn=admin,dc=example,dc=org')
|
||||
config_ldap_serv_password = Column(String, default="")
|
||||
config_ldap_encryption = Column(SmallInteger, default=0)
|
||||
config_ldap_cacert_path = Column(String, default="")
|
||||
config_ldap_cert_path = Column(String, default="")
|
||||
config_ldap_key_path = Column(String, default="")
|
||||
config_ldap_dn = Column(String, default='dc=example,dc=org')
|
||||
config_ldap_user_object = Column(String, default='uid=%s')
|
||||
config_ldap_member_user_object = Column(String, default='') #
|
||||
config_ldap_openldap = Column(Boolean, default=True)
|
||||
config_ldap_group_object_filter = Column(String, default='(&(objectclass=posixGroup)(cn=%s))')
|
||||
config_ldap_group_members_field = Column(String, default='memberUid')
|
||||
config_ldap_group_name = Column(String, default='calibreweb')
|
||||
|
||||
config_kepubifypath = Column(String, default=None)
|
||||
config_converterpath = Column(String, default=None)
|
||||
config_calibre = Column(String)
|
||||
config_rarfile_location = Column(String, default=None)
|
||||
config_upload_formats = Column(String, default=','.join(constants.EXTENSIONS_UPLOAD))
|
||||
config_unicode_filename =Column(Boolean, default=False)
|
||||
|
||||
config_updatechannel = Column(Integer, default=constants.UPDATE_STABLE)
|
||||
|
||||
config_reverse_proxy_login_header_name = Column(String)
|
||||
config_allow_reverse_proxy_header_login = Column(Boolean, default=False)
|
||||
|
||||
def __repr__(self):
|
||||
return self.__class__.__name__
|
||||
|
||||
|
||||
# Class holds all application specific settings in calibre-web
|
||||
class _ConfigSQL(object):
|
||||
# pylint: disable=no-member
|
||||
def __init__(self, session):
|
||||
self._session = session
|
||||
self._settings = None
|
||||
self.db_configured = None
|
||||
self.config_calibre_dir = None
|
||||
self.load()
|
||||
|
||||
change = False
|
||||
if self.config_converterpath == None: # pylint: disable=access-member-before-definition
|
||||
change = True
|
||||
self.config_converterpath = autodetect_calibre_binary()
|
||||
|
||||
if self.config_kepubifypath == None: # pylint: disable=access-member-before-definition
|
||||
|
||||
change = True
|
||||
self.config_kepubifypath = autodetect_kepubify_binary()
|
||||
|
||||
if self.config_rarfile_location == None: # pylint: disable=access-member-before-definition
|
||||
change = True
|
||||
self.config_rarfile_location = autodetect_unrar_binary()
|
||||
if change:
|
||||
self.save()
|
||||
|
||||
|
||||
def _read_from_storage(self):
|
||||
if self._settings is None:
|
||||
log.debug("_ConfigSQL._read_from_storage")
|
||||
self._settings = self._session.query(_Settings).first()
|
||||
return self._settings
|
||||
|
||||
def get_config_certfile(self):
|
||||
if cli.certfilepath:
|
||||
return cli.certfilepath
|
||||
if cli.certfilepath == "":
|
||||
return None
|
||||
return self.config_certfile
|
||||
|
||||
def get_config_keyfile(self):
|
||||
if cli.keyfilepath:
|
||||
return cli.keyfilepath
|
||||
if cli.certfilepath == "":
|
||||
return None
|
||||
return self.config_keyfile
|
||||
|
||||
@staticmethod
|
||||
def get_config_ipaddress():
|
||||
return cli.ip_address or ""
|
||||
|
||||
def _has_role(self, role_flag):
|
||||
return constants.has_flag(self.config_default_role, role_flag)
|
||||
|
||||
def role_admin(self):
|
||||
return self._has_role(constants.ROLE_ADMIN)
|
||||
|
||||
def role_download(self):
|
||||
return self._has_role(constants.ROLE_DOWNLOAD)
|
||||
|
||||
def role_viewer(self):
|
||||
return self._has_role(constants.ROLE_VIEWER)
|
||||
|
||||
def role_upload(self):
|
||||
return self._has_role(constants.ROLE_UPLOAD)
|
||||
|
||||
def role_edit(self):
|
||||
return self._has_role(constants.ROLE_EDIT)
|
||||
|
||||
def role_passwd(self):
|
||||
return self._has_role(constants.ROLE_PASSWD)
|
||||
|
||||
def role_edit_shelfs(self):
|
||||
return self._has_role(constants.ROLE_EDIT_SHELFS)
|
||||
|
||||
def role_delete_books(self):
|
||||
return self._has_role(constants.ROLE_DELETE_BOOKS)
|
||||
|
||||
def show_element_new_user(self, value):
|
||||
return constants.has_flag(self.config_default_show, value)
|
||||
|
||||
def show_detail_random(self):
|
||||
return self.show_element_new_user(constants.DETAIL_RANDOM)
|
||||
|
||||
def list_denied_tags(self):
|
||||
mct = self.config_denied_tags or ""
|
||||
return [t.strip() for t in mct.split(",")]
|
||||
|
||||
def list_allowed_tags(self):
|
||||
mct = self.config_allowed_tags or ""
|
||||
return [t.strip() 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(",")]
|
||||
|
||||
def list_allowed_column_values(self):
|
||||
mct = self.config_allowed_column_value or ""
|
||||
return [t.strip() for t in mct.split(",")]
|
||||
|
||||
def get_log_level(self):
|
||||
return logger.get_level_name(self.config_log_level)
|
||||
|
||||
def get_mail_settings(self):
|
||||
return {k:v for k, v in self.__dict__.items() if k.startswith('mail_')}
|
||||
|
||||
def get_mail_server_configured(self):
|
||||
return bool((self.mail_server != constants.DEFAULT_MAIL_SERVER and self.mail_server_type == 0)
|
||||
or (self.mail_gmail_token != {} and self.mail_server_type == 1))
|
||||
|
||||
|
||||
def set_from_dictionary(self, dictionary, field, convertor=None, default=None, encode=None):
|
||||
"""Possibly updates a field of this object.
|
||||
The new value, if present, is grabbed from the given dictionary, and optionally passed through a convertor.
|
||||
|
||||
:returns: `True` if the field has changed value
|
||||
"""
|
||||
new_value = dictionary.get(field, default)
|
||||
if new_value is None:
|
||||
return False
|
||||
|
||||
if field not in self.__dict__:
|
||||
log.warning("_ConfigSQL trying to set unknown field '%s' = %r", field, new_value)
|
||||
return False
|
||||
|
||||
if convertor is not None:
|
||||
if encode:
|
||||
new_value = convertor(new_value.encode(encode))
|
||||
else:
|
||||
new_value = convertor(new_value)
|
||||
|
||||
current_value = self.__dict__.get(field)
|
||||
if current_value == new_value:
|
||||
return False
|
||||
|
||||
setattr(self, field, new_value)
|
||||
return True
|
||||
|
||||
def toDict(self):
|
||||
storage = {}
|
||||
for k, v in self.__dict__.items():
|
||||
if k[0] != '_' and not k.endswith("password") and not k.endswith("secret"):
|
||||
storage[k] = v
|
||||
return storage
|
||||
|
||||
|
||||
def load(self):
|
||||
'''Load all configuration values from the underlying storage.'''
|
||||
s = self._read_from_storage() # type: _Settings
|
||||
for k, v in s.__dict__.items():
|
||||
if k[0] != '_':
|
||||
if v is None:
|
||||
# if the storage column has no value, apply the (possible) default
|
||||
column = s.__class__.__dict__.get(k)
|
||||
if column.default is not None:
|
||||
v = column.default.arg
|
||||
setattr(self, k, v)
|
||||
|
||||
have_metadata_db = bool(self.config_calibre_dir)
|
||||
if have_metadata_db:
|
||||
if not self.config_use_google_drive:
|
||||
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(',')]
|
||||
if os.environ.get('FLASK_DEBUG'):
|
||||
logfile = logger.setup(logger.LOG_TO_STDOUT, logger.logging.DEBUG)
|
||||
else:
|
||||
# pylint: disable=access-member-before-definition
|
||||
logfile = logger.setup(self.config_logfile, self.config_log_level)
|
||||
if logfile != self.config_logfile:
|
||||
log.warning("Log path %s not valid, falling back to default", self.config_logfile)
|
||||
self.config_logfile = logfile
|
||||
self._session.merge(s)
|
||||
try:
|
||||
self._session.commit()
|
||||
except OperationalError as e:
|
||||
log.error('Database error: %s', e)
|
||||
self._session.rollback()
|
||||
|
||||
def save(self):
|
||||
'''Apply all configuration values to the underlying storage.'''
|
||||
s = self._read_from_storage() # type: _Settings
|
||||
|
||||
for k, v in self.__dict__.items():
|
||||
if k[0] == '_':
|
||||
continue
|
||||
if hasattr(s, k):
|
||||
setattr(s, k, v)
|
||||
|
||||
log.debug("_ConfigSQL updating storage")
|
||||
self._session.merge(s)
|
||||
try:
|
||||
self._session.commit()
|
||||
except OperationalError as e:
|
||||
log.error('Database error: %s', e)
|
||||
self._session.rollback()
|
||||
self.load()
|
||||
|
||||
def invalidate(self, error=None):
|
||||
if error:
|
||||
log.error(error)
|
||||
log.warning("invalidating configuration")
|
||||
self.db_configured = False
|
||||
# self.config_calibre_dir = None
|
||||
self.save()
|
||||
|
||||
|
||||
def _migrate_table(session, orm_class):
|
||||
changed = False
|
||||
|
||||
for column_name, column in orm_class.__dict__.items():
|
||||
if column_name[0] != '_':
|
||||
try:
|
||||
session.query(column).first()
|
||||
except OperationalError as err:
|
||||
log.debug("%s: %s", column_name, err.args[0])
|
||||
if column.default is None:
|
||||
column_default = ""
|
||||
else:
|
||||
if isinstance(column.default.arg, bool):
|
||||
column_default = "DEFAULT {}".format(int(column.default.arg))
|
||||
else:
|
||||
column_default = "DEFAULT `{}`".format(column.default.arg)
|
||||
if isinstance(column.type, JSON):
|
||||
column_type = "JSON"
|
||||
else:
|
||||
column_type = column.type
|
||||
alter_table = text("ALTER TABLE %s ADD COLUMN `%s` %s %s" % (orm_class.__tablename__,
|
||||
column_name,
|
||||
column_type,
|
||||
column_default))
|
||||
log.debug(alter_table)
|
||||
session.execute(alter_table)
|
||||
changed = True
|
||||
except json.decoder.JSONDecodeError as e:
|
||||
log.error("Database corrupt column: {}".format(column_name))
|
||||
log.debug(e)
|
||||
|
||||
if changed:
|
||||
try:
|
||||
session.commit()
|
||||
except OperationalError:
|
||||
session.rollback()
|
||||
|
||||
|
||||
def autodetect_calibre_binary():
|
||||
if sys.platform == "win32":
|
||||
calibre_path = ["C:\\program files\\calibre\\ebook-convert.exe",
|
||||
"C:\\program files(x86)\\calibre\\ebook-convert.exe",
|
||||
"C:\\program files(x86)\\calibre2\\ebook-convert.exe",
|
||||
"C:\\program files\\calibre2\\ebook-convert.exe"]
|
||||
else:
|
||||
calibre_path = ["/opt/calibre/ebook-convert"]
|
||||
for element in calibre_path:
|
||||
if os.path.isfile(element) and os.access(element, os.X_OK):
|
||||
return element
|
||||
return ""
|
||||
|
||||
def autodetect_unrar_binary():
|
||||
if sys.platform == "win32":
|
||||
calibre_path = ["C:\\program files\\WinRar\\unRAR.exe",
|
||||
"C:\\program files(x86)\\WinRar\\unRAR.exe"]
|
||||
else:
|
||||
calibre_path = ["/usr/bin/unrar"]
|
||||
for element in calibre_path:
|
||||
if os.path.isfile(element) and os.access(element, os.X_OK):
|
||||
return element
|
||||
return ""
|
||||
|
||||
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"]
|
||||
else:
|
||||
calibre_path = ["/opt/kepubify/kepubify-linux-64bit", "/opt/kepubify/kepubify-linux-32bit"]
|
||||
for element in calibre_path:
|
||||
if os.path.isfile(element) and os.access(element, os.X_OK):
|
||||
return element
|
||||
return ""
|
||||
|
||||
def _migrate_database(session):
|
||||
# make sure the table is created, if it does not exist
|
||||
_Base.metadata.create_all(session.bind)
|
||||
_migrate_table(session, _Settings)
|
||||
_migrate_table(session, _Flask_Settings)
|
||||
|
||||
|
||||
def load_configuration(session):
|
||||
_migrate_database(session)
|
||||
|
||||
if not session.query(_Settings).count():
|
||||
session.add(_Settings())
|
||||
session.commit()
|
||||
conf = _ConfigSQL(session)
|
||||
# Migrate from global restrictions to user based restrictions
|
||||
#if bool(conf.config_default_show & constants.MATURE_CONTENT) and conf.config_denied_tags == "":
|
||||
# conf.config_denied_tags = conf.config_mature_content_tags
|
||||
# conf.save()
|
||||
# session.query(ub.User).filter(ub.User.mature_content != True). \
|
||||
# update({"denied_tags": conf.config_mature_content_tags}, synchronize_session=False)
|
||||
# session.commit()
|
||||
return conf
|
||||
|
||||
def get_flask_session_key(session):
|
||||
flask_settings = session.query(_Flask_Settings).one_or_none()
|
||||
if flask_settings == None:
|
||||
flask_settings = _Flask_Settings(os.urandom(32))
|
||||
session.add(flask_settings)
|
||||
session.commit()
|
||||
return flask_settings.flask_session_key
|
||||
@@ -0,0 +1,164 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2019 OzzieIsaacs, pwr
|
||||
#
|
||||
# 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 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])
|
||||
|
||||
# if installed via pip this variable is set to true (empty file with name .HOMEDIR present)
|
||||
HOME_CONFIG = os.path.isfile(os.path.join(os.path.dirname(os.path.abspath(__file__)), '.HOMEDIR'))
|
||||
|
||||
#In executables updater is not available, so variable is set to False there
|
||||
UPDATER_AVAILABLE = True
|
||||
|
||||
# Base dir is parent of current file, necessary if called from different folder
|
||||
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),os.pardir))
|
||||
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')
|
||||
|
||||
if HOME_CONFIG:
|
||||
home_dir = os.path.join(os.path.expanduser("~"),".calibre-web")
|
||||
if not os.path.exists(home_dir):
|
||||
os.makedirs(home_dir)
|
||||
CONFIG_DIR = os.environ.get('CALIBRE_DBPATH', home_dir)
|
||||
else:
|
||||
CONFIG_DIR = os.environ.get('CALIBRE_DBPATH', BASE_DIR)
|
||||
|
||||
|
||||
ROLE_USER = 0 << 0
|
||||
ROLE_ADMIN = 1 << 0
|
||||
ROLE_DOWNLOAD = 1 << 1
|
||||
ROLE_UPLOAD = 1 << 2
|
||||
ROLE_EDIT = 1 << 3
|
||||
ROLE_PASSWD = 1 << 4
|
||||
ROLE_ANONYMOUS = 1 << 5
|
||||
ROLE_EDIT_SHELFS = 1 << 6
|
||||
ROLE_DELETE_BOOKS = 1 << 7
|
||||
ROLE_VIEWER = 1 << 8
|
||||
|
||||
ALL_ROLES = {
|
||||
"admin_role": ROLE_ADMIN,
|
||||
"download_role": ROLE_DOWNLOAD,
|
||||
"upload_role": ROLE_UPLOAD,
|
||||
"edit_role": ROLE_EDIT,
|
||||
"passwd_role": ROLE_PASSWD,
|
||||
"edit_shelf_role": ROLE_EDIT_SHELFS,
|
||||
"delete_role": ROLE_DELETE_BOOKS,
|
||||
"viewer_role": ROLE_VIEWER,
|
||||
}
|
||||
|
||||
DETAIL_RANDOM = 1 << 0
|
||||
SIDEBAR_LANGUAGE = 1 << 1
|
||||
SIDEBAR_SERIES = 1 << 2
|
||||
SIDEBAR_CATEGORY = 1 << 3
|
||||
SIDEBAR_HOT = 1 << 4
|
||||
SIDEBAR_RANDOM = 1 << 5
|
||||
SIDEBAR_AUTHOR = 1 << 6
|
||||
SIDEBAR_BEST_RATED = 1 << 7
|
||||
SIDEBAR_READ_AND_UNREAD = 1 << 8
|
||||
SIDEBAR_RECENT = 1 << 9
|
||||
SIDEBAR_SORTED = 1 << 10
|
||||
MATURE_CONTENT = 1 << 11
|
||||
SIDEBAR_PUBLISHER = 1 << 12
|
||||
SIDEBAR_RATING = 1 << 13
|
||||
SIDEBAR_FORMAT = 1 << 14
|
||||
SIDEBAR_ARCHIVED = 1 << 15
|
||||
SIDEBAR_DOWNLOAD = 1 << 16
|
||||
SIDEBAR_LIST = 1 << 17
|
||||
|
||||
sidebar_settings = {
|
||||
"detail_random": DETAIL_RANDOM,
|
||||
"sidebar_language": SIDEBAR_LANGUAGE,
|
||||
"sidebar_series": SIDEBAR_SERIES,
|
||||
"sidebar_category": SIDEBAR_CATEGORY,
|
||||
"sidebar_random": SIDEBAR_RANDOM,
|
||||
"sidebar_author": SIDEBAR_AUTHOR,
|
||||
"sidebar_best_rated": SIDEBAR_BEST_RATED,
|
||||
"sidebar_read_and_unread": SIDEBAR_READ_AND_UNREAD,
|
||||
"sidebar_recent": SIDEBAR_RECENT,
|
||||
"sidebar_sorted": SIDEBAR_SORTED,
|
||||
"sidebar_publisher": SIDEBAR_PUBLISHER,
|
||||
"sidebar_rating": SIDEBAR_RATING,
|
||||
"sidebar_format": SIDEBAR_FORMAT,
|
||||
"sidebar_archived": SIDEBAR_ARCHIVED,
|
||||
"sidebar_download": SIDEBAR_DOWNLOAD,
|
||||
"sidebar_list": SIDEBAR_LIST,
|
||||
}
|
||||
|
||||
|
||||
ADMIN_USER_ROLES = sum(r for r in ALL_ROLES.values()) & ~ROLE_ANONYMOUS
|
||||
ADMIN_USER_SIDEBAR = (SIDEBAR_LIST << 1) - 1
|
||||
|
||||
UPDATE_STABLE = 0 << 0
|
||||
AUTO_UPDATE_STABLE = 1 << 0
|
||||
UPDATE_NIGHTLY = 1 << 1
|
||||
AUTO_UPDATE_NIGHTLY = 1 << 2
|
||||
|
||||
LOGIN_STANDARD = 0
|
||||
LOGIN_LDAP = 1
|
||||
LOGIN_OAUTH = 2
|
||||
|
||||
LDAP_AUTH_ANONYMOUS = 0
|
||||
LDAP_AUTH_UNAUTHENTICATE = 1
|
||||
LDAP_AUTH_SIMPLE = 0
|
||||
|
||||
DEFAULT_MAIL_SERVER = "mail.example.org"
|
||||
|
||||
DEFAULT_PASSWORD = "admin123" # nosec
|
||||
DEFAULT_PORT = 8083
|
||||
env_CALIBRE_PORT = os.environ.get("CALIBRE_PORT", DEFAULT_PORT)
|
||||
try:
|
||||
DEFAULT_PORT = int(env_CALIBRE_PORT)
|
||||
except ValueError:
|
||||
print('Environment variable CALIBRE_PORT has invalid value (%s), faling back to default (8083)' % env_CALIBRE_PORT)
|
||||
del env_CALIBRE_PORT
|
||||
|
||||
|
||||
EXTENSIONS_AUDIO = {'mp3', 'mp4', 'ogg', 'opus', 'wav', 'flac', 'm4a', 'm4b'}
|
||||
EXTENSIONS_CONVERT_FROM = ['pdf', 'epub', 'mobi', 'azw3', 'docx', 'rtf', 'fb2', 'lit', 'lrf', 'txt', 'htmlz', 'rtf', 'odt','cbz','cbr']
|
||||
EXTENSIONS_CONVERT_TO = ['pdf', 'epub', 'mobi', 'azw3', 'docx', 'rtf', 'fb2', 'lit', 'lrf', 'txt', 'htmlz', 'rtf', 'odt']
|
||||
EXTENSIONS_UPLOAD = {'txt', 'pdf', 'epub', 'kepub', 'mobi', 'azw', 'azw3', 'cbr', 'cbz', 'cbt', 'djvu', 'prc', 'doc', 'docx',
|
||||
'fb2', 'html', 'rtf', 'lit', 'odt', 'mp3', 'mp4', 'ogg', 'opus', 'wav', 'flac', 'm4a', 'm4b'}
|
||||
|
||||
|
||||
def has_flag(value, bit_flag):
|
||||
return bit_flag == (bit_flag & (value or 0))
|
||||
|
||||
def selected_roles(dictionary):
|
||||
return sum(v for k, v in ALL_ROLES.items() if k in dictionary)
|
||||
|
||||
|
||||
# :rtype: BookMeta
|
||||
BookMeta = namedtuple('BookMeta', 'file_path, extension, title, author, cover, description, tags, series, '
|
||||
'series_id, languages, publisher')
|
||||
|
||||
STABLE_VERSION = {'version': '0.6.16'}
|
||||
|
||||
NIGHTLY_VERSION = {}
|
||||
NIGHTLY_VERSION[0] = '$Format:%H$'
|
||||
NIGHTLY_VERSION[1] = '$Format:%cI$'
|
||||
# NIGHTLY_VERSION[0] = 'bb7d2c6273ae4560e83950d36d64533343623a57'
|
||||
# NIGHTLY_VERSION[1] = '2018-09-09T10:13:08+02:00'
|
||||
|
||||
|
||||
# clean-up the module namespace
|
||||
del sys, os, namedtuple
|
||||
+32
-38
@@ -1,4 +1,3 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
@@ -17,51 +16,46 @@
|
||||
# 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 os
|
||||
import subprocess
|
||||
import ub
|
||||
import re
|
||||
from flask_babel import gettext as _
|
||||
|
||||
from . import config, logger
|
||||
from .subproc_wrapper import process_wait
|
||||
|
||||
def versionKindle():
|
||||
versions = _(u'not installed')
|
||||
if os.path.exists(ub.config.config_converterpath):
|
||||
|
||||
log = logger.create()
|
||||
|
||||
# _() necessary to make babel aware of string for translation
|
||||
_NOT_CONFIGURED = _('not configured')
|
||||
_NOT_INSTALLED = _('not installed')
|
||||
_EXECUTION_ERROR = _('Execution permissions missing')
|
||||
|
||||
|
||||
def _get_command_version(path, pattern, argument=None):
|
||||
if os.path.exists(path):
|
||||
command = [path]
|
||||
if argument:
|
||||
command.append(argument)
|
||||
try:
|
||||
p = subprocess.Popen(ub.config.config_converterpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
p.wait()
|
||||
for lines in p.stdout.readlines():
|
||||
if isinstance(lines, bytes):
|
||||
lines = lines.decode('utf-8')
|
||||
if re.search('Amazon kindlegen\(', lines):
|
||||
versions = lines
|
||||
except Exception:
|
||||
versions = _(u'Excecution permissions missing')
|
||||
return {'kindlegen' : versions}
|
||||
match = process_wait(command, pattern=pattern)
|
||||
if isinstance(match, re.Match):
|
||||
return match.string
|
||||
except Exception as ex:
|
||||
log.warning("%s: %s", path, ex)
|
||||
return _EXECUTION_ERROR
|
||||
return _NOT_INSTALLED
|
||||
|
||||
|
||||
def versionCalibre():
|
||||
versions = _(u'not installed')
|
||||
if os.path.exists(ub.config.config_converterpath):
|
||||
try:
|
||||
p = subprocess.Popen([ub.config.config_converterpath, '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
p.wait()
|
||||
for lines in p.stdout.readlines():
|
||||
if isinstance(lines, bytes):
|
||||
lines = lines.decode('utf-8')
|
||||
if re.search('ebook-convert.*\(calibre', lines):
|
||||
versions = lines
|
||||
except Exception:
|
||||
versions = _(u'Excecution permissions missing')
|
||||
return {'Calibre converter' : versions}
|
||||
def get_calibre_version():
|
||||
return _get_command_version(config.config_converterpath, r'ebook-convert.*\(calibre', '--version') \
|
||||
or _NOT_CONFIGURED
|
||||
|
||||
|
||||
def versioncheck():
|
||||
if ub.config.config_ebookconverter == 1:
|
||||
return versionKindle()
|
||||
elif ub.config.config_ebookconverter == 2:
|
||||
return versionCalibre()
|
||||
else:
|
||||
return {'ebook_converter':_(u'not configured')}
|
||||
def get_unrar_version():
|
||||
return _get_command_version(config.config_rarfile_location, r'UNRAR.*\d') or _NOT_CONFIGURED
|
||||
|
||||
def get_kepubify_version():
|
||||
return _get_command_version(config.config_kepubifypath, r'kepubify\s','--version') or _NOT_CONFIGURED
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,72 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2012-2019 cervinko, idalin, SiphonSquirrel, ouzklcn, akushsky,
|
||||
# OzzieIsaacs, bodybybuddha, jkrehm, matthazinski, janeczku
|
||||
#
|
||||
# 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 shutil
|
||||
import glob
|
||||
import zipfile
|
||||
import json
|
||||
from io import BytesIO
|
||||
|
||||
import os
|
||||
|
||||
from flask import send_file, __version__
|
||||
|
||||
from . import logger, config
|
||||
from .about import collect_stats
|
||||
|
||||
log = logger.create()
|
||||
|
||||
def assemble_logfiles(file_name):
|
||||
log_list = sorted(glob.glob(file_name + '*'), reverse=True)
|
||||
wfd = BytesIO()
|
||||
for f in log_list:
|
||||
with open(f, 'rb') as fd:
|
||||
shutil.copyfileobj(fd, wfd)
|
||||
wfd.seek(0)
|
||||
if int(__version__.split('.')[0]) < 2:
|
||||
return send_file(wfd,
|
||||
as_attachment=True,
|
||||
attachment_filename=os.path.basename(file_name))
|
||||
else:
|
||||
return send_file(wfd,
|
||||
as_attachment=True,
|
||||
download_name=os.path.basename(file_name))
|
||||
|
||||
|
||||
def send_debug():
|
||||
file_list = glob.glob(logger.get_logfile(config.config_logfile) + '*')
|
||||
file_list.extend(glob.glob(logger.get_accesslogfile(config.config_access_logfile) + '*'))
|
||||
for element in [logger.LOG_TO_STDOUT, logger.LOG_TO_STDERR]:
|
||||
if element in file_list:
|
||||
file_list.remove(element)
|
||||
memory_zip = BytesIO()
|
||||
with zipfile.ZipFile(memory_zip, 'w', compression=zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.writestr('settings.txt', json.dumps(config.toDict()))
|
||||
zf.writestr('libs.txt', json.dumps(collect_stats()))
|
||||
for fp in file_list:
|
||||
zf.write(fp, os.path.basename(fp))
|
||||
memory_zip.seek(0)
|
||||
if int(__version__.split('.')[0]) < 2:
|
||||
return send_file(memory_zip,
|
||||
as_attachment=True,
|
||||
attachment_filename="Calibre-Web-debug-pack.zip")
|
||||
else:
|
||||
return send_file(memory_zip,
|
||||
as_attachment=True,
|
||||
download_name="Calibre-Web-debug-pack.zip")
|
||||
@@ -0,0 +1,96 @@
|
||||
import os
|
||||
import re
|
||||
|
||||
from .constants import BASE_DIR
|
||||
try:
|
||||
from importlib_metadata import version
|
||||
importlib = True
|
||||
ImportNotFound = BaseException
|
||||
except ImportError:
|
||||
importlib = False
|
||||
|
||||
|
||||
if not importlib:
|
||||
try:
|
||||
import pkg_resources
|
||||
from pkg_resources import DistributionNotFound as ImportNotFound
|
||||
pkgresources = True
|
||||
except ImportError as e:
|
||||
pkgresources = False
|
||||
|
||||
def load_dependencys(optional=False):
|
||||
deps = list()
|
||||
if importlib or pkgresources:
|
||||
if optional:
|
||||
req_path = os.path.join(BASE_DIR, "optional-requirements.txt")
|
||||
else:
|
||||
req_path = os.path.join(BASE_DIR, "requirements.txt")
|
||||
if os.path.exists(req_path):
|
||||
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())
|
||||
try:
|
||||
if importlib:
|
||||
dep_version = version(res.group(1))
|
||||
else:
|
||||
dep_version = pkg_resources.get_distribution(res.group(1)).version
|
||||
except ImportNotFound:
|
||||
if optional:
|
||||
continue
|
||||
dep_version = "not installed"
|
||||
deps.append([dep_version, res.group(1), res.group(2), res.group(3), res.group(4), res.group(5)])
|
||||
return deps
|
||||
|
||||
|
||||
def dependency_check(optional=False):
|
||||
d = list()
|
||||
deps = load_dependencys(optional)
|
||||
for dep in deps:
|
||||
try:
|
||||
dep_version_int = [int(x) for x in dep[0].split('.')]
|
||||
low_check = [int(x) for x in dep[3].split('.')]
|
||||
high_check = [int(x) for x in dep[5].split('.')]
|
||||
except AttributeError:
|
||||
high_check = None
|
||||
except ValueError:
|
||||
d.append({'name': dep[1],
|
||||
'target': "available",
|
||||
'found': "Not available"
|
||||
})
|
||||
continue
|
||||
|
||||
if dep[2].strip() == "==":
|
||||
if dep_version_int != low_check:
|
||||
d.append({'name': dep[1],
|
||||
'found': dep[0],
|
||||
"target": dep[2] + dep[3]})
|
||||
continue
|
||||
elif dep[2].strip() == ">=":
|
||||
if dep_version_int < low_check:
|
||||
d.append({'name': dep[1],
|
||||
'found': dep[0],
|
||||
"target": dep[2] + dep[3]})
|
||||
continue
|
||||
elif dep[2].strip() == ">":
|
||||
if dep_version_int <= low_check:
|
||||
d.append({'name': dep[1],
|
||||
'found': dep[0],
|
||||
"target": dep[2] + dep[3]})
|
||||
continue
|
||||
if dep[4] and dep[5]:
|
||||
if dep[4].strip() == "<":
|
||||
if dep_version_int >= high_check:
|
||||
d.append(
|
||||
{'name': dep[1],
|
||||
'found': dep[0],
|
||||
"target": dep[4] + dep[5]})
|
||||
continue
|
||||
elif dep[4].strip() == "<=":
|
||||
if dep_version_int > high_check:
|
||||
d.append(
|
||||
{'name': dep[1],
|
||||
'found': dep[0],
|
||||
"target": dep[4] + dep[5]})
|
||||
continue
|
||||
return d
|
||||
Executable
+1305
File diff suppressed because it is too large
Load Diff
+71
-56
@@ -1,4 +1,3 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
@@ -17,11 +16,14 @@
|
||||
# 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 os
|
||||
import zipfile
|
||||
from lxml import etree
|
||||
import os
|
||||
import uploader
|
||||
import isoLanguages
|
||||
|
||||
from . import isoLanguages
|
||||
from .helper import split_authors
|
||||
from .constants import BookMeta
|
||||
|
||||
|
||||
|
||||
def extractCover(zipFile, coverFile, coverpath, tmp_file_name):
|
||||
@@ -62,31 +64,81 @@ def get_epub_info(tmp_file_path, original_file_name, original_file_extension):
|
||||
for s in ['title', 'description', 'creator', 'language', 'subject']:
|
||||
tmp = p.xpath('dc:%s/text()' % s, namespaces=ns)
|
||||
if len(tmp) > 0:
|
||||
epub_metadata[s] = p.xpath('dc:%s/text()' % s, namespaces=ns)[0]
|
||||
if s == 'creator':
|
||||
epub_metadata[s] = ' & '.join(split_authors(tmp))
|
||||
elif s == 'subject':
|
||||
epub_metadata[s] = ', '.join(tmp)
|
||||
else:
|
||||
epub_metadata[s] = tmp[0]
|
||||
else:
|
||||
epub_metadata[s] = "Unknown"
|
||||
epub_metadata[s] = u'Unknown'
|
||||
|
||||
if epub_metadata['subject'] == "Unknown":
|
||||
if epub_metadata['subject'] == u'Unknown':
|
||||
epub_metadata['subject'] = ''
|
||||
|
||||
if epub_metadata['description'] == "Unknown":
|
||||
if epub_metadata['description'] == u'Unknown':
|
||||
description = tree.xpath("//*[local-name() = 'description']/text()")
|
||||
if len(description) > 0:
|
||||
epub_metadata['description'] = description
|
||||
else:
|
||||
epub_metadata['description'] = ""
|
||||
|
||||
if epub_metadata['language'] == "Unknown":
|
||||
epub_metadata['language'] = ""
|
||||
else:
|
||||
lang = epub_metadata['language'].split('-', 1)[0].lower()
|
||||
if len(lang) == 2:
|
||||
epub_metadata['language'] = isoLanguages.get(part1=lang).name
|
||||
elif len(lang) == 3:
|
||||
epub_metadata['language'] = isoLanguages.get(part3=lang).name
|
||||
else:
|
||||
epub_metadata['language'] = ""
|
||||
lang = epub_metadata['language'].split('-', 1)[0].lower()
|
||||
epub_metadata['language'] = isoLanguages.get_lang3(lang)
|
||||
|
||||
epub_metadata = parse_epbub_series(ns, tree, epub_metadata)
|
||||
|
||||
coverfile = parse_ebpub_cover(ns, tree, epubZip, coverpath, tmp_file_path)
|
||||
|
||||
if not epub_metadata['title']:
|
||||
title = original_file_name
|
||||
else:
|
||||
title = epub_metadata['title']
|
||||
|
||||
return BookMeta(
|
||||
file_path=tmp_file_path,
|
||||
extension=original_file_extension,
|
||||
title=title.encode('utf-8').decode('utf-8'),
|
||||
author=epub_metadata['creator'].encode('utf-8').decode('utf-8'),
|
||||
cover=coverfile,
|
||||
description=epub_metadata['description'],
|
||||
tags=epub_metadata['subject'].encode('utf-8').decode('utf-8'),
|
||||
series=epub_metadata['series'].encode('utf-8').decode('utf-8'),
|
||||
series_id=epub_metadata['series_id'].encode('utf-8').decode('utf-8'),
|
||||
languages=epub_metadata['language'],
|
||||
publisher="")
|
||||
|
||||
def parse_ebpub_cover(ns, tree, epubZip, coverpath, tmp_file_path):
|
||||
coversection = tree.xpath("/pkg:package/pkg:manifest/pkg:item[@id='cover-image']/@href", namespaces=ns)
|
||||
coverfile = None
|
||||
if len(coversection) > 0:
|
||||
coverfile = extractCover(epubZip, coversection[0], coverpath, tmp_file_path)
|
||||
else:
|
||||
meta_cover = tree.xpath("/pkg:package/pkg:metadata/pkg:meta[@name='cover']/@content", namespaces=ns)
|
||||
if len(meta_cover) > 0:
|
||||
coversection = tree.xpath("/pkg:package/pkg:manifest/pkg:item[@id='"+meta_cover[0]+"']/@href", namespaces=ns)
|
||||
else:
|
||||
coversection = tree.xpath("/pkg:package/pkg:guide/pkg:reference/@href", namespaces=ns)
|
||||
if len(coversection) > 0:
|
||||
filetype = coversection[0].rsplit('.', 1)[-1]
|
||||
if filetype == "xhtml" or filetype == "html": # if cover is (x)html format
|
||||
markup = epubZip.read(os.path.join(coverpath, coversection[0]))
|
||||
markupTree = etree.fromstring(markup)
|
||||
# no matter xhtml or html with no namespace
|
||||
imgsrc = markupTree.xpath("//*[local-name() = 'img']/@src")
|
||||
# Alternative image source
|
||||
if not len(imgsrc):
|
||||
imgsrc = markupTree.xpath("//attribute::*[contains(local-name(), 'href')]")
|
||||
if len(imgsrc):
|
||||
# imgsrc maybe startwith "../"" so fullpath join then relpath to cwd
|
||||
filename = os.path.relpath(os.path.join(os.path.dirname(os.path.join(coverpath, coversection[0])),
|
||||
imgsrc[0]))
|
||||
coverfile = extractCover(epubZip, filename, "", tmp_file_path)
|
||||
else:
|
||||
coverfile = extractCover(epubZip, coversection[0], coverpath, tmp_file_path)
|
||||
return coverfile
|
||||
|
||||
def parse_epbub_series(ns, tree, epub_metadata):
|
||||
series = tree.xpath("/pkg:package/pkg:metadata/pkg:meta[@name='calibre:series']/@content", namespaces=ns)
|
||||
if len(series) > 0:
|
||||
epub_metadata['series'] = series[0]
|
||||
@@ -98,41 +150,4 @@ def get_epub_info(tmp_file_path, original_file_name, original_file_extension):
|
||||
epub_metadata['series_id'] = series_id[0]
|
||||
else:
|
||||
epub_metadata['series_id'] = '1'
|
||||
|
||||
coversection = tree.xpath("/pkg:package/pkg:manifest/pkg:item[@id='cover-image']/@href", namespaces=ns)
|
||||
coverfile = None
|
||||
if len(coversection) > 0:
|
||||
coverfile = extractCover(epubZip, coversection[0], coverpath, tmp_file_path)
|
||||
else:
|
||||
meta_cover = tree.xpath("/pkg:package/pkg:metadata/pkg:meta[@name='cover']/@content", namespaces=ns)
|
||||
if len(meta_cover) > 0:
|
||||
coversection = tree.xpath("/pkg:package/pkg:manifest/pkg:item[@id='"+meta_cover[0]+"']/@href", namespaces=ns)
|
||||
if len(coversection) > 0:
|
||||
filetype = coversection[0].rsplit('.', 1)[-1]
|
||||
if filetype == "xhtml" or filetype == "html": # if cover is (x)html format
|
||||
markup = epubZip.read(os.path.join(coverpath, coversection[0]))
|
||||
markupTree = etree.fromstring(markup)
|
||||
# no matter xhtml or html with no namespace
|
||||
imgsrc = markupTree.xpath("//*[local-name() = 'img']/@src")
|
||||
# imgsrc maybe startwith "../"" so fullpath join then relpath to cwd
|
||||
filename = os.path.relpath(os.path.join(os.path.dirname(os.path.join(coverpath, coversection[0])), imgsrc[0]))
|
||||
coverfile = extractCover(epubZip, filename, "", tmp_file_path)
|
||||
else:
|
||||
coverfile = extractCover(epubZip, coversection[0], coverpath, tmp_file_path)
|
||||
|
||||
if not epub_metadata['title']:
|
||||
title = original_file_name
|
||||
else:
|
||||
title = epub_metadata['title']
|
||||
|
||||
return uploader.BookMeta(
|
||||
file_path=tmp_file_path,
|
||||
extension=original_file_extension,
|
||||
title=title.encode('utf-8').decode('utf-8'),
|
||||
author=epub_metadata['creator'].encode('utf-8').decode('utf-8'),
|
||||
cover=coverfile,
|
||||
description=epub_metadata['description'],
|
||||
tags=epub_metadata['subject'].encode('utf-8').decode('utf-8'),
|
||||
series=epub_metadata['series'].encode('utf-8').decode('utf-8'),
|
||||
series_id=epub_metadata['series_id'].encode('utf-8').decode('utf-8'),
|
||||
languages=epub_metadata['language'])
|
||||
return epub_metadata
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2018-2020 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 traceback
|
||||
from flask import render_template
|
||||
from werkzeug.exceptions import default_exceptions
|
||||
try:
|
||||
from werkzeug.exceptions import FailedDependency
|
||||
except ImportError:
|
||||
from werkzeug.exceptions import UnprocessableEntity as FailedDependency
|
||||
|
||||
from . import config, app, logger, services
|
||||
|
||||
|
||||
log = logger.create()
|
||||
|
||||
# custom error page
|
||||
def error_http(error):
|
||||
return render_template('http_error.html',
|
||||
error_code="Error {0}".format(error.code),
|
||||
error_name=error.name,
|
||||
issue=False,
|
||||
unconfigured=not config.db_configured,
|
||||
instance=config.config_calibre_web_title
|
||||
), error.code
|
||||
|
||||
|
||||
def internal_error(error):
|
||||
return render_template('http_error.html',
|
||||
error_code="Internal Server Error",
|
||||
error_name=str(error),
|
||||
issue=True,
|
||||
unconfigured=False,
|
||||
error_stack=traceback.format_exc().split("\n"),
|
||||
instance=config.config_calibre_web_title
|
||||
), 500
|
||||
|
||||
def init_errorhandler():
|
||||
# http error handling
|
||||
for ex in default_exceptions:
|
||||
if ex < 500:
|
||||
app.register_error_handler(ex, error_http)
|
||||
elif ex == 500:
|
||||
app.register_error_handler(ex, internal_error)
|
||||
|
||||
|
||||
if services.ldap:
|
||||
# Only way of catching the LDAPException upon logging in with LDAP server down
|
||||
@app.errorhandler(services.ldap.LDAPException)
|
||||
# pylint: disable=unused-variable
|
||||
def handle_exception(e):
|
||||
log.debug('LDAP server not accessible while trying to login to opds feed')
|
||||
return error_http(FailedDependency())
|
||||
|
||||
+18
-17
@@ -1,4 +1,3 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
@@ -18,7 +17,8 @@
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from lxml import etree
|
||||
import uploader
|
||||
|
||||
from .constants import BookMeta
|
||||
|
||||
|
||||
def get_fb2_info(tmp_file_path, original_file_extension):
|
||||
@@ -28,52 +28,53 @@ def get_fb2_info(tmp_file_path, original_file_extension):
|
||||
'l': 'http://www.w3.org/1999/xlink',
|
||||
}
|
||||
|
||||
fb2_file = open(tmp_file_path)
|
||||
tree = etree.fromstring(fb2_file.read())
|
||||
fb2_file = open(tmp_file_path, encoding="utf-8")
|
||||
tree = etree.fromstring(fb2_file.read().encode())
|
||||
|
||||
authors = tree.xpath('/fb:FictionBook/fb:description/fb:title-info/fb:author', namespaces=ns)
|
||||
|
||||
def get_author(element):
|
||||
last_name = element.xpath('fb:last-name/text()', namespaces=ns)
|
||||
if len(last_name):
|
||||
last_name = last_name[0].encode('utf-8')
|
||||
last_name = last_name[0]
|
||||
else:
|
||||
last_name = u''
|
||||
middle_name = element.xpath('fb:middle-name/text()', namespaces=ns)
|
||||
if len(middle_name):
|
||||
middle_name = middle_name[0].encode('utf-8')
|
||||
middle_name = middle_name[0]
|
||||
else:
|
||||
middle_name = u''
|
||||
first_name = element.xpath('fb:first-name/text()', namespaces=ns)
|
||||
if len(first_name):
|
||||
first_name = first_name[0].encode('utf-8')
|
||||
first_name = first_name[0]
|
||||
else:
|
||||
first_name = u''
|
||||
return (first_name.decode('utf-8') + u' '
|
||||
+ middle_name.decode('utf-8') + u' '
|
||||
+ last_name.decode('utf-8')).encode('utf-8')
|
||||
return (first_name + u' '
|
||||
+ middle_name + u' '
|
||||
+ last_name)
|
||||
|
||||
author = str(", ".join(map(get_author, authors)))
|
||||
|
||||
title = tree.xpath('/fb:FictionBook/fb:description/fb:title-info/fb:book-title/text()', namespaces=ns)
|
||||
if len(title):
|
||||
title = str(title[0].encode('utf-8'))
|
||||
title = str(title[0])
|
||||
else:
|
||||
title = u''
|
||||
description = tree.xpath('/fb:FictionBook/fb:description/fb:publish-info/fb:book-name/text()', namespaces=ns)
|
||||
if len(description):
|
||||
description = str(description[0].encode('utf-8'))
|
||||
description = str(description[0])
|
||||
else:
|
||||
description = u''
|
||||
|
||||
return uploader.BookMeta(
|
||||
return BookMeta(
|
||||
file_path=tmp_file_path,
|
||||
extension=original_file_extension,
|
||||
title=title.decode('utf-8'),
|
||||
author=author.decode('utf-8'),
|
||||
title=title,
|
||||
author=author,
|
||||
cover=None,
|
||||
description=description.decode('utf-8'),
|
||||
description=description,
|
||||
tags="",
|
||||
series="",
|
||||
series_id="",
|
||||
languages="")
|
||||
languages="",
|
||||
publisher="")
|
||||
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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
|
||||
#
|
||||
# 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 os
|
||||
import hashlib
|
||||
import json
|
||||
import tempfile
|
||||
from uuid import uuid4
|
||||
from time import time
|
||||
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
|
||||
|
||||
gdrive = Blueprint('gdrive', __name__, url_prefix='/gdrive')
|
||||
log = logger.create()
|
||||
|
||||
try:
|
||||
from googleapiclient.errors import HttpError
|
||||
except ImportError as err:
|
||||
log.debug("Cannot import googleapiclient, using GDrive will not work: %s", err)
|
||||
|
||||
current_milli_time = lambda: int(round(time() * 1000))
|
||||
|
||||
gdrive_watch_callback_token = 'target=calibreweb-watch_files' #nosec
|
||||
|
||||
|
||||
@gdrive.route("/authenticate")
|
||||
@login_required
|
||||
@admin_required
|
||||
def authenticate_google_drive():
|
||||
try:
|
||||
authUrl = gdriveutils.Gauth.Instance().auth.GetAuthUrl()
|
||||
except gdriveutils.InvalidConfigError:
|
||||
flash(_(u'Google Drive setup not completed, try to deactivate and activate Google Drive again'),
|
||||
category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
return redirect(authUrl)
|
||||
|
||||
|
||||
@gdrive.route("/callback")
|
||||
def google_drive_callback():
|
||||
auth_code = request.args.get('code')
|
||||
if not auth_code:
|
||||
abort(403)
|
||||
try:
|
||||
credentials = gdriveutils.Gauth.Instance().auth.flow.step2_exchange(auth_code)
|
||||
with open(gdriveutils.CREDENTIALS, 'w') as f:
|
||||
f.write(credentials.to_json())
|
||||
except (ValueError, AttributeError) as error:
|
||||
log.error(error)
|
||||
return redirect(url_for('admin.db_configuration'))
|
||||
|
||||
|
||||
@gdrive.route("/watch/subscribe")
|
||||
@login_required
|
||||
@admin_required
|
||||
def watch_gdrive():
|
||||
if not config.config_google_drive_watch_changes_response:
|
||||
with open(gdriveutils.CLIENT_SECRETS, 'r') as settings:
|
||||
filedata = json.load(settings)
|
||||
address = filedata['web']['redirect_uris'][0].rstrip('/').replace('/gdrive/callback', '/gdrive/watch/callback')
|
||||
notification_id = str(uuid4())
|
||||
try:
|
||||
result = gdriveutils.watchChange(gdriveutils.Gdrive.Instance().drive, notification_id,
|
||||
'web_hook', address, gdrive_watch_callback_token, current_milli_time() + 604800*1000)
|
||||
config.config_google_drive_watch_changes_response = result
|
||||
config.save()
|
||||
except HttpError as e:
|
||||
reason=json.loads(e.content)['error']['errors'][0]
|
||||
if reason['reason'] == u'push.webhookUrlUnauthorized':
|
||||
flash(_(u'Callback domain is not verified, '
|
||||
u'please follow steps to verify domain in google developer console'), category="error")
|
||||
else:
|
||||
flash(reason['message'], category="error")
|
||||
|
||||
return redirect(url_for('admin.db_configuration'))
|
||||
|
||||
|
||||
@gdrive.route("/watch/revoke")
|
||||
@login_required
|
||||
@admin_required
|
||||
def revoke_watch_gdrive():
|
||||
last_watch_response = config.config_google_drive_watch_changes_response
|
||||
if last_watch_response:
|
||||
try:
|
||||
gdriveutils.stopChannel(gdriveutils.Gdrive.Instance().drive, last_watch_response['id'],
|
||||
last_watch_response['resourceId'])
|
||||
except (HttpError, AttributeError):
|
||||
pass
|
||||
config.config_google_drive_watch_changes_response = {}
|
||||
config.save()
|
||||
return redirect(url_for('admin.db_configuration'))
|
||||
|
||||
try:
|
||||
@csrf.exempt
|
||||
@gdrive.route("/watch/callback", methods=['GET', 'POST'])
|
||||
def on_received_watch_confirmation():
|
||||
if not config.config_google_drive_watch_changes_response:
|
||||
return ''
|
||||
if request.headers.get('X-Goog-Channel-Token') != gdrive_watch_callback_token \
|
||||
or request.headers.get('X-Goog-Resource-State') != 'change' \
|
||||
or not request.data:
|
||||
return ''
|
||||
|
||||
log.debug('%r', request.headers)
|
||||
log.debug('%r', request.data)
|
||||
log.info('Change received from gdrive')
|
||||
|
||||
try:
|
||||
j = json.loads(request.data)
|
||||
log.info('Getting change details')
|
||||
response = gdriveutils.getChangeById(gdriveutils.Gdrive.Instance().drive, j['id'])
|
||||
log.debug('%r', response)
|
||||
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
|
||||
tmp_dir = os.path.join(tempfile.gettempdir(), 'calibre_web')
|
||||
if not os.path.isdir(tmp_dir):
|
||||
os.mkdir(tmp_dir)
|
||||
|
||||
log.info('Database file updated')
|
||||
copyfile(dbpath, os.path.join(tmp_dir, "metadata.db_" + str(current_milli_time())))
|
||||
log.info('Backing up existing and downloading updated metadata.db')
|
||||
gdriveutils.downloadFile(None, "metadata.db", os.path.join(tmp_dir, "tmp_metadata.db"))
|
||||
log.info('Setting up new DB')
|
||||
# prevent error on windows, as os.rename does on existing files, also allow cross hdd move
|
||||
move(os.path.join(tmp_dir, "tmp_metadata.db"), dbpath)
|
||||
calibre_db.reconnect_db(config, ub.app_DB_path)
|
||||
except Exception as ex:
|
||||
log.debug_or_exception(ex)
|
||||
return ''
|
||||
except AttributeError:
|
||||
pass
|
||||
+235
-74
@@ -1,4 +1,3 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
@@ -17,24 +16,73 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
try:
|
||||
from pydrive.auth import GoogleAuth
|
||||
from pydrive.drive import GoogleDrive
|
||||
from pydrive.auth import RefreshError, InvalidConfigError
|
||||
from apiclient import errors
|
||||
gdrive_support = True
|
||||
except ImportError:
|
||||
gdrive_support = False
|
||||
|
||||
import os
|
||||
from ub import config
|
||||
import cli
|
||||
import json
|
||||
import shutil
|
||||
import chardet
|
||||
import ssl
|
||||
|
||||
from flask import Response, stream_with_context
|
||||
from sqlalchemy import *
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import *
|
||||
import web
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy import Column, UniqueConstraint
|
||||
from sqlalchemy import String, Integer
|
||||
from sqlalchemy.orm import sessionmaker, scoped_session
|
||||
try:
|
||||
# Compatibility with sqlalchemy 2.0
|
||||
from sqlalchemy.orm import declarative_base
|
||||
except ImportError:
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.exc import OperationalError, InvalidRequestError
|
||||
from sqlalchemy.sql.expression import text
|
||||
|
||||
try:
|
||||
from six import __version__ as six_version
|
||||
except ImportError:
|
||||
six_version = "not installed"
|
||||
try:
|
||||
from httplib2 import __version__ as httplib2_version
|
||||
except ImportError:
|
||||
httplib2_version = "not installed"
|
||||
|
||||
try:
|
||||
from apiclient import errors
|
||||
from httplib2 import ServerNotFoundError
|
||||
importError = None
|
||||
gdrive_support = True
|
||||
except ImportError as e:
|
||||
importError = e
|
||||
gdrive_support = False
|
||||
try:
|
||||
from pydrive2.auth import GoogleAuth
|
||||
from pydrive2.drive import GoogleDrive
|
||||
from pydrive2.auth import RefreshError
|
||||
from pydrive2.files import ApiRequestError
|
||||
except ImportError as err:
|
||||
try:
|
||||
from pydrive.auth import GoogleAuth
|
||||
from pydrive.drive import GoogleDrive
|
||||
from pydrive.auth import RefreshError
|
||||
from pydrive.files import ApiRequestError
|
||||
except ImportError as err:
|
||||
importError = err
|
||||
gdrive_support = False
|
||||
|
||||
from . import logger, cli, config
|
||||
from .constants import CONFIG_DIR as _CONFIG_DIR
|
||||
|
||||
|
||||
SETTINGS_YAML = os.path.join(_CONFIG_DIR, 'settings.yaml')
|
||||
CREDENTIALS = os.path.join(_CONFIG_DIR, 'gdrive_credentials')
|
||||
CLIENT_SECRETS = os.path.join(_CONFIG_DIR, 'client_secrets.json')
|
||||
|
||||
log = logger.create()
|
||||
if gdrive_support:
|
||||
logger.get('googleapiclient.discovery_cache').setLevel(logger.logging.ERROR)
|
||||
if not logger.is_debug_enabled():
|
||||
logger.get('googleapiclient.discovery').setLevel(logger.logging.ERROR)
|
||||
else:
|
||||
log.debug("Cannot import pydrive,httplib2, using gdrive will not work: %s", importError)
|
||||
|
||||
|
||||
class Singleton:
|
||||
"""
|
||||
@@ -67,6 +115,9 @@ class Singleton:
|
||||
except AttributeError:
|
||||
self._instance = self._decorated()
|
||||
return self._instance
|
||||
except (ImportError, NameError) as e:
|
||||
log.debug(e)
|
||||
return None
|
||||
|
||||
def __call__(self):
|
||||
raise TypeError('Singletons must be accessed through `Instance()`.')
|
||||
@@ -78,7 +129,11 @@ class Singleton:
|
||||
@Singleton
|
||||
class Gauth:
|
||||
def __init__(self):
|
||||
self.auth = GoogleAuth(settings_file=os.path.join(config.get_main_dir,'settings.yaml'))
|
||||
try:
|
||||
self.auth = GoogleAuth(settings_file=SETTINGS_YAML)
|
||||
except NameError as error:
|
||||
log.error(error)
|
||||
self.auth = None
|
||||
|
||||
|
||||
@Singleton
|
||||
@@ -86,6 +141,9 @@ class Gdrive:
|
||||
def __init__(self):
|
||||
self.drive = getDrive(gauth=Gauth.Instance().auth)
|
||||
|
||||
def is_gdrive_ready():
|
||||
return os.path.exists(SETTINGS_YAML) and os.path.exists(CREDENTIALS)
|
||||
|
||||
|
||||
engine = create_engine('sqlite:///{0}'.format(cli.gdpath), echo=False)
|
||||
Base = declarative_base()
|
||||
@@ -121,7 +179,7 @@ class PermissionAdded(Base):
|
||||
def migrate():
|
||||
if not engine.dialect.has_table(engine.connect(), "permissions_added"):
|
||||
PermissionAdded.__table__.create(bind = engine)
|
||||
for sql in session.execute("select sql from sqlite_master where type='table'"):
|
||||
for sql in session.execute(text("select sql from sqlite_master where type='table'")):
|
||||
if 'CREATE TABLE gdrive_ids' in sql[0]:
|
||||
currUniqueConstraint = 'UNIQUE (gdrive_id)'
|
||||
if currUniqueConstraint in sql[0]:
|
||||
@@ -146,17 +204,17 @@ migrate()
|
||||
def getDrive(drive=None, gauth=None):
|
||||
if not drive:
|
||||
if not gauth:
|
||||
gauth = GoogleAuth(settings_file=os.path.join(config.get_main_dir,'settings.yaml'))
|
||||
gauth = GoogleAuth(settings_file=SETTINGS_YAML)
|
||||
# Try to load saved client credentials
|
||||
gauth.LoadCredentialsFile(os.path.join(config.get_main_dir,'gdrive_credentials'))
|
||||
gauth.LoadCredentialsFile(CREDENTIALS)
|
||||
if gauth.access_token_expired:
|
||||
# Refresh them if expired
|
||||
try:
|
||||
gauth.Refresh()
|
||||
except RefreshError as e:
|
||||
web.app.logger.error("Google Drive error: " + e.message)
|
||||
except Exception as e:
|
||||
web.app.logger.exception(e)
|
||||
log.error("Google Drive error: %s", e)
|
||||
except Exception as ex:
|
||||
log.debug_or_exception(ex)
|
||||
else:
|
||||
# Initialize the saved creds
|
||||
gauth.Authorize()
|
||||
@@ -166,18 +224,22 @@ def getDrive(drive=None, gauth=None):
|
||||
try:
|
||||
drive.auth.Refresh()
|
||||
except RefreshError as e:
|
||||
web.app.logger.error("Google Drive error: " + e.message)
|
||||
log.error("Google Drive error: %s", e)
|
||||
return drive
|
||||
|
||||
def listRootFolders():
|
||||
drive = getDrive(Gdrive.Instance().drive)
|
||||
folder = "'root' in parents and mimeType = 'application/vnd.google-apps.folder' and trashed = false"
|
||||
fileList = drive.ListFile({'q': folder}).GetList()
|
||||
try:
|
||||
drive = getDrive(Gdrive.Instance().drive)
|
||||
folder = "'root' in parents and mimeType = 'application/vnd.google-apps.folder' and trashed = false"
|
||||
fileList = drive.ListFile({'q': folder}).GetList()
|
||||
except (ServerNotFoundError, ssl.SSLError, RefreshError) as e:
|
||||
log.info("GDrive Error %s" % e)
|
||||
fileList = []
|
||||
return fileList
|
||||
|
||||
|
||||
def getEbooksFolder(drive):
|
||||
return getFolderInFolder('root',config.config_google_drive_folder,drive)
|
||||
return getFolderInFolder('root', config.config_google_drive_folder, drive)
|
||||
|
||||
|
||||
def getFolderInFolder(parentId, folderName, drive):
|
||||
@@ -203,11 +265,16 @@ def getEbooksFolderId(drive=None):
|
||||
try:
|
||||
gDriveId.gdrive_id = getEbooksFolder(drive)['id']
|
||||
except Exception:
|
||||
web.app.logger.error('Error gDrive, root ID not found')
|
||||
log.error('Error gDrive, root ID not found')
|
||||
gDriveId.path = '/'
|
||||
session.merge(gDriveId)
|
||||
session.commit()
|
||||
return
|
||||
try:
|
||||
session.commit()
|
||||
except OperationalError as ex:
|
||||
log.error("gdrive.db DB is not Writeable")
|
||||
log.debug('Database error: %s', ex)
|
||||
session.rollback()
|
||||
return gDriveId.gdrive_id
|
||||
|
||||
|
||||
def getFile(pathId, fileName, drive):
|
||||
@@ -221,37 +288,47 @@ def getFile(pathId, fileName, drive):
|
||||
|
||||
def getFolderId(path, drive):
|
||||
# drive = getDrive(drive)
|
||||
currentFolderId = getEbooksFolderId(drive)
|
||||
sqlCheckPath = path if path[-1] == '/' else path + '/'
|
||||
storedPathName = session.query(GdriveId).filter(GdriveId.path == sqlCheckPath).first()
|
||||
try:
|
||||
currentFolderId = getEbooksFolderId(drive)
|
||||
sqlCheckPath = path if path[-1] == '/' else path + '/'
|
||||
storedPathName = session.query(GdriveId).filter(GdriveId.path == sqlCheckPath).first()
|
||||
|
||||
if not storedPathName:
|
||||
dbChange = False
|
||||
s = path.split('/')
|
||||
for i, x in enumerate(s):
|
||||
if len(x) > 0:
|
||||
currentPath = "/".join(s[:i+1])
|
||||
if currentPath[-1] != '/':
|
||||
currentPath = currentPath + '/'
|
||||
storedPathName = session.query(GdriveId).filter(GdriveId.path == currentPath).first()
|
||||
if storedPathName:
|
||||
currentFolderId = storedPathName.gdrive_id
|
||||
else:
|
||||
currentFolder = getFolderInFolder(currentFolderId, x, drive)
|
||||
if currentFolder:
|
||||
gDriveId = GdriveId()
|
||||
gDriveId.gdrive_id = currentFolder['id']
|
||||
gDriveId.path = currentPath
|
||||
session.merge(gDriveId)
|
||||
dbChange = True
|
||||
currentFolderId = currentFolder['id']
|
||||
if not storedPathName:
|
||||
dbChange = False
|
||||
s = path.split('/')
|
||||
for i, x in enumerate(s):
|
||||
if len(x) > 0:
|
||||
currentPath = "/".join(s[:i+1])
|
||||
if currentPath[-1] != '/':
|
||||
currentPath = currentPath + '/'
|
||||
storedPathName = session.query(GdriveId).filter(GdriveId.path == currentPath).first()
|
||||
if storedPathName:
|
||||
currentFolderId = storedPathName.gdrive_id
|
||||
else:
|
||||
currentFolderId = None
|
||||
break
|
||||
if dbChange:
|
||||
session.commit()
|
||||
else:
|
||||
currentFolderId = storedPathName.gdrive_id
|
||||
currentFolder = getFolderInFolder(currentFolderId, x, drive)
|
||||
if currentFolder:
|
||||
gDriveId = GdriveId()
|
||||
gDriveId.gdrive_id = currentFolder['id']
|
||||
gDriveId.path = currentPath
|
||||
session.merge(gDriveId)
|
||||
dbChange = True
|
||||
currentFolderId = currentFolder['id']
|
||||
else:
|
||||
currentFolderId = None
|
||||
break
|
||||
if dbChange:
|
||||
session.commit()
|
||||
else:
|
||||
currentFolderId = storedPathName.gdrive_id
|
||||
except OperationalError as ex:
|
||||
log.error("gdrive.db DB is not Writeable")
|
||||
log.debug('Database error: %s', ex)
|
||||
session.rollback()
|
||||
except ApiRequestError as ex:
|
||||
log.error('{} {}'.format(ex.error['message'], path))
|
||||
session.rollback()
|
||||
except RefreshError as ex:
|
||||
log.error(ex)
|
||||
return currentFolderId
|
||||
|
||||
|
||||
@@ -295,7 +372,7 @@ def moveGdriveFolderRemote(origin_file, target_folder):
|
||||
addParents=gFileTargetDir['id'],
|
||||
removeParents=previous_parents,
|
||||
fields='id, parents').execute()
|
||||
# if previous_parents has no childs anymore, delete original fileparent
|
||||
# if previous_parents has no children anymore, delete original fileparent
|
||||
if len(children['items']) == 1:
|
||||
deleteDatabaseEntry(previous_parents)
|
||||
drive.auth.service.files().delete(fileId=previous_parents).execute()
|
||||
@@ -347,7 +424,8 @@ def uploadFileToEbooksFolder(destFile, f):
|
||||
if len(existingFiles) > 0:
|
||||
driveFile = existingFiles[0]
|
||||
else:
|
||||
driveFile = drive.CreateFile({'title': x, 'parents': [{"kind": "drive#fileLink", 'id': parent['id']}],})
|
||||
driveFile = drive.CreateFile({'title': x,
|
||||
'parents': [{"kind": "drive#fileLink", 'id': parent['id']}], })
|
||||
driveFile.SetContentFile(f)
|
||||
driveFile.Upload()
|
||||
else:
|
||||
@@ -443,17 +521,23 @@ def getChangeById (drive, change_id):
|
||||
change = drive.auth.service.changes().get(changeId=change_id).execute()
|
||||
return change
|
||||
except (errors.HttpError) as error:
|
||||
web.app.logger.info(error.message)
|
||||
log.error(error)
|
||||
return None
|
||||
except Exception as e:
|
||||
web.app.logger.info(e)
|
||||
except Exception as ex:
|
||||
log.error(ex)
|
||||
return None
|
||||
|
||||
|
||||
# Deletes the local hashes database to force search for new folder names
|
||||
def deleteDatabaseOnChange():
|
||||
session.query(GdriveId).delete()
|
||||
session.commit()
|
||||
try:
|
||||
session.query(GdriveId).delete()
|
||||
session.commit()
|
||||
except (OperationalError, InvalidRequestError) as ex:
|
||||
session.rollback()
|
||||
log.debug('Database error: %s', ex)
|
||||
log.error(u"GDrive DB is not Writeable")
|
||||
|
||||
|
||||
def updateGdriveCalibreFromLocal():
|
||||
copyToDrive(Gdrive.Instance().drive, config.config_calibre_dir, False, True)
|
||||
@@ -467,13 +551,23 @@ def updateDatabaseOnEdit(ID,newPath):
|
||||
storedPathName = session.query(GdriveId).filter(GdriveId.gdrive_id == ID).first()
|
||||
if storedPathName:
|
||||
storedPathName.path = sqlCheckPath
|
||||
session.commit()
|
||||
try:
|
||||
session.commit()
|
||||
except OperationalError as ex:
|
||||
log.error("gdrive.db DB is not Writeable")
|
||||
log.debug('Database error: %s', ex)
|
||||
session.rollback()
|
||||
|
||||
|
||||
# Deletes the hashes in database of deleted book
|
||||
def deleteDatabaseEntry(ID):
|
||||
session.query(GdriveId).filter(GdriveId.gdrive_id == ID).delete()
|
||||
session.commit()
|
||||
try:
|
||||
session.commit()
|
||||
except OperationalError as ex:
|
||||
log.error("gdrive.db DB is not Writeable")
|
||||
log.debug('Database error: %s', ex)
|
||||
session.rollback()
|
||||
|
||||
|
||||
# Gets cover file from gdrive
|
||||
@@ -490,7 +584,12 @@ def get_cover_via_gdrive(cover_path):
|
||||
permissionAdded = PermissionAdded()
|
||||
permissionAdded.gdrive_id = df['id']
|
||||
session.add(permissionAdded)
|
||||
session.commit()
|
||||
try:
|
||||
session.commit()
|
||||
except OperationalError as ex:
|
||||
log.error("gdrive.db DB is not Writeable")
|
||||
log.debug('Database error: %s', ex)
|
||||
session.rollback()
|
||||
return df.metadata.get('webContentLink')
|
||||
else:
|
||||
return None
|
||||
@@ -504,18 +603,80 @@ def partial(total_byte_len, part_size_limit):
|
||||
return s
|
||||
|
||||
# downloads files in chunks from gdrive
|
||||
def do_gdrive_download(df, headers):
|
||||
def do_gdrive_download(df, headers, convert_encoding=False):
|
||||
total_size = int(df.metadata.get('fileSize'))
|
||||
download_url = df.metadata.get('downloadUrl')
|
||||
s = partial(total_size, 1024 * 1024) # I'm downloading BIG files, so 100M chunk size is fine for me
|
||||
|
||||
def stream():
|
||||
def stream(convert_encoding):
|
||||
for byte in s:
|
||||
headers = {"Range": 'bytes=%s-%s' % (byte[0], byte[1])}
|
||||
resp, content = df.auth.Get_Http_Object().request(download_url, headers=headers)
|
||||
if resp.status == 206:
|
||||
if convert_encoding:
|
||||
result = chardet.detect(content)
|
||||
content = content.decode(result['encoding']).encode('utf-8')
|
||||
yield content
|
||||
else:
|
||||
web.app.logger.info('An error occurred: %s' % resp)
|
||||
log.warning('An error occurred: %s', resp)
|
||||
return
|
||||
return Response(stream_with_context(stream()), headers=headers)
|
||||
return Response(stream_with_context(stream(convert_encoding)), headers=headers)
|
||||
|
||||
|
||||
_SETTINGS_YAML_TEMPLATE = """
|
||||
client_config_backend: settings
|
||||
client_config_file: %(client_file)s
|
||||
client_config:
|
||||
client_id: %(client_id)s
|
||||
client_secret: %(client_secret)s
|
||||
redirect_uri: %(redirect_uri)s
|
||||
|
||||
save_credentials: True
|
||||
save_credentials_backend: file
|
||||
save_credentials_file: %(credential)s
|
||||
|
||||
get_refresh_token: True
|
||||
|
||||
oauth_scope:
|
||||
- https://www.googleapis.com/auth/drive
|
||||
"""
|
||||
|
||||
def update_settings(client_id, client_secret, redirect_uri):
|
||||
if redirect_uri.endswith('/'):
|
||||
redirect_uri = redirect_uri[:-1]
|
||||
config_params = {
|
||||
'client_file': CLIENT_SECRETS,
|
||||
'client_id': client_id,
|
||||
'client_secret': client_secret,
|
||||
'redirect_uri': redirect_uri,
|
||||
'credential': CREDENTIALS
|
||||
}
|
||||
|
||||
with open(SETTINGS_YAML, 'w') as f:
|
||||
f.write(_SETTINGS_YAML_TEMPLATE % config_params)
|
||||
|
||||
|
||||
def get_error_text(client_secrets=None):
|
||||
if not gdrive_support:
|
||||
return 'Import of optional Google Drive requirements missing'
|
||||
|
||||
if not os.path.isfile(CLIENT_SECRETS):
|
||||
return 'client_secrets.json is missing or not readable'
|
||||
|
||||
try:
|
||||
with open(CLIENT_SECRETS, 'r') as settings:
|
||||
filedata = json.load(settings)
|
||||
except PermissionError:
|
||||
return 'client_secrets.json is missing or not readable'
|
||||
|
||||
if 'web' not in filedata:
|
||||
return 'client_secrets.json is not configured for web application'
|
||||
if 'redirect_uris' not in filedata['web']:
|
||||
return 'Callback url (redirect url) is missing in client_secrets.json'
|
||||
if client_secrets:
|
||||
client_secrets.update(filedata['web'])
|
||||
|
||||
|
||||
def get_versions():
|
||||
return {'six': six_version,
|
||||
'httplib2': httplib2_version}
|
||||
|
||||
+552
-344
File diff suppressed because it is too large
Load Diff
+63
-6
@@ -1,4 +1,3 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
@@ -17,6 +16,12 @@
|
||||
# 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 .iso_language_names import LANGUAGE_NAMES as _LANGUAGE_NAMES
|
||||
from . import logger
|
||||
|
||||
log = logger.create()
|
||||
|
||||
|
||||
try:
|
||||
from iso639 import languages, __version__
|
||||
get = languages.get
|
||||
@@ -30,14 +35,66 @@ except ImportError:
|
||||
__version__ = "? (PyCountry)"
|
||||
|
||||
def _copy_fields(l):
|
||||
l.part1 = l.alpha_2
|
||||
l.part3 = l.alpha_3
|
||||
l.part1 = getattr(l, 'alpha_2', None)
|
||||
l.part3 = getattr(l, 'alpha_3', None)
|
||||
return l
|
||||
|
||||
def get(name=None, part1=None, part3=None):
|
||||
if (part3 is not None):
|
||||
if part3 is not None:
|
||||
return _copy_fields(pyc_languages.get(alpha_3=part3))
|
||||
if (part1 is not None):
|
||||
if part1 is not None:
|
||||
return _copy_fields(pyc_languages.get(alpha_2=part1))
|
||||
if (name is not None):
|
||||
if name is not None:
|
||||
return _copy_fields(pyc_languages.get(name=name))
|
||||
|
||||
|
||||
def get_language_names(locale):
|
||||
return _LANGUAGE_NAMES.get(locale)
|
||||
|
||||
|
||||
def get_language_name(locale, lang_code):
|
||||
try:
|
||||
return get_language_names(locale)[lang_code]
|
||||
except KeyError:
|
||||
log.error('Missing translation for language name: {}'.format(lang_code))
|
||||
return "Unknown"
|
||||
|
||||
|
||||
def get_language_codes(locale, language_names, remainder=None):
|
||||
language_names = set(x.strip().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)
|
||||
if remainder is not None and language_names:
|
||||
remainder.extend(language_names)
|
||||
return lang
|
||||
|
||||
|
||||
|
||||
def get_valid_language_codes(locale, language_names, remainder=None):
|
||||
lang = list()
|
||||
if "" in language_names:
|
||||
language_names.remove("")
|
||||
for k, __ in get_language_names(locale).items():
|
||||
if k in language_names:
|
||||
lang.append(k)
|
||||
language_names.remove(k)
|
||||
if remainder is not None and len(language_names):
|
||||
remainder.extend(language_names)
|
||||
return lang
|
||||
|
||||
|
||||
def get_lang3(lang):
|
||||
try:
|
||||
if len(lang) == 2:
|
||||
ret_value = get(part1=lang).part3
|
||||
elif len(lang) == 3:
|
||||
ret_value = lang
|
||||
else:
|
||||
ret_value = ""
|
||||
except KeyError:
|
||||
ret_value = lang
|
||||
return ret_value
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+139
@@ -0,0 +1,139 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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
|
||||
#
|
||||
# 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/>.
|
||||
|
||||
# custom jinja filters
|
||||
|
||||
import datetime
|
||||
import mimetypes
|
||||
from uuid import uuid4
|
||||
|
||||
from babel.dates import format_date
|
||||
from flask import Blueprint, request, url_for
|
||||
from flask_babel import get_locale
|
||||
from flask_login import current_user
|
||||
from markupsafe import escape
|
||||
from . import logger
|
||||
|
||||
|
||||
jinjia = Blueprint('jinjia', __name__)
|
||||
log = logger.create()
|
||||
|
||||
|
||||
# pagination links in jinja
|
||||
@jinjia.app_template_filter('url_for_other_page')
|
||||
def url_for_other_page(page):
|
||||
args = request.view_args.copy()
|
||||
args['page'] = page
|
||||
for get, val in request.args.items():
|
||||
args[get] = val
|
||||
return url_for(request.endpoint, **args)
|
||||
|
||||
|
||||
# shortentitles to at longest nchar, shorten longer words if necessary
|
||||
@jinjia.app_template_filter('shortentitle')
|
||||
def shortentitle_filter(s, nchar=20):
|
||||
text = s.split()
|
||||
res = "" # result
|
||||
suml = 0 # overall length
|
||||
for line in text:
|
||||
if suml >= 60:
|
||||
res += '...'
|
||||
break
|
||||
# if word longer than 20 chars truncate line and append '...', otherwise add whole word to result
|
||||
# string, and summarize total length to stop at chars given by nchar
|
||||
if len(line) > nchar:
|
||||
res += line[:(nchar-3)] + '[..] '
|
||||
suml += nchar+3
|
||||
else:
|
||||
res += line + ' '
|
||||
suml += len(line) + 1
|
||||
return res.strip()
|
||||
|
||||
|
||||
@jinjia.app_template_filter('mimetype')
|
||||
def mimetype_filter(val):
|
||||
return mimetypes.types_map.get('.' + val, 'application/octet-stream')
|
||||
|
||||
|
||||
@jinjia.app_template_filter('formatdate')
|
||||
def formatdate_filter(val):
|
||||
try:
|
||||
return format_date(val, format='medium', locale=get_locale())
|
||||
except AttributeError as e:
|
||||
log.error('Babel error: %s, Current user locale: %s, Current User: %s', e,
|
||||
current_user.locale,
|
||||
current_user.name
|
||||
)
|
||||
return val
|
||||
|
||||
|
||||
@jinjia.app_template_filter('formatdateinput')
|
||||
def format_date_input(val):
|
||||
input_date = val.isoformat().split('T', 1)[0] # Hack to support dates <1900
|
||||
return '' if input_date == "0101-01-01" else input_date
|
||||
|
||||
|
||||
@jinjia.app_template_filter('strftime')
|
||||
def timestamptodate(date, fmt=None):
|
||||
date = datetime.datetime.fromtimestamp(
|
||||
int(date)/1000
|
||||
)
|
||||
native = date.replace(tzinfo=None)
|
||||
if fmt:
|
||||
time_format = fmt
|
||||
else:
|
||||
time_format = '%d %m %Y - %H:%S'
|
||||
return native.strftime(time_format)
|
||||
|
||||
|
||||
@jinjia.app_template_filter('yesno')
|
||||
def yesno(value, yes, no):
|
||||
return yes if value else 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:
|
||||
return series_index
|
||||
return 0
|
||||
|
||||
@jinjia.app_template_filter('escapedlink')
|
||||
def escapedlink_filter(url, text):
|
||||
return "<a href='{}'>{}</a>".format(url, escape(text))
|
||||
|
||||
@jinjia.app_template_filter('uuidfilter')
|
||||
def uuidfilter(var):
|
||||
return uuid4()
|
||||
|
||||
|
||||
+1262
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,167 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2018-2019 shavitmichael, 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/>.
|
||||
|
||||
|
||||
"""This module is used to control authentication/authorization of Kobo sync requests.
|
||||
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.
|
||||
Upon successful sign-in, the user is redirected to
|
||||
https://auth.kobobooks.com/CrossDomainSignIn?id=<some id>
|
||||
which serves the following response:
|
||||
<script type='text/javascript'>
|
||||
location.href='kobo://UserAuthenticated?userId=<redacted>&userKey<redacted>&email=<redacted>&returnUrl=https%3a%2f%2fwww.kobo.com';
|
||||
</script>
|
||||
And triggers the insertion of a userKey into the device's User table.
|
||||
|
||||
Together, the device's DeviceId and UserKey act as an *irrevocable* authentication
|
||||
token to most (if not all) Kobo APIs. In fact, in most cases only the UserKey is
|
||||
required to authorize the API call.
|
||||
|
||||
Changing Kobo password *does not* invalidate user keys! This is apparently a known
|
||||
issue for a few years now https://www.mobileread.com/forums/showpost.php?p=3476851&postcount=13
|
||||
(although this poster hypothesised that Kobo could blacklist a DeviceId, many endpoints
|
||||
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
|
||||
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
|
||||
v1/auth/device endpoint with the secret UserKey and the device's DeviceId.
|
||||
* The book download endpoint passes an auth token as a URL param instead of a header.
|
||||
|
||||
Our implementation:
|
||||
We pretty much ignore all of the above. To authenticate the user, we generate a random
|
||||
and unique token that they append to the CalibreWeb Url when setting up the api_store
|
||||
setting on the device.
|
||||
Thus, every request from the device to the api_store will hit CalibreWeb with the
|
||||
auth_token in the url (e.g: https://mylibrary.com/<auth_token>/v1/library/sync).
|
||||
In addition, once authenticated we also set the login cookie on the response that will
|
||||
be sent back for the duration of the session to authorize subsequent API calls (in
|
||||
particular calls to non-Kobo specific endpoints such as the CalibreWeb book download).
|
||||
"""
|
||||
|
||||
from binascii import hexlify
|
||||
from datetime import datetime
|
||||
from os import urandom
|
||||
from functools import wraps
|
||||
|
||||
from flask import g, Blueprint, url_for, abort, request
|
||||
from flask_login import login_user, current_user, login_required
|
||||
from flask_babel import gettext as _
|
||||
|
||||
from . import logger, config, calibre_db, db, helper, ub, lm
|
||||
from .render_template import render_title_template
|
||||
|
||||
|
||||
log = logger.create()
|
||||
|
||||
|
||||
def register_url_value_preprocessor(kobo):
|
||||
@kobo.url_value_preprocessor
|
||||
# pylint: disable=unused-variable
|
||||
def pop_auth_token(__, values):
|
||||
g.auth_token = values.pop("auth_token")
|
||||
|
||||
|
||||
def disable_failed_auth_redirect_for_blueprint(bp):
|
||||
lm.blueprint_login_views[bp.name] = None
|
||||
|
||||
|
||||
def get_auth_token():
|
||||
if "auth_token" in g:
|
||||
return g.get("auth_token")
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def requires_kobo_auth(f):
|
||||
@wraps(f)
|
||||
def inner(*args, **kwargs):
|
||||
auth_token = get_auth_token()
|
||||
if auth_token is not None:
|
||||
user = (
|
||||
ub.session.query(ub.User)
|
||||
.join(ub.RemoteAuthToken)
|
||||
.filter(ub.RemoteAuthToken.auth_token == auth_token).filter(ub.RemoteAuthToken.token_type==1)
|
||||
.first()
|
||||
)
|
||||
if user is not None:
|
||||
login_user(user)
|
||||
return f(*args, **kwargs)
|
||||
log.debug("Received Kobo request without a recognizable auth token.")
|
||||
return abort(401)
|
||||
return inner
|
||||
|
||||
|
||||
kobo_auth = Blueprint("kobo_auth", __name__, url_prefix="/kobo_auth")
|
||||
|
||||
|
||||
@kobo_auth.route("/generate_auth_token/<int:user_id>")
|
||||
@login_required
|
||||
def generate_auth_token(user_id):
|
||||
warning = False
|
||||
host_list = request.host.rsplit(':')
|
||||
if len(host_list) == 1:
|
||||
host = ':'.join(host_list)
|
||||
else:
|
||||
host = ':'.join(host_list[0:-1])
|
||||
if host.startswith('127.') or host.lower() == 'localhost' or host.startswith('[::ffff:7f') or host == "[::1]":
|
||||
warning = _('Please access Calibre-Web from non localhost to get valid api_endpoint for kobo device')
|
||||
|
||||
# Generate auth token if none is existing for this user
|
||||
auth_token = ub.session.query(ub.RemoteAuthToken).filter(
|
||||
ub.RemoteAuthToken.user_id == user_id
|
||||
).filter(ub.RemoteAuthToken.token_type==1).first()
|
||||
|
||||
if not auth_token:
|
||||
auth_token = ub.RemoteAuthToken()
|
||||
auth_token.user_id = user_id
|
||||
auth_token.expiration = datetime.max
|
||||
auth_token.auth_token = (hexlify(urandom(16))).decode("utf-8")
|
||||
auth_token.token_type = 1
|
||||
|
||||
ub.session.add(auth_token)
|
||||
ub.session_commit()
|
||||
|
||||
books = calibre_db.session.query(db.Books).join(db.Data).all()
|
||||
|
||||
for book in books:
|
||||
formats = [data.format for data in book.data]
|
||||
if not 'KEPUB' in formats and config.config_kepubifypath and 'EPUB' in formats:
|
||||
helper.convert_book_format(book.id, config.config_calibre_dir, 'EPUB', 'KEPUB', current_user.name)
|
||||
|
||||
return render_title_template(
|
||||
"generate_kobo_auth_url.html",
|
||||
title=_(u"Kobo Setup"),
|
||||
auth_token=auth_token.auth_token,
|
||||
warning = warning
|
||||
)
|
||||
|
||||
|
||||
@kobo_auth.route("/deleteauthtoken/<int:user_id>", methods=["POST"])
|
||||
@login_required
|
||||
def delete_auth_token(user_id):
|
||||
# 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()
|
||||
|
||||
return ub.session_commit()
|
||||
@@ -0,0 +1,88 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2021 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/>.
|
||||
|
||||
|
||||
from flask_login import current_user
|
||||
from . import ub
|
||||
import datetime
|
||||
from sqlalchemy.sql.expression import or_, and_, true
|
||||
from sqlalchemy import exc
|
||||
|
||||
# Add the current book id to kobo_synced_books table for current user, if entry is already present,
|
||||
# do nothing (safety precaution)
|
||||
def add_synced_books(book_id):
|
||||
is_present = ub.session.query(ub.KoboSyncedBooks).filter(ub.KoboSyncedBooks.book_id == book_id)\
|
||||
.filter(ub.KoboSyncedBooks.user_id == current_user.id).count()
|
||||
if not is_present:
|
||||
synced_book = ub.KoboSyncedBooks()
|
||||
synced_book.user_id = current_user.id
|
||||
synced_book.book_id = book_id
|
||||
ub.session.add(synced_book)
|
||||
ub.session_commit()
|
||||
|
||||
|
||||
# Select all entries of current book in kobo_synced_books table, which are from current user and delete them
|
||||
def remove_synced_book(book_id, all=False, session=None):
|
||||
if not all:
|
||||
user = ub.KoboSyncedBooks.user_id == current_user.id
|
||||
else:
|
||||
user = true()
|
||||
if not session:
|
||||
ub.session.query(ub.KoboSyncedBooks).filter(ub.KoboSyncedBooks.book_id == book_id).filter(user).delete()
|
||||
ub.session_commit()
|
||||
else:
|
||||
session.query(ub.KoboSyncedBooks).filter(ub.KoboSyncedBooks.book_id == book_id).filter(user).delete()
|
||||
ub.session_commit(sess=session)
|
||||
|
||||
|
||||
|
||||
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:
|
||||
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()
|
||||
|
||||
ub.session.merge(archived_book)
|
||||
ub.session_commit(message)
|
||||
return archived_book.is_archived
|
||||
|
||||
|
||||
# select all books which are synced by the current user and do not belong to a synced shelf and set them to archive
|
||||
# select all shelves from current user which are synced and do not belong to the "only sync" shelves
|
||||
def update_on_sync_shelfs(user_id):
|
||||
books_to_archive = (ub.session.query(ub.KoboSyncedBooks)
|
||||
.join(ub.BookShelf, ub.KoboSyncedBooks.book_id == ub.BookShelf.book_id, isouter=True)
|
||||
.join(ub.Shelf, ub.Shelf.user_id == user_id, isouter=True)
|
||||
.filter(or_(ub.Shelf.kobo_sync == 0, ub.Shelf.kobo_sync == None))
|
||||
.filter(ub.KoboSyncedBooks.user_id == user_id).all())
|
||||
for b in books_to_archive:
|
||||
change_archived_books(b.book_id, True)
|
||||
ub.session.query(ub.KoboSyncedBooks) \
|
||||
.filter(ub.KoboSyncedBooks.book_id == b.book_id) \
|
||||
.filter(ub.KoboSyncedBooks.user_id == user_id).delete()
|
||||
ub.session_commit()
|
||||
|
||||
# Search all shelf which are currently not synced
|
||||
shelves_to_archive = ub.session.query(ub.Shelf).filter(ub.Shelf.user_id == user_id).filter(
|
||||
ub.Shelf.kobo_sync == 0).all()
|
||||
for a in shelves_to_archive:
|
||||
ub.session.add(ub.ShelfArchive(uuid=a.uuid, user_id=user_id))
|
||||
ub.session_commit()
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2019 pwr
|
||||
#
|
||||
# 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 os
|
||||
import sys
|
||||
import inspect
|
||||
import logging
|
||||
from logging import Formatter, StreamHandler
|
||||
from logging.handlers import RotatingFileHandler
|
||||
|
||||
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")
|
||||
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")
|
||||
LOG_TO_STDERR = '/dev/stderr'
|
||||
LOG_TO_STDOUT = '/dev/stdout'
|
||||
|
||||
logging.addLevelName(logging.WARNING, "WARN")
|
||||
logging.addLevelName(logging.CRITICAL, "CRIT")
|
||||
|
||||
|
||||
class _Logger(logging.Logger):
|
||||
|
||||
def debug_or_exception(self, message, stacklevel=2, *args, **kwargs):
|
||||
if sys.version_info > (3, 7):
|
||||
if is_debug_enabled():
|
||||
self.exception(message, stacklevel=stacklevel, *args, **kwargs)
|
||||
else:
|
||||
self.error(message, stacklevel=stacklevel, *args, **kwargs)
|
||||
else:
|
||||
if is_debug_enabled():
|
||||
self.exception(message, stack_info=True, *args, **kwargs)
|
||||
else:
|
||||
self.error(message, *args, **kwargs)
|
||||
|
||||
|
||||
def debug_no_auth(self, message, *args, **kwargs):
|
||||
message = message.strip("\r\n")
|
||||
if message.startswith("send: AUTH"):
|
||||
self.debug(message[:16], *args, **kwargs)
|
||||
else:
|
||||
self.debug(message, *args, **kwargs)
|
||||
|
||||
|
||||
def get(name=None):
|
||||
return logging.getLogger(name)
|
||||
|
||||
def create():
|
||||
parent_frame = inspect.stack(0)[1]
|
||||
if hasattr(parent_frame, 'frame'):
|
||||
parent_frame = parent_frame.frame
|
||||
else:
|
||||
parent_frame = parent_frame[0]
|
||||
parent_module = inspect.getmodule(parent_frame)
|
||||
return get(parent_module.__name__)
|
||||
|
||||
def is_debug_enabled():
|
||||
return logging.root.level <= logging.DEBUG
|
||||
|
||||
def is_info_enabled(logger):
|
||||
return logging.getLogger(logger).level <= logging.INFO
|
||||
|
||||
|
||||
def get_level_name(level):
|
||||
return logging.getLevelName(level)
|
||||
|
||||
|
||||
def is_valid_logfile(file_path):
|
||||
if file_path == LOG_TO_STDERR or file_path == LOG_TO_STDOUT:
|
||||
return True
|
||||
if not file_path:
|
||||
return True
|
||||
if os.path.isdir(file_path):
|
||||
return False
|
||||
log_dir = os.path.dirname(file_path)
|
||||
return (not log_dir) or os.path.isdir(log_dir)
|
||||
|
||||
|
||||
def _absolute_log_file(log_file, default_log_file):
|
||||
if log_file:
|
||||
if not os.path.dirname(log_file):
|
||||
log_file = os.path.join(_CONFIG_DIR, log_file)
|
||||
return os.path.abspath(log_file)
|
||||
return default_log_file
|
||||
|
||||
|
||||
def get_logfile(log_file):
|
||||
return _absolute_log_file(log_file, DEFAULT_LOG_FILE)
|
||||
|
||||
|
||||
def get_accesslogfile(log_file):
|
||||
return _absolute_log_file(log_file, DEFAULT_ACCESS_LOG)
|
||||
|
||||
|
||||
def setup(log_file, log_level=None):
|
||||
'''
|
||||
Configure the logging output.
|
||||
May be called multiple times.
|
||||
'''
|
||||
log_level = log_level or DEFAULT_LOG_LEVEL
|
||||
logging.setLoggerClass(_Logger)
|
||||
logging.getLogger(__package__).setLevel(log_level)
|
||||
|
||||
r = logging.root
|
||||
if log_level >= logging.INFO or os.environ.get('FLASK_DEBUG'):
|
||||
# avoid spamming the log with debug messages from libraries
|
||||
r.setLevel(log_level)
|
||||
|
||||
# Otherwise name get's destroyed on windows
|
||||
if log_file != LOG_TO_STDERR and log_file != LOG_TO_STDOUT:
|
||||
log_file = _absolute_log_file(log_file, DEFAULT_LOG_FILE)
|
||||
|
||||
previous_handler = r.handlers[0] if r.handlers else None
|
||||
if previous_handler:
|
||||
# if the log_file has not changed, don't create a new handler
|
||||
if getattr(previous_handler, 'baseFilename', None) == log_file:
|
||||
return "" if log_file == DEFAULT_LOG_FILE else log_file
|
||||
logging.debug("logging to %s level %s", log_file, r.level)
|
||||
|
||||
if log_file == LOG_TO_STDERR or log_file == LOG_TO_STDOUT:
|
||||
if log_file == LOG_TO_STDOUT:
|
||||
file_handler = StreamHandler(sys.stdout)
|
||||
file_handler.baseFilename = log_file
|
||||
else:
|
||||
file_handler = StreamHandler(sys.stderr)
|
||||
file_handler.baseFilename = log_file
|
||||
else:
|
||||
try:
|
||||
file_handler = RotatingFileHandler(log_file, maxBytes=100000, backupCount=2, encoding='utf-8')
|
||||
except IOError:
|
||||
if log_file == DEFAULT_LOG_FILE:
|
||||
raise
|
||||
file_handler = RotatingFileHandler(DEFAULT_LOG_FILE, maxBytes=100000, backupCount=2, encoding='utf-8')
|
||||
log_file = ""
|
||||
file_handler.setFormatter(FORMATTER)
|
||||
|
||||
for h in r.handlers:
|
||||
r.removeHandler(h)
|
||||
h.close()
|
||||
r.addHandler(file_handler)
|
||||
return "" if log_file == DEFAULT_LOG_FILE else log_file
|
||||
|
||||
|
||||
def create_access_log(log_file, log_name, formatter):
|
||||
'''
|
||||
One-time configuration for the web server's access log.
|
||||
'''
|
||||
log_file = _absolute_log_file(log_file, DEFAULT_ACCESS_LOG)
|
||||
logging.debug("access log: %s", log_file)
|
||||
|
||||
access_log = logging.getLogger(log_name)
|
||||
access_log.propagate = False
|
||||
access_log.setLevel(logging.INFO)
|
||||
try:
|
||||
file_handler = RotatingFileHandler(log_file, maxBytes=50000, backupCount=2, encoding='utf-8')
|
||||
except IOError:
|
||||
if log_file == DEFAULT_ACCESS_LOG:
|
||||
raise
|
||||
file_handler = RotatingFileHandler(DEFAULT_ACCESS_LOG, maxBytes=50000, backupCount=2, encoding='utf-8')
|
||||
log_file = ""
|
||||
|
||||
file_handler.setFormatter(formatter)
|
||||
access_log.addHandler(file_handler)
|
||||
return access_log, \
|
||||
"" if _absolute_log_file(log_file, DEFAULT_ACCESS_LOG) == DEFAULT_ACCESS_LOG else log_file
|
||||
|
||||
|
||||
# Enable logging of smtp lib debug output
|
||||
class StderrLogger(object):
|
||||
def __init__(self, name=None):
|
||||
self.log = get(name or self.__class__.__name__)
|
||||
self.buffer = ''
|
||||
|
||||
def write(self, message):
|
||||
try:
|
||||
if message == '\n':
|
||||
self.log.debug(self.buffer.replace('\n', '\\n'))
|
||||
self.buffer = ''
|
||||
else:
|
||||
self.buffer += message
|
||||
except Exception:
|
||||
self.log.debug("Logging Error")
|
||||
|
||||
|
||||
# default configuration, before application settings are applied
|
||||
setup(LOG_TO_STDERR, logging.DEBUG if os.environ.get('FLASK_DEBUG') else DEFAULT_LOG_LEVEL)
|
||||
@@ -0,0 +1,65 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2021 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/>.
|
||||
|
||||
# ComicVine api document: https://comicvine.gamespot.com/api/documentation
|
||||
|
||||
import requests
|
||||
from cps.services.Metadata import Metadata
|
||||
|
||||
|
||||
class ComicVine(Metadata):
|
||||
__name__ = "ComicVine"
|
||||
__id__ = "comicvine"
|
||||
|
||||
def search(self, query, generic_cover=""):
|
||||
val = list()
|
||||
apikey = "57558043c53943d5d1e96a9ad425b0eb85532ee6"
|
||||
if self.active:
|
||||
headers = {
|
||||
'User-Agent': 'Not Evil Browser'
|
||||
}
|
||||
|
||||
result = requests.get("https://comicvine.gamespot.com/api/search?api_key="
|
||||
+ apikey + "&resources=issue&query=" + query + "&sort=name:desc&format=json", headers=headers)
|
||||
for r in result.json().get('results'):
|
||||
seriesTitle = r['volume'].get('name', "")
|
||||
if r.get('store_date'):
|
||||
dateFomers = r.get('store_date')
|
||||
else:
|
||||
dateFomers = r.get('date_added')
|
||||
v = dict()
|
||||
v['id'] = r['id']
|
||||
v['title'] = seriesTitle + " #" + r.get('issue_number', "0") + " - " + ( r.get('name', "") or "")
|
||||
v['authors'] = r.get('authors', [])
|
||||
v['description'] = r.get('description', "")
|
||||
v['publisher'] = ""
|
||||
v['publishedDate'] = dateFomers
|
||||
v['tags'] = ["Comics", seriesTitle]
|
||||
v['rating'] = 0
|
||||
v['series'] = seriesTitle
|
||||
v['cover'] = r['image'].get('original_url')
|
||||
v['source'] = {
|
||||
"id": self.__id__,
|
||||
"description": "ComicVine Books",
|
||||
"link": "https://comicvine.gamespot.com/"
|
||||
}
|
||||
v['url'] = r.get('site_detail_url', "")
|
||||
val.append(v)
|
||||
return val
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2021 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/>.
|
||||
|
||||
# Google Books api document: https://developers.google.com/books/docs/v1/using
|
||||
|
||||
|
||||
import requests
|
||||
from cps.services.Metadata import Metadata
|
||||
|
||||
class Google(Metadata):
|
||||
__name__ = "Google"
|
||||
__id__ = "google"
|
||||
|
||||
def search(self, query, generic_cover=""):
|
||||
if self.active:
|
||||
val = list()
|
||||
result = requests.get("https://www.googleapis.com/books/v1/volumes?q="+query.replace(" ","+"))
|
||||
for r in result.json().get('items'):
|
||||
v = dict()
|
||||
v['id'] = r['id']
|
||||
v['title'] = r['volumeInfo'].get('title',"")
|
||||
v['authors'] = r['volumeInfo'].get('authors', [])
|
||||
v['description'] = r['volumeInfo'].get('description', "")
|
||||
v['publisher'] = r['volumeInfo'].get('publisher', "")
|
||||
v['publishedDate'] = r['volumeInfo'].get('publishedDate', "")
|
||||
v['tags'] = r['volumeInfo'].get('categories', [])
|
||||
v['rating'] = r['volumeInfo'].get('averageRating', 0)
|
||||
if r['volumeInfo'].get('imageLinks'):
|
||||
v['cover'] = r['volumeInfo']['imageLinks']['thumbnail'].replace("http://", "https://")
|
||||
else:
|
||||
v['cover'] = "/../../../static/generic_cover.jpg"
|
||||
v['source'] = {
|
||||
"id": self.__id__,
|
||||
"description": "Google Books",
|
||||
"link": "https://books.google.com/"}
|
||||
v['url'] = "https://books.google.com/books?id=" + r['id']
|
||||
val.append(v)
|
||||
return val
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2021 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/>.
|
||||
|
||||
from scholarly import scholarly
|
||||
|
||||
from cps.services.Metadata import Metadata
|
||||
|
||||
class scholar(Metadata):
|
||||
__name__ = "Google Scholar"
|
||||
__id__ = "googlescholar"
|
||||
|
||||
def search(self, query, generic_cover=""):
|
||||
val = list()
|
||||
if self.active:
|
||||
scholar_gen = scholarly.search_pubs(' '.join(query.split('+')))
|
||||
i = 0
|
||||
for publication in scholar_gen:
|
||||
v = dict()
|
||||
v['id'] = publication['url_scholarbib'].split(':')[1]
|
||||
v['title'] = publication['bib'].get('title')
|
||||
v['authors'] = publication['bib'].get('author', [])
|
||||
v['description'] = publication['bib'].get('abstract', "")
|
||||
v['publisher'] = publication['bib'].get('venue', "")
|
||||
if publication['bib'].get('pub_year'):
|
||||
v['publishedDate'] = publication['bib'].get('pub_year')+"-01-01"
|
||||
else:
|
||||
v['publishedDate'] = ""
|
||||
v['tags'] = []
|
||||
v['rating'] = 0
|
||||
v['series'] = ""
|
||||
v['cover'] = ""
|
||||
v['url'] = publication.get('pub_url') or publication.get('eprint_url') or "",
|
||||
v['source'] = {
|
||||
"id": self.__id__,
|
||||
"description": "Google Scholar",
|
||||
"link": "https://scholar.google.com/"
|
||||
}
|
||||
val.append(v)
|
||||
i += 1
|
||||
if (i >= 10):
|
||||
break
|
||||
return val
|
||||
|
||||
|
||||
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2018-2019 jim3ma
|
||||
#
|
||||
# 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 session
|
||||
|
||||
try:
|
||||
from flask_dance.consumer.backend.sqla import SQLAlchemyBackend, first, _get_real_user
|
||||
from sqlalchemy.orm.exc import NoResultFound
|
||||
backend_resultcode = False # prevent storing values with this resultcode
|
||||
except ImportError:
|
||||
# fails on flask-dance >1.3, due to renaming
|
||||
try:
|
||||
from flask_dance.consumer.storage.sqla import SQLAlchemyStorage as SQLAlchemyBackend
|
||||
from flask_dance.consumer.storage.sqla import first, _get_real_user
|
||||
from sqlalchemy.orm.exc import NoResultFound
|
||||
backend_resultcode = True # prevent storing values with this resultcode
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
class OAuthBackend(SQLAlchemyBackend):
|
||||
"""
|
||||
Stores and retrieves OAuth tokens using a relational database through
|
||||
the `SQLAlchemy`_ ORM.
|
||||
|
||||
.. _SQLAlchemy: https://www.sqlalchemy.org/
|
||||
"""
|
||||
def __init__(self, model, session, provider_id,
|
||||
user=None, user_id=None, user_required=None, anon_user=None,
|
||||
cache=None):
|
||||
self.provider_id = provider_id
|
||||
super(OAuthBackend, self).__init__(model, session, user, user_id, user_required, anon_user, cache)
|
||||
|
||||
def get(self, blueprint, user=None, user_id=None):
|
||||
if self.provider_id + '_oauth_token' in session and session[self.provider_id + '_oauth_token'] != '':
|
||||
return session[self.provider_id + '_oauth_token']
|
||||
# check cache
|
||||
cache_key = self.make_cache_key(blueprint=blueprint, user=user, user_id=user_id)
|
||||
token = self.cache.get(cache_key)
|
||||
if token:
|
||||
return token
|
||||
|
||||
# if not cached, make database queries
|
||||
query = (
|
||||
self.session.query(self.model)
|
||||
.filter_by(provider=self.provider_id)
|
||||
)
|
||||
uid = first([user_id, self.user_id, blueprint.config.get("user_id")])
|
||||
u = first(_get_real_user(ref, self.anon_user)
|
||||
for ref in (user, self.user, blueprint.config.get("user")))
|
||||
|
||||
use_provider_user_id = False
|
||||
if self.provider_id + '_oauth_user_id' in session and session[self.provider_id + '_oauth_user_id'] != '':
|
||||
query = query.filter_by(provider_user_id=session[self.provider_id + '_oauth_user_id'])
|
||||
use_provider_user_id = True
|
||||
|
||||
if self.user_required and not u and not uid and not use_provider_user_id:
|
||||
# raise ValueError("Cannot get OAuth token without an associated user")
|
||||
return None
|
||||
# check for user ID
|
||||
if hasattr(self.model, "user_id") and uid:
|
||||
query = query.filter_by(user_id=uid)
|
||||
# check for user (relationship property)
|
||||
elif hasattr(self.model, "user") and u:
|
||||
query = query.filter_by(user=u)
|
||||
# if we have the property, but not value, filter by None
|
||||
elif hasattr(self.model, "user_id"):
|
||||
query = query.filter_by(user_id=None)
|
||||
# run query
|
||||
try:
|
||||
token = query.one().token
|
||||
except NoResultFound:
|
||||
token = None
|
||||
|
||||
# cache the result
|
||||
self.cache.set(cache_key, token)
|
||||
|
||||
return token
|
||||
|
||||
def set(self, blueprint, token, user=None, user_id=None):
|
||||
uid = first([user_id, self.user_id, blueprint.config.get("user_id")])
|
||||
u = first(_get_real_user(ref, self.anon_user)
|
||||
for ref in (user, self.user, blueprint.config.get("user")))
|
||||
|
||||
if self.user_required and not u and not uid:
|
||||
raise ValueError("Cannot set OAuth token without an associated user")
|
||||
|
||||
# if there was an existing model, delete it
|
||||
existing_query = (
|
||||
self.session.query(self.model)
|
||||
.filter_by(provider=self.provider_id)
|
||||
)
|
||||
# check for user ID
|
||||
has_user_id = hasattr(self.model, "user_id")
|
||||
if has_user_id and uid:
|
||||
existing_query = existing_query.filter_by(user_id=uid)
|
||||
# check for user (relationship property)
|
||||
has_user = hasattr(self.model, "user")
|
||||
if has_user and u:
|
||||
existing_query = existing_query.filter_by(user=u)
|
||||
# queue up delete query -- won't be run until commit()
|
||||
existing_query.delete()
|
||||
# create a new model for this token
|
||||
kwargs = {
|
||||
"provider": self.provider_id,
|
||||
"token": token,
|
||||
}
|
||||
if has_user_id and uid:
|
||||
kwargs["user_id"] = uid
|
||||
if has_user and u:
|
||||
kwargs["user"] = u
|
||||
self.session.add(self.model(**kwargs))
|
||||
# commit to delete and add simultaneously
|
||||
self.session.commit()
|
||||
# invalidate cache
|
||||
self.cache.delete(self.make_cache_key(
|
||||
blueprint=blueprint, user=user, user_id=user_id
|
||||
))
|
||||
|
||||
def delete(self, blueprint, user=None, user_id=None):
|
||||
query = (
|
||||
self.session.query(self.model)
|
||||
.filter_by(provider=self.provider_id)
|
||||
)
|
||||
uid = first([user_id, self.user_id, blueprint.config.get("user_id")])
|
||||
u = first(_get_real_user(ref, self.anon_user)
|
||||
for ref in (user, self.user, blueprint.config.get("user")))
|
||||
|
||||
if self.user_required and not u and not uid:
|
||||
raise ValueError("Cannot delete OAuth token without an associated user")
|
||||
|
||||
# check for user ID
|
||||
if hasattr(self.model, "user_id") and uid:
|
||||
query = query.filter_by(user_id=uid)
|
||||
# check for user (relationship property)
|
||||
elif hasattr(self.model, "user") and u:
|
||||
query = query.filter_by(user=u)
|
||||
# if we have the property, but not value, filter by None
|
||||
elif hasattr(self.model, "user_id"):
|
||||
query = query.filter_by(user_id=None)
|
||||
# run query
|
||||
query.delete()
|
||||
self.session.commit()
|
||||
# invalidate cache
|
||||
self.cache.delete(self.make_cache_key(
|
||||
blueprint=blueprint, user=user, user_id=user_id,
|
||||
))
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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
|
||||
#
|
||||
# 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 json
|
||||
from functools import wraps
|
||||
|
||||
from flask import session, request, make_response, abort
|
||||
from flask import Blueprint, flash, redirect, url_for
|
||||
from flask_babel import gettext as _
|
||||
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 sqlalchemy.orm.exc import NoResultFound
|
||||
|
||||
from . import constants, logger, config, app, ub
|
||||
|
||||
try:
|
||||
from .oauth import OAuthBackend, backend_resultcode
|
||||
except NameError:
|
||||
pass
|
||||
|
||||
|
||||
oauth_check = {}
|
||||
oauthblueprints = []
|
||||
oauth = Blueprint('oauth', __name__)
|
||||
log = logger.create()
|
||||
|
||||
|
||||
def oauth_required(f):
|
||||
@wraps(f)
|
||||
def inner(*args, **kwargs):
|
||||
if config.config_login_type == constants.LOGIN_OAUTH:
|
||||
return f(*args, **kwargs)
|
||||
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
|
||||
data = {'status': 'error', 'message': 'Not Found'}
|
||||
response = make_response(json.dumps(data, ensure_ascii=False))
|
||||
response.headers["Content-Type"] = "application/json; charset=utf-8"
|
||||
return response, 404
|
||||
abort(404)
|
||||
|
||||
return inner
|
||||
|
||||
|
||||
def register_oauth_blueprint(cid, show_name):
|
||||
oauth_check[cid] = show_name
|
||||
|
||||
|
||||
def register_user_with_oauth(user=None):
|
||||
all_oauth = {}
|
||||
for oauth_key in oauth_check.keys():
|
||||
if str(oauth_key) + '_oauth_user_id' in session and session[str(oauth_key) + '_oauth_user_id'] != '':
|
||||
all_oauth[oauth_key] = oauth_check[oauth_key]
|
||||
if len(all_oauth.keys()) == 0:
|
||||
return
|
||||
if user is None:
|
||||
flash(_(u"Register with %(provider)s", provider=", ".join(list(all_oauth.values()))), category="success")
|
||||
else:
|
||||
for oauth_key in all_oauth.keys():
|
||||
# Find this OAuth token in the database, or create it
|
||||
query = ub.session.query(ub.OAuth).filter_by(
|
||||
provider=oauth_key,
|
||||
provider_user_id=session[str(oauth_key) + "_oauth_user_id"],
|
||||
)
|
||||
try:
|
||||
oauth_key = query.one()
|
||||
oauth_key.user_id = user.id
|
||||
except NoResultFound:
|
||||
# no found, return error
|
||||
return
|
||||
ub.session_commit("User {} with OAuth for provider {} registered".format(user.name, oauth_key))
|
||||
|
||||
|
||||
def logout_oauth_user():
|
||||
for oauth_key in oauth_check.keys():
|
||||
if str(oauth_key) + '_oauth_user_id' in session:
|
||||
session.pop(str(oauth_key) + '_oauth_user_id')
|
||||
|
||||
|
||||
def oauth_update_token(provider_id, token, provider_user_id):
|
||||
session[provider_id + "_oauth_user_id"] = provider_user_id
|
||||
session[provider_id + "_oauth_token"] = token
|
||||
|
||||
# Find this OAuth token in the database, or create it
|
||||
query = ub.session.query(ub.OAuth).filter_by(
|
||||
provider=provider_id,
|
||||
provider_user_id=provider_user_id,
|
||||
)
|
||||
try:
|
||||
oauth_entry = query.one()
|
||||
# update token
|
||||
oauth_entry.token = token
|
||||
except NoResultFound:
|
||||
oauth_entry = ub.OAuth(
|
||||
provider=provider_id,
|
||||
provider_user_id=provider_user_id,
|
||||
token=token,
|
||||
)
|
||||
ub.session.add(oauth_entry)
|
||||
ub.session_commit()
|
||||
|
||||
# Disable Flask-Dance's default behavior for saving the OAuth token
|
||||
# Value differrs depending on flask-dance version
|
||||
return backend_resultcode
|
||||
|
||||
|
||||
def bind_oauth_or_register(provider_id, provider_user_id, redirect_url, provider_name):
|
||||
query = ub.session.query(ub.OAuth).filter_by(
|
||||
provider=provider_id,
|
||||
provider_user_id=provider_user_id,
|
||||
)
|
||||
try:
|
||||
oauth_entry = query.first()
|
||||
# already bind with user, just login
|
||||
if oauth_entry.user:
|
||||
login_user(oauth_entry.user)
|
||||
log.debug(u"You are now logged in as: '%s'", oauth_entry.user.name)
|
||||
flash(_(u"you are now logged in as: '%(nickname)s'", nickname= oauth_entry.user.name),
|
||||
category="success")
|
||||
return redirect(url_for('web.index'))
|
||||
else:
|
||||
# bind to current user
|
||||
if current_user and current_user.is_authenticated:
|
||||
oauth_entry.user = current_user
|
||||
try:
|
||||
ub.session.add(oauth_entry)
|
||||
ub.session.commit()
|
||||
flash(_(u"Link to %(oauth)s Succeeded", oauth=provider_name), category="success")
|
||||
log.info("Link to {} Succeeded".format(provider_name))
|
||||
return redirect(url_for('web.profile'))
|
||||
except Exception as ex:
|
||||
log.debug_or_exception(ex)
|
||||
ub.session.rollback()
|
||||
else:
|
||||
flash(_(u"Login failed, No User Linked With OAuth Account"), category="error")
|
||||
log.info('Login failed, No User Linked With OAuth Account')
|
||||
return redirect(url_for('web.login'))
|
||||
# return redirect(url_for('web.login'))
|
||||
# if config.config_public_reg:
|
||||
# return redirect(url_for('web.register'))
|
||||
# else:
|
||||
# flash(_(u"Public registration is not enabled"), category="error")
|
||||
# return redirect(url_for(redirect_url))
|
||||
except (NoResultFound, AttributeError):
|
||||
return redirect(url_for(redirect_url))
|
||||
|
||||
|
||||
def get_oauth_status():
|
||||
status = []
|
||||
query = ub.session.query(ub.OAuth).filter_by(
|
||||
user_id=current_user.id,
|
||||
)
|
||||
try:
|
||||
oauths = query.all()
|
||||
for oauth_entry in oauths:
|
||||
status.append(int(oauth_entry.provider))
|
||||
return status
|
||||
except NoResultFound:
|
||||
return None
|
||||
|
||||
|
||||
def unlink_oauth(provider):
|
||||
if request.host_url + 'me' != request.referrer:
|
||||
pass
|
||||
query = ub.session.query(ub.OAuth).filter_by(
|
||||
provider=provider,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
try:
|
||||
oauth_entry = query.one()
|
||||
if current_user and current_user.is_authenticated:
|
||||
oauth_entry.user = current_user
|
||||
try:
|
||||
ub.session.delete(oauth_entry)
|
||||
ub.session.commit()
|
||||
logout_oauth_user()
|
||||
flash(_(u"Unlink to %(oauth)s Succeeded", oauth=oauth_check[provider]), category="success")
|
||||
log.info("Unlink to {} Succeeded".format(oauth_check[provider]))
|
||||
except Exception as ex:
|
||||
log.debug_or_exception(ex)
|
||||
ub.session.rollback()
|
||||
flash(_(u"Unlink to %(oauth)s Failed", oauth=oauth_check[provider]), category="error")
|
||||
except NoResultFound:
|
||||
log.warning("oauth %s for user %d not found", provider, current_user.id)
|
||||
flash(_(u"Not Linked to %(oauth)s", oauth=provider), category="error")
|
||||
return redirect(url_for('web.profile'))
|
||||
|
||||
def generate_oauth_blueprints():
|
||||
if not ub.session.query(ub.OAuthProvider).count():
|
||||
for provider in ("github", "google"):
|
||||
oauthProvider = ub.OAuthProvider()
|
||||
oauthProvider.provider_name = provider
|
||||
oauthProvider.active = False
|
||||
ub.session.add(oauthProvider)
|
||||
ub.session_commit("{} Blueprint Created".format(provider))
|
||||
|
||||
oauth_ids = ub.session.query(ub.OAuthProvider).all()
|
||||
ele1 = dict(provider_name='github',
|
||||
id=oauth_ids[0].id,
|
||||
active=oauth_ids[0].active,
|
||||
oauth_client_id=oauth_ids[0].oauth_client_id,
|
||||
scope=None,
|
||||
oauth_client_secret=oauth_ids[0].oauth_client_secret,
|
||||
obtain_link='https://github.com/settings/developers')
|
||||
ele2 = dict(provider_name='google',
|
||||
id=oauth_ids[1].id,
|
||||
active=oauth_ids[1].active,
|
||||
scope=["https://www.googleapis.com/auth/userinfo.email"],
|
||||
oauth_client_id=oauth_ids[1].oauth_client_id,
|
||||
oauth_client_secret=oauth_ids[1].oauth_client_secret,
|
||||
obtain_link='https://console.developers.google.com/apis/credentials')
|
||||
oauthblueprints.append(ele1)
|
||||
oauthblueprints.append(ele2)
|
||||
|
||||
for element in oauthblueprints:
|
||||
if element['provider_name'] == 'github':
|
||||
blueprint_func = make_github_blueprint
|
||||
else:
|
||||
blueprint_func = make_google_blueprint
|
||||
blueprint = blueprint_func(
|
||||
client_id=element['oauth_client_id'],
|
||||
client_secret=element['oauth_client_secret'],
|
||||
redirect_to="oauth."+element['provider_name']+"_login",
|
||||
scope=element['scope']
|
||||
)
|
||||
element['blueprint'] = blueprint
|
||||
element['blueprint'].backend = OAuthBackend(ub.OAuth, ub.session, str(element['id']),
|
||||
user=current_user, user_required=True)
|
||||
app.register_blueprint(blueprint, url_prefix="/login")
|
||||
if element['active']:
|
||||
register_oauth_blueprint(element['id'], element['provider_name'])
|
||||
return oauthblueprints
|
||||
|
||||
|
||||
if ub.oauth_support:
|
||||
oauthblueprints = generate_oauth_blueprints()
|
||||
|
||||
@oauth_authorized.connect_via(oauthblueprints[0]['blueprint'])
|
||||
def github_logged_in(blueprint, token):
|
||||
if not token:
|
||||
flash(_(u"Failed to log in with GitHub."), category="error")
|
||||
log.error("Failed to log in with GitHub")
|
||||
return False
|
||||
|
||||
resp = blueprint.session.get("/user")
|
||||
if not resp.ok:
|
||||
flash(_(u"Failed to fetch user info from GitHub."), category="error")
|
||||
log.error("Failed to fetch user info from GitHub")
|
||||
return False
|
||||
|
||||
github_info = resp.json()
|
||||
github_user_id = str(github_info["id"])
|
||||
return oauth_update_token(str(oauthblueprints[0]['id']), token, github_user_id)
|
||||
|
||||
|
||||
@oauth_authorized.connect_via(oauthblueprints[1]['blueprint'])
|
||||
def google_logged_in(blueprint, token):
|
||||
if not token:
|
||||
flash(_(u"Failed to log in with Google."), category="error")
|
||||
log.error("Failed to log in with Google")
|
||||
return False
|
||||
|
||||
resp = blueprint.session.get("/oauth2/v2/userinfo")
|
||||
if not resp.ok:
|
||||
flash(_(u"Failed to fetch user info from Google."), category="error")
|
||||
log.error("Failed to fetch user info from Google")
|
||||
return False
|
||||
|
||||
google_info = resp.json()
|
||||
google_user_id = str(google_info["id"])
|
||||
return oauth_update_token(str(oauthblueprints[1]['id']), token, google_user_id)
|
||||
|
||||
|
||||
# notify on OAuth provider error
|
||||
@oauth_error.connect_via(oauthblueprints[0]['blueprint'])
|
||||
def github_error(blueprint, error, error_description=None, error_uri=None):
|
||||
msg = (
|
||||
u"OAuth error from {name}! "
|
||||
u"error={error} description={description} uri={uri}"
|
||||
).format(
|
||||
name=blueprint.name,
|
||||
error=error,
|
||||
description=error_description,
|
||||
uri=error_uri,
|
||||
) # ToDo: Translate
|
||||
flash(msg, category="error")
|
||||
|
||||
@oauth_error.connect_via(oauthblueprints[1]['blueprint'])
|
||||
def google_error(blueprint, error, error_description=None, error_uri=None):
|
||||
msg = (
|
||||
u"OAuth error from {name}! "
|
||||
u"error={error} description={description} uri={uri}"
|
||||
).format(
|
||||
name=blueprint.name,
|
||||
error=error,
|
||||
description=error_description,
|
||||
uri=error_uri,
|
||||
) # ToDo: Translate
|
||||
flash(msg, category="error")
|
||||
|
||||
|
||||
@oauth.route('/link/github')
|
||||
@oauth_required
|
||||
def github_login():
|
||||
if not github.authorized:
|
||||
return redirect(url_for('github.login'))
|
||||
try:
|
||||
account_info = github.get('/user')
|
||||
if account_info.ok:
|
||||
account_info_json = account_info.json()
|
||||
return bind_oauth_or_register(oauthblueprints[0]['id'], account_info_json['id'], 'github.login', 'github')
|
||||
flash(_(u"GitHub Oauth error, please retry later."), category="error")
|
||||
log.error("GitHub Oauth error, please retry later")
|
||||
except (InvalidGrantError, TokenExpiredError) as e:
|
||||
flash(_(u"GitHub Oauth error: {}").format(e), category="error")
|
||||
log.error(e)
|
||||
return redirect(url_for('web.login'))
|
||||
|
||||
|
||||
@oauth.route('/unlink/github', methods=["GET"])
|
||||
@login_required
|
||||
def github_login_unlink():
|
||||
return unlink_oauth(oauthblueprints[0]['id'])
|
||||
|
||||
|
||||
@oauth.route('/link/google')
|
||||
@oauth_required
|
||||
def google_login():
|
||||
if not google.authorized:
|
||||
return redirect(url_for("google.login"))
|
||||
try:
|
||||
resp = google.get("/oauth2/v2/userinfo")
|
||||
if resp.ok:
|
||||
account_info_json = resp.json()
|
||||
return bind_oauth_or_register(oauthblueprints[1]['id'], account_info_json['id'], 'google.login', 'google')
|
||||
flash(_(u"Google Oauth error, please retry later."), category="error")
|
||||
log.error("Google Oauth error, please retry later")
|
||||
except (InvalidGrantError, TokenExpiredError) as e:
|
||||
flash(_(u"Google Oauth error: {}").format(e), category="error")
|
||||
log.error(e)
|
||||
return redirect(url_for('web.login'))
|
||||
|
||||
|
||||
@oauth.route('/unlink/google', methods=["GET"])
|
||||
@login_required
|
||||
def google_login_unlink():
|
||||
return unlink_oauth(oauthblueprints[1]['id'])
|
||||
+588
@@ -0,0 +1,588 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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
|
||||
#
|
||||
# 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 datetime
|
||||
from functools import wraps
|
||||
|
||||
from flask import Blueprint, request, render_template, Response, g, make_response, abort
|
||||
from flask_login import current_user
|
||||
from sqlalchemy.sql.expression import func, text, or_, and_, true
|
||||
from werkzeug.security import check_password_hash
|
||||
|
||||
from . import constants, logger, config, db, calibre_db, ub, services, get_locale, isoLanguages
|
||||
from .helper import get_download_link, get_book_cover
|
||||
from .pagination import Pagination
|
||||
from .web import render_read_books
|
||||
from .usermanagement import load_user_from_request
|
||||
from flask_babel import gettext as _
|
||||
|
||||
opds = Blueprint('opds', __name__)
|
||||
|
||||
log = logger.create()
|
||||
|
||||
|
||||
def requires_basic_auth_if_no_ano(f):
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
auth = request.authorization
|
||||
if config.config_anonbrowse != 1:
|
||||
if not auth or auth.type != 'basic' or not check_auth(auth.username, auth.password):
|
||||
return authenticate()
|
||||
return f(*args, **kwargs)
|
||||
if config.config_login_type == constants.LOGIN_LDAP and services.ldap and config.config_anonbrowse != 1:
|
||||
return services.ldap.basic_auth_required(f)
|
||||
return decorated
|
||||
|
||||
|
||||
class FeedObject:
|
||||
def __init__(self, rating_id, rating_name):
|
||||
self.rating_id = rating_id
|
||||
self.rating_name = rating_name
|
||||
|
||||
@property
|
||||
def id(self):
|
||||
return self.rating_id
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self.rating_name
|
||||
|
||||
|
||||
@opds.route("/opds/")
|
||||
@opds.route("/opds")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_index():
|
||||
return render_xml_template('index.xml')
|
||||
|
||||
|
||||
@opds.route("/opds/osd")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_osd():
|
||||
return render_xml_template('osd.xml', lang='en-EN')
|
||||
|
||||
|
||||
@opds.route("/opds/search", defaults={'query': ""})
|
||||
@opds.route("/opds/search/<query>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_cc_search(query):
|
||||
return feed_search(query.strip())
|
||||
|
||||
|
||||
@opds.route("/opds/search", methods=["GET"])
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_normal_search():
|
||||
return feed_search(request.args.get("query", "").strip())
|
||||
|
||||
|
||||
@opds.route("/opds/books")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_booksindex():
|
||||
shift = 0
|
||||
off = int(request.args.get("offset") or 0)
|
||||
entries = calibre_db.session.query(func.upper(func.substr(db.Books.sort, 1, 1)).label('id'))\
|
||||
.filter(calibre_db.common_filters()).group_by(func.upper(func.substr(db.Books.sort, 1, 1))).all()
|
||||
|
||||
elements = []
|
||||
if off == 0:
|
||||
elements.append({'id': "00", 'name':_("All")})
|
||||
shift = 1
|
||||
for entry in entries[
|
||||
off + shift - 1:
|
||||
int(off + int(config.config_books_per_page) - shift)]:
|
||||
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)
|
||||
return render_xml_template('feed.xml',
|
||||
letterelements=elements,
|
||||
folder='opds.feed_letter_books',
|
||||
pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/books/letter/<book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_letter_books(book_id):
|
||||
off = request.args.get("offset") or 0
|
||||
letter = true() if book_id == "00" else func.upper(db.Books.sort).startswith(book_id)
|
||||
entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,
|
||||
db.Books,
|
||||
letter,
|
||||
[db.Books.sort])
|
||||
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/new")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_new():
|
||||
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()])
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/discover")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_discover():
|
||||
entries = calibre_db.session.query(db.Books).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)
|
||||
|
||||
|
||||
@opds.route("/opds/rated")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_best_rated():
|
||||
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()])
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/hot")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_hot():
|
||||
off = request.args.get("offset") or 0
|
||||
all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id)).order_by(
|
||||
func.count(ub.Downloads.book_id).desc()).group_by(ub.Downloads.book_id)
|
||||
hot_books = all_books.offset(off).limit(config.config_books_per_page)
|
||||
entries = list()
|
||||
for book in hot_books:
|
||||
downloadBook = calibre_db.get_book(book.Downloads.book_id)
|
||||
if downloadBook:
|
||||
entries.append(
|
||||
calibre_db.get_filtered_book(book.Downloads.book_id)
|
||||
)
|
||||
else:
|
||||
ub.delete_download(book.Downloads.book_id)
|
||||
numBooks = entries.__len__()
|
||||
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1),
|
||||
config.config_books_per_page, numBooks)
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/author")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_authorindex():
|
||||
shift = 0
|
||||
off = int(request.args.get("offset") or 0)
|
||||
entries = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('id'))\
|
||||
.join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters())\
|
||||
.group_by(func.upper(func.substr(db.Authors.sort, 1, 1))).all()
|
||||
|
||||
elements = []
|
||||
if off == 0:
|
||||
elements.append({'id': "00", 'name':_("All")})
|
||||
shift = 1
|
||||
for entry in entries[
|
||||
off + shift - 1:
|
||||
int(off + int(config.config_books_per_page) - shift)]:
|
||||
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)
|
||||
return render_xml_template('feed.xml',
|
||||
letterelements=elements,
|
||||
folder='opds.feed_letter_author',
|
||||
pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/author/letter/<book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_letter_author(book_id):
|
||||
off = request.args.get("offset") or 0
|
||||
letter = true() if book_id == "00" else func.upper(db.Authors.sort).startswith(book_id)
|
||||
entries = calibre_db.session.query(db.Authors).join(db.books_authors_link).join(db.Books)\
|
||||
.filter(calibre_db.common_filters()).filter(letter)\
|
||||
.group_by(text('books_authors_link.author'))\
|
||||
.order_by(db.Authors.sort)
|
||||
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)
|
||||
|
||||
|
||||
@opds.route("/opds/author/<int:book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_author(book_id):
|
||||
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.authors.any(db.Authors.id == book_id),
|
||||
[db.Books.timestamp.desc()])
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/publisher")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_publisherindex():
|
||||
off = request.args.get("offset") or 0
|
||||
entries = calibre_db.session.query(db.Publishers)\
|
||||
.join(db.books_publishers_link)\
|
||||
.join(db.Books).filter(calibre_db.common_filters())\
|
||||
.group_by(text('books_publishers_link.publisher'))\
|
||||
.order_by(db.Publishers.sort)\
|
||||
.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)
|
||||
|
||||
|
||||
@opds.route("/opds/publisher/<int:book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_publisher(book_id):
|
||||
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.publishers.any(db.Publishers.id == book_id),
|
||||
[db.Books.timestamp.desc()])
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/category")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_categoryindex():
|
||||
shift = 0
|
||||
off = int(request.args.get("offset") or 0)
|
||||
entries = calibre_db.session.query(func.upper(func.substr(db.Tags.name, 1, 1)).label('id'))\
|
||||
.join(db.books_tags_link).join(db.Books).filter(calibre_db.common_filters())\
|
||||
.group_by(func.upper(func.substr(db.Tags.name, 1, 1))).all()
|
||||
elements = []
|
||||
if off == 0:
|
||||
elements.append({'id': "00", 'name':_("All")})
|
||||
shift = 1
|
||||
for entry in entries[
|
||||
off + shift - 1:
|
||||
int(off + int(config.config_books_per_page) - shift)]:
|
||||
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)
|
||||
return render_xml_template('feed.xml',
|
||||
letterelements=elements,
|
||||
folder='opds.feed_letter_category',
|
||||
pagination=pagination)
|
||||
|
||||
@opds.route("/opds/category/letter/<book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_letter_category(book_id):
|
||||
off = request.args.get("offset") or 0
|
||||
letter = true() if book_id == "00" else func.upper(db.Tags.name).startswith(book_id)
|
||||
entries = calibre_db.session.query(db.Tags)\
|
||||
.join(db.books_tags_link)\
|
||||
.join(db.Books)\
|
||||
.filter(calibre_db.common_filters()).filter(letter)\
|
||||
.group_by(text('books_tags_link.tag'))\
|
||||
.order_by(db.Tags.name)
|
||||
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)
|
||||
|
||||
|
||||
@opds.route("/opds/category/<int:book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_category(book_id):
|
||||
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.tags.any(db.Tags.id == book_id),
|
||||
[db.Books.timestamp.desc()])
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/series")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_seriesindex():
|
||||
shift = 0
|
||||
off = int(request.args.get("offset") or 0)
|
||||
entries = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('id'))\
|
||||
.join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters())\
|
||||
.group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all()
|
||||
elements = []
|
||||
if off == 0:
|
||||
elements.append({'id': "00", 'name':_("All")})
|
||||
shift = 1
|
||||
for entry in entries[
|
||||
off + shift - 1:
|
||||
int(off + int(config.config_books_per_page) - shift)]:
|
||||
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)
|
||||
return render_xml_template('feed.xml',
|
||||
letterelements=elements,
|
||||
folder='opds.feed_letter_series',
|
||||
pagination=pagination)
|
||||
|
||||
@opds.route("/opds/series/letter/<book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_letter_series(book_id):
|
||||
off = request.args.get("offset") or 0
|
||||
letter = true() if book_id == "00" else func.upper(db.Series.sort).startswith(book_id)
|
||||
entries = calibre_db.session.query(db.Series)\
|
||||
.join(db.books_series_link)\
|
||||
.join(db.Books)\
|
||||
.filter(calibre_db.common_filters()).filter(letter)\
|
||||
.group_by(text('books_series_link.series'))\
|
||||
.order_by(db.Series.sort)
|
||||
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)
|
||||
|
||||
|
||||
@opds.route("/opds/series/<int:book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_series(book_id):
|
||||
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.series.any(db.Series.id == book_id),
|
||||
[db.Books.series_index])
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/ratings")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_ratingindex():
|
||||
off = request.args.get("offset") or 0
|
||||
entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'),
|
||||
(db.Ratings.rating / 2).label('name')) \
|
||||
.join(db.books_ratings_link)\
|
||||
.join(db.Books)\
|
||||
.filter(calibre_db.common_filters()) \
|
||||
.group_by(text('books_ratings_link.rating'))\
|
||||
.order_by(db.Ratings.rating).all()
|
||||
|
||||
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
|
||||
len(entries))
|
||||
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)
|
||||
|
||||
|
||||
@opds.route("/opds/ratings/<book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_ratings(book_id):
|
||||
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.id == book_id),
|
||||
[db.Books.timestamp.desc()])
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/formats")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_formatindex():
|
||||
off = request.args.get("offset") or 0
|
||||
entries = calibre_db.session.query(db.Data).join(db.Books)\
|
||||
.filter(calibre_db.common_filters()) \
|
||||
.group_by(db.Data.format)\
|
||||
.order_by(db.Data.format).all()
|
||||
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
|
||||
len(entries))
|
||||
|
||||
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)
|
||||
|
||||
|
||||
@opds.route("/opds/formats/<book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_format(book_id):
|
||||
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.data.any(db.Data.format == book_id.upper()),
|
||||
[db.Books.timestamp.desc()])
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/language")
|
||||
@opds.route("/opds/language/")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_languagesindex():
|
||||
off = request.args.get("offset") or 0
|
||||
if current_user.filter_language() == u"all":
|
||||
languages = calibre_db.speaking_language()
|
||||
else:
|
||||
#try:
|
||||
# cur_l = LC.parse(current_user.filter_language())
|
||||
#except UnknownLocaleError:
|
||||
# cur_l = None
|
||||
languages = calibre_db.session.query(db.Languages).filter(
|
||||
db.Languages.lang_code == current_user.filter_language()).all()
|
||||
languages[0].name = isoLanguages.get_language_name(get_locale(), languages[0].lang_code)
|
||||
#if cur_l:
|
||||
# languages[0].name = cur_l.get_language_name(get_locale())
|
||||
#else:
|
||||
# languages[0].name = _(isoLanguages.get(part3=languages[0].lang_code).name)
|
||||
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)
|
||||
|
||||
|
||||
@opds.route("/opds/language/<int:book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_languages(book_id):
|
||||
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.languages.any(db.Languages.id == book_id),
|
||||
[db.Books.timestamp.desc()])
|
||||
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/shelfindex")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_shelfindex():
|
||||
off = request.args.get("offset") or 0
|
||||
shelf = g.shelves_access
|
||||
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)
|
||||
|
||||
|
||||
@opds.route("/opds/shelf/<int:book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_shelf(book_id):
|
||||
off = request.args.get("offset") or 0
|
||||
if 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),
|
||||
ub.Shelf.id == book_id),
|
||||
and_(ub.Shelf.is_public == 1,
|
||||
ub.Shelf.id == book_id))).first()
|
||||
result = list()
|
||||
# user is allowed to access shelf
|
||||
if shelf:
|
||||
books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == book_id).order_by(
|
||||
ub.BookShelf.order.asc()).all()
|
||||
for book in books_in_shelf:
|
||||
cur_book = calibre_db.get_book(book.book_id)
|
||||
result.append(cur_book)
|
||||
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
|
||||
len(result))
|
||||
return render_xml_template('feed.xml', entries=result, pagination=pagination)
|
||||
|
||||
|
||||
@opds.route("/opds/download/<book_id>/<book_format>/")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def opds_download_link(book_id, book_format):
|
||||
# I gave up with this: With enabled ldap login, the user doesn't get logged in, therefore it's always guest
|
||||
# workaround, loading the user from the request and checking it's download rights here
|
||||
# in case of anonymous browsing user is None
|
||||
user = load_user_from_request(request) or current_user
|
||||
if not user.role_download():
|
||||
return abort(403)
|
||||
if "Kobo" in request.headers.get('User-Agent'):
|
||||
client = "kobo"
|
||||
else:
|
||||
client = ""
|
||||
return get_download_link(book_id, book_format.lower(), client)
|
||||
|
||||
|
||||
@opds.route("/ajax/book/<string:uuid>/<library>")
|
||||
@opds.route("/ajax/book/<string:uuid>", defaults={'library': ""})
|
||||
@requires_basic_auth_if_no_ano
|
||||
def get_metadata_calibre_companion(uuid, library):
|
||||
entry = calibre_db.session.query(db.Books).filter(db.Books.uuid.like("%" + uuid + "%")).first()
|
||||
if entry is not None:
|
||||
js = render_template('json.txt', entry=entry)
|
||||
response = make_response(js)
|
||||
response.headers["Content-Type"] = "application/json; charset=utf-8"
|
||||
return response
|
||||
else:
|
||||
return ""
|
||||
|
||||
|
||||
def feed_search(term):
|
||||
if term:
|
||||
entries, __, ___ = calibre_db.get_search_results(term)
|
||||
entriescount = len(entries) if len(entries) > 0 else 1
|
||||
pagination = Pagination(1, entriescount, entriescount)
|
||||
return render_xml_template('feed.xml', searchterm=term, entries=entries, pagination=pagination)
|
||||
else:
|
||||
return render_xml_template('feed.xml', searchterm="")
|
||||
|
||||
|
||||
def check_auth(username, password):
|
||||
try:
|
||||
username = username.encode('windows-1252')
|
||||
except UnicodeEncodeError:
|
||||
username = username.encode('utf-8')
|
||||
user = ub.session.query(ub.User).filter(func.lower(ub.User.name) ==
|
||||
username.decode('utf-8').lower()).first()
|
||||
if bool(user and check_password_hash(str(user.password), password)):
|
||||
return True
|
||||
else:
|
||||
ip_Address = request.headers.get('X-Forwarded-For', request.remote_addr)
|
||||
log.warning('OPDS Login failed for user "%s" IP-address: %s', username.decode('utf-8'), ip_Address)
|
||||
return False
|
||||
|
||||
|
||||
def authenticate():
|
||||
return Response(
|
||||
'Could not verify your access level for that URL.\n'
|
||||
'You have to login with proper credentials', 401,
|
||||
{'WWW-Authenticate': 'Basic realm="Login Required"'})
|
||||
|
||||
|
||||
def render_xml_template(*args, **kwargs):
|
||||
# ToDo: return time in current timezone similar to %z
|
||||
currtime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S+00:00")
|
||||
xml = render_template(current_time=currtime, instance=config.config_calibre_web_title, *args, **kwargs)
|
||||
response = make_response(xml)
|
||||
response.headers["Content-Type"] = "application/atom+xml; charset=utf-8"
|
||||
return response
|
||||
|
||||
|
||||
@opds.route("/opds/thumb_240_240/<book_id>")
|
||||
@opds.route("/opds/cover_240_240/<book_id>")
|
||||
@opds.route("/opds/cover_90_90/<book_id>")
|
||||
@opds.route("/opds/cover/<book_id>")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_get_cover(book_id):
|
||||
return get_book_cover(book_id)
|
||||
|
||||
|
||||
@opds.route("/opds/readbooks")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_read_books():
|
||||
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)
|
||||
|
||||
|
||||
@opds.route("/opds/unreadbooks")
|
||||
@requires_basic_auth_if_no_ano
|
||||
def feed_unread_books():
|
||||
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)
|
||||
@@ -0,0 +1,75 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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
|
||||
#
|
||||
# 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 math import ceil
|
||||
|
||||
|
||||
# simple pagination for the feed
|
||||
class Pagination(object):
|
||||
def __init__(self, page, per_page, total_count):
|
||||
self.page = int(page)
|
||||
self.per_page = int(per_page)
|
||||
self.total_count = int(total_count)
|
||||
|
||||
@property
|
||||
def next_offset(self):
|
||||
return int(self.page * self.per_page)
|
||||
|
||||
@property
|
||||
def previous_offset(self):
|
||||
return int((self.page - 2) * self.per_page)
|
||||
|
||||
@property
|
||||
def last_offset(self):
|
||||
last = int(self.total_count) - int(self.per_page)
|
||||
if last < 0:
|
||||
last = 0
|
||||
return int(last)
|
||||
|
||||
@property
|
||||
def pages(self):
|
||||
return int(ceil(self.total_count / float(self.per_page)))
|
||||
|
||||
@property
|
||||
def has_prev(self):
|
||||
return self.page > 1
|
||||
|
||||
@property
|
||||
def has_next(self):
|
||||
return self.page < self.pages
|
||||
|
||||
# right_edge: last right_edges count of all pages are shown as number, means, if 10 pages are paginated -> 9,10 shwn
|
||||
# left_edge: first left_edges count of all pages are shown as number -> 1,2 shwn
|
||||
# left_current: left_current count below current page are shown as number, means if current page 5 -> 3,4 shwn
|
||||
# left_current: right_current count above current page are shown as number, means if current page 5 -> 6,7 shwn
|
||||
def iter_pages(self, left_edge=2, left_current=2,
|
||||
right_current=4, right_edge=2):
|
||||
last = 0
|
||||
left_current = self.page - left_current - 1
|
||||
right_current = self.page + right_current + 1
|
||||
right_edge = self.pages - right_edge
|
||||
for num in range(1, (self.pages + 1)):
|
||||
if num <= left_edge or (left_current < num < right_current) or num > right_edge:
|
||||
if last + 1 != num:
|
||||
yield None
|
||||
yield num
|
||||
last = num
|
||||
+3
-5
@@ -1,4 +1,3 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Flask License
|
||||
@@ -28,10 +27,9 @@
|
||||
|
||||
# http://flask.pocoo.org/snippets/62/
|
||||
|
||||
try:
|
||||
from urllib.parse import urlparse, urljoin
|
||||
except ImportError:
|
||||
from urlparse import urlparse, urljoin
|
||||
from urllib.parse import urlparse, urljoin
|
||||
|
||||
|
||||
from flask import request, url_for, redirect
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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
|
||||
#
|
||||
# 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 json
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, request, make_response, abort, url_for, flash, redirect
|
||||
from flask_login import login_required, current_user, login_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
|
||||
|
||||
try:
|
||||
from functools import wraps
|
||||
except ImportError:
|
||||
pass # We're not using Python 3
|
||||
|
||||
remotelogin = Blueprint('remotelogin', __name__)
|
||||
log = logger.create()
|
||||
|
||||
|
||||
def remote_login_required(f):
|
||||
@wraps(f)
|
||||
def inner(*args, **kwargs):
|
||||
if config.config_remote_login:
|
||||
return f(*args, **kwargs)
|
||||
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
|
||||
data = {'status': 'error', 'message': 'Forbidden'}
|
||||
response = make_response(json.dumps(data, ensure_ascii=False))
|
||||
response.headers["Content-Type"] = "application/json; charset=utf-8"
|
||||
return response, 403
|
||||
abort(403)
|
||||
|
||||
return inner
|
||||
|
||||
@remotelogin.route('/remote/login')
|
||||
@remote_login_required
|
||||
def remote_login():
|
||||
auth_token = ub.RemoteAuthToken()
|
||||
ub.session.add(auth_token)
|
||||
ub.session_commit()
|
||||
verify_url = url_for('remotelogin.verify_token', token=auth_token.auth_token, _external=true)
|
||||
log.debug(u"Remot Login request with token: %s", auth_token.auth_token)
|
||||
return render_title_template('remote_login.html', title=_(u"Login"), token=auth_token.auth_token,
|
||||
verify_url=verify_url, page="remotelogin")
|
||||
|
||||
|
||||
@remotelogin.route('/verify/<token>')
|
||||
@remote_login_required
|
||||
@login_required
|
||||
def verify_token(token):
|
||||
auth_token = ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.auth_token == token).first()
|
||||
|
||||
# Token not found
|
||||
if auth_token is None:
|
||||
flash(_(u"Token not found"), category="error")
|
||||
log.error(u"Remote Login token not found")
|
||||
return redirect(url_for('web.index'))
|
||||
|
||||
# Token expired
|
||||
elif datetime.now() > auth_token.expiration:
|
||||
ub.session.delete(auth_token)
|
||||
ub.session_commit()
|
||||
|
||||
flash(_(u"Token has expired"), category="error")
|
||||
log.error(u"Remote Login token expired")
|
||||
return redirect(url_for('web.index'))
|
||||
|
||||
# Update token with user information
|
||||
auth_token.user_id = current_user.id
|
||||
auth_token.verified = True
|
||||
ub.session_commit()
|
||||
|
||||
flash(_(u"Success! Please return to your device"), category="success")
|
||||
log.debug(u"Remote Login token for userid %s verified", auth_token.user_id)
|
||||
return redirect(url_for('web.index'))
|
||||
|
||||
|
||||
@remotelogin.route('/ajax/verify_token', methods=['POST'])
|
||||
@remote_login_required
|
||||
def token_verified():
|
||||
token = request.form['token']
|
||||
auth_token = ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.auth_token == token).first()
|
||||
|
||||
data = {}
|
||||
|
||||
# Token not found
|
||||
if auth_token is None:
|
||||
data['status'] = 'error'
|
||||
data['message'] = _(u"Token not found")
|
||||
|
||||
# Token expired
|
||||
elif datetime.now() > auth_token.expiration:
|
||||
ub.session.delete(auth_token)
|
||||
ub.session_commit()
|
||||
|
||||
data['status'] = 'error'
|
||||
data['message'] = _(u"Token has expired")
|
||||
|
||||
elif not auth_token.verified:
|
||||
data['status'] = 'not_verified'
|
||||
|
||||
else:
|
||||
user = ub.session.query(ub.User).filter(ub.User.id == auth_token.user_id).first()
|
||||
login_user(user)
|
||||
|
||||
ub.session.delete(auth_token)
|
||||
ub.session_commit("User {} logged in via remotelogin, token deleted".format(user.name))
|
||||
|
||||
data['status'] = 'success'
|
||||
log.debug(u"Remote Login for userid %s succeded", user.id)
|
||||
flash(_(u"you are now logged in as: '%(nickname)s'", nickname=user.name), category="success")
|
||||
|
||||
response = make_response(json.dumps(data, ensure_ascii=False))
|
||||
response.headers["Content-Type"] = "application/json; charset=utf-8"
|
||||
|
||||
return response
|
||||
@@ -0,0 +1,122 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2018-2020 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/>.
|
||||
|
||||
from flask import render_template
|
||||
from flask_babel import gettext as _
|
||||
from flask import g
|
||||
from werkzeug.local import LocalProxy
|
||||
from flask_login import current_user
|
||||
|
||||
from . import config, constants, ub, logger, db, calibre_db
|
||||
from .ub import User
|
||||
|
||||
|
||||
log = logger.create()
|
||||
|
||||
def get_sidebar_config(kwargs=None):
|
||||
kwargs = kwargs or []
|
||||
if 'content' in kwargs:
|
||||
content = kwargs['content']
|
||||
content = isinstance(content, (User, LocalProxy)) and not content.role_anonymous()
|
||||
else:
|
||||
content = 'conf' in kwargs
|
||||
sidebar = list()
|
||||
sidebar.append({"glyph": "glyphicon-book", "text": _('Books'), "link": 'web.index', "id": "new",
|
||||
"visibility": constants.SIDEBAR_RECENT, 'public': True, "page": "root",
|
||||
"show_text": _('Show recent books'), "config_show":False})
|
||||
sidebar.append({"glyph": "glyphicon-fire", "text": _('Hot Books'), "link": 'web.books_list', "id": "hot",
|
||||
"visibility": constants.SIDEBAR_HOT, 'public': True, "page": "hot",
|
||||
"show_text": _('Show Hot Books'), "config_show": True})
|
||||
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 g.user.is_anonymous),
|
||||
"page": "download", "show_text": _('Show Downloaded Books'),
|
||||
"config_show": content})
|
||||
else:
|
||||
sidebar.append({"glyph": "glyphicon-download", "text": _('Downloaded Books'), "link": 'web.books_list',
|
||||
"id": "download", "visibility": constants.SIDEBAR_DOWNLOAD, 'public': (not g.user.is_anonymous),
|
||||
"page": "download", "show_text": _('Show Downloaded Books'),
|
||||
"config_show": content})
|
||||
sidebar.append(
|
||||
{"glyph": "glyphicon-star", "text": _('Top Rated Books'), "link": 'web.books_list', "id": "rated",
|
||||
"visibility": constants.SIDEBAR_BEST_RATED, 'public': True, "page": "rated",
|
||||
"show_text": _('Show Top Rated Books'), "config_show": True})
|
||||
sidebar.append({"glyph": "glyphicon-eye-open", "text": _('Read Books'), "link": 'web.books_list', "id": "read",
|
||||
"visibility": constants.SIDEBAR_READ_AND_UNREAD, 'public': (not g.user.is_anonymous),
|
||||
"page": "read", "show_text": _('Show read and unread'), "config_show": content})
|
||||
sidebar.append(
|
||||
{"glyph": "glyphicon-eye-close", "text": _('Unread Books'), "link": 'web.books_list', "id": "unread",
|
||||
"visibility": constants.SIDEBAR_READ_AND_UNREAD, 'public': (not g.user.is_anonymous), "page": "unread",
|
||||
"show_text": _('Show unread'), "config_show": False})
|
||||
sidebar.append({"glyph": "glyphicon-random", "text": _('Discover'), "link": 'web.books_list', "id": "rand",
|
||||
"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",
|
||||
"show_text": _('Show category selection'), "config_show": True})
|
||||
sidebar.append({"glyph": "glyphicon-bookmark", "text": _('Series'), "link": 'web.series_list', "id": "serie",
|
||||
"visibility": constants.SIDEBAR_SERIES, 'public': True, "page": "series",
|
||||
"show_text": _('Show series selection'), "config_show": True})
|
||||
sidebar.append({"glyph": "glyphicon-user", "text": _('Authors'), "link": 'web.author_list', "id": "author",
|
||||
"visibility": constants.SIDEBAR_AUTHOR, 'public': True, "page": "author",
|
||||
"show_text": _('Show author selection'), "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",
|
||||
"show_text": _('Show publisher selection'), "config_show":True})
|
||||
sidebar.append({"glyph": "glyphicon-flag", "text": _('Languages'), "link": 'web.language_overview', "id": "lang",
|
||||
"visibility": constants.SIDEBAR_LANGUAGE, 'public': (g.user.filter_language() == 'all'),
|
||||
"page": "language",
|
||||
"show_text": _('Show language selection'), "config_show": True})
|
||||
sidebar.append({"glyph": "glyphicon-star-empty", "text": _('Ratings'), "link": 'web.ratings_list', "id": "rate",
|
||||
"visibility": constants.SIDEBAR_RATING, 'public': True,
|
||||
"page": "rating", "show_text": _('Show ratings selection'), "config_show": True})
|
||||
sidebar.append({"glyph": "glyphicon-file", "text": _('File formats'), "link": 'web.formats_list', "id": "format",
|
||||
"visibility": constants.SIDEBAR_FORMAT, 'public': True,
|
||||
"page": "format", "show_text": _('Show file formats selection'), "config_show": True})
|
||||
sidebar.append(
|
||||
{"glyph": "glyphicon-trash", "text": _('Archived Books'), "link": 'web.books_list', "id": "archived",
|
||||
"visibility": constants.SIDEBAR_ARCHIVED, 'public': (not g.user.is_anonymous), "page": "archived",
|
||||
"show_text": _('Show archived books'), "config_show": content})
|
||||
sidebar.append(
|
||||
{"glyph": "glyphicon-th-list", "text": _('Books List'), "link": 'web.books_table', "id": "list",
|
||||
"visibility": constants.SIDEBAR_LIST, 'public': (not g.user.is_anonymous), "page": "list",
|
||||
"show_text": _('Show Books List'), "config_show": content})
|
||||
|
||||
return sidebar
|
||||
|
||||
def get_readbooks_ids():
|
||||
if not config.config_read_column:
|
||||
readBooks = ub.session.query(ub.ReadBook).filter(ub.ReadBook.user_id == int(current_user.id))\
|
||||
.filter(ub.ReadBook.read_status == ub.ReadBook.STATUS_FINISHED).all()
|
||||
return frozenset([x.book_id for x in readBooks])
|
||||
else:
|
||||
try:
|
||||
readBooks = calibre_db.session.query(db.cc_classes[config.config_read_column])\
|
||||
.filter(db.cc_classes[config.config_read_column].value == True).all()
|
||||
return frozenset([x.book for x in readBooks])
|
||||
except (KeyError, AttributeError):
|
||||
log.error("Custom Column No.%d is not existing in calibre database", config.config_read_column)
|
||||
return []
|
||||
|
||||
# Returns the template for rendering and includes the instance name
|
||||
def render_title_template(*args, **kwargs):
|
||||
sidebar = get_sidebar_config(kwargs)
|
||||
return render_template(instance=config.config_calibre_web_title, sidebar=sidebar,
|
||||
accept=constants.EXTENSIONS_UPLOAD, read_book_ids=get_readbooks_ids(),
|
||||
*args, **kwargs)
|
||||
+9
-1
@@ -1,4 +1,3 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Flask License
|
||||
@@ -37,6 +36,7 @@
|
||||
#
|
||||
# Inspired by http://flask.pocoo.org/snippets/35/
|
||||
|
||||
|
||||
class ReverseProxied(object):
|
||||
"""Wrap the application in this middleware and configure the
|
||||
front-end server to add these headers, to let you quietly bind
|
||||
@@ -57,10 +57,13 @@ class ReverseProxied(object):
|
||||
|
||||
def __init__(self, application):
|
||||
self.app = application
|
||||
self.proxied = False
|
||||
|
||||
def __call__(self, environ, start_response):
|
||||
self.proxied = False
|
||||
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', '')
|
||||
if path_info and path_info.startswith(script_name):
|
||||
@@ -72,4 +75,9 @@ class ReverseProxied(object):
|
||||
servr = environ.get('HTTP_X_FORWARDED_HOST', '')
|
||||
if servr:
|
||||
environ['HTTP_HOST'] = servr
|
||||
self.proxied = True
|
||||
return self.app(environ, start_response)
|
||||
|
||||
@property
|
||||
def is_proxied(self):
|
||||
return self.proxied
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2021 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 os
|
||||
import json
|
||||
import importlib
|
||||
import sys
|
||||
import inspect
|
||||
import datetime
|
||||
import concurrent.futures
|
||||
|
||||
from flask import Blueprint, request, Response, url_for
|
||||
from flask_login import current_user
|
||||
from flask_login import login_required
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
from sqlalchemy.exc import OperationalError, InvalidRequestError
|
||||
|
||||
from . import constants, logger, ub
|
||||
from cps.services.Metadata import Metadata
|
||||
|
||||
|
||||
meta = Blueprint('metadata', __name__)
|
||||
|
||||
log = logger.create()
|
||||
|
||||
new_list = list()
|
||||
meta_dir = os.path.join(constants.BASE_DIR, "cps", "metadata_provider")
|
||||
modules = os.listdir(os.path.join(constants.BASE_DIR, "cps", "metadata_provider"))
|
||||
for f in modules:
|
||||
if os.path.isfile(os.path.join(meta_dir, f)) and not f.endswith('__init__.py'):
|
||||
a = os.path.basename(f)[:-3]
|
||||
try:
|
||||
importlib.import_module("cps.metadata_provider." + a)
|
||||
new_list.append(a)
|
||||
except ImportError:
|
||||
log.error("Import error for metadata source: {}".format(a))
|
||||
pass
|
||||
|
||||
def list_classes(provider_list):
|
||||
classes = list()
|
||||
for element in provider_list:
|
||||
for name, obj in inspect.getmembers(sys.modules["cps.metadata_provider." + element]):
|
||||
if inspect.isclass(obj) and name != "Metadata" and issubclass(obj, Metadata):
|
||||
classes.append(obj())
|
||||
return classes
|
||||
|
||||
cl = list_classes(new_list)
|
||||
|
||||
@meta.route("/metadata/provider")
|
||||
@login_required
|
||||
def metadata_provider():
|
||||
active = current_user.view_settings.get('metadata', {})
|
||||
provider = list()
|
||||
for c in cl:
|
||||
ac = active.get(c.__id__, True)
|
||||
provider.append({"name": c.__name__, "active": ac, "initial": ac, "id": c.__id__})
|
||||
return Response(json.dumps(provider), mimetype='application/json')
|
||||
|
||||
@meta.route("/metadata/provider", methods=['POST'])
|
||||
@meta.route("/metadata/provider/<prov_name>", methods=['POST'])
|
||||
@login_required
|
||||
def metadata_change_active_provider(prov_name):
|
||||
new_state = request.get_json()
|
||||
active = current_user.view_settings.get('metadata', {})
|
||||
active[new_state['id']] = new_state['value']
|
||||
current_user.view_settings['metadata'] = active
|
||||
try:
|
||||
try:
|
||||
flag_modified(current_user, "view_settings")
|
||||
except AttributeError:
|
||||
pass
|
||||
ub.session.commit()
|
||||
except (InvalidRequestError, OperationalError):
|
||||
log.error("Invalid request received: {}".format(request))
|
||||
return "Invalid request", 400
|
||||
if "initial" in new_state and prov_name:
|
||||
for c in cl:
|
||||
if c.__id__ == prov_name:
|
||||
data = c.search(new_state.get('query', ""))
|
||||
break
|
||||
return Response(json.dumps(data), mimetype='application/json')
|
||||
return ""
|
||||
|
||||
@meta.route("/metadata/search", methods=['POST'])
|
||||
@login_required
|
||||
def metadata_search():
|
||||
query = request.form.to_dict().get('query')
|
||||
data = list()
|
||||
active = current_user.view_settings.get('metadata', {})
|
||||
if query:
|
||||
generic_cover = ""
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
|
||||
meta = {executor.submit(c.search, query, generic_cover): c for c in cl if active.get(c.__id__, True)}
|
||||
for future in concurrent.futures.as_completed(meta):
|
||||
data.extend(future.result())
|
||||
return Response(json.dumps(data), mimetype='application/json')
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+235
-122
@@ -1,4 +1,3 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
@@ -17,149 +16,263 @@
|
||||
# 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 socket import error as SocketError
|
||||
import sys
|
||||
import os
|
||||
import errno
|
||||
import signal
|
||||
import web
|
||||
import socket
|
||||
import subprocess # nosec
|
||||
|
||||
try:
|
||||
from gevent.pywsgi import WSGIServer
|
||||
from gevent.pool import Pool
|
||||
from gevent import __version__ as geventVersion
|
||||
gevent_present = True
|
||||
from gevent import __version__ as _version
|
||||
from greenlet import GreenletExit
|
||||
import ssl
|
||||
VERSION = 'Gevent ' + _version
|
||||
_GEVENT = True
|
||||
except ImportError:
|
||||
from tornado.wsgi import WSGIContainer
|
||||
from tornado.httpserver import HTTPServer
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado import version as tornadoVersion
|
||||
gevent_present = False
|
||||
from tornado import version as _version
|
||||
VERSION = 'Tornado ' + _version
|
||||
_GEVENT = False
|
||||
|
||||
from . import logger
|
||||
|
||||
|
||||
log = logger.create()
|
||||
|
||||
class server:
|
||||
|
||||
wsgiserver = None
|
||||
restart= False
|
||||
def _readable_listen_address(address, port):
|
||||
if ':' in address:
|
||||
address = "[" + address + "]"
|
||||
return '%s:%s' % (address, port)
|
||||
|
||||
|
||||
class WebServer(object):
|
||||
|
||||
def __init__(self):
|
||||
signal.signal(signal.SIGINT, self.killServer)
|
||||
signal.signal(signal.SIGTERM, self.killServer)
|
||||
signal.signal(signal.SIGINT, self._killServer)
|
||||
signal.signal(signal.SIGTERM, self._killServer)
|
||||
|
||||
self.wsgiserver = None
|
||||
self.access_logger = None
|
||||
self.restart = False
|
||||
self.app = None
|
||||
self.listen_address = None
|
||||
self.listen_port = None
|
||||
self.unix_socket_file = None
|
||||
self.ssl_args = None
|
||||
|
||||
def init_app(self, application, config):
|
||||
self.app = application
|
||||
self.listen_address = config.get_config_ipaddress()
|
||||
self.listen_port = config.config_port
|
||||
|
||||
if config.config_access_log:
|
||||
log_name = "gevent.access" if _GEVENT else "tornado.access"
|
||||
formatter = logger.ACCESS_FORMATTER_GEVENT if _GEVENT else logger.ACCESS_FORMATTER_TORNADO
|
||||
self.access_logger, logfile = logger.create_access_log(config.config_access_logfile, log_name, formatter)
|
||||
if logfile != config.config_access_logfile:
|
||||
log.warning("Accesslog path %s not valid, falling back to default", config.config_access_logfile)
|
||||
config.config_access_logfile = logfile
|
||||
config.save()
|
||||
else:
|
||||
if not _GEVENT:
|
||||
logger.get('tornado.access').disabled = True
|
||||
|
||||
certfile_path = config.get_config_certfile()
|
||||
keyfile_path = config.get_config_keyfile()
|
||||
if certfile_path and keyfile_path:
|
||||
if os.path.isfile(certfile_path) and os.path.isfile(keyfile_path):
|
||||
self.ssl_args = dict(certfile=certfile_path, keyfile=keyfile_path)
|
||||
else:
|
||||
log.warning('The specified paths for the ssl certificate file and/or key file seem to be broken. '
|
||||
'Ignoring ssl.')
|
||||
log.warning('Cert path: %s', certfile_path)
|
||||
log.warning('Key path: %s', keyfile_path)
|
||||
|
||||
def _make_gevent_unix_socket(self, socket_file):
|
||||
# the socket file must not exist prior to bind()
|
||||
if os.path.exists(socket_file):
|
||||
# avoid nuking regular files and symbolic links (could be a mistype or security issue)
|
||||
if os.path.isfile(socket_file) or os.path.islink(socket_file):
|
||||
raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), socket_file)
|
||||
os.remove(socket_file)
|
||||
|
||||
unix_sock = WSGIServer.get_listener(socket_file, family=socket.AF_UNIX)
|
||||
self.unix_socket_file = socket_file
|
||||
|
||||
# ensure current user and group have r/w permissions, no permissions for other users
|
||||
# this way the socket can be shared in a semi-secure manner
|
||||
# between the user running calibre-web and the user running the fronting webserver
|
||||
os.chmod(socket_file, 0o660)
|
||||
|
||||
return unix_sock
|
||||
|
||||
def _make_gevent_socket(self):
|
||||
if os.name != 'nt':
|
||||
unix_socket_file = os.environ.get("CALIBRE_UNIX_SOCKET")
|
||||
if unix_socket_file:
|
||||
return self._make_gevent_unix_socket(unix_socket_file), "unix:" + unix_socket_file
|
||||
|
||||
if self.listen_address:
|
||||
return (self.listen_address, self.listen_port), None
|
||||
|
||||
if os.name == 'nt':
|
||||
self.listen_address = '0.0.0.0'
|
||||
return (self.listen_address, self.listen_port), None
|
||||
|
||||
def start_gevent(self):
|
||||
try:
|
||||
ssl_args = dict()
|
||||
certfile_path = web.ub.config.get_config_certfile()
|
||||
keyfile_path = web.ub.config.get_config_keyfile()
|
||||
if certfile_path and keyfile_path:
|
||||
if os.path.isfile(certfile_path) and os.path.isfile(keyfile_path):
|
||||
ssl_args = {"certfile": certfile_path,
|
||||
"keyfile": keyfile_path}
|
||||
else:
|
||||
web.app.logger.info('The specified paths for the ssl certificate file and/or key file seem to be broken. Ignoring ssl. Cert path: %s | Key path: %s' % (certfile_path, keyfile_path))
|
||||
if os.name == 'nt':
|
||||
self.wsgiserver= WSGIServer(('0.0.0.0', web.ub.config.config_port), web.app, spawn=Pool(), **ssl_args)
|
||||
else:
|
||||
self.wsgiserver = WSGIServer(('', web.ub.config.config_port), web.app, spawn=Pool(), **ssl_args)
|
||||
web.py3_gevent_link = self.wsgiserver
|
||||
self.wsgiserver.serve_forever()
|
||||
address = ('::', self.listen_port)
|
||||
sock = WSGIServer.get_listener(address, family=socket.AF_INET6)
|
||||
except socket.error as ex:
|
||||
log.error('%s', ex)
|
||||
log.warning('Unable to listen on "", trying on IPv4 only...')
|
||||
address = ('', self.listen_port)
|
||||
sock = WSGIServer.get_listener(address, family=socket.AF_INET)
|
||||
|
||||
except SocketError:
|
||||
try:
|
||||
web.app.logger.info('Unable to listen on \'\', trying on IPv4 only...')
|
||||
self.wsgiserver = WSGIServer(('0.0.0.0', web.ub.config.config_port), web.app, spawn=Pool(), **ssl_args)
|
||||
web.py3_gevent_link = self.wsgiserver
|
||||
self.wsgiserver.serve_forever()
|
||||
except (OSError, SocketError) as e:
|
||||
web.app.logger.info("Error starting server: %s" % e.strerror)
|
||||
print("Error starting server: %s" % e.strerror)
|
||||
web.helper.global_WorkerThread.stop()
|
||||
sys.exit(1)
|
||||
except Exception:
|
||||
web.app.logger.info("Unknown error while starting gevent")
|
||||
|
||||
def startServer(self):
|
||||
if gevent_present:
|
||||
web.app.logger.info('Starting Gevent server')
|
||||
# leave subprocess out to allow forking for fetchers and processors
|
||||
self.start_gevent()
|
||||
else:
|
||||
try:
|
||||
ssl = None
|
||||
web.app.logger.info('Starting Tornado server')
|
||||
certfile_path = web.ub.config.get_config_certfile()
|
||||
keyfile_path = web.ub.config.get_config_keyfile()
|
||||
if certfile_path and keyfile_path:
|
||||
if os.path.isfile(certfile_path) and os.path.isfile(keyfile_path):
|
||||
ssl = {"certfile": certfile_path,
|
||||
"keyfile": keyfile_path}
|
||||
else:
|
||||
web.app.logger.info('The specified paths for the ssl certificate file and/or key file seem to be broken. Ignoring ssl. Cert path: %s | Key path: %s' % (certfile_path, keyfile_path))
|
||||
|
||||
# Max Buffersize set to 200MB
|
||||
http_server = HTTPServer(WSGIContainer(web.app),
|
||||
max_buffer_size = 209700000,
|
||||
ssl_options=ssl)
|
||||
http_server.listen(web.ub.config.config_port)
|
||||
self.wsgiserver=IOLoop.instance()
|
||||
web.py3_gevent_link = self.wsgiserver
|
||||
self.wsgiserver.start()
|
||||
# wait for stop signal
|
||||
self.wsgiserver.close(True)
|
||||
except SocketError as e:
|
||||
web.app.logger.info("Error starting server: %s" % e.strerror)
|
||||
print("Error starting server: %s" % e.strerror)
|
||||
web.helper.global_WorkerThread.stop()
|
||||
sys.exit(1)
|
||||
|
||||
# ToDo: Somehow caused by circular import under python3 refactor
|
||||
if sys.version_info > (3, 0):
|
||||
self.restart = web.py3_restart_Typ
|
||||
if self.restart == True:
|
||||
web.app.logger.info("Performing restart of Calibre-Web")
|
||||
web.helper.global_WorkerThread.stop()
|
||||
if os.name == 'nt':
|
||||
arguments = ["\"" + sys.executable + "\""]
|
||||
for e in sys.argv:
|
||||
arguments.append("\"" + e + "\"")
|
||||
os.execv(sys.executable, arguments)
|
||||
else:
|
||||
os.execl(sys.executable, sys.executable, *sys.argv)
|
||||
else:
|
||||
web.app.logger.info("Performing shutdown of Calibre-Web")
|
||||
web.helper.global_WorkerThread.stop()
|
||||
sys.exit(0)
|
||||
|
||||
def setRestartTyp(self,starttyp):
|
||||
self.restart = starttyp
|
||||
# ToDo: Somehow caused by circular import under python3 refactor
|
||||
web.py3_restart_Typ = starttyp
|
||||
|
||||
def killServer(self, signum, frame):
|
||||
self.stopServer()
|
||||
|
||||
def stopServer(self):
|
||||
# ToDo: Somehow caused by circular import under python3 refactor
|
||||
if sys.version_info > (3, 0):
|
||||
if not self.wsgiserver:
|
||||
# if gevent_present:
|
||||
self.wsgiserver = web.py3_gevent_link
|
||||
#else:
|
||||
# self.wsgiserver = IOLoop.instance()
|
||||
if self.wsgiserver:
|
||||
if gevent_present:
|
||||
self.wsgiserver.close()
|
||||
else:
|
||||
self.wsgiserver.add_callback(self.wsgiserver.stop)
|
||||
return sock, _readable_listen_address(*address)
|
||||
|
||||
@staticmethod
|
||||
def getNameVersion():
|
||||
if gevent_present:
|
||||
return {'Gevent':'v'+geventVersion}
|
||||
def _get_args_for_reloading():
|
||||
"""Determine how the script was executed, and return the args needed
|
||||
to execute it again in a new process.
|
||||
Code from https://github.com/pyload/pyload. Author GammaC0de, voulter
|
||||
"""
|
||||
rv = [sys.executable]
|
||||
py_script = sys.argv[0]
|
||||
args = sys.argv[1:]
|
||||
# Need to look at main module to determine how it was executed.
|
||||
__main__ = sys.modules["__main__"]
|
||||
|
||||
# The value of __package__ indicates how Python was called. It may
|
||||
# not exist if a setuptools script is installed as an egg. It may be
|
||||
# set incorrectly for entry points created with pip on Windows.
|
||||
if getattr(__main__, "__package__", None) is None or (
|
||||
os.name == "nt"
|
||||
and __main__.__package__ == ""
|
||||
and not os.path.exists(py_script)
|
||||
and os.path.exists("{}.exe".format(py_script))
|
||||
):
|
||||
# Executed a file, like "python app.py".
|
||||
py_script = os.path.abspath(py_script)
|
||||
|
||||
if os.name == "nt":
|
||||
# Windows entry points have ".exe" extension and should be
|
||||
# called directly.
|
||||
if not os.path.exists(py_script) and os.path.exists("{}.exe".format(py_script)):
|
||||
py_script += ".exe"
|
||||
|
||||
if (
|
||||
os.path.splitext(sys.executable)[1] == ".exe"
|
||||
and os.path.splitext(py_script)[1] == ".exe"
|
||||
):
|
||||
rv.pop(0)
|
||||
|
||||
rv.append(py_script)
|
||||
else:
|
||||
return {'Tornado':'v'+tornadoVersion}
|
||||
# Executed a module, like "python -m module".
|
||||
if sys.argv[0] == "-m":
|
||||
args = sys.argv
|
||||
else:
|
||||
if os.path.isfile(py_script):
|
||||
# Rewritten by Python from "-m script" to "/path/to/script.py".
|
||||
py_module = __main__.__package__
|
||||
name = os.path.splitext(os.path.basename(py_script))[0]
|
||||
|
||||
if name != "__main__":
|
||||
py_module += ".{}".format(name)
|
||||
else:
|
||||
# Incorrectly rewritten by pydevd debugger from "-m script" to "script".
|
||||
py_module = py_script
|
||||
|
||||
# Start Instance of Server
|
||||
Server=server()
|
||||
rv.extend(("-m", py_module.lstrip(".")))
|
||||
|
||||
rv.extend(args)
|
||||
return rv
|
||||
|
||||
def _start_gevent(self):
|
||||
ssl_args = self.ssl_args or {}
|
||||
|
||||
try:
|
||||
sock, output = self._make_gevent_socket()
|
||||
if output is None:
|
||||
output = _readable_listen_address(self.listen_address, self.listen_port)
|
||||
log.info('Starting Gevent server on %s', output)
|
||||
self.wsgiserver = WSGIServer(sock, self.app, log=self.access_logger, spawn=Pool(), **ssl_args)
|
||||
if ssl_args:
|
||||
wrap_socket = self.wsgiserver.wrap_socket
|
||||
def my_wrap_socket(*args, **kwargs):
|
||||
try:
|
||||
return wrap_socket(*args, **kwargs)
|
||||
except (ssl.SSLError, OSError) as ex:
|
||||
log.warning('Gevent SSL Error: %s', ex)
|
||||
raise GreenletExit
|
||||
|
||||
self.wsgiserver.wrap_socket = my_wrap_socket
|
||||
self.wsgiserver.serve_forever()
|
||||
finally:
|
||||
if self.unix_socket_file:
|
||||
os.remove(self.unix_socket_file)
|
||||
self.unix_socket_file = None
|
||||
|
||||
def _start_tornado(self):
|
||||
if os.name == 'nt' and sys.version_info > (3, 7):
|
||||
import asyncio
|
||||
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||||
log.info('Starting Tornado server on %s', _readable_listen_address(self.listen_address, self.listen_port))
|
||||
|
||||
# Max Buffersize set to 200MB )
|
||||
http_server = HTTPServer(WSGIContainer(self.app),
|
||||
max_buffer_size=209700000,
|
||||
ssl_options=self.ssl_args)
|
||||
http_server.listen(self.listen_port, self.listen_address)
|
||||
self.wsgiserver = IOLoop.current()
|
||||
self.wsgiserver.start()
|
||||
# wait for stop signal
|
||||
self.wsgiserver.close(True)
|
||||
|
||||
def start(self):
|
||||
try:
|
||||
if _GEVENT:
|
||||
# leave subprocess out to allow forking for fetchers and processors
|
||||
self._start_gevent()
|
||||
else:
|
||||
self._start_tornado()
|
||||
except Exception as ex:
|
||||
log.error("Error starting server: %s", ex)
|
||||
print("Error starting server: %s" % ex)
|
||||
self.stop()
|
||||
return False
|
||||
finally:
|
||||
self.wsgiserver = None
|
||||
|
||||
# prevent irritating log of pending tasks message from asyncio
|
||||
logger.get('asyncio').setLevel(logger.logging.CRITICAL)
|
||||
|
||||
if not self.restart:
|
||||
log.info("Performing shutdown of Calibre-Web")
|
||||
return True
|
||||
|
||||
log.info("Performing restart of Calibre-Web")
|
||||
args = self._get_args_for_reloading()
|
||||
subprocess.call(args, close_fds=True) # nosec
|
||||
return True
|
||||
|
||||
def _killServer(self, __, ___):
|
||||
self.stop()
|
||||
|
||||
def stop(self, restart=False):
|
||||
from . import updater_thread
|
||||
updater_thread.stop()
|
||||
|
||||
log.info("webserver stop (restart=%s)", restart)
|
||||
self.restart = restart
|
||||
if self.wsgiserver:
|
||||
if _GEVENT:
|
||||
self.wsgiserver.close()
|
||||
else:
|
||||
self.wsgiserver.add_callback_from_signal(self.wsgiserver.stop)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2021 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/>.
|
||||
|
||||
|
||||
class Metadata():
|
||||
__name__ = "Generic"
|
||||
|
||||
def __init__(self):
|
||||
self.active = True
|
||||
|
||||
def set_status(self, state):
|
||||
self.active = state
|
||||
@@ -0,0 +1,187 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2018-2019 shavitmichael, 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 sys
|
||||
from base64 import b64decode, b64encode
|
||||
from jsonschema import validate, exceptions, __version__
|
||||
from datetime import datetime
|
||||
|
||||
from urllib.parse import unquote
|
||||
|
||||
from flask import json
|
||||
from .. import logger
|
||||
|
||||
|
||||
log = logger.create()
|
||||
|
||||
|
||||
def b64encode_json(json_data):
|
||||
return b64encode(json.dumps(json_data).encode())
|
||||
|
||||
|
||||
# Python3 has a timestamp() method we could be calling, however it's not avaiable in python2.
|
||||
def to_epoch_timestamp(datetime_object):
|
||||
return (datetime_object - datetime(1970, 1, 1)).total_seconds()
|
||||
|
||||
|
||||
def get_datetime_from_json(json_object, field_name):
|
||||
try:
|
||||
return datetime.utcfromtimestamp(json_object[field_name])
|
||||
except (KeyError, OSError, OverflowError):
|
||||
# OSError is thrown on Windows if timestamp is <1970 or >2038
|
||||
return datetime.min
|
||||
|
||||
|
||||
class SyncToken:
|
||||
""" The SyncToken is used to persist state accross requests.
|
||||
When serialized over the response headers, the Kobo device will propagate the token onto following
|
||||
requests to the service. As an example use-case, the SyncToken is used to detect books that have been added
|
||||
to the library since the last time the device synced to the server.
|
||||
|
||||
Attributes:
|
||||
books_last_created: Datetime representing the newest book that the device knows about.
|
||||
books_last_modified: Datetime representing the last modified book that the device knows about.
|
||||
"""
|
||||
|
||||
SYNC_TOKEN_HEADER = "x-kobo-synctoken" # nosec
|
||||
VERSION = "1-1-0"
|
||||
LAST_MODIFIED_ADDED_VERSION = "1-1-0"
|
||||
MIN_VERSION = "1-0-0"
|
||||
|
||||
token_schema = {
|
||||
"type": "object",
|
||||
"properties": {"version": {"type": "string"}, "data": {"type": "object"}, },
|
||||
}
|
||||
# This Schema doesn't contain enough information to detect and propagate book deletions from Calibre to the device.
|
||||
# A potential solution might be to keep a list of all known book uuids in the token, and look for any missing
|
||||
# from the db.
|
||||
data_schema_v1 = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"raw_kobo_store_token": {"type": "string"},
|
||||
"books_last_modified": {"type": "string"},
|
||||
"books_last_created": {"type": "string"},
|
||||
"archive_last_modified": {"type": "string"},
|
||||
"reading_state_last_modified": {"type": "string"},
|
||||
"tags_last_modified": {"type": "string"}
|
||||
# "books_last_id": {"type": "integer", "optional": True}
|
||||
},
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
raw_kobo_store_token="",
|
||||
books_last_created=datetime.min,
|
||||
books_last_modified=datetime.min,
|
||||
archive_last_modified=datetime.min,
|
||||
reading_state_last_modified=datetime.min,
|
||||
tags_last_modified=datetime.min
|
||||
# books_last_id=-1
|
||||
): # nosec
|
||||
self.raw_kobo_store_token = raw_kobo_store_token
|
||||
self.books_last_created = books_last_created
|
||||
self.books_last_modified = books_last_modified
|
||||
self.archive_last_modified = archive_last_modified
|
||||
self.reading_state_last_modified = reading_state_last_modified
|
||||
self.tags_last_modified = tags_last_modified
|
||||
# self.books_last_id = books_last_id
|
||||
|
||||
@staticmethod
|
||||
def from_headers(headers):
|
||||
sync_token_header = headers.get(SyncToken.SYNC_TOKEN_HEADER, "")
|
||||
if sync_token_header == "": # nosec
|
||||
return SyncToken()
|
||||
|
||||
# On the first sync from a Kobo device, we may receive the SyncToken
|
||||
# from the official Kobo store. Without digging too deep into it, that
|
||||
# token is of the form [b64encoded blob].[b64encoded blob 2]
|
||||
if "." in sync_token_header:
|
||||
return SyncToken(raw_kobo_store_token=sync_token_header)
|
||||
|
||||
try:
|
||||
sync_token_json = json.loads(
|
||||
b64decode(sync_token_header + "=" * (-len(sync_token_header) % 4))
|
||||
)
|
||||
validate(sync_token_json, SyncToken.token_schema)
|
||||
if sync_token_json["version"] < SyncToken.MIN_VERSION:
|
||||
raise ValueError
|
||||
|
||||
data_json = sync_token_json["data"]
|
||||
validate(sync_token_json, SyncToken.data_schema_v1)
|
||||
except (exceptions.ValidationError, ValueError):
|
||||
log.error("Sync token contents do not follow the expected json schema.")
|
||||
return SyncToken()
|
||||
|
||||
raw_kobo_store_token = data_json["raw_kobo_store_token"]
|
||||
try:
|
||||
books_last_modified = get_datetime_from_json(data_json, "books_last_modified")
|
||||
books_last_created = get_datetime_from_json(data_json, "books_last_created")
|
||||
archive_last_modified = get_datetime_from_json(data_json, "archive_last_modified")
|
||||
reading_state_last_modified = get_datetime_from_json(data_json, "reading_state_last_modified")
|
||||
tags_last_modified = get_datetime_from_json(data_json, "tags_last_modified")
|
||||
# books_last_id = data_json["books_last_id"]
|
||||
except TypeError:
|
||||
log.error("SyncToken timestamps don't parse to a datetime.")
|
||||
return SyncToken(raw_kobo_store_token=raw_kobo_store_token)
|
||||
#except KeyError:
|
||||
# books_last_id = -1
|
||||
|
||||
return SyncToken(
|
||||
raw_kobo_store_token=raw_kobo_store_token,
|
||||
books_last_created=books_last_created,
|
||||
books_last_modified=books_last_modified,
|
||||
archive_last_modified=archive_last_modified,
|
||||
reading_state_last_modified=reading_state_last_modified,
|
||||
tags_last_modified=tags_last_modified,
|
||||
#books_last_id=books_last_id
|
||||
)
|
||||
|
||||
def set_kobo_store_header(self, store_headers):
|
||||
store_headers.set(SyncToken.SYNC_TOKEN_HEADER, self.raw_kobo_store_token)
|
||||
|
||||
def merge_from_store_response(self, store_response):
|
||||
self.raw_kobo_store_token = store_response.headers.get(
|
||||
SyncToken.SYNC_TOKEN_HEADER, ""
|
||||
)
|
||||
|
||||
def to_headers(self, headers):
|
||||
headers[SyncToken.SYNC_TOKEN_HEADER] = self.build_sync_token()
|
||||
|
||||
def build_sync_token(self):
|
||||
token = {
|
||||
"version": SyncToken.VERSION,
|
||||
"data": {
|
||||
"raw_kobo_store_token": self.raw_kobo_store_token,
|
||||
"books_last_modified": to_epoch_timestamp(self.books_last_modified),
|
||||
"books_last_created": to_epoch_timestamp(self.books_last_created),
|
||||
"archive_last_modified": to_epoch_timestamp(self.archive_last_modified),
|
||||
"reading_state_last_modified": to_epoch_timestamp(self.reading_state_last_modified),
|
||||
"tags_last_modified": to_epoch_timestamp(self.tags_last_modified),
|
||||
#"books_last_id":self.books_last_id
|
||||
},
|
||||
}
|
||||
return b64encode_json(token)
|
||||
|
||||
def __str__(self):
|
||||
return "{},{},{},{},{},{}".format(self.books_last_created,
|
||||
self.books_last_modified,
|
||||
self.archive_last_modified,
|
||||
self.reading_state_last_modified,
|
||||
self.tags_last_modified, self.raw_kobo_store_token)
|
||||
#self.books_last_id)
|
||||
@@ -0,0 +1,51 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2019 pwr
|
||||
#
|
||||
# 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 .. import logger
|
||||
|
||||
|
||||
log = logger.create()
|
||||
|
||||
|
||||
try: from . import goodreads_support
|
||||
except ImportError as err:
|
||||
log.debug("Cannot import goodreads, showing authors-metadata will not work: %s", err)
|
||||
goodreads_support = None
|
||||
|
||||
|
||||
try:
|
||||
from . import simpleldap as ldap
|
||||
from .simpleldap import ldapVersion
|
||||
except ImportError as err:
|
||||
log.debug("Cannot import simpleldap, logging in with ldap will not work: %s", err)
|
||||
ldap = None
|
||||
ldapVersion = None
|
||||
|
||||
try:
|
||||
from . import SyncToken as SyncToken
|
||||
kobo = True
|
||||
except ImportError as err:
|
||||
log.debug("Cannot import SyncToken, syncing books with Kobo Devices will not work: %s", err)
|
||||
kobo = None
|
||||
SyncToken = None
|
||||
|
||||
try:
|
||||
from . import gmail
|
||||
except ImportError as err:
|
||||
log.debug("Cannot import gmail, sending books via Gmail Oauth2 Verification will not work: %s", err)
|
||||
gmail = None
|
||||
@@ -0,0 +1,100 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2021 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 os.path
|
||||
from google_auth_oauthlib.flow import InstalledAppFlow
|
||||
from google.auth.transport.requests import Request
|
||||
from googleapiclient.discovery import build
|
||||
from google.oauth2.credentials import Credentials
|
||||
|
||||
from datetime import datetime
|
||||
import base64
|
||||
from flask_babel import gettext as _
|
||||
from ..constants import BASE_DIR
|
||||
from .. import logger
|
||||
|
||||
|
||||
log = logger.create()
|
||||
|
||||
SCOPES = ['openid', 'https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/userinfo.email']
|
||||
|
||||
def setup_gmail(token):
|
||||
# If there are no (valid) credentials available, let the user log in.
|
||||
creds = None
|
||||
if "token" in token:
|
||||
creds = Credentials(
|
||||
token=token['token'],
|
||||
refresh_token=token['refresh_token'],
|
||||
token_uri=token['token_uri'],
|
||||
client_id=token['client_id'],
|
||||
client_secret=token['client_secret'],
|
||||
scopes=token['scopes'],
|
||||
)
|
||||
creds.expiry = datetime.fromisoformat(token['expiry'])
|
||||
|
||||
if not creds or not creds.valid:
|
||||
# don't forget to dump one more time after the refresh
|
||||
# also, some file-locking routines wouldn't be needless
|
||||
if creds and creds.expired and creds.refresh_token:
|
||||
creds.refresh(Request())
|
||||
else:
|
||||
cred_file = os.path.join(BASE_DIR, 'gmail.json')
|
||||
if not os.path.exists(cred_file):
|
||||
raise Exception(_("Found no valid gmail.json file with OAuth information"))
|
||||
flow = InstalledAppFlow.from_client_secrets_file(
|
||||
os.path.join(BASE_DIR, 'gmail.json'), SCOPES)
|
||||
creds = flow.run_local_server(port=0)
|
||||
user_info = get_user_info(creds)
|
||||
return {
|
||||
'token': creds.token,
|
||||
'refresh_token': creds.refresh_token,
|
||||
'token_uri': creds.token_uri,
|
||||
'client_id': creds.client_id,
|
||||
'client_secret': creds.client_secret,
|
||||
'scopes': creds.scopes,
|
||||
'expiry': creds.expiry.isoformat(),
|
||||
'email': user_info
|
||||
}
|
||||
return {}
|
||||
|
||||
def get_user_info(credentials):
|
||||
user_info_service = build(serviceName='oauth2', version='v2',credentials=credentials)
|
||||
user_info = user_info_service.userinfo().get().execute()
|
||||
return user_info.get('email', "")
|
||||
|
||||
def send_messsage(token, msg):
|
||||
log.debug("Start sending e-mail via Gmail")
|
||||
creds = Credentials(
|
||||
token=token['token'],
|
||||
refresh_token=token['refresh_token'],
|
||||
token_uri=token['token_uri'],
|
||||
client_id=token['client_id'],
|
||||
client_secret=token['client_secret'],
|
||||
scopes=token['scopes'],
|
||||
)
|
||||
creds.expiry = datetime.fromisoformat(token['expiry'])
|
||||
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_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}
|
||||
|
||||
(service.users().messages().send(userId='me', body=body).execute())
|
||||
log.debug("E-mail send successfully via Gmail")
|
||||
@@ -0,0 +1,112 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2018-2019 OzzieIsaacs, pwr
|
||||
#
|
||||
# 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 time
|
||||
from functools import reduce
|
||||
|
||||
try:
|
||||
from goodreads.client import GoodreadsClient
|
||||
except ImportError:
|
||||
from betterreads.client import GoodreadsClient
|
||||
|
||||
try: import Levenshtein
|
||||
except ImportError: Levenshtein = False
|
||||
|
||||
from .. import logger
|
||||
|
||||
|
||||
log = logger.create()
|
||||
_client = None # type: GoodreadsClient
|
||||
|
||||
# GoodReads TOS allows for 24h caching of data
|
||||
_CACHE_TIMEOUT = 23 * 60 * 60 # 23 hours (in seconds)
|
||||
_AUTHORS_CACHE = {}
|
||||
|
||||
|
||||
def connect(key=None, secret=None, enabled=True):
|
||||
global _client
|
||||
|
||||
if not enabled or not key or not secret:
|
||||
_client = None
|
||||
return
|
||||
|
||||
if _client:
|
||||
# make sure the configuration has not changed since last we used the client
|
||||
if _client.client_key != key or _client.client_secret != secret:
|
||||
_client = None
|
||||
|
||||
if not _client:
|
||||
_client = GoodreadsClient(key, secret)
|
||||
|
||||
|
||||
def get_author_info(author_name):
|
||||
now = time.time()
|
||||
author_info = _AUTHORS_CACHE.get(author_name, None)
|
||||
if author_info:
|
||||
if now < author_info._timestamp + _CACHE_TIMEOUT:
|
||||
return author_info
|
||||
# clear expired entries
|
||||
del _AUTHORS_CACHE[author_name]
|
||||
|
||||
if not _client:
|
||||
log.warning("failed to get a Goodreads client")
|
||||
return
|
||||
|
||||
try:
|
||||
author_info = _client.find_author(author_name=author_name)
|
||||
except Exception as ex:
|
||||
# Skip goodreads, if site is down/inaccessible
|
||||
log.warning('Goodreads website is down/inaccessible? %s', ex.__str__())
|
||||
return
|
||||
|
||||
if author_info:
|
||||
author_info._timestamp = now
|
||||
_AUTHORS_CACHE[author_name] = author_info
|
||||
return author_info
|
||||
|
||||
|
||||
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
|
||||
# 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
|
||||
|
||||
if not author_info:
|
||||
return
|
||||
|
||||
identifiers = []
|
||||
library_titles = []
|
||||
if library_books:
|
||||
identifiers = list(reduce(lambda acc, book: acc + [i.val for i in book.identifiers if i.val], library_books, []))
|
||||
library_titles = [book.title for book in library_books]
|
||||
|
||||
for book in author_info.books:
|
||||
if book.isbn in identifiers:
|
||||
continue
|
||||
if isinstance(book.gid, int):
|
||||
if book.gid in identifiers:
|
||||
continue
|
||||
else:
|
||||
if book.gid["#text"] in identifiers:
|
||||
continue
|
||||
|
||||
if Levenshtein and library_titles:
|
||||
goodreads_title = book._book_dict['title_without_series']
|
||||
if any(Levenshtein.ratio(goodreads_title, title) > 0.7 for title in library_titles):
|
||||
continue
|
||||
|
||||
yield book
|
||||
@@ -0,0 +1,127 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2018-2019 OzzieIsaacs, pwr
|
||||
#
|
||||
# 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 base64
|
||||
|
||||
from flask_simpleldap import LDAP, LDAPException
|
||||
from flask_simpleldap import ldap as pyLDAP
|
||||
from .. import constants, logger
|
||||
|
||||
try:
|
||||
from ldap.pkginfo import __version__ as ldapVersion
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
log = logger.create()
|
||||
_ldap = LDAP()
|
||||
|
||||
|
||||
def init_app(app, config):
|
||||
if config.config_login_type != constants.LOGIN_LDAP:
|
||||
return
|
||||
|
||||
app.config['LDAP_HOST'] = config.config_ldap_provider_url
|
||||
app.config['LDAP_PORT'] = config.config_ldap_port
|
||||
app.config['LDAP_CUSTOM_OPTIONS'] = {pyLDAP.OPT_REFERRALS: 0}
|
||||
if config.config_ldap_encryption == 2:
|
||||
app.config['LDAP_SCHEMA'] = 'ldaps'
|
||||
else:
|
||||
app.config['LDAP_SCHEMA'] = 'ldap'
|
||||
if config.config_ldap_authentication > constants.LDAP_AUTH_ANONYMOUS:
|
||||
if config.config_ldap_authentication > constants.LDAP_AUTH_UNAUTHENTICATE:
|
||||
if config.config_ldap_serv_password is None:
|
||||
config.config_ldap_serv_password = ''
|
||||
app.config['LDAP_PASSWORD'] = base64.b64decode(config.config_ldap_serv_password)
|
||||
else:
|
||||
app.config['LDAP_PASSWORD'] = base64.b64decode("")
|
||||
app.config['LDAP_USERNAME'] = config.config_ldap_serv_username
|
||||
else:
|
||||
app.config['LDAP_USERNAME'] = ""
|
||||
app.config['LDAP_PASSWORD'] = base64.b64decode("")
|
||||
if bool(config.config_ldap_cert_path):
|
||||
app.config['LDAP_CUSTOM_OPTIONS'].update({
|
||||
pyLDAP.OPT_X_TLS_REQUIRE_CERT: pyLDAP.OPT_X_TLS_DEMAND,
|
||||
pyLDAP.OPT_X_TLS_CACERTFILE: config.config_ldap_cacert_path,
|
||||
pyLDAP.OPT_X_TLS_CERTFILE: config.config_ldap_cert_path,
|
||||
pyLDAP.OPT_X_TLS_KEYFILE: config.config_ldap_key_path,
|
||||
pyLDAP.OPT_X_TLS_NEWCTX: 0
|
||||
})
|
||||
|
||||
app.config['LDAP_BASE_DN'] = config.config_ldap_dn
|
||||
app.config['LDAP_USER_OBJECT_FILTER'] = config.config_ldap_user_object
|
||||
|
||||
app.config['LDAP_USE_TLS'] = bool(config.config_ldap_encryption == 1)
|
||||
app.config['LDAP_USE_SSL'] = bool(config.config_ldap_encryption == 2)
|
||||
app.config['LDAP_OPENLDAP'] = bool(config.config_ldap_openldap)
|
||||
app.config['LDAP_GROUP_OBJECT_FILTER'] = config.config_ldap_group_object_filter
|
||||
app.config['LDAP_GROUP_MEMBERS_FIELD'] = config.config_ldap_group_members_field
|
||||
|
||||
try:
|
||||
_ldap.init_app(app)
|
||||
except ValueError:
|
||||
if bool(config.config_ldap_cert_path):
|
||||
app.config['LDAP_CUSTOM_OPTIONS'].pop(pyLDAP.OPT_X_TLS_NEWCTX)
|
||||
try:
|
||||
_ldap.init_app(app)
|
||||
except RuntimeError as e:
|
||||
log.error(e)
|
||||
except RuntimeError as e:
|
||||
log.error(e)
|
||||
|
||||
|
||||
def get_object_details(user=None,query_filter=None):
|
||||
return _ldap.get_object_details(user, query_filter=query_filter)
|
||||
|
||||
|
||||
def bind():
|
||||
return _ldap.bind()
|
||||
|
||||
|
||||
def get_group_members(group):
|
||||
return _ldap.get_group_members(group)
|
||||
|
||||
|
||||
def basic_auth_required(func):
|
||||
return _ldap.basic_auth_required(func)
|
||||
|
||||
|
||||
def bind_user(username, password):
|
||||
'''Attempts a LDAP login.
|
||||
|
||||
:returns: True if login succeeded, False if login failed, None if server unavailable.
|
||||
'''
|
||||
try:
|
||||
if _ldap.get_object_details(username):
|
||||
result = _ldap.bind_user(username, password)
|
||||
log.debug("LDAP login '%s': %r", username, result)
|
||||
return result is not None, None
|
||||
return None, None # User not found
|
||||
except (TypeError, AttributeError, KeyError) as ex:
|
||||
error = ("LDAP bind_user: %s" % ex)
|
||||
return None, error
|
||||
except LDAPException as ex:
|
||||
if ex.message == 'Invalid credentials':
|
||||
error = "LDAP admin login failed"
|
||||
return None, error
|
||||
if ex.message == "Can't contact LDAP server":
|
||||
# log.warning('LDAP Server down: %s', ex)
|
||||
error = ('LDAP Server down: %s' % ex)
|
||||
return None, error
|
||||
else:
|
||||
error = ('LDAP Server error: %s' % ex.message)
|
||||
return None, error
|
||||
@@ -0,0 +1,239 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web)
|
||||
# Copyright (C) 2020 pwr
|
||||
#
|
||||
# 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 threading
|
||||
import abc
|
||||
import uuid
|
||||
import time
|
||||
|
||||
try:
|
||||
import queue
|
||||
except ImportError:
|
||||
import Queue as queue
|
||||
from datetime import datetime
|
||||
from collections import namedtuple
|
||||
|
||||
from cps import logger
|
||||
|
||||
log = logger.create()
|
||||
|
||||
# task 'status' consts
|
||||
STAT_WAITING = 0
|
||||
STAT_FAIL = 1
|
||||
STAT_STARTED = 2
|
||||
STAT_FINISH_SUCCESS = 3
|
||||
|
||||
# Only retain this many tasks in dequeued list
|
||||
TASK_CLEANUP_TRIGGER = 20
|
||||
|
||||
QueuedTask = namedtuple('QueuedTask', 'num, user, added, task')
|
||||
|
||||
|
||||
def _get_main_thread():
|
||||
for t in threading.enumerate():
|
||||
if t.__class__.__name__ == '_MainThread':
|
||||
return t
|
||||
raise Exception("main thread not found?!")
|
||||
|
||||
|
||||
|
||||
class ImprovedQueue(queue.Queue):
|
||||
def to_list(self):
|
||||
"""
|
||||
Returns a copy of all items in the queue without removing them.
|
||||
"""
|
||||
|
||||
with self.mutex:
|
||||
return list(self.queue)
|
||||
|
||||
# Class for all worker tasks in the background
|
||||
class WorkerThread(threading.Thread):
|
||||
_instance = None
|
||||
|
||||
@classmethod
|
||||
def getInstance(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = WorkerThread()
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
threading.Thread.__init__(self)
|
||||
|
||||
self.dequeued = list()
|
||||
|
||||
self.doLock = threading.Lock()
|
||||
self.queue = ImprovedQueue()
|
||||
self.num = 0
|
||||
self.start()
|
||||
|
||||
@classmethod
|
||||
def add(cls, user, task):
|
||||
ins = cls.getInstance()
|
||||
ins.num += 1
|
||||
log.debug("Add Task for user: {} - {}".format(user, task))
|
||||
ins.queue.put(QueuedTask(
|
||||
num=ins.num,
|
||||
user=user,
|
||||
added=datetime.now(),
|
||||
task=task,
|
||||
))
|
||||
|
||||
@property
|
||||
def tasks(self):
|
||||
with self.doLock:
|
||||
tasks = self.queue.to_list() + self.dequeued
|
||||
return sorted(tasks, key=lambda x: x.num)
|
||||
|
||||
def cleanup_tasks(self):
|
||||
with self.doLock:
|
||||
dead = []
|
||||
alive = []
|
||||
for x in self.dequeued:
|
||||
(dead if x.task.dead else alive).append(x)
|
||||
|
||||
# if the ones that we need to keep are within the trigger, do nothing else
|
||||
delta = len(self.dequeued) - len(dead)
|
||||
if delta > TASK_CLEANUP_TRIGGER:
|
||||
ret = alive
|
||||
else:
|
||||
# otherwise, lop off the oldest dead tasks until we hit the target trigger
|
||||
ret = sorted(dead, key=lambda x: x.task.end_time)[-TASK_CLEANUP_TRIGGER:] + alive
|
||||
|
||||
self.dequeued = sorted(ret, key=lambda x: x.num)
|
||||
|
||||
# Main thread loop starting the different tasks
|
||||
def run(self):
|
||||
main_thread = _get_main_thread()
|
||||
while main_thread.is_alive():
|
||||
try:
|
||||
# this blocks until something is available. This can cause issues when the main thread dies - this
|
||||
# thread will remain alive. We implement a timeout to unblock every second which allows us to check if
|
||||
# the main thread is still alive.
|
||||
# We don't use a daemon here because we don't want the tasks to just be abruptly halted, leading to
|
||||
# possible file / database corruption
|
||||
item = self.queue.get(timeout=1)
|
||||
except queue.Empty:
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
with self.doLock:
|
||||
# add to list so that in-progress tasks show up
|
||||
self.dequeued.append(item)
|
||||
|
||||
# once we hit our trigger, start cleaning up dead tasks
|
||||
if len(self.dequeued) > TASK_CLEANUP_TRIGGER:
|
||||
self.cleanup_tasks()
|
||||
|
||||
# sometimes tasks (like Upload) don't actually have work to do and are created as already finished
|
||||
if item.task.stat is STAT_WAITING:
|
||||
# CalibreTask.start() should wrap all exceptions in it's own error handling
|
||||
item.task.start(self)
|
||||
|
||||
self.queue.task_done()
|
||||
|
||||
|
||||
class CalibreTask:
|
||||
__metaclass__ = abc.ABCMeta
|
||||
|
||||
def __init__(self, message):
|
||||
self._progress = 0
|
||||
self.stat = STAT_WAITING
|
||||
self.error = None
|
||||
self.start_time = None
|
||||
self.end_time = None
|
||||
self.message = message
|
||||
self.id = uuid.uuid4()
|
||||
|
||||
@abc.abstractmethod
|
||||
def run(self, worker_thread):
|
||||
"""Provides the caller some human-readable name for this class"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abc.abstractmethod
|
||||
def name(self):
|
||||
"""Provides the caller some human-readable name for this class"""
|
||||
raise NotImplementedError
|
||||
|
||||
def start(self, *args):
|
||||
self.start_time = datetime.now()
|
||||
self.stat = STAT_STARTED
|
||||
|
||||
# catch any unhandled exceptions in a task and automatically fail it
|
||||
try:
|
||||
self.run(*args)
|
||||
except Exception as ex:
|
||||
self._handleError(str(ex))
|
||||
log.debug_or_exception(ex)
|
||||
|
||||
self.end_time = datetime.now()
|
||||
|
||||
@property
|
||||
def stat(self):
|
||||
return self._stat
|
||||
|
||||
@stat.setter
|
||||
def stat(self, x):
|
||||
self._stat = x
|
||||
|
||||
@property
|
||||
def progress(self):
|
||||
return self._progress
|
||||
|
||||
@progress.setter
|
||||
def progress(self, x):
|
||||
if not 0 <= x <= 1:
|
||||
raise ValueError("Task progress should within [0, 1] range")
|
||||
self._progress = x
|
||||
|
||||
@property
|
||||
def error(self):
|
||||
return self._error
|
||||
|
||||
@error.setter
|
||||
def error(self, x):
|
||||
self._error = x
|
||||
|
||||
@property
|
||||
def runtime(self):
|
||||
return (self.end_time or datetime.now()) - self.start_time
|
||||
|
||||
@property
|
||||
def dead(self):
|
||||
"""Determines whether or not this task can be garbage collected
|
||||
|
||||
We have a separate dictating this because there may be certain tasks that want to override this
|
||||
"""
|
||||
# By default, we're good to clean a task if it's "Done"
|
||||
return self.stat in (STAT_FINISH_SUCCESS, STAT_FAIL)
|
||||
|
||||
'''@progress.setter
|
||||
def progress(self, x):
|
||||
if x > 1:
|
||||
x = 1
|
||||
if x < 0:
|
||||
x = 0
|
||||
self._progress = x'''
|
||||
|
||||
def _handleError(self, error_message):
|
||||
self.stat = STAT_FAIL
|
||||
self.progress = 1
|
||||
self.error = error_message
|
||||
|
||||
def _handleSuccess(self):
|
||||
self.stat = STAT_FINISH_SUCCESS
|
||||
self.progress = 1
|
||||
+461
@@ -0,0 +1,461 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# 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
|
||||
#
|
||||
# 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 sys
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, flash, redirect, request, url_for
|
||||
from flask_babel import gettext as _
|
||||
from flask_login import current_user, login_required
|
||||
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
|
||||
|
||||
shelf = Blueprint('shelf', __name__)
|
||||
log = logger.create()
|
||||
|
||||
|
||||
def check_shelf_edit_permissions(cur_shelf):
|
||||
if not cur_shelf.is_public and not cur_shelf.user_id == int(current_user.id):
|
||||
log.error("User %s not allowed to edit shelf %s", current_user, cur_shelf)
|
||||
return False
|
||||
if cur_shelf.is_public and not current_user.role_edit_shelfs():
|
||||
log.info("User %s not allowed to edit public shelves", current_user)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def check_shelf_view_permissions(cur_shelf):
|
||||
if cur_shelf.is_public:
|
||||
return True
|
||||
if current_user.is_anonymous or cur_shelf.user_id != current_user.id:
|
||||
log.error("User is unauthorized to view non-public shelf: %s", cur_shelf)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
@shelf.route("/shelf/add/<int:shelf_id>/<int:book_id>", methods=["POST"])
|
||||
@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()
|
||||
if shelf is None:
|
||||
log.error("Invalid shelf specified: %s", shelf_id)
|
||||
if not xhr:
|
||||
flash(_(u"Invalid shelf specified"), category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
return "Invalid shelf specified", 400
|
||||
|
||||
if not check_shelf_edit_permissions(shelf):
|
||||
if not xhr:
|
||||
flash(_(u"Sorry you are not allowed to add a book to that shelf"), category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
return "Sorry you are not allowed to add a book to the that shelf", 403
|
||||
|
||||
book_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id,
|
||||
ub.BookShelf.book_id == book_id).first()
|
||||
if book_in_shelf:
|
||||
log.error("Book %s is already part of %s", book_id, shelf)
|
||||
if not xhr:
|
||||
flash(_(u"Book is already part of the shelf: %(shelfname)s", shelfname=shelf.name), category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
return "Book is already part of the shelf: %s" % shelf.name, 400
|
||||
|
||||
maxOrder = ub.session.query(func.max(ub.BookShelf.order)).filter(ub.BookShelf.shelf == shelf_id).first()
|
||||
if maxOrder[0] is None:
|
||||
maxOrder = 0
|
||||
else:
|
||||
maxOrder = maxOrder[0]
|
||||
|
||||
shelf.books.append(ub.BookShelf(shelf=shelf.id, book_id=book_id, order=maxOrder + 1))
|
||||
shelf.last_modified = datetime.utcnow()
|
||||
try:
|
||||
ub.session.merge(shelf)
|
||||
ub.session.commit()
|
||||
except (OperationalError, InvalidRequestError):
|
||||
ub.session.rollback()
|
||||
log.error("Settings DB is not Writeable")
|
||||
flash(_(u"Settings DB is not Writeable"), category="error")
|
||||
if "HTTP_REFERER" in request.environ:
|
||||
return redirect(request.environ["HTTP_REFERER"])
|
||||
else:
|
||||
return redirect(url_for('web.index'))
|
||||
if not xhr:
|
||||
log.debug("Book has been added to shelf: {}".format(shelf.name))
|
||||
flash(_(u"Book has been added to shelf: %(sname)s", sname=shelf.name), category="success")
|
||||
if "HTTP_REFERER" in request.environ:
|
||||
return redirect(request.environ["HTTP_REFERER"])
|
||||
else:
|
||||
return redirect(url_for('web.index'))
|
||||
return "", 204
|
||||
|
||||
|
||||
@shelf.route("/shelf/massadd/<int:shelf_id>", methods=["POST"])
|
||||
@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:
|
||||
log.error("Invalid shelf specified: %s", shelf_id)
|
||||
flash(_(u"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 add a book to the shelf".format(shelf.name))
|
||||
flash(_(u"You are not allowed to add a book to 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_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)
|
||||
for searchid in ub.searched_ids[current_user.id]:
|
||||
if searchid not in book_ids:
|
||||
books_for_shelf.append(searchid)
|
||||
else:
|
||||
books_for_shelf = ub.searched_ids[current_user.id]
|
||||
|
||||
if not books_for_shelf:
|
||||
log.error("Books are already part of {}".format(shelf.name))
|
||||
flash(_(u"Books are already 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_for_shelf:
|
||||
maxOrder += 1
|
||||
shelf.books.append(ub.BookShelf(shelf=shelf.id, book_id=book, order=maxOrder))
|
||||
shelf.last_modified = datetime.utcnow()
|
||||
try:
|
||||
ub.session.merge(shelf)
|
||||
ub.session.commit()
|
||||
flash(_(u"Books have been added to shelf: %(sname)s", sname=shelf.name), category="success")
|
||||
except (OperationalError, InvalidRequestError):
|
||||
ub.session.rollback()
|
||||
log.error("Settings DB is not Writeable")
|
||||
flash(_("Settings DB is not Writeable"), category="error")
|
||||
else:
|
||||
log.error("Could not add books to shelf: {}".format(shelf.name))
|
||||
flash(_(u"Could not add books to shelf: %(sname)s", sname=shelf.name), category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
|
||||
|
||||
@shelf.route("/shelf/remove/<int:shelf_id>/<int:book_id>", methods=["POST"])
|
||||
@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()
|
||||
if shelf is None:
|
||||
log.error("Invalid shelf specified: {}".format(shelf_id))
|
||||
if not xhr:
|
||||
return redirect(url_for('web.index'))
|
||||
return "Invalid shelf specified", 400
|
||||
|
||||
# if shelf is public and use is allowed to edit shelfs, or if shelf is private and user is owner
|
||||
# allow editing shelfs
|
||||
# result shelf public user allowed user owner
|
||||
# false 1 0 x
|
||||
# true 1 1 x
|
||||
# true 0 x 1
|
||||
# false 0 x 0
|
||||
|
||||
if check_shelf_edit_permissions(shelf):
|
||||
book_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id,
|
||||
ub.BookShelf.book_id == book_id).first()
|
||||
|
||||
if book_shelf is None:
|
||||
log.error("Book %s already removed from %s", book_id, shelf)
|
||||
if not xhr:
|
||||
return redirect(url_for('web.index'))
|
||||
return "Book already removed from shelf", 410
|
||||
|
||||
try:
|
||||
ub.session.delete(book_shelf)
|
||||
shelf.last_modified = datetime.utcnow()
|
||||
ub.session.commit()
|
||||
except (OperationalError, InvalidRequestError):
|
||||
ub.session.rollback()
|
||||
log.error("Settings DB is not Writeable")
|
||||
flash(_("Settings DB is not Writeable"), category="error")
|
||||
if "HTTP_REFERER" in request.environ:
|
||||
return redirect(request.environ["HTTP_REFERER"])
|
||||
else:
|
||||
return redirect(url_for('web.index'))
|
||||
if not xhr:
|
||||
flash(_(u"Book has been removed from shelf: %(sname)s", sname=shelf.name), category="success")
|
||||
if "HTTP_REFERER" in request.environ:
|
||||
return redirect(request.environ["HTTP_REFERER"])
|
||||
else:
|
||||
return redirect(url_for('web.index'))
|
||||
return "", 204
|
||||
else:
|
||||
if not xhr:
|
||||
log.warning("You are not allowed to remove a book from shelf: {}".format(shelf.name))
|
||||
flash(_(u"Sorry you are not allowed to remove a book from this shelf"),
|
||||
category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
return "Sorry you are not allowed to remove a book from this shelf", 403
|
||||
|
||||
|
||||
@shelf.route("/shelf/create", methods=["GET", "POST"])
|
||||
@login_required
|
||||
def create_shelf():
|
||||
shelf = ub.Shelf()
|
||||
return create_edit_shelf(shelf, page_title=_(u"Create a Shelf"), page="shelfcreate")
|
||||
|
||||
|
||||
|
||||
@shelf.route("/shelf/edit/<int:shelf_id>", methods=["GET", "POST"])
|
||||
@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):
|
||||
flash(_(u"Sorry you are not allowed to edit this shelf"), category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
return create_edit_shelf(shelf, page_title=_(u"Edit a shelf"), page="shelfedit", shelf_id=shelf_id)
|
||||
|
||||
|
||||
# if shelf ID is set, we are editing a shelf
|
||||
def create_edit_shelf(shelf, page_title, page, shelf_id=False):
|
||||
sync_only_selected_shelves = current_user.kobo_only_shelves_sync
|
||||
# calibre_db.session.query(ub.Shelf).filter(ub.Shelf.user_id == current_user.id).filter(ub.Shelf.kobo_sync).count()
|
||||
if request.method == "POST":
|
||||
to_save = request.form.to_dict()
|
||||
if not current_user.role_edit_shelfs() and to_save.get("is_public") == "on":
|
||||
flash(_(u"Sorry you are not allowed to create a public shelf"), category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
is_public = 1 if to_save.get("is_public") == "on" else 0
|
||||
if config.config_kobo_sync:
|
||||
shelf.kobo_sync = True if to_save.get("kobo_sync") else False
|
||||
if shelf.kobo_sync:
|
||||
ub.session.query(ub.ShelfArchive).filter(ub.ShelfArchive.user_id == current_user.id).filter(
|
||||
ub.ShelfArchive.uuid == shelf.uuid).delete()
|
||||
ub.session_commit()
|
||||
shelf_title = to_save.get("title", "")
|
||||
if check_shelf_is_unique(shelf, shelf_title, is_public, shelf_id):
|
||||
shelf.name = shelf_title
|
||||
shelf.is_public = is_public
|
||||
if not shelf_id:
|
||||
shelf.user_id = int(current_user.id)
|
||||
ub.session.add(shelf)
|
||||
shelf_action = "created"
|
||||
flash_text = _(u"Shelf %(title)s created", title=shelf_title)
|
||||
else:
|
||||
shelf_action = "changed"
|
||||
flash_text = _(u"Shelf %(title)s changed", title=shelf_title)
|
||||
try:
|
||||
ub.session.commit()
|
||||
log.info(u"Shelf {} {}".format(shelf_title, shelf_action))
|
||||
flash(flash_text, category="success")
|
||||
return redirect(url_for('shelf.show_shelf', shelf_id=shelf.id))
|
||||
except (OperationalError, InvalidRequestError) as ex:
|
||||
ub.session.rollback()
|
||||
log.debug_or_exception(ex)
|
||||
log.error("Settings DB is not Writeable")
|
||||
flash(_("Settings DB is not Writeable"), category="error")
|
||||
except Exception as ex:
|
||||
ub.session.rollback()
|
||||
log.debug_or_exception(ex)
|
||||
flash(_(u"There was an error"), category="error")
|
||||
return render_title_template('shelf_edit.html',
|
||||
shelf=shelf,
|
||||
title=page_title,
|
||||
page=page,
|
||||
kobo_sync_enabled=config.config_kobo_sync,
|
||||
sync_only_selected_shelves=sync_only_selected_shelves)
|
||||
|
||||
|
||||
def check_shelf_is_unique(shelf, title, is_public, shelf_id=False):
|
||||
if shelf_id:
|
||||
ident = ub.Shelf.id != shelf_id
|
||||
else:
|
||||
ident = true()
|
||||
if is_public == 1:
|
||||
is_shelf_name_unique = ub.session.query(ub.Shelf) \
|
||||
.filter((ub.Shelf.name == title) & (ub.Shelf.is_public == 1)) \
|
||||
.filter(ident) \
|
||||
.first() is None
|
||||
|
||||
if not is_shelf_name_unique:
|
||||
log.error("A public shelf with the name '{}' already exists.".format(title))
|
||||
flash(_(u"A public shelf with the name '%(title)s' already exists.", title=title),
|
||||
category="error")
|
||||
else:
|
||||
is_shelf_name_unique = ub.session.query(ub.Shelf) \
|
||||
.filter((ub.Shelf.name == title) & (ub.Shelf.is_public == 0) &
|
||||
(ub.Shelf.user_id == int(current_user.id))) \
|
||||
.filter(ident) \
|
||||
.first() is None
|
||||
|
||||
if not is_shelf_name_unique:
|
||||
log.error("A private shelf with the name '{}' already exists.".format(title))
|
||||
flash(_(u"A private shelf with the name '%(title)s' already exists.", title=title),
|
||||
category="error")
|
||||
return is_shelf_name_unique
|
||||
|
||||
|
||||
def delete_shelf_helper(cur_shelf):
|
||||
if not cur_shelf or not check_shelf_edit_permissions(cur_shelf):
|
||||
return
|
||||
shelf_id = cur_shelf.id
|
||||
ub.session.delete(cur_shelf)
|
||||
ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).delete()
|
||||
ub.session.add(ub.ShelfArchive(uuid=cur_shelf.uuid, user_id=cur_shelf.user_id))
|
||||
ub.session_commit("successfully deleted Shelf {}".format(cur_shelf.name))
|
||||
|
||||
|
||||
@shelf.route("/shelf/delete/<int:shelf_id>", methods=["POST"])
|
||||
@login_required
|
||||
def delete_shelf(shelf_id):
|
||||
cur_shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
|
||||
try:
|
||||
delete_shelf_helper(cur_shelf)
|
||||
flash(_("Shelf successfully deleted"), category="success")
|
||||
except InvalidRequestError:
|
||||
ub.session.rollback()
|
||||
log.error("Settings DB is not Writeable")
|
||||
flash(_("Settings DB is not Writeable"), category="error")
|
||||
return redirect(url_for('web.index'))
|
||||
|
||||
|
||||
@shelf.route("/simpleshelf/<int:shelf_id>")
|
||||
@login_required_if_no_ano
|
||||
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>/<sort_param>", defaults={'page': 1})
|
||||
@shelf.route("/shelf/<int:shelf_id>/<sort_param>/<int:page>")
|
||||
@login_required_if_no_ano
|
||||
def show_shelf(shelf_id, sort_param, page):
|
||||
return render_show_shelf(1, shelf_id, page, sort_param)
|
||||
|
||||
|
||||
@shelf.route("/shelf/order/<int:shelf_id>", methods=["GET", "POST"])
|
||||
@login_required
|
||||
def order_shelf(shelf_id):
|
||||
if request.method == "POST":
|
||||
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()
|
||||
counter = 0
|
||||
for book in books_in_shelf:
|
||||
setattr(book, 'order', to_save[str(book.book_id)])
|
||||
counter += 1
|
||||
# if order diffrent from before -> shelf.last_modified = datetime.utcnow()
|
||||
try:
|
||||
ub.session.commit()
|
||||
except (OperationalError, InvalidRequestError):
|
||||
ub.session.rollback()
|
||||
log.error("Settings DB is not Writeable")
|
||||
flash(_("Settings DB is not Writeable"), category="error")
|
||||
|
||||
shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first()
|
||||
result = list()
|
||||
if shelf and check_shelf_view_permissions(shelf):
|
||||
result = calibre_db.session.query(db.Books) \
|
||||
.join(ub.BookShelf, ub.BookShelf.book_id == db.Books.id, isouter=True) \
|
||||
.add_columns(calibre_db.common_filters().label("visible")) \
|
||||
.filter(ub.BookShelf.shelf == shelf_id).order_by(ub.BookShelf.order.asc()).all()
|
||||
return render_title_template('shelf_order.html', entries=result,
|
||||
title=_(u"Change order of Shelf: '%(name)s'", name=shelf.name),
|
||||
shelf=shelf, page="shelforder")
|
||||
|
||||
|
||||
def change_shelf_order(shelf_id, order):
|
||||
result = calibre_db.session.query(db.Books).outerjoin(db.books_series_link,
|
||||
db.Books.id == db.books_series_link.c.book)\
|
||||
.outerjoin(db.Series).join(ub.BookShelf, ub.BookShelf.book_id == db.Books.id) \
|
||||
.filter(ub.BookShelf.shelf == shelf_id).order_by(*order).all()
|
||||
for index, entry in enumerate(result):
|
||||
book = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id) \
|
||||
.filter(ub.BookShelf.book_id == entry.id).first()
|
||||
book.order = index
|
||||
ub.session_commit("Shelf-id:{} - Order changed".format(shelf_id))
|
||||
|
||||
|
||||
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()
|
||||
|
||||
# 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()])
|
||||
page = "shelf.html"
|
||||
pagesize = 0
|
||||
else:
|
||||
pagesize = sys.maxsize
|
||||
page = 'shelfdown.html'
|
||||
|
||||
result, __, pagination = calibre_db.fill_indexpage(page_no, pagesize,
|
||||
db.Books,
|
||||
ub.BookShelf.shelf == shelf_id,
|
||||
[ub.BookShelf.order.asc()],
|
||||
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
|
||||
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()
|
||||
for entry in wrong_entries:
|
||||
log.info('Not existing book {} in {} deleted'.format(entry.book_id, shelf))
|
||||
try:
|
||||
ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == entry.book_id).delete()
|
||||
ub.session.commit()
|
||||
except (OperationalError, InvalidRequestError):
|
||||
ub.session.rollback()
|
||||
log.error("Settings DB is not Writeable")
|
||||
flash(_("Settings DB is not Writeable"), category="error")
|
||||
|
||||
return render_title_template(page,
|
||||
entries=result,
|
||||
pagination=pagination,
|
||||
title=_(u"Shelf: '%(name)s'", name=shelf.name),
|
||||
shelf=shelf,
|
||||
page="shelf")
|
||||
else:
|
||||
flash(_(u"Error opening shelf. Shelf does not exist or is not accessible"), category="error")
|
||||
return redirect(url_for("web.index"))
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user