mirror of
https://github.com/rmcrackan/Libation.git
synced 2026-09-08 11:47:57 -04:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
915906e6ed | ||
|
|
358c8b577e | ||
|
|
5c450a01a4 | ||
|
|
36264c6c6e | ||
|
|
fca946bf15 | ||
|
|
452ceef285 | ||
|
|
7fafee804d | ||
|
|
3a48479435 | ||
|
|
cab8555ab5 | ||
|
|
e3b7cbcc2a | ||
|
|
ed15614288 | ||
|
|
acb6d1b335 | ||
|
|
fe804796ab | ||
|
|
4725fe36d1 | ||
|
|
5c73beff4b | ||
|
|
1f7000c2c9 | ||
|
|
f09baa1318 | ||
|
|
7eaa03e43c | ||
|
|
26099303fa | ||
|
|
6417aee780 | ||
|
|
f9deaba4c5 | ||
|
|
ddd6a3b279 | ||
|
|
9359950666 | ||
|
|
d31b2a1b65 | ||
|
|
b89b4e0af4 | ||
|
|
cbcde027b3 | ||
|
|
d306e6bd22 | ||
|
|
9ec877999e | ||
|
|
f4189bf409 | ||
|
|
0ed5062683 | ||
|
|
7ef666dc91 | ||
|
|
1ac825919a | ||
|
|
a7bf30954d | ||
|
|
613cfdd903 | ||
|
|
28802c8279 | ||
|
|
6d7b3bd5f0 | ||
|
|
b97d8e9403 | ||
|
|
b4838d364e | ||
|
|
05ac5c63e1 | ||
|
|
874bf9e7c0 | ||
|
|
c9497ef39e | ||
|
|
496830d01d | ||
|
|
ccebcdd4c7 | ||
|
|
c900fe8461 | ||
|
|
a0158db37e | ||
|
|
b8c26b01ad | ||
|
|
3a44bef0d9 | ||
|
|
57a4ee781b | ||
|
|
e12f475850 | ||
|
|
f822a23daa | ||
|
|
6901b8be35 | ||
|
|
83fb2cd1d0 | ||
|
|
c98664d584 | ||
|
|
d098be8b03 | ||
|
|
3f6689d032 | ||
|
|
b4206fc203 | ||
|
|
cfa4a0c07f | ||
|
|
357b220ace | ||
|
|
47968304c9 | ||
|
|
2024d5e116 | ||
|
|
5ae2a99c14 | ||
|
|
7fd002d2c9 | ||
|
|
b7b7038244 | ||
|
|
b5519c4875 | ||
|
|
44feab9eb2 | ||
|
|
96c45c33e5 | ||
|
|
36efbcb812 | ||
|
|
03f44b4e9c | ||
|
|
19860e9f09 | ||
|
|
0701cb3970 | ||
|
|
7d6000e3b6 | ||
|
|
ef973ac56a | ||
|
|
91a1033c52 | ||
|
|
4197db6af9 | ||
|
|
210ab065c2 | ||
|
|
9cd10eca58 | ||
|
|
ba676be46d | ||
|
|
665a2e1866 | ||
|
|
94469cae3d | ||
|
|
a0dd2ccad6 | ||
|
|
b2cf837de7 | ||
|
|
80bcf60b5b | ||
|
|
7ad0ab566a | ||
|
|
2b16e86c7b | ||
|
|
f2ea02ae0b | ||
|
|
f65cd39040 | ||
|
|
5ca0d2a399 | ||
|
|
d1528a095b | ||
|
|
749173a463 | ||
|
|
6fbd90a6b3 | ||
|
|
f39d272e6a | ||
|
|
bb3854f512 | ||
|
|
e40daecfb8 | ||
|
|
3716ab9cb5 | ||
|
|
0cc6d6337a | ||
|
|
ce711a36ba | ||
|
|
451af7bea9 | ||
|
|
63200592bf | ||
|
|
d165dfbeb5 | ||
|
|
eed3d84517 | ||
|
|
ba7d890966 | ||
|
|
5140fc63d9 | ||
|
|
78509c07e0 | ||
|
|
5084141215 | ||
|
|
3f2ac83474 | ||
|
|
58a0468728 | ||
|
|
8e13aa7513 | ||
|
|
48e2d91fc8 | ||
|
|
a7f119217f | ||
|
|
865f2261fe | ||
|
|
dfedb23efd | ||
|
|
c01e1c3e4b | ||
|
|
ad8dac5fb0 | ||
|
|
84e81b6218 | ||
|
|
86efe631fe | ||
|
|
f5f1dc483b | ||
|
|
8aa4328c6c | ||
|
|
a01a8c4b19 | ||
|
|
4b2387b621 | ||
|
|
74d16d8ef9 | ||
|
|
b1ea8f9fa7 | ||
|
|
c666fdeaff | ||
|
|
7068782975 | ||
|
|
c4cebbebe7 | ||
|
|
53d43d9fa9 | ||
|
|
11d59beeed | ||
|
|
ef71e297f4 | ||
|
|
1e4d1d1973 | ||
|
|
893d99854b | ||
|
|
db93980cd5 | ||
|
|
34fac30b2b | ||
|
|
2fa0bcb765 | ||
|
|
78fd09aa91 | ||
|
|
a54516b4f5 | ||
|
|
f193d6f376 | ||
|
|
8a82c294a1 | ||
|
|
9392cf4bf0 | ||
|
|
ec4deb9099 | ||
|
|
cf0548aab9 | ||
|
|
064801380b | ||
|
|
9dc2a7424a | ||
|
|
4c8a56a5b9 | ||
|
|
9aad263996 | ||
|
|
ce1ab7c20d | ||
|
|
c9217990cd | ||
|
|
90cbf3b7a6 | ||
|
|
c4f1b22ddf | ||
|
|
fb612ea6ab | ||
|
|
bce44b6f6d | ||
|
|
7575736991 | ||
|
|
06f8d055fc | ||
|
|
d64e043fe8 | ||
|
|
99564d9c25 | ||
|
|
29bccd3e33 | ||
|
|
20f65f6534 | ||
|
|
8ca72b2e2d | ||
|
|
75429f288f | ||
|
|
d1bb921346 | ||
|
|
b979b6ddad | ||
|
|
4eba41ddbb | ||
|
|
418f5062ff | ||
|
|
f736f7f909 | ||
|
|
96ead28246 | ||
|
|
34bad7a53d | ||
|
|
7ac1fff3a0 | ||
|
|
a4c5c53df3 | ||
|
|
87db5cfd94 | ||
|
|
85e7bbf366 | ||
|
|
c55c5fac23 | ||
|
|
e25e2f7211 | ||
|
|
f310d583d8 | ||
|
|
f05465b29b | ||
|
|
959e31972e | ||
|
|
17181811f0 | ||
|
|
6d2624d52b | ||
|
|
9dd5940c8c | ||
|
|
1927d19961 | ||
|
|
09cc838bb4 | ||
|
|
8af4c71101 | ||
|
|
7ffdf45164 | ||
|
|
e0999dc9ae | ||
|
|
a0f3d44e97 | ||
|
|
1510a86579 | ||
|
|
b3581455d2 | ||
|
|
8ee1019fa5 | ||
|
|
285b10a95f | ||
|
|
0ca33f864b | ||
|
|
a0823fa26c | ||
|
|
aa9040da5d | ||
|
|
222031ecc5 | ||
|
|
dda8f5a974 | ||
|
|
e9b484df04 | ||
|
|
d505264e86 | ||
|
|
c0b1f1dc0a | ||
|
|
1524d558a4 | ||
|
|
aea8c11dc4 | ||
|
|
86c7f89788 | ||
|
|
3272541e81 | ||
|
|
3b3d40e4e6 | ||
|
|
a47866b6f7 | ||
|
|
0df4dfdef5 | ||
|
|
fe2de6ecf7 | ||
|
|
fc25e73b1a | ||
|
|
a3df85c87e | ||
|
|
553a936e7e | ||
|
|
635764625e | ||
|
|
f5599f7c57 | ||
|
|
dc6aaf2dd6 | ||
|
|
f1ba2b4ae8 | ||
|
|
742310b8d6 | ||
|
|
073787173d | ||
|
|
66679ace2f | ||
|
|
3982537d46 | ||
|
|
7cf4c63d79 | ||
|
|
7c4575cf66 | ||
|
|
f4749d703f | ||
|
|
f2f562619b | ||
|
|
16c019a9c6 | ||
|
|
644dcbdd4d | ||
|
|
6b112f5248 | ||
|
|
0bfa609058 | ||
|
|
8020ded642 | ||
|
|
c4cd6b16fc | ||
|
|
310012fd17 | ||
|
|
06163db6ff | ||
|
|
7689eed711 | ||
|
|
d396d697d7 | ||
|
|
27ed11d904 | ||
|
|
9e7670b918 | ||
|
|
31e97defd1 | ||
|
|
1a447627c7 | ||
|
|
962b386d07 | ||
|
|
d69ff24c2d | ||
|
|
070ed1d373 | ||
|
|
47729bf7b0 | ||
|
|
ed0ce2976b | ||
|
|
2224f46ed5 | ||
|
|
433974323c | ||
|
|
7525d318c0 | ||
|
|
92327dcc0d | ||
|
|
aeaf234edd | ||
|
|
a99b644917 | ||
|
|
d79a55e5c9 | ||
|
|
16b0feeb82 | ||
|
|
7b3a25e45a | ||
|
|
8effdcb92d | ||
|
|
b12bef81bd | ||
|
|
f04a5e0168 | ||
|
|
e093729707 | ||
|
|
369151ada2 | ||
|
|
1f685ae8a0 | ||
|
|
bbe91099cb | ||
|
|
92015ba4c2 | ||
|
|
3bcacabadc | ||
|
|
f5736d9151 | ||
|
|
59015f438e | ||
|
|
3af47ab395 | ||
|
|
308619b01a | ||
|
|
4efce57488 | ||
|
|
c8ee950f7d | ||
|
|
0bba0f9256 | ||
|
|
05bdff5123 | ||
|
|
e58e6cfb9f | ||
|
|
b052871004 | ||
|
|
d738f4f35f | ||
|
|
7286aee9dd | ||
|
|
ca455978a5 | ||
|
|
9c38bea5b7 | ||
|
|
fbec1bc569 | ||
|
|
6dd885f0b2 | ||
|
|
ab38eb5571 | ||
|
|
0e4b9ab396 | ||
|
|
7dfedbc73b | ||
|
|
625ae1d63c | ||
|
|
71098ef02f | ||
|
|
d63a6de543 | ||
|
|
2a71a85306 | ||
|
|
6de3a8a2bf | ||
|
|
3fc1da66de | ||
|
|
683c221ca8 | ||
|
|
fe6cfc899b | ||
|
|
ffd947eb2e | ||
|
|
8dd59cb08a | ||
|
|
1e4c489983 | ||
|
|
17b0da358f | ||
|
|
6aa0a1f8b9 | ||
|
|
ab731a63af | ||
|
|
07d2c656fc | ||
|
|
9ecb32c3d2 | ||
|
|
503e1e143e | ||
|
|
e34ce67a2c | ||
|
|
a0fd0a3de6 | ||
|
|
7f3cbc454f | ||
|
|
30eb117fa1 | ||
|
|
63877160aa | ||
|
|
77e61479cf | ||
|
|
ca71283108 | ||
|
|
285563af5e | ||
|
|
62cbad0d8f | ||
|
|
2cb2479d63 | ||
|
|
e7c5b1d8dc | ||
|
|
7f086aeaac | ||
|
|
78186d4973 | ||
|
|
4d84174ba6 | ||
|
|
579536f65a | ||
|
|
a4ff739684 | ||
|
|
9e06c70319 | ||
|
|
0c98ce000b | ||
|
|
230b23dc80 | ||
|
|
d55b8eeeba | ||
|
|
decf75411f | ||
|
|
c69f14dac5 | ||
|
|
10359aa5e8 | ||
|
|
72e030faaf | ||
|
|
b21055d0ea | ||
|
|
720fd64c97 | ||
|
|
e9a331292a | ||
|
|
51fee4ae24 | ||
|
|
4cfe72a63b | ||
|
|
6a8476c976 | ||
|
|
8bb17d09c3 | ||
|
|
ad6b86fcb4 | ||
|
|
1578be2520 | ||
|
|
82d8d954ef | ||
|
|
eff9c2b35d | ||
|
|
ccdd1dc9f3 | ||
|
|
952173d450 | ||
|
|
35f677a0fa | ||
|
|
51d0645699 | ||
|
|
0189a197a8 | ||
|
|
1ce5fedc8c | ||
|
|
d336848ed0 | ||
|
|
8cd6219bd9 | ||
|
|
c2a2e51bde | ||
|
|
d62821cd60 | ||
|
|
180d591b0a | ||
|
|
7b7e1d8574 | ||
|
|
efd6156fa8 | ||
|
|
428ea5e864 | ||
|
|
2b6d1201b6 | ||
|
|
de3524d688 | ||
|
|
61a529e62b | ||
|
|
a5d225dc44 | ||
|
|
7b28a274a8 | ||
|
|
26508e6a8a | ||
|
|
c8d91032c0 | ||
|
|
7a8e910697 | ||
|
|
31d6fc8197 | ||
|
|
e23e267d17 | ||
|
|
c727286d22 | ||
|
|
3a61c32881 | ||
|
|
e33fd6ea1b | ||
|
|
aa8e3ac09b | ||
|
|
eb49dcfc54 | ||
|
|
6182b2bcee | ||
|
|
6e091230cf | ||
|
|
5f45d28b9f | ||
|
|
f8e9c16bc1 | ||
|
|
a66b7a6eab | ||
|
|
3b42b52ff4 | ||
|
|
df5293ce1e | ||
|
|
664ff6aabd | ||
|
|
0de62ce010 | ||
|
|
9eafbacad9 | ||
|
|
058eb31110 | ||
|
|
29de8f5706 | ||
|
|
ef869dbe09 | ||
|
|
9f8b320493 | ||
|
|
ef72e04be3 | ||
|
|
38d280b7f4 | ||
|
|
468356d676 | ||
|
|
7364700899 | ||
|
|
e65f19cf24 | ||
|
|
4272dfe03d | ||
|
|
3b739328fb | ||
|
|
81c3dca740 | ||
|
|
dceb3121b1 | ||
|
|
cb60a97b91 | ||
|
|
eb658396d2 | ||
|
|
0a1cefdb76 | ||
|
|
fb618e6719 | ||
|
|
2d529539cd | ||
|
|
9d93a98a58 | ||
|
|
38dcb10a6e | ||
|
|
50651339ec | ||
|
|
d0b2889fec | ||
|
|
3ce1f94f87 | ||
|
|
888967be31 | ||
|
|
6826237657 | ||
|
|
a8987cf1d3 | ||
|
|
d48a74912a | ||
|
|
1668b7c9a1 | ||
|
|
efa2cfb50b | ||
|
|
071b1a54d5 | ||
|
|
7c3bba2ffd | ||
|
|
d58092968a | ||
|
|
1b20bb06ad | ||
|
|
5815a04712 | ||
|
|
85c449bec0 | ||
|
|
10bdddb262 | ||
|
|
b65875386d | ||
|
|
76b5e09f72 | ||
|
|
0fe07695b2 | ||
|
|
51f9b4f473 | ||
|
|
153e1b92bf | ||
|
|
fc5ae7403a | ||
|
|
13149eff08 | ||
|
|
9c53d9bf87 | ||
|
|
bc9625fece | ||
|
|
7e00162ef2 | ||
|
|
af38750e29 | ||
|
|
314f4850bc | ||
|
|
9ff2a83ba3 | ||
|
|
2ab466c570 | ||
|
|
184ba84600 | ||
|
|
99dddb1af4 | ||
|
|
48eca3f5af | ||
|
|
71192cc2ee | ||
|
|
29c7344540 | ||
|
|
6411d23744 | ||
|
|
1a74736115 | ||
|
|
7c11ecb3a7 | ||
|
|
fd7c833de0 | ||
|
|
7fec8b0d7e | ||
|
|
52622fadbb | ||
|
|
57255e0aec | ||
|
|
17ecfa132d | ||
|
|
d1365c3d7d | ||
|
|
c33891a4bc | ||
|
|
9a63f57147 | ||
|
|
839a62cb07 | ||
|
|
dc598e466e | ||
|
|
b698697256 | ||
|
|
f802d1524f | ||
|
|
0cb18f9e1a | ||
|
|
ba722487d8 | ||
|
|
eff2634b32 | ||
|
|
1470aefd42 | ||
|
|
b7fd87b09c | ||
|
|
ab82a1656d | ||
|
|
71387e94d8 | ||
|
|
503379079b | ||
|
|
1ae767087f | ||
|
|
cfd2b7b7aa | ||
|
|
2c42b4c585 | ||
|
|
d3a9ff539e | ||
|
|
58f01bd642 | ||
|
|
38806740e1 | ||
|
|
df583e73c2 | ||
|
|
e787d33e5a | ||
|
|
91db665428 | ||
|
|
94d155cff2 | ||
|
|
ad79075fd7 | ||
|
|
7baefe2f44 | ||
|
|
141a4c29bb | ||
|
|
b2992da370 | ||
|
|
fdee254020 | ||
|
|
c51489ac74 | ||
|
|
3cd394ec10 | ||
|
|
8374fea776 | ||
|
|
733ca891de | ||
|
|
490d121db3 | ||
|
|
45c5efffbd | ||
|
|
a24c929acf | ||
|
|
86a39f10d1 | ||
|
|
4658afdc20 | ||
|
|
ae6c2afb30 | ||
|
|
a3844a3535 | ||
|
|
b710075544 | ||
|
|
c4c9786050 | ||
|
|
b4cc81139a | ||
|
|
fb20eb9162 | ||
|
|
263987d2c9 | ||
|
|
0b30a35383 | ||
|
|
47df1fc602 | ||
|
|
d8375454b9 | ||
|
|
ad535501c4 | ||
|
|
159f5cbd00 | ||
|
|
2bc74d5378 | ||
|
|
eb513f563e | ||
|
|
09dc5e9846 | ||
|
|
cf35a87d85 | ||
|
|
9f25f619a8 | ||
|
|
7e989c730c | ||
|
|
0926e86956 | ||
|
|
75967730fd | ||
|
|
a3be3e354f | ||
|
|
58c52196f1 | ||
|
|
b7b49a60cf | ||
|
|
fa195483d6 | ||
|
|
2341f6ea3b | ||
|
|
ffe0f0730d | ||
|
|
23b512910e | ||
|
|
b1c624b104 | ||
|
|
fe35be6682 | ||
|
|
2d3eb29bd5 | ||
|
|
26f0ff62df | ||
|
|
5e145846bd | ||
|
|
1ae5f99bf0 | ||
|
|
984119c7ee | ||
|
|
f8f5eac109 | ||
|
|
4111d5fa48 | ||
|
|
2eca9056b9 | ||
|
|
60e96572ff | ||
|
|
52193933b2 | ||
|
|
7bcabdda38 | ||
|
|
d993941c4d | ||
|
|
b447bff9a6 | ||
|
|
73cb5ffba4 | ||
|
|
7d694229c1 | ||
|
|
cdb6c9a1a4 | ||
|
|
cc1d2b423f | ||
|
|
508e031143 | ||
|
|
5a093a9a04 | ||
|
|
074d647d19 | ||
|
|
6cb98f99c5 | ||
|
|
7d28681b23 | ||
|
|
859a8e933c | ||
|
|
a476d5986d | ||
|
|
31812bc2d9 | ||
|
|
30ba69eca7 | ||
|
|
cf1bc1c252 | ||
|
|
ee109ba67d | ||
|
|
9c6211e8e0 | ||
|
|
0729e4ab09 | ||
|
|
5cbe728631 | ||
|
|
920f4df213 | ||
|
|
c48eacd9af | ||
|
|
30e6deeeaa | ||
|
|
5bc76a3160 | ||
|
|
114925ebce | ||
|
|
5a80a0cc06 | ||
|
|
aebefac7e6 | ||
|
|
b2d0ee41f2 | ||
|
|
9c20250b0a | ||
|
|
b196836fca | ||
|
|
d9fbcc615a | ||
|
|
fb247fb33f | ||
|
|
61f4dbd896 | ||
|
|
2c86571818 | ||
|
|
1b2ec67726 | ||
|
|
845af854bd | ||
|
|
15b6a66d98 | ||
|
|
c95ba0764b | ||
|
|
42c0648ba7 | ||
|
|
0a6e55dcb7 | ||
|
|
99b77decff | ||
|
|
9e2ca4e586 | ||
|
|
2e8acfdeef | ||
|
|
630096e06d | ||
|
|
d92d892dc7 | ||
|
|
a8f41841bd | ||
|
|
76954b5a0a | ||
|
|
c57b184a09 | ||
|
|
20ca4e0739 | ||
|
|
a972ed5e2e | ||
|
|
2b15bc6ebb | ||
|
|
f7a482659c | ||
|
|
99527453a7 | ||
|
|
3408b4637c | ||
|
|
3f2899e97e | ||
|
|
562496cfaa | ||
|
|
8283f19d6b | ||
|
|
242909b542 | ||
|
|
a7b83ad5e0 | ||
|
|
ed66019d9a | ||
|
|
bc0009be6c | ||
|
|
c88f47eed4 | ||
|
|
59de048ced | ||
|
|
7987dfb819 | ||
|
|
1b101106e7 | ||
|
|
7b75955aec | ||
|
|
8f5467e6ca | ||
|
|
28764f92b9 | ||
|
|
777dfe4c62 | ||
|
|
0878a704d9 | ||
|
|
f880897542 | ||
|
|
b37472a954 | ||
|
|
68735a45dd | ||
|
|
e26deb9092 | ||
|
|
43d6ea82cd | ||
|
|
db1aa495ac | ||
|
|
ee62d9ae8d | ||
|
|
4001124cfa | ||
|
|
43a4d0d1d7 | ||
|
|
632b432b7c | ||
|
|
e778c7a59d | ||
|
|
d71cdecd35 | ||
|
|
4a82541ffd | ||
|
|
f29dff3386 | ||
|
|
718d21f6cb | ||
|
|
440550ded9 | ||
|
|
593fe57ea1 | ||
|
|
e8a320dac9 | ||
|
|
3cb43e5d3e | ||
|
|
f86bdba3c3 | ||
|
|
98c3940297 | ||
|
|
b9e789bbcf | ||
|
|
a108846731 | ||
|
|
0b4ce8d6e7 | ||
|
|
42df61b7dd | ||
|
|
6b46fa4cbc | ||
|
|
c0762eba18 | ||
|
|
036fb848e1 | ||
|
|
7198ae9025 | ||
|
|
d2822b06aa | ||
|
|
17feca28b9 | ||
|
|
898d38cb6a | ||
|
|
95a99a2f0b | ||
|
|
29a1e8ad34 | ||
|
|
19f3a4f266 | ||
|
|
12ddbc308a | ||
|
|
999bc7604e | ||
|
|
3648de3a8d | ||
|
|
051fa0a28f | ||
|
|
72e667e825 | ||
|
|
5ed59b41b5 | ||
|
|
c7c0d1632e | ||
|
|
2dc73acd20 | ||
|
|
ed71668c48 | ||
|
|
801e154d15 | ||
|
|
a89b07394f | ||
|
|
982f9b7c58 | ||
|
|
789b9207b5 | ||
|
|
133dbb7471 | ||
|
|
5d3ec493cd | ||
|
|
6d7f234497 | ||
|
|
29a50bb640 | ||
|
|
843fddabde | ||
|
|
109ce0dd1f | ||
|
|
42508a82a0 | ||
|
|
d860d39f5f | ||
|
|
15396c611a | ||
|
|
41c4b12ae1 | ||
|
|
e51c30462f | ||
|
|
9b5df99a61 | ||
|
|
3535156ea5 | ||
|
|
577145096d | ||
|
|
89059510fd | ||
|
|
aabc14c639 | ||
|
|
c28872544c | ||
|
|
7b8a4e4d72 | ||
|
|
5dcdf670be | ||
|
|
9721890a3c | ||
|
|
1b9c4cfc23 | ||
|
|
98a552e9af | ||
|
|
e1e265a101 | ||
|
|
b60a854de0 | ||
|
|
d1bddeccc8 | ||
|
|
0a106e64d8 | ||
|
|
91d6181aec | ||
|
|
255c0a3359 | ||
|
|
3a5ef999f0 | ||
|
|
983aa845d6 | ||
|
|
d1779726e6 | ||
|
|
8e23062d0e | ||
|
|
7efbfffd99 | ||
|
|
ff4b2d2ecc | ||
|
|
e079be0ad7 | ||
|
|
a8a54aa443 | ||
|
|
88cbcf6baf | ||
|
|
8d6d26c9d2 | ||
|
|
a490df0f7e | ||
|
|
a46041c958 | ||
|
|
0a6a78bc58 | ||
|
|
c9e850515e | ||
|
|
0ff8da2cf0 | ||
|
|
c0ef3ccbea | ||
|
|
1ab628dee8 | ||
|
|
b24df24b10 | ||
|
|
341678d979 | ||
|
|
49d10273a6 | ||
|
|
5b05c018d5 | ||
|
|
d18d8c0ba4 | ||
|
|
84a8fb0074 | ||
|
|
a40fb7f4bd | ||
|
|
84eb3a3508 | ||
|
|
73a5d76503 | ||
|
|
50c35ed519 | ||
|
|
a7b7e3efea | ||
|
|
88e892196f | ||
|
|
7f08da96bb | ||
|
|
193f24768e | ||
|
|
a8bca3de98 | ||
|
|
9692a802d0 | ||
|
|
28a8b2e685 | ||
|
|
3c9121b4af | ||
|
|
dec1035258 | ||
|
|
9d81c86c1b | ||
|
|
eeb4f4681a | ||
|
|
676af0210b | ||
|
|
77c6a2890b | ||
|
|
c39e748749 | ||
|
|
36e5a6ac8d | ||
|
|
9bdcaa5eaa | ||
|
|
5511004db8 | ||
|
|
0e46cdb514 | ||
|
|
b028899949 | ||
|
|
55285427f1 | ||
|
|
763a6cb31a | ||
|
|
24cb1aa84f | ||
|
|
886aa4938d | ||
|
|
8871651549 | ||
|
|
2ae8ef87d9 | ||
|
|
de4fbe05f7 | ||
|
|
b8abed37c2 | ||
|
|
255e26435c | ||
|
|
9e0550619b | ||
|
|
5c171fd0f0 | ||
|
|
3dd3b710b7 | ||
|
|
3c0485cfa9 | ||
|
|
d5ba405de0 | ||
|
|
71b8bca86d | ||
|
|
c53b9eabd6 | ||
|
|
6d6434b4d4 | ||
|
|
a447e88b86 | ||
|
|
e2d2e00913 | ||
|
|
cbfea37b3a | ||
|
|
d6de647974 | ||
|
|
dad36c73e5 | ||
|
|
936a1d60a0 |
No files matched your search
@@ -0,0 +1,31 @@
|
|||||||
|
---
|
||||||
|
name: Bug report
|
||||||
|
about: Create a report to help us improve Libation
|
||||||
|
title: ''
|
||||||
|
labels: bug
|
||||||
|
assignees: ''
|
||||||
|
---
|
||||||
|
|
||||||
|
**Describe the bug**
|
||||||
|
A clear and concise description of what the bug is.
|
||||||
|
|
||||||
|
**To Reproduce**
|
||||||
|
Steps to reproduce the behavior:
|
||||||
|
|
||||||
|
1. Go to '...'
|
||||||
|
2. Click on '....'
|
||||||
|
3. Scroll down to '....'
|
||||||
|
4. See error
|
||||||
|
|
||||||
|
**Expected behavior**
|
||||||
|
A clear and concise description of what you expected to happen.
|
||||||
|
|
||||||
|
**Screenshots**
|
||||||
|
If applicable, add screenshots to help explain your problem.
|
||||||
|
|
||||||
|
**Platform**
|
||||||
|
|
||||||
|
[e.g. Windows 10, Windows 11, Mac, Linux (State distribution)]
|
||||||
|
|
||||||
|
**Log Files**
|
||||||
|
Attach your Libation log file here.
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
---
|
||||||
|
name: Feature request
|
||||||
|
about: Suggest an idea for this project
|
||||||
|
title: ''
|
||||||
|
labels: enhancement
|
||||||
|
assignees: ''
|
||||||
|
---
|
||||||
|
|
||||||
|
**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.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
---
|
||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
# Maintain dependencies for GitHub Actions
|
||||||
|
- package-ecosystem: "github-actions"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: "daily"
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
# build-linux.yml
|
||||||
|
# Reusable workflow that builds the Linux and MacOS versions of Libation.
|
||||||
|
---
|
||||||
|
name: build
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
version_override:
|
||||||
|
type: string
|
||||||
|
description: 'Version number override'
|
||||||
|
required: false
|
||||||
|
run_unit_tests:
|
||||||
|
type: boolean
|
||||||
|
description: 'Skip running unit tests'
|
||||||
|
required: false
|
||||||
|
default: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
DOTNET_CONFIGURATION: 'Release'
|
||||||
|
DOTNET_VERSION: '7.0.x'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [Linux, MacOS]
|
||||||
|
ui: [Avalonia]
|
||||||
|
release_name: [chardonnay]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- name: Setup .NET
|
||||||
|
uses: actions/setup-dotnet@v3
|
||||||
|
with:
|
||||||
|
dotnet-version: ${{ env.DOTNET_VERSION }}
|
||||||
|
env:
|
||||||
|
NUGET_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Get version
|
||||||
|
id: get_version
|
||||||
|
run: |
|
||||||
|
inputVersion="${{ inputs.version_override }}"
|
||||||
|
if [[ "${#inputVersion}" -gt 0 ]]
|
||||||
|
then
|
||||||
|
version="${inputVersion}"
|
||||||
|
else
|
||||||
|
version="$(grep -oP '(?<=<Version>).*(?=</Version)' ./Source/AppScaffolding/AppScaffolding.csproj)"
|
||||||
|
fi
|
||||||
|
echo "version=${version}" >> "${GITHUB_OUTPUT}"
|
||||||
|
|
||||||
|
- name: Unit test
|
||||||
|
if: ${{ inputs.run_unit_tests }}
|
||||||
|
working-directory: ./Source
|
||||||
|
run: dotnet test
|
||||||
|
|
||||||
|
- name: Publish
|
||||||
|
working-directory: ./Source
|
||||||
|
run: |
|
||||||
|
dotnet publish -c ${{ env.DOTNET_CONFIGURATION }} -o bin/Publish/${{ matrix.os }}-${{ matrix.release_name }} Libation${{ matrix.ui }}/Libation${{ matrix.ui }}.csproj -p:PublishProfile=Libation${{ matrix.ui }}/Properties/PublishProfiles/${{ matrix.os }}Profile.pubxml
|
||||||
|
dotnet publish -c ${{ env.DOTNET_CONFIGURATION }} -o bin/Publish/${{ matrix.os }}-${{ matrix.release_name }} LoadByOS/${{ matrix.os }}ConfigApp/${{ matrix.os }}ConfigApp.csproj -p:PublishProfile=LoadByOS/Properties/${{ matrix.os }}ConfigApp/PublishProfiles/${{ matrix.os }}Profile.pubxml
|
||||||
|
dotnet publish -c ${{ env.DOTNET_CONFIGURATION }} -o bin/Publish/${{ matrix.os }}-${{ matrix.release_name }} LibationCli/LibationCli.csproj -p:PublishProfile=LibationCli/Properties/PublishProfiles/${{ matrix.os }}Profile.pubxml
|
||||||
|
dotnet publish -c ${{ env.DOTNET_CONFIGURATION }} -o bin/Publish/${{ matrix.os }}-${{ matrix.release_name }} Hangover${{ matrix.ui }}/Hangover${{ matrix.ui }}.csproj -p:PublishProfile=Hangover${{ matrix.ui }}/Properties/PublishProfiles/${{ matrix.os }}Profile.pubxml
|
||||||
|
|
||||||
|
- name: Zip artifact
|
||||||
|
id: zip
|
||||||
|
working-directory: ./Source/bin/Publish/${{ matrix.os }}-${{ matrix.release_name }}
|
||||||
|
run: |
|
||||||
|
osbuild="$(echo '${{ matrix.os }}' | tr '[:upper:]' '[:lower:]')"
|
||||||
|
artifact="Libation.${{ steps.get_version.outputs.version }}-${osbuild}-${{ matrix.release_name }}"
|
||||||
|
echo "artifact=${artifact}" >> "${GITHUB_OUTPUT}"
|
||||||
|
tar -zcvf "../${artifact}.tar.gz" .
|
||||||
|
|
||||||
|
- name: Publish artifact
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: ${{ steps.zip.outputs.artifact }}.tar.gz
|
||||||
|
path: ./Source/bin/Publish/${{ steps.zip.outputs.artifact }}.tar.gz
|
||||||
|
if-no-files-found: error
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# build-windows.yml
|
||||||
|
# Reusable workflow that builds the Windows versions of Libation.
|
||||||
|
---
|
||||||
|
name: build
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
version_override:
|
||||||
|
type: string
|
||||||
|
description: 'Version number override'
|
||||||
|
required: false
|
||||||
|
run_unit_tests:
|
||||||
|
type: boolean
|
||||||
|
description: 'Skip running unit tests'
|
||||||
|
required: false
|
||||||
|
default: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
DOTNET_CONFIGURATION: 'Release'
|
||||||
|
DOTNET_VERSION: '7.0.x'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: windows-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [Windows]
|
||||||
|
ui: [Avalonia]
|
||||||
|
release_name: [chardonnay]
|
||||||
|
include:
|
||||||
|
- os: Windows
|
||||||
|
ui: WinForms
|
||||||
|
release_name: classic
|
||||||
|
prefix: Classic-
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- name: Setup .NET
|
||||||
|
uses: actions/setup-dotnet@v3
|
||||||
|
with:
|
||||||
|
dotnet-version: ${{ env.DOTNET_VERSION }}
|
||||||
|
env:
|
||||||
|
NUGET_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Get version
|
||||||
|
id: get_version
|
||||||
|
run: |
|
||||||
|
if ("${{ inputs.version_override }}".length -gt 0) {
|
||||||
|
$version = "${{ inputs.version_override }}"
|
||||||
|
} else {
|
||||||
|
[xml]$appScaffolding = Get-Content -Path ./Source/AppScaffolding/AppScaffolding.csproj
|
||||||
|
$version = $appScaffolding.Project.PropertyGroup.Version
|
||||||
|
}
|
||||||
|
"version=$version" >> $env:GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Unit test
|
||||||
|
if: ${{ inputs.run_unit_tests }}
|
||||||
|
working-directory: ./Source
|
||||||
|
run: dotnet test
|
||||||
|
|
||||||
|
- name: Publish
|
||||||
|
working-directory: ./Source
|
||||||
|
run: |
|
||||||
|
dotnet publish -c ${{ env.DOTNET_CONFIGURATION }} -o bin/Publish/${{ matrix.os }}-${{ matrix.release_name }} Libation${{ matrix.ui }}/Libation${{ matrix.ui }}.csproj -p:PublishProfile=Libation${{ matrix.ui }}/Properties/PublishProfiles/${{ matrix.os }}Profile.pubxml
|
||||||
|
dotnet publish -c ${{ env.DOTNET_CONFIGURATION }} -o bin/Publish/${{ matrix.os }}-${{ matrix.release_name }} LoadByOS/${{ matrix.os }}ConfigApp/${{ matrix.os }}ConfigApp.csproj -p:PublishProfile=LoadByOS/Properties/${{ matrix.os }}ConfigApp/PublishProfiles/${{ matrix.os }}Profile.pubxml
|
||||||
|
dotnet publish -c ${{ env.DOTNET_CONFIGURATION }} -o bin/Publish/${{ matrix.os }}-${{ matrix.release_name }} LibationCli/LibationCli.csproj -p:PublishProfile=LibationCli/Properties/PublishProfiles/${{ matrix.os }}Profile.pubxml
|
||||||
|
dotnet publish -c ${{ env.DOTNET_CONFIGURATION }} -o bin/Publish/${{ matrix.os }}-${{ matrix.release_name }} Hangover${{ matrix.ui }}/Hangover${{ matrix.ui }}.csproj -p:PublishProfile=Hangover${{ matrix.ui }}/Properties/PublishProfiles/${{ matrix.os }}Profile.pubxml
|
||||||
|
|
||||||
|
- name: Zip artifact
|
||||||
|
id: zip
|
||||||
|
working-directory: ./Source/bin/Publish
|
||||||
|
run: |
|
||||||
|
$artifact="${{ matrix.prefix }}Libation.${{ steps.get_version.outputs.version }}-" + "${{ matrix.os }}".ToLower() + "-${{ matrix.release_name }}"
|
||||||
|
"artifact=$artifact" >> $env:GITHUB_OUTPUT
|
||||||
|
Compress-Archive -Path "${{ matrix.os }}-${{ matrix.release_name }}\*" -DestinationPath "$artifact.zip"
|
||||||
|
|
||||||
|
- name: Publish artifact
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: ${{ steps.zip.outputs.artifact }}.zip
|
||||||
|
path: ./Source/bin/Publish/${{ steps.zip.outputs.artifact }}.zip
|
||||||
|
if-no-files-found: error
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# build.yml
|
||||||
|
# Reusable workflow that builds Libation for all platforms.
|
||||||
|
---
|
||||||
|
name: build
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
version_override:
|
||||||
|
type: string
|
||||||
|
description: 'Version number override'
|
||||||
|
required: false
|
||||||
|
run_unit_tests:
|
||||||
|
type: boolean
|
||||||
|
description: 'Skip running unit tests'
|
||||||
|
required: false
|
||||||
|
default: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
windows:
|
||||||
|
uses: ./.github/workflows/build-windows.yml
|
||||||
|
with:
|
||||||
|
version_override: ${{ inputs.version_override }}
|
||||||
|
run_unit_tests: ${{ inputs.run_unit_tests }}
|
||||||
|
|
||||||
|
linux:
|
||||||
|
uses: ./.github/workflows/build-linux.yml
|
||||||
|
with:
|
||||||
|
version_override: ${{ inputs.version_override }}
|
||||||
|
run_unit_tests: ${{ inputs.run_unit_tests }}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# docker.yml
|
||||||
|
# Reusable workflow that builds a docker image for Libation.
|
||||||
|
---
|
||||||
|
name: docker
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
version:
|
||||||
|
type: string
|
||||||
|
description: 'Version number'
|
||||||
|
required: true
|
||||||
|
secrets:
|
||||||
|
docker_username:
|
||||||
|
required: true
|
||||||
|
docker_token:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
DOCKER_IMAGE: ${{ secrets.docker_username }}/libation
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
docker:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v2
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v2
|
||||||
|
|
||||||
|
- name: Login to Docker Hub
|
||||||
|
uses: docker/login-action@v2
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.docker_username }}
|
||||||
|
password: ${{ secrets.docker_token }}
|
||||||
|
|
||||||
|
- name: Build and push
|
||||||
|
uses: docker/build-push-action@v3
|
||||||
|
with:
|
||||||
|
push: true
|
||||||
|
build-args: 'FOLDER_NAME=Linux-chardonnay'
|
||||||
|
tags: ${{ env.DOCKER_IMAGE }}:latest,${{ env.DOCKER_IMAGE }}:${{ inputs.version }}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# release.yml
|
||||||
|
# Builds and creates the release on any tags starting with a `v`
|
||||||
|
---
|
||||||
|
name: release
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
jobs:
|
||||||
|
prerelease:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
version: ${{ steps.get_version.outputs.version }}
|
||||||
|
steps:
|
||||||
|
- name: Get tag version
|
||||||
|
id: get_version
|
||||||
|
run: |
|
||||||
|
export TAG='${{ github.ref_name }}'
|
||||||
|
echo "version=${TAG#v}" >> "${GITHUB_OUTPUT}"
|
||||||
|
|
||||||
|
docker:
|
||||||
|
needs: [prerelease]
|
||||||
|
uses: ./.github/workflows/docker.yml
|
||||||
|
with:
|
||||||
|
version: ${{ needs.prerelease.outputs.version }}
|
||||||
|
secrets:
|
||||||
|
docker_username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||||
|
docker_token: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
|
|
||||||
|
build:
|
||||||
|
needs: [prerelease]
|
||||||
|
uses: ./.github/workflows/build.yml
|
||||||
|
with:
|
||||||
|
version_override: ${{ needs.prerelease.outputs.version }}
|
||||||
|
run_unit_tests: false
|
||||||
|
|
||||||
|
release:
|
||||||
|
needs: [prerelease,build]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Download artifacts
|
||||||
|
uses: actions/download-artifact@v3
|
||||||
|
with:
|
||||||
|
path: artifacts
|
||||||
|
|
||||||
|
- name: Create release
|
||||||
|
id: create_release
|
||||||
|
uses: actions/create-release@v1
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}'
|
||||||
|
with:
|
||||||
|
tag_name: '${{ github.ref }}'
|
||||||
|
release_name: 'Libation ${{ steps.version.outputs.version }}'
|
||||||
|
body: <Put a body here>
|
||||||
|
draft: true
|
||||||
|
prerelease: false
|
||||||
|
|
||||||
|
- name: Upload release assets
|
||||||
|
uses: dwenegar/upload-release-assets@v1
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}'
|
||||||
|
with:
|
||||||
|
release_id: '${{ steps.create_release.outputs.id }}'
|
||||||
|
assets_path: ./artifacts
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# validate.yml
|
||||||
|
# Validates that Libation will build on a pull request or push to master.
|
||||||
|
---
|
||||||
|
name: validate
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [master]
|
||||||
|
pull_request:
|
||||||
|
branches: [master]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
uses: ./.github/workflows/build.yml
|
||||||
+2
-1
@@ -184,7 +184,7 @@ publish/
|
|||||||
*.azurePubxml
|
*.azurePubxml
|
||||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||||
# but database connection strings (with potential passwords) will be unencrypted
|
# but database connection strings (with potential passwords) will be unencrypted
|
||||||
*.pubxml
|
#*.pubxml
|
||||||
*.publishproj
|
*.publishproj
|
||||||
|
|
||||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||||
@@ -370,3 +370,4 @@ FodyWeavers.xsd
|
|||||||
|
|
||||||
/__TODO.txt
|
/__TODO.txt
|
||||||
/DataLayer/LibationContext.db
|
/DataLayer/LibationContext.db
|
||||||
|
*/bin-Avalonia
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"WindowsClassic": "Libation\\.\\d+\\.\\d+\\.\\d+-win(dows)?-classic\\.zip",
|
||||||
|
"WindowsAvalonia": "Libation\\.\\d+\\.\\d+\\.\\d+-win(dows)?-chardonnay\\.zip",
|
||||||
|
"LinuxAvalonia": "Libation\\.\\d+\\.\\d+\\.\\d+-linux-chardonnay",
|
||||||
|
"MacOSAvalonia": "Libation\\.\\d+\\.\\d+\\.\\d+-macos-chardonnay"
|
||||||
|
}
|
||||||
Executable
+68
@@ -0,0 +1,68 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Rewire echo to print date time
|
||||||
|
echo() {
|
||||||
|
if [[ -n $1 ]]; then
|
||||||
|
printf "$(date '+%F %T'): %s\n" "$1"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# ################################
|
||||||
|
# Setup
|
||||||
|
# ################################
|
||||||
|
echo "Starting"
|
||||||
|
if [[ -z "${SLEEP_TIME}" ]]; then
|
||||||
|
echo "No sleep time passed in. Will run once and exit."
|
||||||
|
else
|
||||||
|
echo "Sleep time is set to ${SLEEP_TIME}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Check if the config directory is passed in, and there is no link to it then create the link.
|
||||||
|
if [ -d "/config" ] && [ ! -d "/root/Libation" ]; then
|
||||||
|
echo "Linking config directory to the Libation config directory"
|
||||||
|
ln -s /config/ /root/Libation
|
||||||
|
fi
|
||||||
|
|
||||||
|
# If no config error and exit
|
||||||
|
if [ ! -d "/config" ]; then
|
||||||
|
echo "ERROR: No /config directory. You must pass in a volume containing your config mapped to /config"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# If user passes in db from a /db/ folder and a db does not already exist / is not already linked
|
||||||
|
FILE=/db/LibationContext.db
|
||||||
|
if [ -f "${FILE}" ] && [ ! -f "/config/LibationContext.db" ]; then
|
||||||
|
echo "Linking passed in Libation database from /db/ to the Libation config directory"
|
||||||
|
ln -s $FILE /config/LibationContext.db
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Confirm we have a db in the config direcotry.
|
||||||
|
if [ ! -f "/config/LibationContext.db" ]; then
|
||||||
|
echo "ERROR: No Libation database detected, exiting."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ################################
|
||||||
|
# Loop and liberate
|
||||||
|
# ################################
|
||||||
|
while true
|
||||||
|
do
|
||||||
|
echo ""
|
||||||
|
echo "Scanning accounts"
|
||||||
|
/libation/LibationCli scan
|
||||||
|
echo "Liberating books"
|
||||||
|
/libation/LibationCli liberate
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Liberate only once if SLEEP_TIME was set to -1
|
||||||
|
if [ "${SLEEP_TIME}" = -1 ]; then
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Sleeping for ${SLEEP_TIME}"
|
||||||
|
sleep "${SLEEP_TIME}"
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "Exiting"
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
# Dockerfile
|
||||||
|
FROM mcr.microsoft.com/dotnet/sdk:7.0 as build-env
|
||||||
|
|
||||||
|
COPY Source /Source
|
||||||
|
RUN dotnet publish -c Release -o /Source/bin/Publish/Linux-chardonnay /Source/LibationCli/LibationCli.csproj -p:PublishProfile=/Source/LibationCli/Properties/PublishProfiles/LinuxProfile.pubxml
|
||||||
|
COPY Docker/liberate.sh /Source/bin/Publish/Linux-chardonnay
|
||||||
|
|
||||||
|
|
||||||
|
FROM mcr.microsoft.com/dotnet/runtime:7.0
|
||||||
|
|
||||||
|
ENV SLEEP_TIME "30m"
|
||||||
|
|
||||||
|
# Sets the character set that will be used for folder and filenames when liberating
|
||||||
|
ENV LANG C.UTF-8
|
||||||
|
ENV LC_ALL C.UTF-8
|
||||||
|
|
||||||
|
RUN mkdir /db /config /data
|
||||||
|
|
||||||
|
COPY --from=build-env /Source/bin/Publish/Linux-chardonnay /libation
|
||||||
|
|
||||||
|
|
||||||
|
CMD ["./libation/liberate.sh"]
|
||||||
@@ -8,7 +8,6 @@
|
|||||||
# Advanced: Table of Contents
|
# Advanced: Table of Contents
|
||||||
|
|
||||||
- [Files and folders](#files-and-folders)
|
- [Files and folders](#files-and-folders)
|
||||||
- [Linux and Mac (unofficial)](#linux-and-mac)
|
|
||||||
- [Settings](#settings)
|
- [Settings](#settings)
|
||||||
- [Custom File Naming](#custom-file-naming)
|
- [Custom File Naming](#custom-file-naming)
|
||||||
- [Command Line Interface](#command-line-interface)
|
- [Command Line Interface](#command-line-interface)
|
||||||
@@ -25,10 +24,6 @@ To make upgrades and reinstalls easier, Libation separates all of its responsibi
|
|||||||
|
|
||||||
* The last important folder is the "books location." This is where Libation looks for your downloaded and decrypted books. This is how it knows which books still need to be downloaded. The Audible id must be somewhere in the book's file or folder name for Libation to detect your downloaded book.
|
* The last important folder is the "books location." This is where Libation looks for your downloaded and decrypted books. This is how it knows which books still need to be downloaded. The Audible id must be somewhere in the book's file or folder name for Libation to detect your downloaded book.
|
||||||
|
|
||||||
### Linux and Mac
|
|
||||||
|
|
||||||
Although Libation only currently officially supports Windows, some users have had success with WINE. ([Linux](https://github.com/rmcrackan/Libation/issues/28#issuecomment-890594158), [OSX Crossover and WINE](https://github.com/rmcrackan/Libation/issues/150#issuecomment-1004918592))
|
|
||||||
|
|
||||||
### Settings
|
### Settings
|
||||||
|
|
||||||
* Allow Libation to fix up audiobook metadata. After decrypting a title, Libation attempts to fix details like chapters and cover art. Some power users and/or control freaks prefer to manage this themselves. By unchecking this setting, Libation will only decrypt the book and will leave metadata as-is, warts and all.
|
* Allow Libation to fix up audiobook metadata. After decrypting a title, Libation attempts to fix details like chapters and cover art. Some power users and/or control freaks prefer to manage this themselves. By unchecking this setting, Libation will only decrypt the book and will leave metadata as-is, warts and all.
|
||||||
@@ -76,4 +71,15 @@ export library to file
|
|||||||
libationcli export -p "C:\foo\bar\my.csv" -c
|
libationcli export -p "C:\foo\bar\my.csv" -c
|
||||||
libationcli export -p "C:\foo\bar\my.xlsx" --xlsx
|
libationcli export -p "C:\foo\bar\my.xlsx" --xlsx
|
||||||
libationcli export -p "C:\foo\bar\my.xlsx" -x
|
libationcli export -p "C:\foo\bar\my.xlsx" -x
|
||||||
|
|
||||||
|
Set download statuses throughout library based on whether each book's audio file can be found.
|
||||||
|
Must include at least one flag: --downloaded , --not-downloaded.
|
||||||
|
Downloaded: If the audio file can be found, set download status to 'Downloaded'.
|
||||||
|
Not Downloaded: If the audio file cannot be found, set download status to 'Not Downloaded'
|
||||||
|
UI: Visible Books \> Set 'Downloaded' status automatically. Visible books. Prompts before saving changes
|
||||||
|
CLI: Full library. No prompt
|
||||||
|
|
||||||
|
libationcli set-status -d
|
||||||
|
libationcli set-status -n
|
||||||
|
libationcli set-status -d -n
|
||||||
```
|
```
|
||||||
@@ -22,7 +22,12 @@
|
|||||||
|
|
||||||
### Installation
|
### Installation
|
||||||
|
|
||||||
To install Libation, extract the zip file to a folder, for example `C:\Libation`, and then run Libation.exe from that folder to begin the configuration process and configure your account(s).
|
* Windows
|
||||||
|
|
||||||
|
Extract the zip file to a folder and then run `Libation.exe` from inside of that folder. Do not put it in Program Files. The inability to edit files from there causes problems with configuration and updating.
|
||||||
|
|
||||||
|
* [Ubuntu Linux (beta)](InstallOnLinux.md)
|
||||||
|
* [MacOS (beta)](InstallOnMac.md)
|
||||||
|
|
||||||
### Create Accounts
|
### Create Accounts
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
## [Download Libation](https://github.com/rmcrackan/Libation/releases/latest)
|
||||||
|
|
||||||
|
### If you found this useful, tell a friend. If you found this REALLY useful, you can click here to [PalPal.me](https://paypal.me/mcrackan?locale.x=en_us)
|
||||||
|
...or just tell more friends. As long as I'm maintaining this software, it will remain **free** and **open source**.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Run Libation on Ubuntu (Beta)
|
||||||
|
This walkthrough should get you up and running with Libation on your Ubuntu machine.
|
||||||
|
|
||||||
|
Some limitations of the linux release are:
|
||||||
|
- Cannot customize how illegial filename characters are replaced.
|
||||||
|
- The Auto-update function is unavailable
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
### FFMpeg (Optional)
|
||||||
|
If you want to convert your audiobooks to mp3, install FFMpeg using the following command:
|
||||||
|
|
||||||
|
```console
|
||||||
|
sudo apt-get install -y ffmpeg
|
||||||
|
```
|
||||||
|
|
||||||
|
## Install Libation
|
||||||
|
|
||||||
|
Download the most recent linux-64 binaries zip file and save it as `libation-linux-bin.zip`. Save the 'install-libation.sh' bash script to a file. From the terminal make the script file executable:
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>install-libation.sh</summary>
|
||||||
|
|
||||||
|
```BASH
|
||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
FILE=$1
|
||||||
|
|
||||||
|
if [ -z "$FILE" ]
|
||||||
|
then echo "This script must be called with a the Libation Linux bin zip file as an argument."
|
||||||
|
exit
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "$EUID" -ne 0 ]]
|
||||||
|
then echo "Please run as root"
|
||||||
|
exit
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -f "$FILE" ]
|
||||||
|
then echo "The file \"$FILE\" does not exist."
|
||||||
|
exit
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Extracting $FILE"
|
||||||
|
|
||||||
|
FOLDER="$(dirname "$FILE")/libation_src"
|
||||||
|
echo "$FOLDER"
|
||||||
|
|
||||||
|
sudo -u $SUDO_USER unzip -q -o ${FILE} -d ${FOLDER}
|
||||||
|
|
||||||
|
if [ $? -ne 0 ]
|
||||||
|
then echo "Error unzipping ${FILE}"
|
||||||
|
exit
|
||||||
|
fi
|
||||||
|
|
||||||
|
sudo -u $SUDO_USER chmod +700 ${FOLDER}/Libation
|
||||||
|
sudo -u $SUDO_USER chmod +700 ${FOLDER}/Hangover
|
||||||
|
sudo -u $SUDO_USER chmod +700 ${FOLDER}/LibationCli
|
||||||
|
|
||||||
|
#Remove previous installation program files and sym link
|
||||||
|
rm /usr/bin/Libation
|
||||||
|
rm /usr/bin/Hangover
|
||||||
|
rm /usr/bin/LibationCli
|
||||||
|
rm /usr/bin/libationcli
|
||||||
|
rm /usr/lib/libation -r
|
||||||
|
|
||||||
|
#Copy install files, icon and desktop file
|
||||||
|
cp ${FOLDER}/glass-with-glow_256.svg /usr/share/icons/hicolor/scalable/apps/libation.svg
|
||||||
|
cp ${FOLDER}/Libation.desktop /usr/share/applications/Libation.desktop
|
||||||
|
mv ${FOLDER}/ /usr/lib/libation
|
||||||
|
|
||||||
|
chmod +666 /usr/share/icons/hicolor/scalable/apps/libation.svg
|
||||||
|
gtk-update-icon-cache -f /usr/share/icons/hicolor/
|
||||||
|
ln -s /usr/lib/libation/Libation /usr/bin/Libation
|
||||||
|
ln -s /usr/lib/libation/Hangover /usr/bin/Hangover
|
||||||
|
ln -s /usr/lib/libation/LibationCli /usr/bin/LibationCli
|
||||||
|
ln -s /usr/lib/libation/LibationCli /usr/bin/libationcli
|
||||||
|
|
||||||
|
echo "Done!"
|
||||||
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
|
```console
|
||||||
|
chmod +700 install-libation.sh
|
||||||
|
```
|
||||||
|
Then run the script with the libation binaries zipfile as an argument.
|
||||||
|
```console
|
||||||
|
sudo ./install-libation.sh libation-linux-bin.zip
|
||||||
|
```
|
||||||
|
|
||||||
|
You should now see Libation among your applications.
|
||||||
|
|
||||||
|
Report bugs to https://github.com/rmcrackan/Libation/issues
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
## [Download Libation](https://github.com/rmcrackan/Libation/releases/latest)
|
||||||
|
|
||||||
|
### If you found this useful, tell a friend. If you found this REALLY useful, you can click here to [PalPal.me](https://paypal.me/mcrackan?locale.x=en_us)
|
||||||
|
...or just tell more friends. As long as I'm maintaining this software, it will remain **free** and **open source**.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Run Libation on MacOS (Beta)
|
||||||
|
This walkthrough should get you up and running with Libation on your Mac.
|
||||||
|
|
||||||
|
## Install Libation
|
||||||
|
|
||||||
|
- Download latest MacOS zip to downloads folder
|
||||||
|
- Extract and rename folder to Libation
|
||||||
|
- in terminal type cd and then drag your folder of libation to terminal so it looks like `cd/users/YourName/Downloads/Libation`
|
||||||
|
- Type following commands
|
||||||
|
|
||||||
|
```console
|
||||||
|
chmod +x ./Libation
|
||||||
|
sudo spctl --add --label "Libation" ./Libation
|
||||||
|
./Libation
|
||||||
|
```
|
||||||
|
|
||||||
|
## Trouble with Gatekeeper?
|
||||||
|
|
||||||
|
If Gatekeeper is giving you trouble with Libation:
|
||||||
|
|
||||||
|
Disable the block
|
||||||
|
|
||||||
|
`sudo spctl --master-disable`
|
||||||
|
|
||||||
|
Launch Libation and login, etc. and allow the rules to update then re-enable the block.
|
||||||
|
|
||||||
|
`sudo spctl --master-enable`
|
||||||
|
|
||||||
|
Once Gatekeeper reenabled, you can open Libation again without it being blocked.
|
||||||
|
|
||||||
|
Thanks [joseph-holland](https://github.com/rmcrackan/Libation/issues/327#issuecomment-1268993349)!
|
||||||
|
|
||||||
|
Report bugs to https://github.com/rmcrackan/Libation/issues
|
||||||
@@ -40,7 +40,7 @@ Libation's advanced searching is built on the powerful Lucene search engine. Sim
|
|||||||
* Full official guide: https://lucene.apache.org/core/2_9_4/queryparsersyntax.html
|
* Full official guide: https://lucene.apache.org/core/2_9_4/queryparsersyntax.html
|
||||||
* Tons of search fields, specific to audiobooks
|
* Tons of search fields, specific to audiobooks
|
||||||
* Synonyms so you don't have to memorize magic words. Eg: author and author**s** will both work
|
* Synonyms so you don't have to memorize magic words. Eg: author and author**s** will both work
|
||||||
* Click [?] button for a full list of search fields and synonyms 
|
* Click [?] button for a full list of search fields and synonyms 
|
||||||
* Search by tag like \[this\]
|
* Search by tag like \[this\]
|
||||||
* When tags have an underscore you can use part of the tag. This is useful for quick categories. The below examples make this more clear.
|
* When tags have an underscore you can use part of the tag. This is useful for quick categories. The below examples make this more clear.
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,6 @@
|
|||||||
- [Filters](Documentation/SearchingAndFiltering.md#filters)
|
- [Filters](Documentation/SearchingAndFiltering.md#filters)
|
||||||
- [Advanced](Documentation/Advanced.md)
|
- [Advanced](Documentation/Advanced.md)
|
||||||
- [Files and folders](Documentation/Advanced.md#files-and-folders)
|
- [Files and folders](Documentation/Advanced.md#files-and-folders)
|
||||||
- [Linux and Mac (unofficial)](Documentation/Advanced.md#linux-and-mac)
|
|
||||||
- [Settings](Documentation/Advanced.md#settings)
|
- [Settings](Documentation/Advanced.md#settings)
|
||||||
- [Custom File Naming](Documentation/Advanced.md#custom-file-naming)
|
- [Custom File Naming](Documentation/Advanced.md#custom-file-naming)
|
||||||
- [Command Line Interface](Documentation/Advanced.md#command-line-interface)
|
- [Command Line Interface](Documentation/Advanced.md#command-line-interface)
|
||||||
@@ -54,7 +53,7 @@
|
|||||||
|
|
||||||
### The bad
|
### The bad
|
||||||
|
|
||||||
* Windows only
|
* Only fully supported in Windows. (Mac and Linux are in beta)
|
||||||
* Large file size
|
* Large file size
|
||||||
* Made by a programmer, not a designer so the goals are function rather than beauty. And it shows
|
* Made by a programmer, not a designer so the goals are function rather than beauty. And it shows
|
||||||
|
|
||||||
@@ -66,4 +65,4 @@
|
|||||||
|
|
||||||
Disclaimer: I've made every good-faith effort to include nothing insecure, malicious, anti-privacy, or destructive. That said: use at your own risk.
|
Disclaimer: I've made every good-faith effort to include nothing insecure, malicious, anti-privacy, or destructive. That said: use at your own risk.
|
||||||
|
|
||||||
I made this for myself and I want to share it with the great programming and audible/audiobook communiites which have been so generous with their time and help.
|
I made this for myself and I want to share it with the great programming and audible/audiobook communities which have been so generous with their time and help.
|
||||||
@@ -1,15 +1,22 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net6.0-windows</TargetFramework>
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
<PackageReference Include="AAXClean" Version="0.4.6" />
|
<DebugType>embedded</DebugType>
|
||||||
<PackageReference Include="AAXClean.Codecs" Version="0.2.7" />
|
</PropertyGroup>
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="AAXClean.Codecs" Version="0.2.15" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\FileManager\FileManager.csproj" />
|
<ProjectReference Include="..\FileManager\FileManager.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using AAXClean;
|
using AAXClean;
|
||||||
using Dinah.Core.Net.Http;
|
using Dinah.Core.Net.Http;
|
||||||
|
|
||||||
@@ -10,8 +11,8 @@ namespace AaxDecrypter
|
|||||||
|
|
||||||
protected AaxFile AaxFile;
|
protected AaxFile AaxFile;
|
||||||
|
|
||||||
protected AaxcDownloadConvertBase(string outFileName, string cacheDirectory, DownloadOptions dlLic)
|
protected AaxcDownloadConvertBase(string outFileName, string cacheDirectory, IDownloadOptions dlOptions)
|
||||||
: base(outFileName, cacheDirectory, dlLic) { }
|
: base(outFileName, cacheDirectory, dlOptions) { }
|
||||||
|
|
||||||
/// <summary>Setting cover art by this method will insert the art into the audiobook metadata</summary>
|
/// <summary>Setting cover art by this method will insert the art into the audiobook metadata</summary>
|
||||||
public override void SetCoverArt(byte[] coverArt)
|
public override void SetCoverArt(byte[] coverArt)
|
||||||
@@ -31,29 +32,17 @@ namespace AaxDecrypter
|
|||||||
AaxFile.AppleTags.Album = AaxFile.AppleTags.Album?.Replace(" (Unabridged)", "");
|
AaxFile.AppleTags.Album = AaxFile.AppleTags.Album?.Replace(" (Unabridged)", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (DownloadOptions.FixupFile)
|
||||||
|
AaxFile.AppleTags.AppleListBox.EditOrAddTag("TCOM", AaxFile.AppleTags.Narrator);
|
||||||
|
|
||||||
//Finishing configuring lame encoder.
|
//Finishing configuring lame encoder.
|
||||||
if (DownloadOptions.OutputFormat == OutputFormat.Mp3)
|
if (DownloadOptions.OutputFormat == OutputFormat.Mp3)
|
||||||
{
|
MpegUtil.ConfigureLameOptions(
|
||||||
double bitrateMultiple = 1;
|
AaxFile,
|
||||||
|
DownloadOptions.LameConfig,
|
||||||
|
DownloadOptions.Downsample,
|
||||||
|
DownloadOptions.MatchSourceBitrate);
|
||||||
|
|
||||||
if (AaxFile.AudioChannels == 2)
|
|
||||||
{
|
|
||||||
if (DownloadOptions.Downsample)
|
|
||||||
bitrateMultiple = 0.5;
|
|
||||||
else
|
|
||||||
DownloadOptions.LameConfig.Mode = NAudio.Lame.MPEGMode.Stereo;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (DownloadOptions.MatchSourceBitrate)
|
|
||||||
{
|
|
||||||
int kbps = (int)(AaxFile.AverageBitrate * bitrateMultiple / 1024);
|
|
||||||
|
|
||||||
if (DownloadOptions.LameConfig.VBR is null)
|
|
||||||
DownloadOptions.LameConfig.BitRate = kbps;
|
|
||||||
else if (DownloadOptions.LameConfig.VBR == NAudio.Lame.VBRMode.ABR)
|
|
||||||
DownloadOptions.LameConfig.ABRRateKbps = kbps;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
OnRetrievedTitle(AaxFile.AppleTags.TitleSansUnabridged);
|
OnRetrievedTitle(AaxFile.AppleTags.TitleSansUnabridged);
|
||||||
OnRetrievedAuthors(AaxFile.AppleTags.FirstAuthor ?? "[unknown]");
|
OnRetrievedAuthors(AaxFile.AppleTags.FirstAuthor ?? "[unknown]");
|
||||||
@@ -109,10 +98,11 @@ namespace AaxDecrypter
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public override void Cancel()
|
public override async Task CancelAsync()
|
||||||
{
|
{
|
||||||
IsCanceled = true;
|
IsCanceled = true;
|
||||||
AaxFile?.Cancel();
|
if (AaxFile != null)
|
||||||
|
await AaxFile.CancelAsync();
|
||||||
AaxFile?.Dispose();
|
AaxFile?.Dispose();
|
||||||
CloseInputFileStream();
|
CloseInputFileStream();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,38 +2,82 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using AAXClean;
|
using AAXClean;
|
||||||
using AAXClean.Codecs;
|
using AAXClean.Codecs;
|
||||||
using Dinah.Core.StepRunner;
|
|
||||||
using FileManager;
|
using FileManager;
|
||||||
|
|
||||||
namespace AaxDecrypter
|
namespace AaxDecrypter
|
||||||
{
|
{
|
||||||
public class AaxcDownloadMultiConverter : AaxcDownloadConvertBase
|
public class AaxcDownloadMultiConverter : AaxcDownloadConvertBase
|
||||||
{
|
{
|
||||||
protected override StepSequence Steps { get; }
|
private static TimeSpan minChapterLength { get; } = TimeSpan.FromSeconds(3);
|
||||||
|
|
||||||
private Func<MultiConvertFileProperties, string> multipartFileNameCallback { get; }
|
|
||||||
|
|
||||||
private static TimeSpan minChapterLength { get; } = TimeSpan.FromSeconds(3);
|
|
||||||
private List<string> multiPartFilePaths { get; } = new List<string>();
|
private List<string> multiPartFilePaths { get; } = new List<string>();
|
||||||
|
|
||||||
public AaxcDownloadMultiConverter(string outFileName, string cacheDirectory, DownloadOptions dlLic,
|
public AaxcDownloadMultiConverter(string outFileName, string cacheDirectory, IDownloadOptions dlOptions)
|
||||||
Func<MultiConvertFileProperties, string> multipartFileNameCallback = null)
|
: base(outFileName, cacheDirectory, dlOptions) { }
|
||||||
: base(outFileName, cacheDirectory, dlLic)
|
|
||||||
{
|
|
||||||
Steps = new StepSequence
|
|
||||||
{
|
|
||||||
Name = "Download and Convert Aaxc To " + DownloadOptions.OutputFormat,
|
|
||||||
|
|
||||||
["Step 1: Get Aaxc Metadata"] = Step_GetMetadata,
|
public override async Task<bool> RunAsync()
|
||||||
["Step 2: Download Decrypted Audiobook"] = Step_DownloadAudiobookAsMultipleFilesPerChapter,
|
{
|
||||||
["Step 3: Cleanup"] = Step_Cleanup,
|
try
|
||||||
};
|
{
|
||||||
this.multipartFileNameCallback = multipartFileNameCallback ?? MultiConvertFileProperties.DefaultMultipartFilename;
|
Serilog.Log.Information("Begin download and convert Aaxc To {format}", DownloadOptions.OutputFormat);
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
//Step 1
|
||||||
|
Serilog.Log.Information("Begin Get Aaxc Metadata");
|
||||||
|
if (await Task.Run(Step_GetMetadata))
|
||||||
|
Serilog.Log.Information("Completed Get Aaxc Metadata");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Failed to Complete Get Aaxc Metadata");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Step 2
|
||||||
|
Serilog.Log.Information("Begin Download Decrypted Audiobook");
|
||||||
|
if (await Step_DownloadAudiobookAsMultipleFilesPerChapter())
|
||||||
|
Serilog.Log.Information("Completed Download Decrypted Audiobook");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Failed to Complete Download Decrypted Audiobook");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//Step 3
|
||||||
|
if (DownloadOptions.DownloadClipsBookmarks)
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Begin Downloading Clips and Bookmarks");
|
||||||
|
if (await Task.Run(Step_DownloadClipsBookmarks))
|
||||||
|
Serilog.Log.Information("Completed Downloading Clips and Bookmarks");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Failed to Download Clips and Bookmarks");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Step 4
|
||||||
|
Serilog.Log.Information("Begin Cleanup");
|
||||||
|
if (await Task.Run(Step_Cleanup))
|
||||||
|
Serilog.Log.Information("Completed Cleanup");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Failed to Complete Cleanup");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serilog.Log.Information("Completed download and convert Aaxc To {format}", DownloadOptions.OutputFormat);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Serilog.Log.Error(ex, "Error encountered in download and convert Aaxc To {format}", DownloadOptions.OutputFormat);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
https://github.com/rmcrackan/Libation/pull/127#issuecomment-939088489
|
https://github.com/rmcrackan/Libation/pull/127#issuecomment-939088489
|
||||||
|
|
||||||
If the chapter truly is empty, that is, 0 audio frames in length, then yes it is ignored.
|
If the chapter truly is empty, that is, 0 audio frames in length, then yes it is ignored.
|
||||||
@@ -56,86 +100,104 @@ The book will be split into the following files:
|
|||||||
01:41:00 - 02:05:00 | Book - 04 - Chapter 4.m4b
|
01:41:00 - 02:05:00 | Book - 04 - Chapter 4.m4b
|
||||||
|
|
||||||
That naming may not be desirable for everyone, but it's an easy change to instead use the last of the combined chapter's title in the file name.
|
That naming may not be desirable for everyone, but it's an easy change to instead use the last of the combined chapter's title in the file name.
|
||||||
*/
|
*/
|
||||||
private bool Step_DownloadAudiobookAsMultipleFilesPerChapter()
|
private async Task<bool> Step_DownloadAudiobookAsMultipleFilesPerChapter()
|
||||||
{
|
{
|
||||||
var zeroProgress = Step_DownloadAudiobook_Start();
|
var zeroProgress = Step_DownloadAudiobook_Start();
|
||||||
|
|
||||||
var chapters = DownloadOptions.ChapterInfo.Chapters.ToList();
|
var chapters = DownloadOptions.ChapterInfo.Chapters;
|
||||||
|
|
||||||
// Ensure split files are at least minChapterLength in duration.
|
// Ensure split files are at least minChapterLength in duration.
|
||||||
var splitChapters = new ChapterInfo(DownloadOptions.ChapterInfo.StartOffset);
|
var splitChapters = new ChapterInfo(DownloadOptions.ChapterInfo.StartOffset);
|
||||||
|
|
||||||
var runningTotal = TimeSpan.Zero;
|
var runningTotal = TimeSpan.Zero;
|
||||||
string title = "";
|
string title = "";
|
||||||
|
|
||||||
for (int i = 0; i < chapters.Count; i++)
|
for (int i = 0; i < chapters.Count; i++)
|
||||||
{
|
{
|
||||||
if (runningTotal == TimeSpan.Zero)
|
if (runningTotal == TimeSpan.Zero)
|
||||||
title = chapters[i].Title;
|
title = chapters[i].Title;
|
||||||
|
|
||||||
runningTotal += chapters[i].Duration;
|
runningTotal += chapters[i].Duration;
|
||||||
|
|
||||||
if (runningTotal >= minChapterLength)
|
if (runningTotal >= minChapterLength)
|
||||||
{
|
{
|
||||||
splitChapters.AddChapter(title, runningTotal);
|
splitChapters.AddChapter(title, runningTotal);
|
||||||
runningTotal = TimeSpan.Zero;
|
runningTotal = TimeSpan.Zero;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// reset, just in case
|
// reset, just in case
|
||||||
multiPartFilePaths.Clear();
|
multiPartFilePaths.Clear();
|
||||||
|
|
||||||
ConversionResult result;
|
ConversionResult result;
|
||||||
|
|
||||||
AaxFile.ConversionProgressUpdate += AaxFile_ConversionProgressUpdate;
|
AaxFile.ConversionProgressUpdate += AaxFile_ConversionProgressUpdate;
|
||||||
if (DownloadOptions.OutputFormat == OutputFormat.M4b)
|
if (DownloadOptions.OutputFormat == OutputFormat.M4b)
|
||||||
result = ConvertToMultiMp4a(splitChapters);
|
result = await ConvertToMultiMp4a(splitChapters);
|
||||||
else
|
else
|
||||||
result = ConvertToMultiMp3(splitChapters);
|
result = await ConvertToMultiMp3(splitChapters);
|
||||||
AaxFile.ConversionProgressUpdate -= AaxFile_ConversionProgressUpdate;
|
AaxFile.ConversionProgressUpdate -= AaxFile_ConversionProgressUpdate;
|
||||||
|
|
||||||
Step_DownloadAudiobook_End(zeroProgress);
|
Step_DownloadAudiobook_End(zeroProgress);
|
||||||
|
|
||||||
return result == ConversionResult.NoErrorsDetected;
|
return result == ConversionResult.NoErrorsDetected;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ConversionResult ConvertToMultiMp4a(ChapterInfo splitChapters)
|
private Task<ConversionResult> ConvertToMultiMp4a(ChapterInfo splitChapters)
|
||||||
{
|
{
|
||||||
var chapterCount = 0;
|
var chapterCount = 0;
|
||||||
return AaxFile.ConvertToMultiMp4a(splitChapters, newSplitCallback =>
|
return AaxFile.ConvertToMultiMp4aAsync
|
||||||
createOutputFileStream(++chapterCount, splitChapters, newSplitCallback),
|
(
|
||||||
DownloadOptions.TrimOutputToChapterLength);
|
splitChapters,
|
||||||
}
|
newSplitCallback => Callback(++chapterCount, splitChapters, newSplitCallback),
|
||||||
|
DownloadOptions.TrimOutputToChapterLength
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private ConversionResult ConvertToMultiMp3(ChapterInfo splitChapters)
|
private Task<ConversionResult> ConvertToMultiMp3(ChapterInfo splitChapters)
|
||||||
{
|
{
|
||||||
var chapterCount = 0;
|
var chapterCount = 0;
|
||||||
return AaxFile.ConvertToMultiMp3(splitChapters, newSplitCallback =>
|
return AaxFile.ConvertToMultiMp3Async
|
||||||
{
|
(
|
||||||
createOutputFileStream(++chapterCount, splitChapters, newSplitCallback);
|
splitChapters,
|
||||||
((NAudio.Lame.LameConfig)newSplitCallback.UserState).ID3.Track = chapterCount.ToString();
|
newSplitCallback => Callback(++chapterCount, splitChapters, newSplitCallback),
|
||||||
}, DownloadOptions.LameConfig, DownloadOptions.TrimOutputToChapterLength);
|
DownloadOptions.LameConfig,
|
||||||
}
|
DownloadOptions.TrimOutputToChapterLength
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private void createOutputFileStream(int currentChapter, ChapterInfo splitChapters, NewSplitCallback newSplitCallback)
|
|
||||||
{
|
|
||||||
var fileName = multipartFileNameCallback(new()
|
|
||||||
{
|
|
||||||
OutputFileName = OutputFileName,
|
|
||||||
PartsPosition = currentChapter,
|
|
||||||
PartsTotal = splitChapters.Count,
|
|
||||||
Title = newSplitCallback?.Chapter?.Title
|
|
||||||
});
|
|
||||||
fileName = FileUtility.GetValidFilename(fileName);
|
|
||||||
|
|
||||||
multiPartFilePaths.Add(fileName);
|
private void Callback(int currentChapter, ChapterInfo splitChapters, NewMP3SplitCallback newSplitCallback)
|
||||||
|
=> Callback(currentChapter, splitChapters, newSplitCallback as NewSplitCallback);
|
||||||
|
|
||||||
FileUtility.SaferDelete(fileName);
|
private void Callback(int currentChapter, ChapterInfo splitChapters, NewSplitCallback newSplitCallback)
|
||||||
|
{
|
||||||
|
MultiConvertFileProperties props = new()
|
||||||
|
{
|
||||||
|
OutputFileName = OutputFileName,
|
||||||
|
PartsPosition = currentChapter,
|
||||||
|
PartsTotal = splitChapters.Count,
|
||||||
|
Title = newSplitCallback?.Chapter?.Title,
|
||||||
|
};
|
||||||
|
newSplitCallback.OutputFile = createOutputFileStream(props);
|
||||||
|
newSplitCallback.TrackTitle = DownloadOptions.GetMultipartTitleName(props);
|
||||||
|
newSplitCallback.TrackNumber = currentChapter;
|
||||||
|
newSplitCallback.TrackCount = splitChapters.Count;
|
||||||
|
}
|
||||||
|
|
||||||
newSplitCallback.OutputFile = File.Open(fileName, FileMode.OpenOrCreate);
|
private FileStream createOutputFileStream(MultiConvertFileProperties multiConvertFileProperties)
|
||||||
|
{
|
||||||
|
var fileName = DownloadOptions.GetMultipartFileName(multiConvertFileProperties);
|
||||||
|
fileName = FileUtility.GetValidFilename(fileName, DownloadOptions.ReplacementCharacters);
|
||||||
|
|
||||||
OnFileCreated(fileName);
|
multiPartFilePaths.Add(fileName);
|
||||||
}
|
|
||||||
}
|
FileUtility.SaferDelete(fileName);
|
||||||
|
|
||||||
|
var file = File.Open(fileName, FileMode.OpenOrCreate);
|
||||||
|
OnFileCreated(fileName);
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,55 +1,126 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using AAXClean;
|
using AAXClean;
|
||||||
using AAXClean.Codecs;
|
using AAXClean.Codecs;
|
||||||
using Dinah.Core.StepRunner;
|
|
||||||
using FileManager;
|
using FileManager;
|
||||||
|
|
||||||
namespace AaxDecrypter
|
namespace AaxDecrypter
|
||||||
{
|
{
|
||||||
public class AaxcDownloadSingleConverter : AaxcDownloadConvertBase
|
public class AaxcDownloadSingleConverter : AaxcDownloadConvertBase
|
||||||
{
|
{
|
||||||
protected override StepSequence Steps { get; }
|
public AaxcDownloadSingleConverter(string outFileName, string cacheDirectory, IDownloadOptions dlOptions)
|
||||||
|
: base(outFileName, cacheDirectory, dlOptions) { }
|
||||||
|
|
||||||
public AaxcDownloadSingleConverter(string outFileName, string cacheDirectory, DownloadOptions dlLic)
|
public override async Task<bool> RunAsync()
|
||||||
: base(outFileName, cacheDirectory, dlLic)
|
{
|
||||||
{
|
try
|
||||||
Steps = new StepSequence
|
{
|
||||||
{
|
Serilog.Log.Information("Begin download and convert Aaxc To {format}", DownloadOptions.OutputFormat);
|
||||||
Name = "Download and Convert Aaxc To " + DownloadOptions.OutputFormat,
|
|
||||||
|
|
||||||
["Step 1: Get Aaxc Metadata"] = Step_GetMetadata,
|
//Step 1
|
||||||
["Step 2: Download Decrypted Audiobook"] = Step_DownloadAudiobookAsSingleFile,
|
Serilog.Log.Information("Begin Step 1: Get Aaxc Metadata");
|
||||||
["Step 3: Create Cue"] = Step_CreateCue,
|
if (await Task.Run(Step_GetMetadata))
|
||||||
["Step 4: Cleanup"] = Step_Cleanup,
|
Serilog.Log.Information("Completed Step 1: Get Aaxc Metadata");
|
||||||
};
|
else
|
||||||
}
|
{
|
||||||
|
Serilog.Log.Information("Failed to Complete Step 1: Get Aaxc Metadata");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
private bool Step_DownloadAudiobookAsSingleFile()
|
//Step 2
|
||||||
{
|
Serilog.Log.Information("Begin Step 2: Download Decrypted Audiobook");
|
||||||
var zeroProgress = Step_DownloadAudiobook_Start();
|
if (await Step_DownloadAudiobookAsSingleFile())
|
||||||
|
Serilog.Log.Information("Completed Step 2: Download Decrypted Audiobook");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Failed to Complete Step 2: Download Decrypted Audiobook");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
FileUtility.SaferDelete(OutputFileName);
|
//Step 3
|
||||||
|
Serilog.Log.Information("Begin Step 3: Create Cue");
|
||||||
|
if (await Task.Run(Step_CreateCue))
|
||||||
|
Serilog.Log.Information("Completed Step 3: Create Cue");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Failed to Complete Step 3: Create Cue");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
var outputFile = File.Open(OutputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
|
//Step 4
|
||||||
OnFileCreated(OutputFileName);
|
if (DownloadOptions.DownloadClipsBookmarks)
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Begin Downloading Clips and Bookmarks");
|
||||||
|
if (await Task.Run(Step_DownloadClipsBookmarks))
|
||||||
|
Serilog.Log.Information("Completed Downloading Clips and Bookmarks");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Failed to Download Clips and Bookmarks");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
AaxFile.ConversionProgressUpdate += AaxFile_ConversionProgressUpdate;
|
//Step 5
|
||||||
var decryptionResult
|
Serilog.Log.Information("Begin Step 4: Cleanup");
|
||||||
= DownloadOptions.OutputFormat == OutputFormat.M4b
|
if (await Task.Run(Step_Cleanup))
|
||||||
? AaxFile.ConvertToMp4a(outputFile, DownloadOptions.ChapterInfo, DownloadOptions.TrimOutputToChapterLength)
|
Serilog.Log.Information("Completed Step 4: Cleanup");
|
||||||
: AaxFile.ConvertToMp3(outputFile, DownloadOptions.LameConfig, DownloadOptions.ChapterInfo, DownloadOptions.TrimOutputToChapterLength);
|
else
|
||||||
AaxFile.ConversionProgressUpdate -= AaxFile_ConversionProgressUpdate;
|
{
|
||||||
|
Serilog.Log.Information("Failed to Complete Step 4: Cleanup");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
DownloadOptions.ChapterInfo = AaxFile.Chapters;
|
Serilog.Log.Information("Completed download and convert Aaxc To {format}", DownloadOptions.OutputFormat);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Serilog.Log.Error(ex, "Error encountered in download and convert Aaxc To {format}", DownloadOptions.OutputFormat);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Step_DownloadAudiobook_End(zeroProgress);
|
private async Task<bool> Step_DownloadAudiobookAsSingleFile()
|
||||||
|
{
|
||||||
|
var zeroProgress = Step_DownloadAudiobook_Start();
|
||||||
|
|
||||||
var success = decryptionResult == ConversionResult.NoErrorsDetected && !IsCanceled;
|
FileUtility.SaferDelete(OutputFileName);
|
||||||
if (success)
|
|
||||||
base.OnFileCreated(OutputFileName);
|
|
||||||
|
|
||||||
return success;
|
var outputFile = File.Open(OutputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
|
||||||
}
|
OnFileCreated(OutputFileName);
|
||||||
}
|
|
||||||
|
AaxFile.ConversionProgressUpdate += AaxFile_ConversionProgressUpdate;
|
||||||
|
|
||||||
|
ConversionResult decryptionResult = await decryptAsync(outputFile);
|
||||||
|
|
||||||
|
AaxFile.ConversionProgressUpdate -= AaxFile_ConversionProgressUpdate;
|
||||||
|
|
||||||
|
Step_DownloadAudiobook_End(zeroProgress);
|
||||||
|
|
||||||
|
var success = decryptionResult == ConversionResult.NoErrorsDetected && !IsCanceled;
|
||||||
|
if (success)
|
||||||
|
base.OnFileCreated(OutputFileName);
|
||||||
|
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<ConversionResult> decryptAsync(Stream outputFile)
|
||||||
|
=> DownloadOptions.OutputFormat == OutputFormat.Mp3 ?
|
||||||
|
AaxFile.ConvertToMp3Async
|
||||||
|
(
|
||||||
|
outputFile,
|
||||||
|
DownloadOptions.LameConfig,
|
||||||
|
DownloadOptions.ChapterInfo,
|
||||||
|
DownloadOptions.TrimOutputToChapterLength
|
||||||
|
)
|
||||||
|
: DownloadOptions.FixupFile ?
|
||||||
|
AaxFile.ConvertToMp4aAsync
|
||||||
|
(
|
||||||
|
outputFile,
|
||||||
|
DownloadOptions.ChapterInfo,
|
||||||
|
DownloadOptions.TrimOutputToChapterLength
|
||||||
|
)
|
||||||
|
: AaxFile.ConvertToMp4aAsync(outputFile);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using Dinah.Core;
|
using Dinah.Core;
|
||||||
using Dinah.Core.Net.Http;
|
using Dinah.Core.Net.Http;
|
||||||
using Dinah.Core.StepRunner;
|
|
||||||
using FileManager;
|
using FileManager;
|
||||||
|
|
||||||
namespace AaxDecrypter
|
namespace AaxDecrypter
|
||||||
@@ -20,42 +19,42 @@ namespace AaxDecrypter
|
|||||||
public event EventHandler<TimeSpan> DecryptTimeRemaining;
|
public event EventHandler<TimeSpan> DecryptTimeRemaining;
|
||||||
public event EventHandler<string> FileCreated;
|
public event EventHandler<string> FileCreated;
|
||||||
|
|
||||||
protected bool IsCanceled { get; set; }
|
public bool IsCanceled { get; set; }
|
||||||
|
public string TempFilePath { get; }
|
||||||
|
|
||||||
protected string OutputFileName { get; private set; }
|
protected string OutputFileName { get; private set; }
|
||||||
protected DownloadOptions DownloadOptions { get; }
|
protected IDownloadOptions DownloadOptions { get; }
|
||||||
protected NetworkFileStream InputFileStream => (nfsPersister ??= OpenNetworkFileStream()).NetworkFileStream;
|
protected NetworkFileStream InputFileStream => (nfsPersister ??= OpenNetworkFileStream()).NetworkFileStream;
|
||||||
|
|
||||||
// Don't give the property a 'set'. This should have to be an obvious choice; not accidental
|
// Don't give the property a 'set'. This should have to be an obvious choice; not accidental
|
||||||
protected void SetOutputFileName(string newOutputFileName) => OutputFileName = newOutputFileName;
|
protected void SetOutputFileName(string newOutputFileName) => OutputFileName = newOutputFileName;
|
||||||
|
|
||||||
protected abstract StepSequence Steps { get; }
|
|
||||||
private NetworkFileStreamPersister nfsPersister;
|
private NetworkFileStreamPersister nfsPersister;
|
||||||
|
|
||||||
private string jsonDownloadState { get; }
|
private string jsonDownloadState { get; }
|
||||||
public string TempFilePath { get; }
|
|
||||||
|
|
||||||
protected AudiobookDownloadBase(string outFileName, string cacheDirectory, DownloadOptions dlLic)
|
protected AudiobookDownloadBase(string outFileName, string cacheDirectory, IDownloadOptions dlOptions)
|
||||||
{
|
{
|
||||||
OutputFileName = ArgumentValidator.EnsureNotNullOrWhiteSpace(outFileName, nameof(outFileName));
|
OutputFileName = ArgumentValidator.EnsureNotNullOrWhiteSpace(outFileName, nameof(outFileName));
|
||||||
|
|
||||||
var outDir = Path.GetDirectoryName(OutputFileName);
|
var outDir = Path.GetDirectoryName(OutputFileName);
|
||||||
if (!Directory.Exists(outDir))
|
if (!Directory.Exists(outDir))
|
||||||
throw new DirectoryNotFoundException($"Directory does not exist: {nameof(outDir)}");
|
Directory.CreateDirectory(outDir);
|
||||||
|
|
||||||
if (!Directory.Exists(cacheDirectory))
|
if (!Directory.Exists(cacheDirectory))
|
||||||
throw new DirectoryNotFoundException($"Directory does not exist: {nameof(cacheDirectory)}");
|
Directory.CreateDirectory(cacheDirectory);
|
||||||
|
|
||||||
jsonDownloadState = Path.Combine(cacheDirectory, Path.GetFileName(Path.ChangeExtension(OutputFileName, ".json")));
|
jsonDownloadState = Path.Combine(cacheDirectory, Path.GetFileName(Path.ChangeExtension(OutputFileName, ".json")));
|
||||||
TempFilePath = Path.ChangeExtension(jsonDownloadState, ".aaxc");
|
TempFilePath = Path.ChangeExtension(jsonDownloadState, ".aaxc");
|
||||||
|
|
||||||
DownloadOptions = ArgumentValidator.EnsureNotNull(dlLic, nameof(dlLic));
|
DownloadOptions = ArgumentValidator.EnsureNotNull(dlOptions, nameof(dlOptions));
|
||||||
|
DownloadOptions.DownloadSpeedChanged += (_, speed) => InputFileStream.SpeedLimit = speed;
|
||||||
|
|
||||||
// delete file after validation is complete
|
// delete file after validation is complete
|
||||||
FileUtility.SaferDelete(OutputFileName);
|
FileUtility.SaferDelete(OutputFileName);
|
||||||
}
|
}
|
||||||
|
|
||||||
public abstract void Cancel();
|
public abstract Task CancelAsync();
|
||||||
|
|
||||||
public virtual void SetCoverArt(byte[] coverArt)
|
public virtual void SetCoverArt(byte[] coverArt)
|
||||||
{
|
{
|
||||||
@@ -63,15 +62,7 @@ namespace AaxDecrypter
|
|||||||
OnRetrievedCoverArt(coverArt);
|
OnRetrievedCoverArt(coverArt);
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool Run()
|
public abstract Task<bool> RunAsync();
|
||||||
{
|
|
||||||
var (IsSuccess, Elapsed) = Steps.Run();
|
|
||||||
|
|
||||||
if (!IsSuccess)
|
|
||||||
Serilog.Log.Logger.Error("Conversion failed");
|
|
||||||
|
|
||||||
return IsSuccess;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void OnRetrievedTitle(string title)
|
protected void OnRetrievedTitle(string title)
|
||||||
=> RetrievedTitle?.Invoke(this, title);
|
=> RetrievedTitle?.Invoke(this, title);
|
||||||
@@ -79,11 +70,9 @@ namespace AaxDecrypter
|
|||||||
=> RetrievedAuthors?.Invoke(this, authors);
|
=> RetrievedAuthors?.Invoke(this, authors);
|
||||||
protected void OnRetrievedNarrators(string narrators)
|
protected void OnRetrievedNarrators(string narrators)
|
||||||
=> RetrievedNarrators?.Invoke(this, narrators);
|
=> RetrievedNarrators?.Invoke(this, narrators);
|
||||||
|
|
||||||
protected void OnRetrievedCoverArt(byte[] coverArt)
|
protected void OnRetrievedCoverArt(byte[] coverArt)
|
||||||
=> RetrievedCoverArt?.Invoke(this, coverArt);
|
=> RetrievedCoverArt?.Invoke(this, coverArt);
|
||||||
|
protected void OnDecryptProgressUpdate(DownloadProgress downloadProgress)
|
||||||
protected void OnDecryptProgressUpdate(DownloadProgress downloadProgress)
|
|
||||||
=> DecryptProgressUpdate?.Invoke(this, downloadProgress);
|
=> DecryptProgressUpdate?.Invoke(this, downloadProgress);
|
||||||
protected void OnDecryptTimeRemaining(TimeSpan timeRemaining)
|
protected void OnDecryptTimeRemaining(TimeSpan timeRemaining)
|
||||||
=> DecryptTimeRemaining?.Invoke(this, timeRemaining);
|
=> DecryptTimeRemaining?.Invoke(this, timeRemaining);
|
||||||
@@ -104,7 +93,7 @@ namespace AaxDecrypter
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var path = Path.ChangeExtension(OutputFileName, ".cue");
|
var path = Path.ChangeExtension(OutputFileName, ".cue");
|
||||||
path = FileUtility.GetValidFilename(path);
|
path = FileUtility.GetValidFilename(path, DownloadOptions.ReplacementCharacters);
|
||||||
File.WriteAllText(path, Cue.CreateContents(Path.GetFileName(OutputFileName), DownloadOptions.ChapterInfo));
|
File.WriteAllText(path, Cue.CreateContents(Path.GetFileName(OutputFileName), DownloadOptions.ChapterInfo));
|
||||||
OnFileCreated(path);
|
OnFileCreated(path);
|
||||||
}
|
}
|
||||||
@@ -122,8 +111,8 @@ namespace AaxDecrypter
|
|||||||
{
|
{
|
||||||
FileUtility.SaferDelete(jsonDownloadState);
|
FileUtility.SaferDelete(jsonDownloadState);
|
||||||
|
|
||||||
if (DownloadOptions.AudibleKey is not null &&
|
if (DownloadOptions.AudibleKey is not null &&
|
||||||
DownloadOptions.AudibleIV is not null &&
|
DownloadOptions.AudibleIV is not null &&
|
||||||
DownloadOptions.RetainEncryptedFile)
|
DownloadOptions.RetainEncryptedFile)
|
||||||
{
|
{
|
||||||
string aaxPath = Path.ChangeExtension(TempFilePath, ".aax");
|
string aaxPath = Path.ChangeExtension(TempFilePath, ".aax");
|
||||||
@@ -144,14 +133,27 @@ namespace AaxDecrypter
|
|||||||
return success;
|
return success;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected async Task<bool> Step_DownloadClipsBookmarks()
|
||||||
|
{
|
||||||
|
if (!IsCanceled && DownloadOptions.DownloadClipsBookmarks)
|
||||||
|
{
|
||||||
|
var recordsFile = await DownloadOptions.SaveClipsAndBookmarks(OutputFileName);
|
||||||
|
|
||||||
|
if (File.Exists(recordsFile))
|
||||||
|
OnFileCreated(recordsFile);
|
||||||
|
}
|
||||||
|
return !IsCanceled;
|
||||||
|
}
|
||||||
|
|
||||||
private NetworkFileStreamPersister OpenNetworkFileStream()
|
private NetworkFileStreamPersister OpenNetworkFileStream()
|
||||||
{
|
{
|
||||||
if (!File.Exists(jsonDownloadState))
|
NetworkFileStreamPersister nfsp = default;
|
||||||
return NewNetworkFilePersister();
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var nfsp = new NetworkFileStreamPersister(jsonDownloadState);
|
if (!File.Exists(jsonDownloadState))
|
||||||
|
return nfsp = NewNetworkFilePersister();
|
||||||
|
|
||||||
|
nfsp = new NetworkFileStreamPersister(jsonDownloadState);
|
||||||
// If More than ~1 hour has elapsed since getting the download url, it will expire.
|
// If More than ~1 hour has elapsed since getting the download url, it will expire.
|
||||||
// The new url will be to the same file.
|
// The new url will be to the same file.
|
||||||
nfsp.NetworkFileStream.SetUriForSameFile(new Uri(DownloadOptions.DownloadUrl));
|
nfsp.NetworkFileStream.SetUriForSameFile(new Uri(DownloadOptions.DownloadUrl));
|
||||||
@@ -161,18 +163,18 @@ namespace AaxDecrypter
|
|||||||
{
|
{
|
||||||
FileUtility.SaferDelete(jsonDownloadState);
|
FileUtility.SaferDelete(jsonDownloadState);
|
||||||
FileUtility.SaferDelete(TempFilePath);
|
FileUtility.SaferDelete(TempFilePath);
|
||||||
return NewNetworkFilePersister();
|
return nfsp = NewNetworkFilePersister();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (nfsp?.NetworkFileStream is not null)
|
||||||
|
nfsp.NetworkFileStream.SpeedLimit = DownloadOptions.DownloadSpeedBps;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private NetworkFileStreamPersister NewNetworkFilePersister()
|
private NetworkFileStreamPersister NewNetworkFilePersister()
|
||||||
{
|
{
|
||||||
var headers = new System.Net.WebHeaderCollection
|
var networkFileStream = new NetworkFileStream(TempFilePath, new Uri(DownloadOptions.DownloadUrl), 0, new() { { "User-Agent", DownloadOptions.UserAgent } });
|
||||||
{
|
|
||||||
{ "User-Agent", DownloadOptions.UserAgent }
|
|
||||||
};
|
|
||||||
|
|
||||||
var networkFileStream = new NetworkFileStream(TempFilePath, new Uri(DownloadOptions.DownloadUrl), 0, headers);
|
|
||||||
return new NetworkFileStreamPersister(networkFileStream, jsonDownloadState);
|
return new NetworkFileStreamPersister(networkFileStream, jsonDownloadState);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
using AAXClean;
|
|
||||||
using Dinah.Core;
|
|
||||||
|
|
||||||
namespace AaxDecrypter
|
|
||||||
{
|
|
||||||
public class DownloadOptions
|
|
||||||
{
|
|
||||||
public string DownloadUrl { get; }
|
|
||||||
public string UserAgent { get; }
|
|
||||||
public string AudibleKey { get; init; }
|
|
||||||
public string AudibleIV { get; init; }
|
|
||||||
public OutputFormat OutputFormat { get; init; }
|
|
||||||
public bool TrimOutputToChapterLength { get; init; }
|
|
||||||
public bool RetainEncryptedFile { get; init; }
|
|
||||||
public bool StripUnabridged { get; init; }
|
|
||||||
public bool CreateCueSheet { get; init; }
|
|
||||||
public ChapterInfo ChapterInfo { get; set; }
|
|
||||||
public NAudio.Lame.LameConfig LameConfig { get; set; }
|
|
||||||
public bool Downsample { get; set; }
|
|
||||||
public bool MatchSourceBitrate { get; set; }
|
|
||||||
|
|
||||||
public DownloadOptions(string downloadUrl, string userAgent)
|
|
||||||
{
|
|
||||||
DownloadUrl = ArgumentValidator.EnsureNotNullOrEmpty(downloadUrl, nameof(downloadUrl));
|
|
||||||
UserAgent = ArgumentValidator.EnsureNotNullOrEmpty(userAgent, nameof(userAgent));
|
|
||||||
|
|
||||||
// no null/empty check for key/iv. unencrypted files do not have them
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
using AAXClean;
|
||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace AaxDecrypter
|
||||||
|
{
|
||||||
|
public interface IDownloadOptions
|
||||||
|
{
|
||||||
|
event EventHandler<long> DownloadSpeedChanged;
|
||||||
|
FileManager.ReplacementCharacters ReplacementCharacters { get; }
|
||||||
|
string DownloadUrl { get; }
|
||||||
|
string UserAgent { get; }
|
||||||
|
string AudibleKey { get; }
|
||||||
|
string AudibleIV { get; }
|
||||||
|
OutputFormat OutputFormat { get; }
|
||||||
|
bool TrimOutputToChapterLength { get; }
|
||||||
|
bool RetainEncryptedFile { get; }
|
||||||
|
bool StripUnabridged { get; }
|
||||||
|
bool CreateCueSheet { get; }
|
||||||
|
bool DownloadClipsBookmarks { get; }
|
||||||
|
long DownloadSpeedBps { get; }
|
||||||
|
ChapterInfo ChapterInfo { get; }
|
||||||
|
bool FixupFile { get; }
|
||||||
|
NAudio.Lame.LameConfig LameConfig { get; }
|
||||||
|
bool Downsample { get; }
|
||||||
|
bool MatchSourceBitrate { get; }
|
||||||
|
string GetMultipartFileName(MultiConvertFileProperties props);
|
||||||
|
string GetMultipartTitleName(MultiConvertFileProperties props);
|
||||||
|
Task<string> SaveClipsAndBookmarks(string fileName);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
using AAXClean;
|
||||||
|
using NAudio.Lame;
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace AaxDecrypter
|
||||||
|
{
|
||||||
|
public static class MpegUtil
|
||||||
|
{
|
||||||
|
public static void ConfigureLameOptions(Mp4File mp4File, LameConfig lameConfig, bool downsample, bool matchSourceBitrate)
|
||||||
|
{
|
||||||
|
double bitrateMultiple = 1;
|
||||||
|
|
||||||
|
if (mp4File.AudioChannels == 2)
|
||||||
|
{
|
||||||
|
if (downsample)
|
||||||
|
bitrateMultiple = 0.5;
|
||||||
|
else
|
||||||
|
lameConfig.Mode = MPEGMode.Stereo;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (matchSourceBitrate)
|
||||||
|
{
|
||||||
|
int kbps = (int)(mp4File.AverageBitrate * bitrateMultiple / 1024);
|
||||||
|
|
||||||
|
if (lameConfig.VBR is null)
|
||||||
|
lameConfig.BitRate = kbps;
|
||||||
|
else if (lameConfig.VBR == VBRMode.ABR)
|
||||||
|
lameConfig.ABRRateKbps = kbps;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,15 +11,5 @@ namespace AaxDecrypter
|
|||||||
public int PartsTotal { get; set; }
|
public int PartsTotal { get; set; }
|
||||||
public string Title { get; set; }
|
public string Title { get; set; }
|
||||||
|
|
||||||
public static string DefaultMultipartFilename(MultiConvertFileProperties multiConvertFileProperties)
|
|
||||||
{
|
|
||||||
var template = Path.ChangeExtension(multiConvertFileProperties.OutputFileName, null) + " - <ch# 0> - <title>" + Path.GetExtension(multiConvertFileProperties.OutputFileName);
|
|
||||||
|
|
||||||
var fileNamingTemplate = new FileNamingTemplate(template) { IllegalCharacterReplacements = " " };
|
|
||||||
fileNamingTemplate.AddParameterReplacement("ch# 0", FileUtility.GetSequenceFormatted(multiConvertFileProperties.PartsPosition, multiConvertFileProperties.PartsTotal));
|
|
||||||
fileNamingTemplate.AddParameterReplacement("title", multiConvertFileProperties.Title ?? "");
|
|
||||||
|
|
||||||
return fileNamingTemplate.GetFilePath();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,443 +1,336 @@
|
|||||||
using Dinah.Core;
|
using Dinah.Core;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using Newtonsoft.Json.Linq;
|
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
|
using System.Net.Http;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace AaxDecrypter
|
namespace AaxDecrypter
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>A resumable, simultaneous file downloader and reader. </summary>
|
||||||
/// A <see cref="CookieContainer"/> for a single Uri.
|
public class NetworkFileStream : Stream, IUpdatable
|
||||||
/// </summary>
|
{
|
||||||
public class SingleUriCookieContainer : CookieContainer
|
public event EventHandler Updated;
|
||||||
{
|
|
||||||
private Uri baseAddress;
|
#region Public Properties
|
||||||
public Uri Uri
|
|
||||||
{
|
/// <summary> Location to save the downloaded data. </summary>
|
||||||
get => baseAddress;
|
[JsonProperty(Required = Required.Always)]
|
||||||
set
|
public string SaveFilePath { get; }
|
||||||
{
|
|
||||||
baseAddress = new UriBuilder(value.Scheme, value.Host).Uri;
|
/// <summary> Http(s) address of the file to download. </summary>
|
||||||
}
|
[JsonProperty(Required = Required.Always)]
|
||||||
}
|
public Uri Uri { get; private set; }
|
||||||
|
|
||||||
public CookieCollection GetCookies()
|
/// <summary> Http headers to be sent to the server with the request. </summary>
|
||||||
{
|
[JsonProperty(Required = Required.Always)]
|
||||||
return GetCookies(Uri);
|
public Dictionary<string, string> RequestHeaders { get; private set; }
|
||||||
}
|
|
||||||
}
|
/// <summary> The position in <see cref="SaveFilePath"/> that has been written and flushed to disk. </summary>
|
||||||
|
[JsonProperty(Required = Required.Always)]
|
||||||
/// <summary>
|
public long WritePosition { get; private set; }
|
||||||
/// A resumable, simultaneous file downloader and reader.
|
|
||||||
/// </summary>
|
/// <summary> The total length of the <see cref="Uri"/> file to download. </summary>
|
||||||
public class NetworkFileStream : Stream, IUpdatable
|
[JsonProperty(Required = Required.Always)]
|
||||||
{
|
public long ContentLength { get; private set; }
|
||||||
public event EventHandler Updated;
|
|
||||||
|
[JsonIgnore]
|
||||||
#region Public Properties
|
public bool IsCancelled => _cancellationSource.IsCancellationRequested;
|
||||||
|
|
||||||
/// <summary>
|
private long _speedLimit = 0;
|
||||||
/// Location to save the downloaded data.
|
/// <summary>bytes per second</summary>
|
||||||
/// </summary>
|
public long SpeedLimit { get => _speedLimit; set => _speedLimit = value <= 0 ? 0 : Math.Max(value, MIN_BYTES_PER_SECOND); }
|
||||||
[JsonProperty(Required = Required.Always)]
|
|
||||||
public string SaveFilePath { get; }
|
#endregion
|
||||||
|
|
||||||
/// <summary>
|
#region Private Properties
|
||||||
/// Http(s) address of the file to download.
|
private FileStream _writeFile { get; }
|
||||||
/// </summary>
|
private FileStream _readFile { get; }
|
||||||
[JsonProperty(Required = Required.Always)]
|
private CancellationTokenSource _cancellationSource { get; } = new();
|
||||||
public Uri Uri { get; private set; }
|
private EventWaitHandle _downloadedPiece { get; set; }
|
||||||
|
private Task _backgroundDownloadTask { get; set; }
|
||||||
/// <summary>
|
|
||||||
/// All cookies set by caller or by the remote server.
|
#endregion
|
||||||
/// </summary>
|
|
||||||
[JsonProperty(Required = Required.Always)]
|
#region Constants
|
||||||
public SingleUriCookieContainer CookieContainer { get; }
|
|
||||||
|
//Download buffer size
|
||||||
/// <summary>
|
private const int DOWNLOAD_BUFF_SZ = 32 * 1024;
|
||||||
/// Http headers to be sent to the server with the request.
|
|
||||||
/// </summary>
|
//NetworkFileStream will flush all data in _writeFile to disk after every
|
||||||
[JsonProperty(Required = Required.Always)]
|
//DATA_FLUSH_SZ bytes are written to the file stream.
|
||||||
public WebHeaderCollection RequestHeaders { get; private set; }
|
private const int DATA_FLUSH_SZ = 1024 * 1024;
|
||||||
|
|
||||||
/// <summary>
|
//Number of times per second the download rate is checkd and throttled
|
||||||
/// The position in <see cref="SaveFilePath"/> that has been written and flushed to disk.
|
private const int THROTTLE_FREQUENCY = 8;
|
||||||
/// </summary>
|
|
||||||
[JsonProperty(Required = Required.Always)]
|
//Minimum throttle rate. The minimum amount of data that can be throttled
|
||||||
public long WritePosition { get; private set; }
|
//on each iteration of the download loop is DOWNLOAD_BUFF_SZ.
|
||||||
|
public const int MIN_BYTES_PER_SECOND = DOWNLOAD_BUFF_SZ * THROTTLE_FREQUENCY;
|
||||||
/// <summary>
|
|
||||||
/// The total length of the <see cref="Uri"/> file to download.
|
#endregion
|
||||||
/// </summary>
|
|
||||||
[JsonProperty(Required = Required.Always)]
|
#region Constructor
|
||||||
public long ContentLength { get; private set; }
|
|
||||||
|
/// <summary> A resumable, simultaneous file downloader and reader. </summary>
|
||||||
#endregion
|
/// <param name="saveFilePath">Path to a location on disk to save the downloaded data from <paramref name="uri"/></param>
|
||||||
|
/// <param name="uri">Http(s) address of the file to download.</param>
|
||||||
#region Private Properties
|
/// <param name="writePosition">The position in <paramref name="uri"/> to begin downloading.</param>
|
||||||
private HttpWebRequest HttpRequest { get; set; }
|
/// <param name="requestHeaders">Http headers to be sent to the server with the <see cref="HttpWebRequest"/>.</param>
|
||||||
private FileStream _writeFile { get; }
|
public NetworkFileStream(string saveFilePath, Uri uri, long writePosition = 0, Dictionary<string, string> requestHeaders = null)
|
||||||
private FileStream _readFile { get; }
|
{
|
||||||
private Stream _networkStream { get; set; }
|
ArgumentValidator.EnsureNotNullOrWhiteSpace(saveFilePath, nameof(saveFilePath));
|
||||||
private bool hasBegunDownloading { get; set; }
|
ArgumentValidator.EnsureNotNullOrWhiteSpace(uri?.AbsoluteUri, nameof(uri));
|
||||||
public bool IsCancelled { get; private set; }
|
ArgumentValidator.EnsureGreaterThan(writePosition, nameof(writePosition), -1);
|
||||||
private EventWaitHandle downloadEnded { get; set; }
|
|
||||||
private EventWaitHandle downloadedPiece { get; set; }
|
if (!Directory.Exists(Path.GetDirectoryName(saveFilePath)))
|
||||||
|
throw new ArgumentException($"Specified {nameof(saveFilePath)} directory \"{Path.GetDirectoryName(saveFilePath)}\" does not exist.");
|
||||||
#endregion
|
|
||||||
|
SaveFilePath = saveFilePath;
|
||||||
#region Constants
|
Uri = uri;
|
||||||
|
WritePosition = writePosition;
|
||||||
//Download buffer size
|
RequestHeaders = requestHeaders ?? new();
|
||||||
private const int DOWNLOAD_BUFF_SZ = 4 * 1024;
|
|
||||||
|
_writeFile = new FileStream(SaveFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)
|
||||||
//NetworkFileStream will flush all data in _writeFile to disk after every
|
{
|
||||||
//DATA_FLUSH_SZ bytes are written to the file stream.
|
Position = WritePosition
|
||||||
private const int DATA_FLUSH_SZ = 1024 * 1024;
|
};
|
||||||
|
|
||||||
#endregion
|
_readFile = new FileStream(SaveFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||||
|
|
||||||
#region Constructor
|
SetUriForSameFile(uri);
|
||||||
|
}
|
||||||
/// <summary>
|
|
||||||
/// A resumable, simultaneous file downloader and reader.
|
#endregion
|
||||||
/// </summary>
|
|
||||||
/// <param name="saveFilePath">Path to a location on disk to save the downloaded data from <paramref name="uri"/></param>
|
#region Downloader
|
||||||
/// <param name="uri">Http(s) address of the file to download.</param>
|
|
||||||
/// <param name="writePosition">The position in <paramref name="uri"/> to begin downloading.</param>
|
/// <summary> Update the <see cref="JsonFilePersister"/>. </summary>
|
||||||
/// <param name="requestHeaders">Http headers to be sent to the server with the <see cref="HttpWebRequest"/>.</param>
|
private void Update()
|
||||||
/// <param name="cookies">A <see cref="SingleUriCookieContainer"/> with cookies to send with the <see cref="HttpWebRequest"/>. It will also be populated with any cookies set by the server. </param>
|
{
|
||||||
public NetworkFileStream(string saveFilePath, Uri uri, long writePosition = 0, WebHeaderCollection requestHeaders = null, SingleUriCookieContainer cookies = null)
|
RequestHeaders["Range"] = $"bytes={WritePosition}-";
|
||||||
{
|
try
|
||||||
ArgumentValidator.EnsureNotNullOrWhiteSpace(saveFilePath, nameof(saveFilePath));
|
{
|
||||||
ArgumentValidator.EnsureNotNullOrWhiteSpace(uri?.AbsoluteUri, nameof(uri));
|
Updated?.Invoke(this, EventArgs.Empty);
|
||||||
ArgumentValidator.EnsureGreaterThan(writePosition, nameof(writePosition), -1);
|
}
|
||||||
|
catch (Exception ex)
|
||||||
if (!Directory.Exists(Path.GetDirectoryName(saveFilePath)))
|
{
|
||||||
throw new ArgumentException($"Specified {nameof(saveFilePath)} directory \"{Path.GetDirectoryName(saveFilePath)}\" does not exist.");
|
Serilog.Log.Error(ex, "An error was encountered while saving the download progress to JSON");
|
||||||
|
}
|
||||||
SaveFilePath = saveFilePath;
|
}
|
||||||
Uri = uri;
|
|
||||||
WritePosition = writePosition;
|
/// <summary> Set a different <see cref="System.Uri"/> to the same file targeted by this instance of <see cref="NetworkFileStream"/> </summary>
|
||||||
RequestHeaders = requestHeaders ?? new WebHeaderCollection();
|
/// <param name="uriToSameFile">New <see cref="System.Uri"/> host must match existing host.</param>
|
||||||
CookieContainer = cookies ?? new SingleUriCookieContainer { Uri = uri };
|
public void SetUriForSameFile(Uri uriToSameFile)
|
||||||
|
{
|
||||||
_writeFile = new FileStream(SaveFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)
|
ArgumentValidator.EnsureNotNullOrWhiteSpace(uriToSameFile?.AbsoluteUri, nameof(uriToSameFile));
|
||||||
{
|
|
||||||
Position = WritePosition
|
if (uriToSameFile.Host != Uri.Host)
|
||||||
};
|
throw new ArgumentException($"New uri to the same file must have the same host.\r\n Old Host :{Uri.Host}\r\nNew Host: {uriToSameFile.Host}");
|
||||||
|
if (_backgroundDownloadTask is not null)
|
||||||
_readFile = new FileStream(SaveFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
throw new InvalidOperationException("Cannot change Uri after download has started.");
|
||||||
|
|
||||||
SetUriForSameFile(uri);
|
Uri = uriToSameFile;
|
||||||
}
|
RequestHeaders["Range"] = $"bytes={WritePosition}-";
|
||||||
|
}
|
||||||
#endregion
|
|
||||||
|
/// <summary> Begins downloading <see cref="Uri"/> to <see cref="SaveFilePath"/> in a background thread. </summary>
|
||||||
#region Downloader
|
/// <returns>The downloader <see cref="Task"/></returns>
|
||||||
|
private Task BeginDownloading()
|
||||||
/// <summary>
|
{
|
||||||
/// Update the <see cref="JsonFilePersister"/>.
|
if (ContentLength != 0 && WritePosition == ContentLength)
|
||||||
/// </summary>
|
return Task.CompletedTask;
|
||||||
private void Update()
|
|
||||||
{
|
if (ContentLength != 0 && WritePosition > ContentLength)
|
||||||
RequestHeaders = HttpRequest.Headers;
|
throw new WebException($"Specified write position (0x{WritePosition:X10}) is larger than {nameof(ContentLength)} (0x{ContentLength:X10}).");
|
||||||
Updated?.Invoke(this, EventArgs.Empty);
|
|
||||||
}
|
var request = new HttpRequestMessage(HttpMethod.Get, Uri);
|
||||||
|
|
||||||
/// <summary>
|
foreach (var header in RequestHeaders)
|
||||||
/// Set a different <see cref="System.Uri"/> to the same file targeted by this instance of <see cref="NetworkFileStream"/>
|
request.Headers.Add(header.Key, header.Value);
|
||||||
/// </summary>
|
|
||||||
/// <param name="uriToSameFile">New <see cref="System.Uri"/> host must match existing host.</param>
|
var response = new HttpClient().Send(request, HttpCompletionOption.ResponseHeadersRead, _cancellationSource.Token);
|
||||||
public void SetUriForSameFile(Uri uriToSameFile)
|
|
||||||
{
|
if (response.StatusCode != HttpStatusCode.PartialContent)
|
||||||
ArgumentValidator.EnsureNotNullOrWhiteSpace(uriToSameFile?.AbsoluteUri, nameof(uriToSameFile));
|
throw new WebException($"Server at {Uri.Host} responded with unexpected status code: {response.StatusCode}.");
|
||||||
|
|
||||||
if (uriToSameFile.Host != Uri.Host)
|
//Content length is the length of the range request, and it is only equal
|
||||||
throw new ArgumentException($"New uri to the same file must have the same host.\r\n Old Host :{Uri.Host}\r\nNew Host: {uriToSameFile.Host}");
|
//to the complete file length if requesting Range: bytes=0-
|
||||||
if (hasBegunDownloading)
|
if (WritePosition == 0)
|
||||||
throw new InvalidOperationException("Cannot change Uri after download has started.");
|
ContentLength = response.Content.Headers.ContentLength.GetValueOrDefault();
|
||||||
|
|
||||||
Uri = uriToSameFile;
|
var networkStream = response.Content.ReadAsStream(_cancellationSource.Token);
|
||||||
HttpRequest = WebRequest.CreateHttp(Uri);
|
_downloadedPiece = new EventWaitHandle(false, EventResetMode.AutoReset);
|
||||||
|
|
||||||
HttpRequest.CookieContainer = CookieContainer;
|
//Download the file in the background.
|
||||||
HttpRequest.Headers = RequestHeaders;
|
return Task.Run(async () => await DownloadFile(networkStream), _cancellationSource.Token);
|
||||||
//If NetworkFileStream is resuming, Header will already contain a range.
|
}
|
||||||
HttpRequest.Headers.Remove("Range");
|
|
||||||
HttpRequest.AddRange(WritePosition);
|
/// <summary> Download <see cref="Uri"/> to <see cref="SaveFilePath"/>.</summary>
|
||||||
}
|
private async Task DownloadFile(Stream networkStream)
|
||||||
|
{
|
||||||
/// <summary>
|
var downloadPosition = WritePosition;
|
||||||
/// Begins downloading <see cref="Uri"/> to <see cref="SaveFilePath"/> in a background thread.
|
var nextFlush = downloadPosition + DATA_FLUSH_SZ;
|
||||||
/// </summary>
|
var buff = new byte[DOWNLOAD_BUFF_SZ];
|
||||||
private void BeginDownloading()
|
|
||||||
{
|
try
|
||||||
downloadEnded = new EventWaitHandle(false, EventResetMode.ManualReset);
|
{
|
||||||
|
DateTime startTime = DateTime.Now;
|
||||||
if (ContentLength != 0 && WritePosition == ContentLength)
|
long bytesReadSinceThrottle = 0;
|
||||||
{
|
int bytesRead;
|
||||||
hasBegunDownloading = true;
|
do
|
||||||
downloadEnded.Set();
|
{
|
||||||
return;
|
bytesRead = await networkStream.ReadAsync(buff, 0, DOWNLOAD_BUFF_SZ, _cancellationSource.Token);
|
||||||
}
|
await _writeFile.WriteAsync(buff, 0, bytesRead, _cancellationSource.Token);
|
||||||
|
|
||||||
if (ContentLength != 0 && WritePosition > ContentLength)
|
downloadPosition += bytesRead;
|
||||||
throw new WebException($"Specified write position (0x{WritePosition:X10}) is larger than {nameof(ContentLength)} (0x{ContentLength:X10}).");
|
|
||||||
|
if (downloadPosition > nextFlush)
|
||||||
var response = HttpRequest.GetResponse() as HttpWebResponse;
|
{
|
||||||
|
await _writeFile.FlushAsync(_cancellationSource.Token);
|
||||||
if (response.StatusCode != HttpStatusCode.PartialContent)
|
WritePosition = downloadPosition;
|
||||||
throw new WebException($"Server at {Uri.Host} responded with unexpected status code: {response.StatusCode}.");
|
Update();
|
||||||
|
nextFlush = downloadPosition + DATA_FLUSH_SZ;
|
||||||
//Content length is the length of the range request, and it is only equal
|
_downloadedPiece.Set();
|
||||||
//to the complete file length if requesting Range: bytes=0-
|
}
|
||||||
if (WritePosition == 0)
|
|
||||||
ContentLength = response.ContentLength;
|
#region throttle
|
||||||
|
|
||||||
_networkStream = response.GetResponseStream();
|
bytesReadSinceThrottle += bytesRead;
|
||||||
downloadedPiece = new EventWaitHandle(false, EventResetMode.AutoReset);
|
|
||||||
|
if (SpeedLimit >= MIN_BYTES_PER_SECOND && bytesReadSinceThrottle > SpeedLimit / THROTTLE_FREQUENCY)
|
||||||
//Download the file in the background.
|
{
|
||||||
new Thread(() => DownloadFile())
|
var delayMS = (int)(startTime.AddSeconds(1d / THROTTLE_FREQUENCY) - DateTime.Now).TotalMilliseconds;
|
||||||
{ IsBackground = true }
|
if (delayMS > 0)
|
||||||
.Start();
|
await Task.Delay(delayMS, _cancellationSource.Token);
|
||||||
|
|
||||||
hasBegunDownloading = true;
|
startTime = DateTime.Now;
|
||||||
return;
|
bytesReadSinceThrottle = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
#endregion
|
||||||
/// Downlod <see cref="Uri"/> to <see cref="SaveFilePath"/>.
|
|
||||||
/// </summary>
|
} while (downloadPosition < ContentLength && !IsCancelled && bytesRead > 0);
|
||||||
private void DownloadFile()
|
|
||||||
{
|
WritePosition = downloadPosition;
|
||||||
var downloadPosition = WritePosition;
|
|
||||||
var nextFlush = downloadPosition + DATA_FLUSH_SZ;
|
if (!IsCancelled && WritePosition < ContentLength)
|
||||||
|
throw new WebException($"Downloaded size (0x{WritePosition:X10}) is less than {nameof(ContentLength)} (0x{ContentLength:X10}).");
|
||||||
var buff = new byte[DOWNLOAD_BUFF_SZ];
|
|
||||||
do
|
if (WritePosition > ContentLength)
|
||||||
{
|
throw new WebException($"Downloaded size (0x{WritePosition:X10}) is greater than {nameof(ContentLength)} (0x{ContentLength:X10}).");
|
||||||
var bytesRead = _networkStream.Read(buff, 0, DOWNLOAD_BUFF_SZ);
|
}
|
||||||
_writeFile.Write(buff, 0, bytesRead);
|
catch (TaskCanceledException)
|
||||||
|
{
|
||||||
downloadPosition += bytesRead;
|
Serilog.Log.Information("Download was cancelled");
|
||||||
|
}
|
||||||
if (downloadPosition > nextFlush)
|
finally
|
||||||
{
|
{
|
||||||
_writeFile.Flush();
|
networkStream.Close();
|
||||||
WritePosition = downloadPosition;
|
_writeFile.Close();
|
||||||
Update();
|
_downloadedPiece.Set();
|
||||||
nextFlush = downloadPosition + DATA_FLUSH_SZ;
|
Update();
|
||||||
downloadedPiece.Set();
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} while (downloadPosition < ContentLength && !IsCancelled);
|
#endregion
|
||||||
|
|
||||||
_writeFile.Close();
|
#region Json Connverters
|
||||||
_networkStream.Close();
|
|
||||||
WritePosition = downloadPosition;
|
public static JsonSerializerSettings GetJsonSerializerSettings()
|
||||||
Update();
|
=> new JsonSerializerSettings();
|
||||||
|
|
||||||
downloadedPiece.Set();
|
#endregion
|
||||||
downloadEnded.Set();
|
|
||||||
|
#region Download Stream Reader
|
||||||
if (!IsCancelled && WritePosition < ContentLength)
|
|
||||||
throw new WebException($"Downloaded size (0x{WritePosition:X10}) is less than {nameof(ContentLength)} (0x{ContentLength:X10}).");
|
[JsonIgnore]
|
||||||
|
public override bool CanRead => true;
|
||||||
if (WritePosition > ContentLength)
|
|
||||||
throw new WebException($"Downloaded size (0x{WritePosition:X10}) is greater than {nameof(ContentLength)} (0x{ContentLength:X10}).");
|
[JsonIgnore]
|
||||||
|
public override bool CanSeek => true;
|
||||||
}
|
|
||||||
|
[JsonIgnore]
|
||||||
#endregion
|
public override bool CanWrite => false;
|
||||||
|
|
||||||
#region Json Connverters
|
[JsonIgnore]
|
||||||
|
public override long Length
|
||||||
public static JsonSerializerSettings GetJsonSerializerSettings()
|
{
|
||||||
{
|
get
|
||||||
var settings = new JsonSerializerSettings();
|
{
|
||||||
settings.Converters.Add(new CookieContainerConverter());
|
_backgroundDownloadTask ??= BeginDownloading();
|
||||||
settings.Converters.Add(new WebHeaderCollectionConverter());
|
return ContentLength;
|
||||||
return settings;
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal class CookieContainerConverter : JsonConverter
|
[JsonIgnore]
|
||||||
{
|
public override long Position { get => _readFile.Position; set => Seek(value, SeekOrigin.Begin); }
|
||||||
public override bool CanConvert(Type objectType)
|
|
||||||
=> objectType == typeof(SingleUriCookieContainer);
|
[JsonIgnore]
|
||||||
|
public override bool CanTimeout => false;
|
||||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
|
||||||
{
|
[JsonIgnore]
|
||||||
var jObj = JObject.Load(reader);
|
public override int ReadTimeout { get => base.ReadTimeout; set => base.ReadTimeout = value; }
|
||||||
|
|
||||||
var result = new SingleUriCookieContainer()
|
[JsonIgnore]
|
||||||
{
|
public override int WriteTimeout { get => base.WriteTimeout; set => base.WriteTimeout = value; }
|
||||||
Uri = new Uri(jObj["Uri"].Value<string>()),
|
|
||||||
Capacity = jObj["Capacity"].Value<int>(),
|
public override void Flush() => throw new InvalidOperationException();
|
||||||
MaxCookieSize = jObj["MaxCookieSize"].Value<int>(),
|
public override void SetLength(long value) => throw new InvalidOperationException();
|
||||||
PerDomainCapacity = jObj["PerDomainCapacity"].Value<int>()
|
public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException();
|
||||||
};
|
|
||||||
|
public override int Read(byte[] buffer, int offset, int count)
|
||||||
var cookieList = jObj["Cookies"].ToList();
|
{
|
||||||
|
_backgroundDownloadTask ??= BeginDownloading();
|
||||||
foreach (var cookie in cookieList)
|
|
||||||
{
|
var toRead = Math.Min(count, Length - Position);
|
||||||
result.Add(
|
WaitToPosition(Position + toRead);
|
||||||
new Cookie
|
return IsCancelled ? 0: _readFile.Read(buffer, offset, count);
|
||||||
{
|
}
|
||||||
Comment = cookie["Comment"].Value<string>(),
|
|
||||||
HttpOnly = cookie["HttpOnly"].Value<bool>(),
|
public override long Seek(long offset, SeekOrigin origin)
|
||||||
Discard = cookie["Discard"].Value<bool>(),
|
{
|
||||||
Domain = cookie["Domain"].Value<string>(),
|
var newPosition = origin switch
|
||||||
Expired = cookie["Expired"].Value<bool>(),
|
|
||||||
Expires = cookie["Expires"].Value<DateTime>(),
|
|
||||||
Name = cookie["Name"].Value<string>(),
|
|
||||||
Path = cookie["Path"].Value<string>(),
|
|
||||||
Port = cookie["Port"].Value<string>(),
|
|
||||||
Secure = cookie["Secure"].Value<bool>(),
|
|
||||||
Value = cookie["Value"].Value<string>(),
|
|
||||||
Version = cookie["Version"].Value<int>(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public override bool CanWrite => true;
|
|
||||||
|
|
||||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
|
||||||
{
|
|
||||||
var cookies = value as SingleUriCookieContainer;
|
|
||||||
var obj = (JObject)JToken.FromObject(value);
|
|
||||||
var container = cookies.GetCookies();
|
|
||||||
var propertyNames = container.Select(c => JToken.FromObject(c));
|
|
||||||
obj.AddFirst(new JProperty("Cookies", new JArray(propertyNames)));
|
|
||||||
obj.WriteTo(writer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal class WebHeaderCollectionConverter : JsonConverter
|
|
||||||
{
|
|
||||||
public override bool CanConvert(Type objectType)
|
|
||||||
=> objectType == typeof(WebHeaderCollection);
|
|
||||||
|
|
||||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
|
||||||
{
|
|
||||||
var jObj = JObject.Load(reader);
|
|
||||||
var result = new WebHeaderCollection();
|
|
||||||
|
|
||||||
foreach (var kvp in jObj)
|
|
||||||
result.Add(kvp.Key, kvp.Value.Value<string>());
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public override bool CanWrite => true;
|
|
||||||
|
|
||||||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
|
||||||
{
|
|
||||||
var jObj = new JObject();
|
|
||||||
var type = value.GetType();
|
|
||||||
var headers = value as WebHeaderCollection;
|
|
||||||
var jHeaders = headers.AllKeys.Select(k => new JProperty(k, headers[k]));
|
|
||||||
jObj.Add(jHeaders);
|
|
||||||
jObj.WriteTo(writer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region Download Stream Reader
|
|
||||||
|
|
||||||
[JsonIgnore]
|
|
||||||
public override bool CanRead => true;
|
|
||||||
|
|
||||||
[JsonIgnore]
|
|
||||||
public override bool CanSeek => true;
|
|
||||||
|
|
||||||
[JsonIgnore]
|
|
||||||
public override bool CanWrite => false;
|
|
||||||
|
|
||||||
[JsonIgnore]
|
|
||||||
public override long Length
|
|
||||||
{
|
|
||||||
get
|
|
||||||
{
|
|
||||||
if (!hasBegunDownloading)
|
|
||||||
BeginDownloading();
|
|
||||||
return ContentLength;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[JsonIgnore]
|
|
||||||
public override long Position { get => _readFile.Position; set => Seek(value, SeekOrigin.Begin); }
|
|
||||||
|
|
||||||
[JsonIgnore]
|
|
||||||
public override bool CanTimeout => false;
|
|
||||||
|
|
||||||
[JsonIgnore]
|
|
||||||
public override int ReadTimeout { get => base.ReadTimeout; set => base.ReadTimeout = value; }
|
|
||||||
|
|
||||||
[JsonIgnore]
|
|
||||||
public override int WriteTimeout { get => base.WriteTimeout; set => base.WriteTimeout = value; }
|
|
||||||
|
|
||||||
public override void Flush() => throw new NotImplementedException();
|
|
||||||
public override void SetLength(long value) => throw new NotImplementedException();
|
|
||||||
public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException();
|
|
||||||
|
|
||||||
public override int Read(byte[] buffer, int offset, int count)
|
|
||||||
{
|
|
||||||
if (!hasBegunDownloading)
|
|
||||||
BeginDownloading();
|
|
||||||
|
|
||||||
var toRead = Math.Min(count, Length - Position);
|
|
||||||
WaitToPosition(Position + toRead);
|
|
||||||
return _readFile.Read(buffer, offset, count);
|
|
||||||
}
|
|
||||||
|
|
||||||
public override long Seek(long offset, SeekOrigin origin)
|
|
||||||
{
|
|
||||||
var newPosition = origin switch
|
|
||||||
{
|
{
|
||||||
SeekOrigin.Current => Position + offset,
|
SeekOrigin.Current => Position + offset,
|
||||||
SeekOrigin.End => ContentLength + offset,
|
SeekOrigin.End => ContentLength + offset,
|
||||||
_ => offset,
|
_ => offset,
|
||||||
};
|
};
|
||||||
|
|
||||||
WaitToPosition(newPosition);
|
WaitToPosition(newPosition);
|
||||||
return _readFile.Position = newPosition;
|
return _readFile.Position = newPosition;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>Blocks until the file has downloaded to at least <paramref name="requiredPosition"/>, then returns. </summary>
|
||||||
/// Blocks until the file has downloaded to at least <paramref name="requiredPosition"/>, then returns.
|
/// <param name="requiredPosition">The minimum required flished data length in <see cref="SaveFilePath"/>.</param>
|
||||||
/// </summary>
|
private void WaitToPosition(long requiredPosition)
|
||||||
/// <param name="requiredPosition">The minimum required flished data length in <see cref="SaveFilePath"/>.</param>
|
|
||||||
private void WaitToPosition(long requiredPosition)
|
|
||||||
{
|
{
|
||||||
while (requiredPosition > WritePosition && !IsCancelled && hasBegunDownloading && !downloadedPiece.WaitOne(1000)) ;
|
while (WritePosition < requiredPosition
|
||||||
}
|
&& _backgroundDownloadTask?.IsCompleted is false
|
||||||
|
&& !IsCancelled)
|
||||||
|
{
|
||||||
|
_downloadedPiece.WaitOne(50);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public override void Close()
|
public override void Close()
|
||||||
{
|
{
|
||||||
IsCancelled = true;
|
_cancellationSource.Cancel();
|
||||||
|
_backgroundDownloadTask?.Wait();
|
||||||
|
|
||||||
while (downloadEnded is not null && !downloadEnded.WaitOne(1000)) ;
|
_readFile.Close();
|
||||||
|
_writeFile.Close();
|
||||||
|
Update();
|
||||||
|
}
|
||||||
|
|
||||||
_readFile.Close();
|
#endregion
|
||||||
_writeFile.Close();
|
~NetworkFileStream()
|
||||||
_networkStream?.Close();
|
{
|
||||||
Update();
|
_downloadedPiece?.Close();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
#endregion
|
|
||||||
~NetworkFileStream()
|
|
||||||
{
|
|
||||||
downloadEnded?.Close();
|
|
||||||
downloadedPiece?.Close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,33 +1,81 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using Dinah.Core.Net.Http;
|
using Dinah.Core.Net.Http;
|
||||||
using Dinah.Core.StepRunner;
|
|
||||||
using FileManager;
|
using FileManager;
|
||||||
|
|
||||||
namespace AaxDecrypter
|
namespace AaxDecrypter
|
||||||
{
|
{
|
||||||
public class UnencryptedAudiobookDownloader : AudiobookDownloadBase
|
public class UnencryptedAudiobookDownloader : AudiobookDownloadBase
|
||||||
{
|
{
|
||||||
protected override StepSequence Steps { get; }
|
|
||||||
|
|
||||||
public UnencryptedAudiobookDownloader(string outFileName, string cacheDirectory, DownloadOptions dlLic)
|
public UnencryptedAudiobookDownloader(string outFileName, string cacheDirectory, IDownloadOptions dlLic)
|
||||||
: base(outFileName, cacheDirectory, dlLic)
|
: base(outFileName, cacheDirectory, dlLic) { }
|
||||||
|
|
||||||
|
public override async Task<bool> RunAsync()
|
||||||
{
|
{
|
||||||
Steps = new StepSequence
|
try
|
||||||
{
|
{
|
||||||
Name = "Download Mp3 Audiobook",
|
Serilog.Log.Information("Begin downloading unencrypted audiobook.");
|
||||||
|
|
||||||
["Step 1: Get Mp3 Metadata"] = Step_GetMetadata,
|
//Step 1
|
||||||
["Step 2: Download Audiobook"] = Step_DownloadAudiobookAsSingleFile,
|
Serilog.Log.Information("Begin Step 1: Get Mp3 Metadata");
|
||||||
["Step 3: Create Cue"] = Step_CreateCue,
|
if (await Task.Run(Step_GetMetadata))
|
||||||
["Step 4: Cleanup"] = Step_Cleanup,
|
Serilog.Log.Information("Completed Step 1: Get Mp3 Metadata");
|
||||||
};
|
else
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Failed to Complete Step 1: Get Mp3 Metadata");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Step 2
|
||||||
|
Serilog.Log.Information("Begin Step 2: Download Audiobook");
|
||||||
|
if (await Task.Run(Step_DownloadAudiobookAsSingleFile))
|
||||||
|
Serilog.Log.Information("Completed Step 2: Download Audiobook");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Failed to Complete Step 2: Download Audiobook");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Step 3
|
||||||
|
if (DownloadOptions.DownloadClipsBookmarks)
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Begin Downloading Clips and Bookmarks");
|
||||||
|
if (await Task.Run(Step_DownloadClipsBookmarks))
|
||||||
|
Serilog.Log.Information("Completed Downloading Clips and Bookmarks");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Failed to Download Clips and Bookmarks");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Step 4
|
||||||
|
Serilog.Log.Information("Begin Step 3: Cleanup");
|
||||||
|
if (await Task.Run(Step_Cleanup))
|
||||||
|
Serilog.Log.Information("Completed Step 3: Cleanup");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Serilog.Log.Information("Failed to Complete Step 3: Cleanup");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serilog.Log.Information("Completed download and convert Aaxc To {format}", DownloadOptions.OutputFormat);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Serilog.Log.Error(ex, "Error encountered in download and convert Aaxc To {format}", DownloadOptions.OutputFormat);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public override void Cancel()
|
public override Task CancelAsync()
|
||||||
{
|
{
|
||||||
IsCanceled = true;
|
IsCanceled = true;
|
||||||
CloseInputFileStream();
|
CloseInputFileStream();
|
||||||
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected bool Step_GetMetadata()
|
protected bool Step_GetMetadata()
|
||||||
@@ -65,8 +113,8 @@ namespace AaxDecrypter
|
|||||||
}
|
}
|
||||||
|
|
||||||
CloseInputFileStream();
|
CloseInputFileStream();
|
||||||
|
|
||||||
var realOutputFileName = FileUtility.SaferMoveToValidPath(InputFileStream.SaveFilePath, OutputFileName);
|
var realOutputFileName = FileUtility.SaferMoveToValidPath(InputFileStream.SaveFilePath, OutputFileName, DownloadOptions.ReplacementCharacters);
|
||||||
SetOutputFileName(realOutputFileName);
|
SetOutputFileName(realOutputFileName);
|
||||||
OnFileCreated(realOutputFileName);
|
OnFileCreated(realOutputFileName);
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
{
|
|
||||||
"//": "https://github.com/BalassaMarton/MSBump",
|
|
||||||
BumpRevision: true
|
|
||||||
}
|
|
||||||
@@ -1,21 +1,21 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net6.0-windows</TargetFramework>
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
<Version>7.5.0.1</Version>
|
<Version>8.8.1.1</Version>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="MSBump" Version="2.3.2">
|
<PackageReference Include="Octokit" Version="4.0.3" />
|
||||||
<PrivateAssets>all</PrivateAssets>
|
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
|
||||||
</PackageReference>
|
|
||||||
<PackageReference Include="Octokit" Version="0.51.0" />
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\ApplicationServices\ApplicationServices.csproj" />
|
||||||
<ProjectReference Include="..\AudibleUtilities\AudibleUtilities.csproj" />
|
<ProjectReference Include="..\AudibleUtilities\AudibleUtilities.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
||||||
@@ -3,18 +3,44 @@ using System.Collections.Generic;
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
|
using ApplicationServices;
|
||||||
using AudibleUtilities;
|
using AudibleUtilities;
|
||||||
using Dinah.Core;
|
using Dinah.Core;
|
||||||
using Dinah.Core.IO;
|
using Dinah.Core.IO;
|
||||||
using Dinah.Core.Logging;
|
using Dinah.Core.Logging;
|
||||||
using LibationFileManager;
|
using LibationFileManager;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
|
|
||||||
namespace AppScaffolding
|
namespace AppScaffolding
|
||||||
{
|
{
|
||||||
|
public enum ReleaseIdentifier
|
||||||
|
{
|
||||||
|
None,
|
||||||
|
WindowsClassic,
|
||||||
|
WindowsAvalonia,
|
||||||
|
LinuxAvalonia,
|
||||||
|
MacOSAvalonia
|
||||||
|
}
|
||||||
|
|
||||||
|
// I know I'm taking the wine metaphor a bit far by naming this "Variety", but I don't know what else to call it
|
||||||
|
public enum VarietyType { None, Classic, Chardonnay }
|
||||||
|
|
||||||
public static class LibationScaffolding
|
public static class LibationScaffolding
|
||||||
{
|
{
|
||||||
|
public const string RepositoryUrl = "ht" + "tps://github.com/rmcrackan/Libation";
|
||||||
|
public const string WebsiteUrl = "ht" + "tps://getlibation.com";
|
||||||
|
public const string RepositoryLatestUrl = "ht" + "tps://github.com/rmcrackan/Libation/releases/latest";
|
||||||
|
public static ReleaseIdentifier ReleaseIdentifier { get; private set; }
|
||||||
|
public static VarietyType Variety
|
||||||
|
=> ReleaseIdentifier == ReleaseIdentifier.WindowsClassic ? VarietyType.Classic
|
||||||
|
: ReleaseIdentifier.In(ReleaseIdentifier.WindowsAvalonia, ReleaseIdentifier.LinuxAvalonia, ReleaseIdentifier.MacOSAvalonia) ? VarietyType.Chardonnay
|
||||||
|
: VarietyType.None;
|
||||||
|
|
||||||
|
public static void SetReleaseIdentifier(ReleaseIdentifier releaseID)
|
||||||
|
=> ReleaseIdentifier = releaseID;
|
||||||
|
|
||||||
// AppScaffolding
|
// AppScaffolding
|
||||||
private static Assembly _executingAssembly;
|
private static Assembly _executingAssembly;
|
||||||
private static Assembly ExecutingAssembly
|
private static Assembly ExecutingAssembly
|
||||||
@@ -32,11 +58,12 @@ namespace AppScaffolding
|
|||||||
??= new[] { ExecutingAssembly.GetName(), EntryAssembly.GetName() }
|
??= new[] { ExecutingAssembly.GetName(), EntryAssembly.GetName() }
|
||||||
.Max(a => a.Version);
|
.Max(a => a.Version);
|
||||||
|
|
||||||
/// <summary>Run migrations before loading Configuration for the first time. Then load and return Configuration</summary>
|
/// <summary>Run migrations before loading Configuration for the first time. Then load and return Configuration</summary>
|
||||||
public static Configuration RunPreConfigMigrations()
|
public static Configuration RunPreConfigMigrations()
|
||||||
{
|
{
|
||||||
// must occur before access to Configuration instance
|
// must occur before access to Configuration instance
|
||||||
Migrations.migrate_to_v5_2_0__pre_config();
|
// // outdated. kept here as an example of what belongs in this area
|
||||||
|
// // Migrations.migrate_to_v5_2_0__pre_config();
|
||||||
|
|
||||||
//***********************************************//
|
//***********************************************//
|
||||||
// //
|
// //
|
||||||
@@ -63,7 +90,13 @@ namespace AppScaffolding
|
|||||||
{
|
{
|
||||||
config.InProgress ??= Configuration.WinTemp;
|
config.InProgress ??= Configuration.WinTemp;
|
||||||
|
|
||||||
if (!config.Exists(nameof(config.AllowLibationFixup)))
|
if (!config.Exists(nameof(config.UseCoverAsFolderIcon)))
|
||||||
|
config.UseCoverAsFolderIcon = false;
|
||||||
|
|
||||||
|
if (!config.Exists(nameof(config.BetaOptIn)))
|
||||||
|
config.BetaOptIn = false;
|
||||||
|
|
||||||
|
if (!config.Exists(nameof(config.AllowLibationFixup)))
|
||||||
config.AllowLibationFixup = true;
|
config.AllowLibationFixup = true;
|
||||||
|
|
||||||
if (!config.Exists(nameof(config.CreateCueSheet)))
|
if (!config.Exists(nameof(config.CreateCueSheet)))
|
||||||
@@ -85,20 +118,20 @@ namespace AppScaffolding
|
|||||||
config.DecryptToLossy = false;
|
config.DecryptToLossy = false;
|
||||||
|
|
||||||
if (!config.Exists(nameof(config.LameTargetBitrate)))
|
if (!config.Exists(nameof(config.LameTargetBitrate)))
|
||||||
config.LameTargetBitrate = false;
|
config.LameTargetBitrate = false;
|
||||||
|
|
||||||
if (!config.Exists(nameof(config.LameDownsampleMono)))
|
if (!config.Exists(nameof(config.LameDownsampleMono)))
|
||||||
config.LameDownsampleMono = true;
|
config.LameDownsampleMono = true;
|
||||||
|
|
||||||
if (!config.Exists(nameof(config.LameBitrate)))
|
if (!config.Exists(nameof(config.LameBitrate)))
|
||||||
config.LameBitrate = 64;
|
config.LameBitrate = 64;
|
||||||
|
|
||||||
if (!config.Exists(nameof(config.LameConstantBitrate)))
|
if (!config.Exists(nameof(config.LameConstantBitrate)))
|
||||||
config.LameConstantBitrate = false;
|
config.LameConstantBitrate = false;
|
||||||
|
|
||||||
if (!config.Exists(nameof(config.LameMatchSourceBR)))
|
if (!config.Exists(nameof(config.LameMatchSourceBR)))
|
||||||
config.LameMatchSourceBR = true;
|
config.LameMatchSourceBR = true;
|
||||||
|
|
||||||
if (!config.Exists(nameof(config.LameVBRQuality)))
|
if (!config.Exists(nameof(config.LameVBRQuality)))
|
||||||
config.LameVBRQuality = 2;
|
config.LameVBRQuality = 2;
|
||||||
|
|
||||||
@@ -114,6 +147,9 @@ namespace AppScaffolding
|
|||||||
if (!config.Exists(nameof(config.DownloadEpisodes)))
|
if (!config.Exists(nameof(config.DownloadEpisodes)))
|
||||||
config.DownloadEpisodes = true;
|
config.DownloadEpisodes = true;
|
||||||
|
|
||||||
|
if (!config.Exists(nameof(config.ReplacementCharacters)))
|
||||||
|
config.ReplacementCharacters = FileManager.ReplacementCharacters.Default;
|
||||||
|
|
||||||
if (!config.Exists(nameof(config.FolderTemplate)))
|
if (!config.Exists(nameof(config.FolderTemplate)))
|
||||||
config.FolderTemplate = Templates.Folder.DefaultTemplate;
|
config.FolderTemplate = Templates.Folder.DefaultTemplate;
|
||||||
|
|
||||||
@@ -123,6 +159,9 @@ namespace AppScaffolding
|
|||||||
if (!config.Exists(nameof(config.ChapterFileTemplate)))
|
if (!config.Exists(nameof(config.ChapterFileTemplate)))
|
||||||
config.ChapterFileTemplate = Templates.ChapterFile.DefaultTemplate;
|
config.ChapterFileTemplate = Templates.ChapterFile.DefaultTemplate;
|
||||||
|
|
||||||
|
if (!config.Exists(nameof(config.ChapterTitleTemplate)))
|
||||||
|
config.ChapterTitleTemplate = Templates.ChapterTitle.DefaultTemplate;
|
||||||
|
|
||||||
if (!config.Exists(nameof(config.AutoScan)))
|
if (!config.Exists(nameof(config.AutoScan)))
|
||||||
config.AutoScan = true;
|
config.AutoScan = true;
|
||||||
|
|
||||||
@@ -137,14 +176,30 @@ namespace AppScaffolding
|
|||||||
|
|
||||||
if (!config.Exists(nameof(config.DownloadCoverArt)))
|
if (!config.Exists(nameof(config.DownloadCoverArt)))
|
||||||
config.DownloadCoverArt = true;
|
config.DownloadCoverArt = true;
|
||||||
|
|
||||||
|
if (!config.Exists(nameof(config.DownloadClipsBookmarks)))
|
||||||
|
config.DownloadClipsBookmarks = false;
|
||||||
|
|
||||||
|
if (!config.Exists(nameof(config.ClipsBookmarksFileFormat)))
|
||||||
|
config.ClipsBookmarksFileFormat = Configuration.ClipBookmarkFormat.CSV;
|
||||||
|
|
||||||
|
if (!config.Exists(nameof(config.AutoDownloadEpisodes)))
|
||||||
|
config.AutoDownloadEpisodes = false;
|
||||||
|
|
||||||
|
if (!config.Exists(nameof(config.DownloadSpeedLimit)))
|
||||||
|
config.DownloadSpeedLimit = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Initialize logging. Run after migration</summary>
|
/// <summary>Initialize logging. Wire-up events. Run after migration</summary>
|
||||||
public static void RunPostMigrationScaffolding(Configuration config)
|
public static void RunPostMigrationScaffolding(Configuration config)
|
||||||
{
|
{
|
||||||
ensureSerilogConfig(config);
|
ensureSerilogConfig(config);
|
||||||
configureLogging(config);
|
configureLogging(config);
|
||||||
logStartupState(config);
|
logStartupState(config);
|
||||||
|
|
||||||
|
// all else should occur after logging
|
||||||
|
|
||||||
|
wireUpSystemEvents(config);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void ensureSerilogConfig(Configuration config)
|
private static void ensureSerilogConfig(Configuration config)
|
||||||
@@ -183,7 +238,7 @@ namespace AppScaffolding
|
|||||||
{ "Using", new JArray{ "Dinah.Core", "Serilog.Exceptions" } }, // dll's name, NOT namespace
|
{ "Using", new JArray{ "Dinah.Core", "Serilog.Exceptions" } }, // dll's name, NOT namespace
|
||||||
{ "Enrich", new JArray{ "WithCaller", "WithExceptionDetails" } },
|
{ "Enrich", new JArray{ "WithCaller", "WithExceptionDetails" } },
|
||||||
};
|
};
|
||||||
config.SetObject("Serilog", serilogObj);
|
config.SetNonString(serilogObj, "Serilog");
|
||||||
}
|
}
|
||||||
|
|
||||||
// to restore original: Console.SetOut(origOut);
|
// to restore original: Console.SetOut(origOut);
|
||||||
@@ -201,8 +256,8 @@ namespace AppScaffolding
|
|||||||
// However, empirical testing so far has shown no issues.
|
// However, empirical testing so far has shown no issues.
|
||||||
Console.SetOut(new MultiTextWriter(origOut, new SerilogTextWriter()));
|
Console.SetOut(new MultiTextWriter(origOut, new SerilogTextWriter()));
|
||||||
|
|
||||||
#region Console => Serilog tests
|
#region Console => Serilog tests
|
||||||
/*
|
/*
|
||||||
// all below apply to "Console." and "Console.Out."
|
// all below apply to "Console." and "Console.Out."
|
||||||
|
|
||||||
// captured
|
// captured
|
||||||
@@ -241,27 +296,33 @@ namespace AppScaffolding
|
|||||||
Console.Write("{0}{1}{2}", "zero|", "one|", "two");
|
Console.Write("{0}{1}{2}", "zero|", "one|", "two");
|
||||||
Console.Write("{0}", new object[] { "arr" });
|
Console.Write("{0}", new object[] { "arr" });
|
||||||
*/
|
*/
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
// .Here() captures debug info via System.Runtime.CompilerServices attributes. Warning: expensive
|
// .Here() captures debug info via System.Runtime.CompilerServices attributes. Warning: expensive
|
||||||
//var withLineNumbers_outputTemplate = "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message}{NewLine}in method {MemberName} at {FilePath}:{LineNumber}{NewLine}{Exception}{NewLine}";
|
//var withLineNumbers_outputTemplate = "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message}{NewLine}in method {MemberName} at {FilePath}:{LineNumber}{NewLine}{Exception}{NewLine}";
|
||||||
//Log.Logger.Here().Debug("Begin Libation. Debug with line numbers");
|
//Log.Logger.Here().Debug("Begin Libation. Debug with line numbers");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void logStartupState(Configuration config)
|
private static void logStartupState(Configuration config)
|
||||||
{
|
{
|
||||||
|
#if DEBUG
|
||||||
|
var mode = "Debug";
|
||||||
|
#else
|
||||||
|
var mode = "Release";
|
||||||
|
#endif
|
||||||
|
if (System.Diagnostics.Debugger.IsAttached)
|
||||||
|
mode += " (Debugger attached)";
|
||||||
|
|
||||||
// begin logging session with a form feed
|
// begin logging session with a form feed
|
||||||
Log.Logger.Information("\r\n\f");
|
Log.Logger.Information("\r\n\f");
|
||||||
Log.Logger.Information("Begin. {@DebugInfo}", new
|
Log.Logger.Information("Begin. {@DebugInfo}", new
|
||||||
{
|
{
|
||||||
AppName = EntryAssembly.GetName().Name,
|
AppName = EntryAssembly.GetName().Name,
|
||||||
Version = BuildVersion.ToString(),
|
Version = BuildVersion.ToString(),
|
||||||
#if DEBUG
|
ReleaseIdentifier,
|
||||||
Mode = "Debug",
|
Configuration.OS,
|
||||||
#else
|
InteropFactory.InteropFunctionsType,
|
||||||
Mode = "Release",
|
Mode = mode,
|
||||||
#endif
|
|
||||||
|
|
||||||
LogLevel_Verbose_Enabled = Log.Logger.IsVerboseEnabled(),
|
LogLevel_Verbose_Enabled = Log.Logger.IsVerboseEnabled(),
|
||||||
LogLevel_Debug_Enabled = Log.Logger.IsDebugEnabled(),
|
LogLevel_Debug_Enabled = Log.Logger.IsDebugEnabled(),
|
||||||
LogLevel_Information_Enabled = Log.Logger.IsInformationEnabled(),
|
LogLevel_Information_Enabled = Log.Logger.IsInformationEnabled(),
|
||||||
@@ -269,7 +330,9 @@ namespace AppScaffolding
|
|||||||
LogLevel_Error_Enabled = Log.Logger.IsErrorEnabled(),
|
LogLevel_Error_Enabled = Log.Logger.IsErrorEnabled(),
|
||||||
LogLevel_Fatal_Enabled = Log.Logger.IsFatalEnabled(),
|
LogLevel_Fatal_Enabled = Log.Logger.IsFatalEnabled(),
|
||||||
|
|
||||||
config.LibationFiles,
|
config.BetaOptIn,
|
||||||
|
config.UseCoverAsFolderIcon,
|
||||||
|
config.LibationFiles,
|
||||||
AudibleFileStorage.BooksDirectory,
|
AudibleFileStorage.BooksDirectory,
|
||||||
|
|
||||||
config.InProgress,
|
config.InProgress,
|
||||||
@@ -280,27 +343,35 @@ namespace AppScaffolding
|
|||||||
AudibleFileStorage.DecryptInProgressDirectory,
|
AudibleFileStorage.DecryptInProgressDirectory,
|
||||||
DecryptInProgressFiles = FileManager.FileUtility.SaferEnumerateFiles(AudibleFileStorage.DecryptInProgressDirectory).Count(),
|
DecryptInProgressFiles = FileManager.FileUtility.SaferEnumerateFiles(AudibleFileStorage.DecryptInProgressDirectory).Count(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (InteropFactory.InteropFunctionsType is null)
|
||||||
|
Serilog.Log.Logger.Warning("WARNING: OSInteropProxy.InteropFunctionsType is null");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void wireUpSystemEvents(Configuration configuration)
|
||||||
|
{
|
||||||
|
LibraryCommands.LibrarySizeChanged += (_, __) => SearchEngineCommands.FullReIndex();
|
||||||
|
LibraryCommands.BookUserDefinedItemCommitted += (_, books) => SearchEngineCommands.UpdateBooks(books);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static (bool hasUpgrade, string zipUrl, string htmlUrl, string zipName) GetLatestRelease()
|
public static UpgradeProperties GetLatestRelease()
|
||||||
{
|
{
|
||||||
(bool, string, string, string) isFalse = (false, null, null, null);
|
|
||||||
|
|
||||||
// timed out
|
// timed out
|
||||||
var latest = getLatestRelease(TimeSpan.FromSeconds(10));
|
(var latest, var zip) = getLatestRelease(TimeSpan.FromSeconds(10));
|
||||||
if (latest is null)
|
|
||||||
return isFalse;
|
if (latest is null || zip is null)
|
||||||
|
return null;
|
||||||
|
|
||||||
var latestVersionString = latest.TagName.Trim('v');
|
var latestVersionString = latest.TagName.Trim('v');
|
||||||
if (!Version.TryParse(latestVersionString, out var latestRelease))
|
if (!Version.TryParse(latestVersionString, out var latestRelease))
|
||||||
return isFalse;
|
return null;
|
||||||
|
|
||||||
// we're up to date
|
// we're up to date
|
||||||
if (latestRelease <= BuildVersion)
|
if (latestRelease <= BuildVersion)
|
||||||
return isFalse;
|
return null;
|
||||||
|
|
||||||
// we have an update
|
// we have an update
|
||||||
var zip = latest.Assets.FirstOrDefault(a => a.BrowserDownloadUrl.EndsWith(".zip"));
|
|
||||||
var zipUrl = zip?.BrowserDownloadUrl;
|
var zipUrl = zip?.BrowserDownloadUrl;
|
||||||
|
|
||||||
Log.Logger.Information("Update available: {@DebugInfo}", new
|
Log.Logger.Information("Update available: {@DebugInfo}", new
|
||||||
@@ -310,13 +381,13 @@ namespace AppScaffolding
|
|||||||
zipUrl
|
zipUrl
|
||||||
});
|
});
|
||||||
|
|
||||||
return (true, zipUrl, latest.HtmlUrl, zip.Name);
|
return new(zipUrl, latest.HtmlUrl, zip.Name, latestRelease, latest.Body);
|
||||||
}
|
}
|
||||||
private static Octokit.Release getLatestRelease(TimeSpan timeout)
|
private static (Octokit.Release, Octokit.ReleaseAsset) getLatestRelease(TimeSpan timeout)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var task = System.Threading.Tasks.Task.Run(() => getLatestRelease());
|
var task = getLatestRelease();
|
||||||
if (task.Wait(timeout))
|
if (task.Wait(timeout))
|
||||||
return task.Result;
|
return task.Result;
|
||||||
|
|
||||||
@@ -326,56 +397,31 @@ namespace AppScaffolding
|
|||||||
{
|
{
|
||||||
Log.Logger.Error(aggEx, "Checking for new version too often");
|
Log.Logger.Error(aggEx, "Checking for new version too often");
|
||||||
}
|
}
|
||||||
return null;
|
return (null, null);
|
||||||
}
|
}
|
||||||
private static Octokit.Release getLatestRelease()
|
private static async System.Threading.Tasks.Task<(Octokit.Release, Octokit.ReleaseAsset)> getLatestRelease()
|
||||||
{
|
{
|
||||||
var gitHubClient = new Octokit.GitHubClient(new Octokit.ProductHeaderValue("Libation"));
|
var ownerAccount = "rmcrackan";
|
||||||
|
var repoName = "Libation";
|
||||||
|
|
||||||
|
var gitHubClient = new Octokit.GitHubClient(new Octokit.ProductHeaderValue(repoName));
|
||||||
|
|
||||||
|
//Download the release index
|
||||||
|
var bts = await gitHubClient.Repository.Content.GetRawContent(ownerAccount, repoName, ".releaseindex.json");
|
||||||
|
var releaseIndex = JObject.Parse(System.Text.Encoding.ASCII.GetString(bts));
|
||||||
|
var regexPattern = releaseIndex.Value<string>(ReleaseIdentifier.ToString());
|
||||||
|
|
||||||
// https://octokitnet.readthedocs.io/en/latest/releases/
|
// https://octokitnet.readthedocs.io/en/latest/releases/
|
||||||
var releases = gitHubClient.Repository.Release.GetAll("rmcrackan", "Libation").GetAwaiter().GetResult();
|
var releases = await gitHubClient.Repository.Release.GetAll(ownerAccount, repoName);
|
||||||
var latest = releases.First(r => !r.Draft && !r.Prerelease);
|
|
||||||
return latest;
|
var regex = new System.Text.RegularExpressions.Regex(regexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||||
|
var latestRelease = releases.FirstOrDefault(r => !r.Draft && !r.Prerelease && r.Assets.Any(a => regex.IsMatch(a.Name)));
|
||||||
|
return (latestRelease, latestRelease?.Assets?.FirstOrDefault(a => regex.IsMatch(a.Name)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static class Migrations
|
internal static class Migrations
|
||||||
{
|
{
|
||||||
#region migrate to v5.2.0
|
|
||||||
// get rid of meta-directories, combine DownloadsInProgressEnum and DecryptInProgressEnum => InProgress
|
|
||||||
public static void migrate_to_v5_2_0__pre_config()
|
|
||||||
{
|
|
||||||
{
|
|
||||||
var settingsKey = "DownloadsInProgressEnum";
|
|
||||||
if (UNSAFE_MigrationHelper.Settings_TryGet(settingsKey, out var value))
|
|
||||||
{
|
|
||||||
UNSAFE_MigrationHelper.Settings_Delete(settingsKey);
|
|
||||||
UNSAFE_MigrationHelper.Settings_Insert("InProgress", translatePath(value));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
{
|
|
||||||
UNSAFE_MigrationHelper.Settings_Delete("DecryptInProgressEnum");
|
|
||||||
}
|
|
||||||
|
|
||||||
{ // appsettings.json
|
|
||||||
var appSettingsKey = UNSAFE_MigrationHelper.LIBATION_FILES_KEY;
|
|
||||||
if (UNSAFE_MigrationHelper.APPSETTINGS_TryGet(appSettingsKey, out var value))
|
|
||||||
UNSAFE_MigrationHelper.APPSETTINGS_Update(appSettingsKey, translatePath(value));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string translatePath(string path)
|
|
||||||
=> path switch
|
|
||||||
{
|
|
||||||
"AppDir" => @".\LibationFiles",
|
|
||||||
"MyDocs" => Path.GetFullPath(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "LibationFiles")),
|
|
||||||
"UserProfile" => Path.GetFullPath(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Libation")),
|
|
||||||
"WinTemp" => Path.GetFullPath(Path.Combine(Path.GetTempPath(), "Libation")),
|
|
||||||
_ => path
|
|
||||||
};
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
public static void migrate_to_v6_6_9(Configuration config)
|
public static void migrate_to_v6_6_9(Configuration config)
|
||||||
{
|
{
|
||||||
var writeToPath = $"Serilog.WriteTo";
|
var writeToPath = $"Serilog.WriteTo";
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace AppScaffolding
|
||||||
|
{
|
||||||
|
public abstract class OSConfigBase
|
||||||
|
{
|
||||||
|
public abstract Type InteropFunctionsType { get; }
|
||||||
|
public virtual Type[] ReferencedTypes { get; } = new Type[0];
|
||||||
|
|
||||||
|
public void Run()
|
||||||
|
{
|
||||||
|
//Each of these types belongs to a different windows-only assembly that's needed by
|
||||||
|
//the WinInterop methods. By referencing these types in main we force the runtime to
|
||||||
|
//load their assemblies before execution reaches inside main. This allows the calling
|
||||||
|
//process to find these assemblies in its module list.
|
||||||
|
_ = ReferencedTypes;
|
||||||
|
_ = InteropFunctionsType;
|
||||||
|
|
||||||
|
//Wait for the calling process to be ready to read the WriteLine()
|
||||||
|
Console.ReadLine();
|
||||||
|
|
||||||
|
// Signal the calling process that execution has reached inside main, and that all referenced assemblies have been loaded.
|
||||||
|
Console.WriteLine();
|
||||||
|
|
||||||
|
// Wait for the calling process to finish reading the process module list, then exit.
|
||||||
|
Console.ReadLine();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,10 +17,15 @@ namespace AppScaffolding
|
|||||||
///
|
///
|
||||||
///
|
///
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal static class UNSAFE_MigrationHelper
|
public static class UNSAFE_MigrationHelper
|
||||||
{
|
{
|
||||||
|
public static string SettingsDirectory
|
||||||
|
=> !APPSETTINGS_TryGet(LIBATION_FILES_KEY, out var value) || value is null
|
||||||
|
? null
|
||||||
|
: value;
|
||||||
|
|
||||||
#region appsettings.json
|
#region appsettings.json
|
||||||
private static string APPSETTINGS_JSON { get; } = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "appsettings.json");
|
private static string APPSETTINGS_JSON { get; } = Path.Combine(Path.GetDirectoryName(Environment.ProcessPath), "appsettings.json");
|
||||||
|
|
||||||
public static bool APPSETTINGS_Json_Exists => File.Exists(APPSETTINGS_JSON);
|
public static bool APPSETTINGS_Json_Exists => File.Exists(APPSETTINGS_JSON);
|
||||||
|
|
||||||
@@ -87,19 +92,11 @@ namespace AppScaffolding
|
|||||||
System.Threading.Thread.Sleep(100);
|
System.Threading.Thread.Sleep(100);
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Settings.json
|
#region Settings.json
|
||||||
public const string LIBATION_FILES_KEY = "LibationFiles";
|
public const string LIBATION_FILES_KEY = "LibationFiles";
|
||||||
private const string SETTINGS_JSON = "Settings.json";
|
private const string SETTINGS_JSON = "Settings.json";
|
||||||
|
|
||||||
public static string SettingsJsonPath
|
public static string SettingsJsonPath => SettingsDirectory is null ? null : Path.Combine(SettingsDirectory, SETTINGS_JSON);
|
||||||
{
|
|
||||||
get
|
|
||||||
{
|
|
||||||
var success = APPSETTINGS_TryGet(LIBATION_FILES_KEY, out var value);
|
|
||||||
return !success || value is null ? null : Path.Combine(value, SETTINGS_JSON);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
public static bool SettingsJson_Exists => SettingsJsonPath is not null && File.Exists(SettingsJsonPath);
|
public static bool SettingsJson_Exists => SettingsJsonPath is not null && File.Exists(SettingsJsonPath);
|
||||||
|
|
||||||
public static bool Settings_TryGet(string key, out string value)
|
public static bool Settings_TryGet(string key, out string value)
|
||||||
@@ -267,5 +264,10 @@ namespace AppScaffolding
|
|||||||
System.Threading.Thread.Sleep(100);
|
System.Threading.Thread.Sleep(100);
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
#region LibationContext.db
|
||||||
|
public const string LIBATION_CONTEXT = "LibationContext.db";
|
||||||
|
public static string DatabaseFile => SettingsDirectory is null ? null : Path.Combine(SettingsDirectory, LIBATION_CONTEXT);
|
||||||
|
public static bool DatabaseFile_Exists => DatabaseFile is not null && File.Exists(DatabaseFile);
|
||||||
|
#endregion
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using System;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace AppScaffolding
|
||||||
|
{
|
||||||
|
public record UpgradeProperties
|
||||||
|
{
|
||||||
|
private static readonly Regex linkstripper = new Regex(@"\[(.*)\]\(.*\)");
|
||||||
|
public string ZipUrl { get; }
|
||||||
|
public string HtmlUrl { get; }
|
||||||
|
public string ZipName { get; }
|
||||||
|
public Version LatestRelease { get; }
|
||||||
|
public string Notes { get; }
|
||||||
|
|
||||||
|
public UpgradeProperties(string zipUrl, string htmlUrl, string zipName, Version latestRelease, string notes)
|
||||||
|
{
|
||||||
|
ZipName = zipName;
|
||||||
|
HtmlUrl = htmlUrl;
|
||||||
|
ZipUrl = zipUrl;
|
||||||
|
LatestRelease = latestRelease;
|
||||||
|
Notes = stripMarkdownLinks(notes);
|
||||||
|
}
|
||||||
|
private string stripMarkdownLinks(string body)
|
||||||
|
{
|
||||||
|
body = body.Replace(@"\", "");
|
||||||
|
var matches = linkstripper.Matches(body);
|
||||||
|
|
||||||
|
foreach (Match match in matches)
|
||||||
|
body = body.Replace(match.Groups[0].Value, match.Groups[1].Value);
|
||||||
|
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net6.0-windows</TargetFramework>
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="CsvHelper" Version="27.2.1" />
|
<PackageReference Include="CsvHelper" Version="30.0.1" />
|
||||||
<PackageReference Include="NPOI" Version="2.5.6" />
|
<PackageReference Include="NPOI" Version="2.6.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@@ -14,4 +14,12 @@
|
|||||||
<ProjectReference Include="..\LibationSearchEngine\LibationSearchEngine.csproj" />
|
<ProjectReference Include="..\LibationSearchEngine\LibationSearchEngine.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using DataLayer;
|
||||||
|
using Dinah.Core;
|
||||||
|
using LibationFileManager;
|
||||||
|
|
||||||
|
namespace ApplicationServices
|
||||||
|
{
|
||||||
|
public class BulkSetDownloadStatus
|
||||||
|
{
|
||||||
|
private List<(string message, LiberatedStatus newStatus, IEnumerable<Book> Books)> actionSets { get; } = new();
|
||||||
|
|
||||||
|
public int Count => actionSets.Count;
|
||||||
|
|
||||||
|
public IEnumerable<string> Messages => actionSets.Select(a => a.message);
|
||||||
|
public string AggregateMessage => $"Are you sure you want to set {Messages.Aggregate((a, b) => $"{a} and {b}")}?";
|
||||||
|
|
||||||
|
private List<LibraryBook> _libraryBooks;
|
||||||
|
private bool _setDownloaded;
|
||||||
|
private bool _setNotDownloaded;
|
||||||
|
|
||||||
|
public BulkSetDownloadStatus(List<LibraryBook> libraryBooks, bool setDownloaded, bool setNotDownloaded)
|
||||||
|
{
|
||||||
|
_libraryBooks = libraryBooks;
|
||||||
|
_setDownloaded = setDownloaded;
|
||||||
|
_setNotDownloaded = setNotDownloaded;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Discover()
|
||||||
|
{
|
||||||
|
var bookExistsList = _libraryBooks
|
||||||
|
.Select(libraryBook => new
|
||||||
|
{
|
||||||
|
libraryBook.Book,
|
||||||
|
FileExists = AudibleFileStorage.Audio.GetPath(libraryBook.Book.AudibleProductId) is not null
|
||||||
|
})
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
if (_setDownloaded)
|
||||||
|
{
|
||||||
|
var books2change = bookExistsList
|
||||||
|
.Where(a => a.FileExists && a.Book.UserDefinedItem.BookStatus != LiberatedStatus.Liberated)
|
||||||
|
.Select(a => a.Book)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
if (books2change.Any())
|
||||||
|
actionSets.Add((
|
||||||
|
$"{"book".PluralizeWithCount(books2change.Count)} to 'Downloaded'",
|
||||||
|
LiberatedStatus.Liberated,
|
||||||
|
books2change));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_setNotDownloaded)
|
||||||
|
{
|
||||||
|
var books2change = bookExistsList
|
||||||
|
.Where(a => !a.FileExists && a.Book.UserDefinedItem.BookStatus != LiberatedStatus.NotLiberated)
|
||||||
|
.Select(a => a.Book)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
if (books2change.Any())
|
||||||
|
actionSets.Add((
|
||||||
|
$"{"book".PluralizeWithCount(books2change.Count)} to 'Not Downloaded'",
|
||||||
|
LiberatedStatus.NotLiberated,
|
||||||
|
books2change));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Execute()
|
||||||
|
{
|
||||||
|
foreach (var a in actionSets)
|
||||||
|
a.Books.UpdateBookStatus(a.newStatus);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,10 +12,10 @@ namespace ApplicationServices
|
|||||||
=> LibationContext.Create(SqliteStorage.ConnectionString);
|
=> LibationContext.Create(SqliteStorage.ConnectionString);
|
||||||
|
|
||||||
/// <summary>Use for full library querying. No lazy loading</summary>
|
/// <summary>Use for full library querying. No lazy loading</summary>
|
||||||
public static List<LibraryBook> GetLibrary_Flat_NoTracking()
|
public static List<LibraryBook> GetLibrary_Flat_NoTracking(bool includeParents = false)
|
||||||
{
|
{
|
||||||
using var context = GetContext();
|
using var context = GetContext();
|
||||||
return context.GetLibrary_Flat_NoTracking();
|
return context.GetLibrary_Flat_NoTracking(includeParents);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -13,197 +13,205 @@ using static DtoImporterService.PerfLogger;
|
|||||||
|
|
||||||
namespace ApplicationServices
|
namespace ApplicationServices
|
||||||
{
|
{
|
||||||
public static class LibraryCommands
|
public static class LibraryCommands
|
||||||
{
|
{
|
||||||
public static event EventHandler<int> ScanBegin;
|
public static event EventHandler<int> ScanBegin;
|
||||||
public static event EventHandler ScanEnd;
|
public static event EventHandler ScanEnd;
|
||||||
|
|
||||||
public static bool Scanning { get; private set; }
|
public static bool Scanning { get; private set; }
|
||||||
private static object _lock { get; } = new();
|
private static object _lock { get; } = new();
|
||||||
|
|
||||||
static LibraryCommands()
|
static LibraryCommands()
|
||||||
{
|
{
|
||||||
ScanBegin += (_, __) => Scanning = true;
|
ScanBegin += (_, __) => Scanning = true;
|
||||||
ScanEnd += (_, __) => Scanning = false;
|
ScanEnd += (_, __) => Scanning = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task<List<LibraryBook>> FindInactiveBooks(Func<Account, Task<ApiExtended>> apiExtendedfunc, List<LibraryBook> existingLibrary, params Account[] accounts)
|
public static async Task<List<LibraryBook>> FindInactiveBooks(Func<Account, Task<ApiExtended>> apiExtendedfunc, IEnumerable<LibraryBook> existingLibrary, params Account[] accounts)
|
||||||
{
|
{
|
||||||
logRestart();
|
logRestart();
|
||||||
|
|
||||||
//These are the minimum response groups required for the
|
lock (_lock)
|
||||||
//library scanner to pass all validation and filtering.
|
|
||||||
var libraryOptions = new LibraryOptions
|
|
||||||
{
|
{
|
||||||
ResponseGroups
|
if (Scanning)
|
||||||
= LibraryOptions.ResponseGroupOptions.ProductAttrs
|
return new();
|
||||||
| LibraryOptions.ResponseGroupOptions.ProductDesc
|
}
|
||||||
| LibraryOptions.ResponseGroupOptions.Relationships
|
ScanBegin?.Invoke(null, accounts.Length);
|
||||||
};
|
|
||||||
|
//These are the minimum response groups required for the
|
||||||
|
//library scanner to pass all validation and filtering.
|
||||||
|
var libraryOptions = new LibraryOptions
|
||||||
|
{
|
||||||
|
ResponseGroups
|
||||||
|
= LibraryOptions.ResponseGroupOptions.ProductAttrs
|
||||||
|
| LibraryOptions.ResponseGroupOptions.ProductDesc
|
||||||
|
| LibraryOptions.ResponseGroupOptions.Relationships
|
||||||
|
};
|
||||||
if (accounts is null || accounts.Length == 0)
|
if (accounts is null || accounts.Length == 0)
|
||||||
return new List<LibraryBook>();
|
return new List<LibraryBook>();
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
logTime($"pre {nameof(scanAccountsAsync)} all");
|
logTime($"pre {nameof(scanAccountsAsync)} all");
|
||||||
var libraryItems = await scanAccountsAsync(apiExtendedfunc, accounts, libraryOptions);
|
var libraryItems = await scanAccountsAsync(apiExtendedfunc, accounts, libraryOptions);
|
||||||
logTime($"post {nameof(scanAccountsAsync)} all");
|
logTime($"post {nameof(scanAccountsAsync)} all");
|
||||||
|
|
||||||
var totalCount = libraryItems.Count;
|
var totalCount = libraryItems.Count;
|
||||||
Log.Logger.Information($"GetAllLibraryItems: Total count {totalCount}");
|
Log.Logger.Information($"GetAllLibraryItems: Total count {totalCount}");
|
||||||
|
|
||||||
var missingBookList = existingLibrary.Where(b => !libraryItems.Any(i => i.DtoItem.Asin == b.Book.AudibleProductId)).ToList();
|
var missingBookList = existingLibrary.Where(b => !libraryItems.Any(i => i.DtoItem.Asin == b.Book.AudibleProductId)).ToList();
|
||||||
|
|
||||||
return missingBookList;
|
return missingBookList;
|
||||||
}
|
}
|
||||||
catch (AudibleApi.Authentication.LoginFailedException lfEx)
|
catch (AudibleApi.Authentication.LoginFailedException lfEx)
|
||||||
{
|
{
|
||||||
lfEx.SaveFiles(Configuration.Instance.LibationFiles);
|
lfEx.SaveFiles(Configuration.Instance.LibationFiles);
|
||||||
|
|
||||||
// nuget Serilog.Exceptions would automatically log custom properties
|
// nuget Serilog.Exceptions would automatically log custom properties
|
||||||
// However, it comes with a scary warning when used with EntityFrameworkCore which I'm not yet ready to implement:
|
// However, it comes with a scary warning when used with EntityFrameworkCore which I'm not yet ready to implement:
|
||||||
// https://github.com/RehanSaeed/Serilog.Exceptions
|
// https://github.com/RehanSaeed/Serilog.Exceptions
|
||||||
// work-around: use 3rd param. don't just put exception object in 3rd param -- info overload: stack trace, etc
|
// work-around: use 3rd param. don't just put exception object in 3rd param -- info overload: stack trace, etc
|
||||||
Log.Logger.Error(lfEx, "Error scanning library. Login failed. {@DebugInfo}", new
|
Log.Logger.Error(lfEx, "Error scanning library. Login failed. {@DebugInfo}", new
|
||||||
{
|
|
||||||
lfEx.RequestUrl,
|
|
||||||
ResponseStatusCodeNumber = (int)lfEx.ResponseStatusCode,
|
|
||||||
ResponseStatusCodeDesc = lfEx.ResponseStatusCode,
|
|
||||||
lfEx.ResponseInputFields,
|
|
||||||
lfEx.ResponseBodyFilePaths
|
|
||||||
});
|
|
||||||
throw;
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Log.Logger.Error(ex, "Error scanning library");
|
|
||||||
throw;
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
stop();
|
|
||||||
var putBreakPointHere = logOutput;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#region FULL LIBRARY scan and import
|
|
||||||
public static async Task<(int totalCount, int newCount)> ImportAccountAsync(Func<Account, Task<ApiExtended>> apiExtendedfunc, params Account[] accounts)
|
|
||||||
{
|
|
||||||
logRestart();
|
|
||||||
|
|
||||||
if (accounts is null || accounts.Length == 0)
|
|
||||||
return (0, 0);
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
{
|
||||||
if (Scanning)
|
lfEx.RequestUrl,
|
||||||
return (0, 0);
|
ResponseStatusCodeNumber = (int)lfEx.ResponseStatusCode,
|
||||||
ScanBegin?.Invoke(null, accounts.Length);
|
ResponseStatusCodeDesc = lfEx.ResponseStatusCode,
|
||||||
}
|
lfEx.ResponseInputFields,
|
||||||
|
lfEx.ResponseBodyFilePaths
|
||||||
|
});
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log.Logger.Error(ex, "Error scanning library");
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
stop();
|
||||||
|
var putBreakPointHere = logOutput;
|
||||||
|
ScanEnd?.Invoke(null, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
logTime($"pre {nameof(scanAccountsAsync)} all");
|
#region FULL LIBRARY scan and import
|
||||||
var libraryOptions = new LibraryOptions
|
public static async Task<(int totalCount, int newCount)> ImportAccountAsync(Func<Account, Task<ApiExtended>> apiExtendedfunc, params Account[] accounts)
|
||||||
{
|
{
|
||||||
ResponseGroups = LibraryOptions.ResponseGroupOptions.ALL_OPTIONS,
|
logRestart();
|
||||||
ImageSizes = LibraryOptions.ImageSizeOptions._500 | LibraryOptions.ImageSizeOptions._1215
|
|
||||||
};
|
if (accounts is null || accounts.Length == 0)
|
||||||
|
return (0, 0);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (Scanning)
|
||||||
|
return (0, 0);
|
||||||
|
}
|
||||||
|
ScanBegin?.Invoke(null, accounts.Length);
|
||||||
|
|
||||||
|
logTime($"pre {nameof(scanAccountsAsync)} all");
|
||||||
|
var libraryOptions = new LibraryOptions
|
||||||
|
{
|
||||||
|
ResponseGroups = LibraryOptions.ResponseGroupOptions.ALL_OPTIONS,
|
||||||
|
ImageSizes = LibraryOptions.ImageSizeOptions._500 | LibraryOptions.ImageSizeOptions._1215
|
||||||
|
};
|
||||||
var importItems = await scanAccountsAsync(apiExtendedfunc, accounts, libraryOptions);
|
var importItems = await scanAccountsAsync(apiExtendedfunc, accounts, libraryOptions);
|
||||||
logTime($"post {nameof(scanAccountsAsync)} all");
|
logTime($"post {nameof(scanAccountsAsync)} all");
|
||||||
|
|
||||||
var totalCount = importItems.Count;
|
var totalCount = importItems.Count;
|
||||||
Log.Logger.Information($"GetAllLibraryItems: Total count {totalCount}");
|
Log.Logger.Information($"GetAllLibraryItems: Total count {totalCount}");
|
||||||
|
|
||||||
if (totalCount == 0)
|
if (totalCount == 0)
|
||||||
return default;
|
return default;
|
||||||
|
|
||||||
Log.Logger.Information("Begin long-running import");
|
Log.Logger.Information("Begin long-running import");
|
||||||
logTime($"pre {nameof(importIntoDbAsync)}");
|
logTime($"pre {nameof(importIntoDbAsync)}");
|
||||||
var newCount = await importIntoDbAsync(importItems);
|
var newCount = await importIntoDbAsync(importItems);
|
||||||
logTime($"post {nameof(importIntoDbAsync)}");
|
logTime($"post {nameof(importIntoDbAsync)}");
|
||||||
Log.Logger.Information($"Import complete. New count {newCount}");
|
Log.Logger.Information($"Import complete. New count {newCount}");
|
||||||
|
|
||||||
return (totalCount, newCount);
|
return (totalCount, newCount);
|
||||||
}
|
}
|
||||||
catch (AudibleApi.Authentication.LoginFailedException lfEx)
|
catch (AudibleApi.Authentication.LoginFailedException lfEx)
|
||||||
{
|
{
|
||||||
lfEx.SaveFiles(Configuration.Instance.LibationFiles);
|
lfEx.SaveFiles(Configuration.Instance.LibationFiles);
|
||||||
|
|
||||||
// nuget Serilog.Exceptions would automatically log custom properties
|
// nuget Serilog.Exceptions would automatically log custom properties
|
||||||
// However, it comes with a scary warning when used with EntityFrameworkCore which I'm not yet ready to implement:
|
// However, it comes with a scary warning when used with EntityFrameworkCore which I'm not yet ready to implement:
|
||||||
// https://github.com/RehanSaeed/Serilog.Exceptions
|
// https://github.com/RehanSaeed/Serilog.Exceptions
|
||||||
// work-around: use 3rd param. don't just put exception object in 3rd param -- info overload: stack trace, etc
|
// work-around: use 3rd param. don't just put exception object in 3rd param -- info overload: stack trace, etc
|
||||||
Log.Logger.Error(lfEx, "Error importing library. Login failed. {@DebugInfo}", new
|
Log.Logger.Error(lfEx, "Error importing library. Login failed. {@DebugInfo}", new
|
||||||
{
|
{
|
||||||
lfEx.RequestUrl,
|
lfEx.RequestUrl,
|
||||||
ResponseStatusCodeNumber = (int)lfEx.ResponseStatusCode,
|
ResponseStatusCodeNumber = (int)lfEx.ResponseStatusCode,
|
||||||
ResponseStatusCodeDesc = lfEx.ResponseStatusCode,
|
ResponseStatusCodeDesc = lfEx.ResponseStatusCode,
|
||||||
lfEx.ResponseInputFields,
|
lfEx.ResponseInputFields,
|
||||||
lfEx.ResponseBodyFilePaths
|
lfEx.ResponseBodyFilePaths
|
||||||
});
|
});
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Log.Logger.Error(ex, "Error importing library");
|
Log.Logger.Error(ex, "Error importing library");
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
stop();
|
stop();
|
||||||
var putBreakPointHere = logOutput;
|
var putBreakPointHere = logOutput;
|
||||||
ScanEnd?.Invoke(null, null);
|
ScanEnd?.Invoke(null, null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task<List<ImportItem>> scanAccountsAsync(Func<Account, Task<ApiExtended>> apiExtendedfunc, Account[] accounts, LibraryOptions libraryOptions)
|
private static async Task<List<ImportItem>> scanAccountsAsync(Func<Account, Task<ApiExtended>> apiExtendedfunc, Account[] accounts, LibraryOptions libraryOptions)
|
||||||
{
|
{
|
||||||
var tasks = new List<Task<List<ImportItem>>>();
|
var tasks = new List<Task<List<ImportItem>>>();
|
||||||
foreach (var account in accounts)
|
foreach (var account in accounts)
|
||||||
{
|
{
|
||||||
// get APIs in serial b/c of logins. do NOT move inside of parallel (Task.WhenAll)
|
// get APIs in serial b/c of logins. do NOT move inside of parallel (Task.WhenAll)
|
||||||
var apiExtended = await apiExtendedfunc(account);
|
var apiExtended = await apiExtendedfunc(account);
|
||||||
|
|
||||||
// add scanAccountAsync as a TASK: do not await
|
// add scanAccountAsync as a TASK: do not await
|
||||||
tasks.Add(scanAccountAsync(apiExtended, account, libraryOptions));
|
tasks.Add(scanAccountAsync(apiExtended, account, libraryOptions));
|
||||||
}
|
}
|
||||||
|
|
||||||
// import library in parallel
|
// import library in parallel
|
||||||
var arrayOfLists = await Task.WhenAll(tasks);
|
var arrayOfLists = await Task.WhenAll(tasks);
|
||||||
var importItems = arrayOfLists.SelectMany(a => a).ToList();
|
var importItems = arrayOfLists.SelectMany(a => a).ToList();
|
||||||
return importItems;
|
return importItems;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task<List<ImportItem>> scanAccountAsync(ApiExtended apiExtended, Account account, LibraryOptions libraryOptions)
|
private static async Task<List<ImportItem>> scanAccountAsync(ApiExtended apiExtended, Account account, LibraryOptions libraryOptions)
|
||||||
{
|
{
|
||||||
ArgumentValidator.EnsureNotNull(account, nameof(account));
|
ArgumentValidator.EnsureNotNull(account, nameof(account));
|
||||||
|
|
||||||
Log.Logger.Information("ImportLibraryAsync. {@DebugInfo}", new
|
Log.Logger.Information("ImportLibraryAsync. {@DebugInfo}", new
|
||||||
{
|
{
|
||||||
Account = account?.MaskedLogEntry ?? "[null]"
|
Account = account?.MaskedLogEntry ?? "[null]"
|
||||||
});
|
});
|
||||||
|
|
||||||
logTime($"pre scanAccountAsync {account.AccountName}");
|
logTime($"pre scanAccountAsync {account.AccountName}");
|
||||||
|
|
||||||
var dtoItems = await apiExtended.GetLibraryValidatedAsync(libraryOptions, Configuration.Instance.ImportEpisodes);
|
var dtoItems = await apiExtended.GetLibraryValidatedAsync(libraryOptions, Configuration.Instance.ImportEpisodes);
|
||||||
|
|
||||||
logTime($"post scanAccountAsync {account.AccountName} qty: {dtoItems.Count}");
|
logTime($"post scanAccountAsync {account.AccountName} qty: {dtoItems.Count}");
|
||||||
|
|
||||||
return dtoItems.Select(d => new ImportItem { DtoItem = d, AccountId = account.AccountId, LocaleName = account.Locale?.Name }).ToList();
|
return dtoItems.Select(d => new ImportItem { DtoItem = d, AccountId = account.AccountId, LocaleName = account.Locale?.Name }).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task<int> importIntoDbAsync(List<ImportItem> importItems)
|
private static async Task<int> importIntoDbAsync(List<ImportItem> importItems)
|
||||||
{
|
{
|
||||||
logTime("importIntoDbAsync -- pre db");
|
logTime("importIntoDbAsync -- pre db");
|
||||||
using var context = DbContexts.GetContext();
|
using var context = DbContexts.GetContext();
|
||||||
var libraryBookImporter = new LibraryBookImporter(context);
|
var libraryBookImporter = new LibraryBookImporter(context);
|
||||||
var newCount = await Task.Run(() => libraryBookImporter.Import(importItems));
|
var newCount = await Task.Run(() => libraryBookImporter.Import(importItems));
|
||||||
logTime("importIntoDbAsync -- post Import()");
|
logTime("importIntoDbAsync -- post Import()");
|
||||||
int qtyChanges = saveChanges(context);
|
int qtyChanges = SaveContext(context);
|
||||||
logTime("importIntoDbAsync -- post SaveChanges");
|
logTime("importIntoDbAsync -- post SaveChanges");
|
||||||
|
|
||||||
// this is any changes at all to the database, not just new books
|
// this is any changes at all to the database, not just new books
|
||||||
if (qtyChanges > 0)
|
if (qtyChanges > 0)
|
||||||
await Task.Run(() => finalizeLibrarySizeChange());
|
await Task.Run(() => finalizeLibrarySizeChange());
|
||||||
logTime("importIntoDbAsync -- post finalizeLibrarySizeChange");
|
logTime("importIntoDbAsync -- post finalizeLibrarySizeChange");
|
||||||
@@ -211,144 +219,249 @@ namespace ApplicationServices
|
|||||||
return newCount;
|
return newCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int saveChanges(LibationContext context)
|
public static int SaveContext(LibationContext context)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
return context.SaveChanges();
|
return context.SaveChanges();
|
||||||
}
|
}
|
||||||
catch (Microsoft.EntityFrameworkCore.DbUpdateException ex)
|
catch (Microsoft.EntityFrameworkCore.DbUpdateException ex)
|
||||||
{
|
{
|
||||||
// DbUpdateException exceptions can wreck serilog. Condense it until we can find a better solution. I suspect the culpret is the "WithExceptionDetails" serilog extension
|
// DbUpdateException exceptions can wreck serilog. Condense it until we can find a better solution. I suspect the culprit is the "WithExceptionDetails" serilog extension
|
||||||
|
|
||||||
static string format(Exception ex) => $"\r\nMessage: {ex.Message}\r\nStack Trace:\r\n{ex.StackTrace}";
|
static string format(Exception ex) => $"\r\nMessage: {ex.Message}\r\nStack Trace:\r\n{ex.StackTrace}";
|
||||||
|
|
||||||
var msg = "Microsoft.EntityFrameworkCore.DbUpdateException";
|
var msg = "Microsoft.EntityFrameworkCore.DbUpdateException";
|
||||||
if (ex.InnerException is null)
|
if (ex.InnerException is null)
|
||||||
throw new Exception($"{msg}{format(ex)}");
|
throw new Exception($"{msg}{format(ex)}");
|
||||||
throw new Exception(
|
throw new Exception(
|
||||||
$"{msg}{format(ex)}",
|
$"{msg}{format(ex)}",
|
||||||
new Exception($"Inner Exception{format(ex.InnerException)}"));
|
new Exception($"Inner Exception{format(ex.InnerException)}"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region remove books
|
#region remove/restore books
|
||||||
public static Task<List<LibraryBook>> RemoveBooksAsync(List<string> idsToRemove) => Task.Run(() => removeBooks(idsToRemove));
|
public static Task<int> RemoveBooksAsync(List<string> idsToRemove) => Task.Run(() => removeBooks(idsToRemove));
|
||||||
private static List<LibraryBook> removeBooks(List<string> idsToRemove)
|
public static int RemoveBook(string idToRemove) => removeBooks(new() { idToRemove });
|
||||||
{
|
private static int removeBooks(List<string> idsToRemove)
|
||||||
using var context = DbContexts.GetContext();
|
{
|
||||||
var libBooks = context.GetLibrary_Flat_NoTracking();
|
try
|
||||||
|
{
|
||||||
|
if (idsToRemove is null || !idsToRemove.Any())
|
||||||
|
return 0;
|
||||||
|
|
||||||
var removeLibraryBooks = libBooks.Where(lb => idsToRemove.Contains(lb.Book.AudibleProductId)).ToList();
|
using var context = DbContexts.GetContext();
|
||||||
context.LibraryBooks.RemoveRange(removeLibraryBooks);
|
var libBooks = context.GetLibrary_Flat_NoTracking();
|
||||||
context.Books.RemoveRange(removeLibraryBooks.Select(lb => lb.Book));
|
var removeLibraryBooks = libBooks.Where(lb => idsToRemove.Contains(lb.Book.AudibleProductId)).ToList();
|
||||||
|
|
||||||
var qtyChanges = context.SaveChanges();
|
// Attach() NoTracking entities before SaveChanges()
|
||||||
if (qtyChanges > 0)
|
foreach (var lb in removeLibraryBooks)
|
||||||
finalizeLibrarySizeChange();
|
{
|
||||||
|
lb.IsDeleted = true;
|
||||||
|
context.Attach(lb).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
|
||||||
|
}
|
||||||
|
|
||||||
return removeLibraryBooks;
|
var qtyChanges = context.SaveChanges();
|
||||||
}
|
if (qtyChanges > 0)
|
||||||
#endregion
|
finalizeLibrarySizeChange();
|
||||||
|
|
||||||
// call this whenever books are added or removed from library
|
return qtyChanges;
|
||||||
private static void finalizeLibrarySizeChange()
|
}
|
||||||
{
|
catch (Exception ex)
|
||||||
SearchEngineCommands.FullReIndex();
|
{
|
||||||
LibrarySizeChanged?.Invoke(null, null);
|
Log.Logger.Error(ex, "Error removing books");
|
||||||
}
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Occurs when the size of the library changes. ie: books are added or removed</summary>
|
public static int RestoreBooks(this List<LibraryBook> libraryBooks)
|
||||||
public static event EventHandler LibrarySizeChanged;
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (libraryBooks is null || !libraryBooks.Any())
|
||||||
|
return 0;
|
||||||
|
|
||||||
/// <summary>
|
using var context = DbContexts.GetContext();
|
||||||
/// Occurs when the size of the library does not change but book(s) details do. Especially when <see cref="UserDefinedItem.Tags"/>, <see cref="UserDefinedItem.BookStatus"/>, or <see cref="UserDefinedItem.PdfStatus"/> changed values are successfully persisted.
|
|
||||||
/// </summary>
|
|
||||||
public static event EventHandler BookUserDefinedItemCommitted;
|
|
||||||
|
|
||||||
#region Update book details
|
// Attach() NoTracking entities before SaveChanges()
|
||||||
public static int UpdateUserDefinedItem(params Book[] books) => UpdateUserDefinedItem(books.ToList());
|
foreach (var lb in libraryBooks)
|
||||||
public static int UpdateUserDefinedItem(IEnumerable<Book> books)
|
{
|
||||||
{
|
lb.IsDeleted = false;
|
||||||
try
|
context.Attach(lb).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
|
||||||
{
|
}
|
||||||
if (books is null || !books.Any())
|
|
||||||
return 0;
|
|
||||||
|
|
||||||
using var context = DbContexts.GetContext();
|
var qtyChanges = context.SaveChanges();
|
||||||
|
if (qtyChanges > 0)
|
||||||
|
finalizeLibrarySizeChange();
|
||||||
|
|
||||||
// Attach() NoTracking entities before SaveChanges()
|
return qtyChanges;
|
||||||
foreach (var book in books)
|
}
|
||||||
context.Attach(book.UserDefinedItem).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log.Logger.Error(ex, "Error restoring books");
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
var qtyChanges = context.SaveChanges();
|
// call this whenever books are added or removed from library
|
||||||
if (qtyChanges == 0)
|
private static void finalizeLibrarySizeChange() => LibrarySizeChanged?.Invoke(null, null);
|
||||||
return 0;
|
|
||||||
|
|
||||||
// semi-arbitrary. At some point it's more worth it to do a full re-index than to do one offs.
|
/// <summary>Occurs when the size of the library changes. ie: books are added or removed</summary>
|
||||||
// I did not benchmark before choosing the number here
|
public static event EventHandler LibrarySizeChanged;
|
||||||
if (qtyChanges > 15)
|
|
||||||
SearchEngineCommands.FullReIndex();
|
|
||||||
else
|
|
||||||
{
|
|
||||||
foreach (var book in books)
|
|
||||||
{
|
|
||||||
SearchEngineCommands.UpdateLiberatedStatus(book);
|
|
||||||
SearchEngineCommands.UpdateBookTags(book);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
BookUserDefinedItemCommitted?.Invoke(null, null);
|
/// <summary>
|
||||||
|
/// Occurs when the size of the library does not change but book(s) details do. Especially when <see cref="UserDefinedItem.Tags"/>, <see cref="UserDefinedItem.BookStatus"/>, or <see cref="UserDefinedItem.PdfStatus"/> changed values are successfully persisted.
|
||||||
|
/// </summary>
|
||||||
|
public static event EventHandler<IEnumerable<Book>> BookUserDefinedItemCommitted;
|
||||||
|
|
||||||
return qtyChanges;
|
#region Update book details
|
||||||
}
|
public static int UpdateUserDefinedItem(
|
||||||
catch (Exception ex)
|
this Book book,
|
||||||
{
|
string tags = null,
|
||||||
Log.Logger.Error(ex, $"Error updating {nameof(Book.UserDefinedItem)}");
|
LiberatedStatus? bookStatus = null,
|
||||||
throw;
|
LiberatedStatus? pdfStatus = null,
|
||||||
}
|
Rating rating = null)
|
||||||
}
|
=> new[] { book }.UpdateUserDefinedItem(tags, bookStatus, pdfStatus, rating);
|
||||||
#endregion
|
|
||||||
|
|
||||||
// must be here instead of in db layer due to AaxcExists
|
public static int UpdateUserDefinedItem(
|
||||||
public static LiberatedStatus Liberated_Status(Book book)
|
this IEnumerable<Book> books,
|
||||||
=> book.Audio_Exists() ? book.UserDefinedItem.BookStatus
|
string tags = null,
|
||||||
: AudibleFileStorage.AaxcExists(book.AudibleProductId) ? LiberatedStatus.PartialDownload
|
LiberatedStatus? bookStatus = null,
|
||||||
: LiberatedStatus.NotLiberated;
|
LiberatedStatus? pdfStatus = null,
|
||||||
|
Rating rating = null)
|
||||||
|
=> updateUserDefinedItem(
|
||||||
|
books,
|
||||||
|
udi => {
|
||||||
|
// blank tags are expected. null tags are not
|
||||||
|
if (tags is not null)
|
||||||
|
udi.Tags = tags;
|
||||||
|
|
||||||
// exists here for feature predictability. It makes sense for this to be where Liberated_Status is
|
if (bookStatus.HasValue)
|
||||||
public static LiberatedStatus? Pdf_Status(Book book) => book.UserDefinedItem.PdfStatus;
|
udi.BookStatus = bookStatus.Value;
|
||||||
|
|
||||||
// below are queries, not commands. maybe I should make a LibraryQueries. except there's already one of those...
|
// method handles null logic
|
||||||
|
udi.SetPdfStatus(pdfStatus);
|
||||||
|
|
||||||
public record LibraryStats(int booksFullyBackedUp, int booksDownloadedOnly, int booksNoProgress, int booksError, int pdfsDownloaded, int pdfsNotDownloaded) { }
|
if (rating is not null)
|
||||||
public static LibraryStats GetCounts()
|
udi.UpdateRating(rating.OverallRating, rating.PerformanceRating, rating.StoryRating);
|
||||||
{
|
});
|
||||||
var libraryBooks = DbContexts.GetLibrary_Flat_NoTracking();
|
|
||||||
|
|
||||||
var results = libraryBooks
|
public static int UpdateBookStatus(this Book book, LiberatedStatus bookStatus)
|
||||||
.AsParallel()
|
=> book.UpdateUserDefinedItem(udi => udi.BookStatus = bookStatus);
|
||||||
.Select(lb => Liberated_Status(lb.Book))
|
public static int UpdateBookStatus(this IEnumerable<Book> books, LiberatedStatus bookStatus)
|
||||||
.ToList();
|
=> books.UpdateUserDefinedItem(udi => udi.BookStatus = bookStatus);
|
||||||
var booksFullyBackedUp = results.Count(r => r == LiberatedStatus.Liberated);
|
public static int UpdateBookStatus(this LibraryBook libraryBook, LiberatedStatus bookStatus)
|
||||||
var booksDownloadedOnly = results.Count(r => r == LiberatedStatus.PartialDownload);
|
=> libraryBook.UpdateUserDefinedItem(udi => udi.BookStatus = bookStatus);
|
||||||
var booksNoProgress = results.Count(r => r == LiberatedStatus.NotLiberated);
|
public static int UpdateBookStatus(this IEnumerable<LibraryBook> libraryBooks, LiberatedStatus bookStatus)
|
||||||
var booksError = results.Count(r => r == LiberatedStatus.Error);
|
=> libraryBooks.UpdateUserDefinedItem(udi => udi.BookStatus = bookStatus);
|
||||||
|
|
||||||
Log.Logger.Information("Book counts. {@DebugInfo}", new { total = results.Count, booksFullyBackedUp, booksDownloadedOnly, booksNoProgress, booksError });
|
public static int UpdatePdfStatus(this Book book, LiberatedStatus pdfStatus)
|
||||||
|
=> book.UpdateUserDefinedItem(udi => udi.SetPdfStatus(pdfStatus));
|
||||||
|
public static int UpdatePdfStatus(this IEnumerable<Book> books, LiberatedStatus pdfStatus)
|
||||||
|
=> books.UpdateUserDefinedItem(udi => udi.SetPdfStatus(pdfStatus));
|
||||||
|
public static int UpdatePdfStatus(this LibraryBook libraryBook, LiberatedStatus pdfStatus)
|
||||||
|
=> libraryBook.UpdateUserDefinedItem(udi => udi.SetPdfStatus(pdfStatus));
|
||||||
|
public static int UpdatePdfStatus(this IEnumerable<LibraryBook> libraryBooks, LiberatedStatus pdfStatus)
|
||||||
|
=> libraryBooks.UpdateUserDefinedItem(udi => udi.SetPdfStatus(pdfStatus));
|
||||||
|
|
||||||
var boolResults = libraryBooks
|
public static int UpdateTags(this Book book, string tags)
|
||||||
.AsParallel()
|
=> book.UpdateUserDefinedItem(udi => udi.Tags = tags);
|
||||||
.Where(lb => lb.Book.HasPdf())
|
public static int UpdateTags(this IEnumerable<Book> books, string tags)
|
||||||
.Select(lb => Pdf_Status(lb.Book))
|
=> books.UpdateUserDefinedItem(udi => udi.Tags = tags);
|
||||||
.ToList();
|
public static int UpdateTags(this LibraryBook libraryBook, string tags)
|
||||||
var pdfsDownloaded = boolResults.Count(r => r == LiberatedStatus.Liberated);
|
=> libraryBook.UpdateUserDefinedItem(udi => udi.Tags = tags);
|
||||||
var pdfsNotDownloaded = boolResults.Count(r => r == LiberatedStatus.NotLiberated);
|
public static int UpdateTags(this IEnumerable<LibraryBook> libraryBooks, string tags)
|
||||||
|
=> libraryBooks.UpdateUserDefinedItem(udi => udi.Tags = tags);
|
||||||
|
|
||||||
Log.Logger.Information("PDF counts. {@DebugInfo}", new { total = boolResults.Count, pdfsDownloaded, pdfsNotDownloaded });
|
public static int UpdateUserDefinedItem(this LibraryBook libraryBook, Action<UserDefinedItem> action)
|
||||||
|
=> libraryBook.Book.updateUserDefinedItem(action);
|
||||||
|
public static int UpdateUserDefinedItem(this IEnumerable<LibraryBook> libraryBooks, Action<UserDefinedItem> action)
|
||||||
|
=> libraryBooks.Select(lb => lb.Book).updateUserDefinedItem(action);
|
||||||
|
|
||||||
return new(booksFullyBackedUp, booksDownloadedOnly, booksNoProgress, booksError, pdfsDownloaded, pdfsNotDownloaded);
|
public static int UpdateUserDefinedItem(this Book book, Action<UserDefinedItem> action) => book.updateUserDefinedItem(action);
|
||||||
}
|
public static int UpdateUserDefinedItem(this IEnumerable<Book> books, Action<UserDefinedItem> action) => books.updateUserDefinedItem(action);
|
||||||
}
|
|
||||||
|
private static int updateUserDefinedItem(this Book book, Action<UserDefinedItem> action) => new[] { book }.updateUserDefinedItem(action);
|
||||||
|
private static int updateUserDefinedItem(this IEnumerable<Book> books, Action<UserDefinedItem> action)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (books is null || !books.Any())
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
foreach (var book in books)
|
||||||
|
action?.Invoke(book.UserDefinedItem);
|
||||||
|
|
||||||
|
using var context = DbContexts.GetContext();
|
||||||
|
|
||||||
|
// Attach() NoTracking entities before SaveChanges()
|
||||||
|
foreach (var book in books)
|
||||||
|
{
|
||||||
|
context.Attach(book.UserDefinedItem).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
|
||||||
|
context.Attach(book.UserDefinedItem.Rating).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
|
||||||
|
}
|
||||||
|
|
||||||
|
var qtyChanges = context.SaveChanges();
|
||||||
|
if (qtyChanges > 0)
|
||||||
|
BookUserDefinedItemCommitted?.Invoke(null, books);
|
||||||
|
|
||||||
|
return qtyChanges;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log.Logger.Error(ex, $"Error updating {nameof(Book.UserDefinedItem)}");
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
// must be here instead of in db layer due to AaxcExists
|
||||||
|
public static LiberatedStatus Liberated_Status(Book book)
|
||||||
|
=> book.Audio_Exists() ? book.UserDefinedItem.BookStatus
|
||||||
|
: AudibleFileStorage.AaxcExists(book.AudibleProductId) ? LiberatedStatus.PartialDownload
|
||||||
|
: LiberatedStatus.NotLiberated;
|
||||||
|
|
||||||
|
// exists here for feature predictability. It makes sense for this to be where Liberated_Status is
|
||||||
|
public static LiberatedStatus? Pdf_Status(Book book) => book.UserDefinedItem.PdfStatus;
|
||||||
|
|
||||||
|
// below are queries, not commands. maybe I should make a LibraryQueries. except there's already one of those...
|
||||||
|
|
||||||
|
public record LibraryStats(int booksFullyBackedUp, int booksDownloadedOnly, int booksNoProgress, int booksError, int pdfsDownloaded, int pdfsNotDownloaded)
|
||||||
|
{
|
||||||
|
public int PendingBooks => booksNoProgress + booksDownloadedOnly;
|
||||||
|
public bool HasPendingBooks => PendingBooks > 0;
|
||||||
|
|
||||||
|
public bool HasBookResults => 0 < (booksFullyBackedUp + booksDownloadedOnly + booksNoProgress + booksError);
|
||||||
|
public bool HasPdfResults => 0 < (pdfsNotDownloaded + pdfsDownloaded);
|
||||||
|
}
|
||||||
|
public static LibraryStats GetCounts()
|
||||||
|
{
|
||||||
|
var libraryBooks = DbContexts.GetLibrary_Flat_NoTracking();
|
||||||
|
|
||||||
|
var results = libraryBooks
|
||||||
|
.AsParallel()
|
||||||
|
.Select(lb => Liberated_Status(lb.Book))
|
||||||
|
.ToList();
|
||||||
|
var booksFullyBackedUp = results.Count(r => r == LiberatedStatus.Liberated);
|
||||||
|
var booksDownloadedOnly = results.Count(r => r == LiberatedStatus.PartialDownload);
|
||||||
|
var booksNoProgress = results.Count(r => r == LiberatedStatus.NotLiberated);
|
||||||
|
var booksError = results.Count(r => r == LiberatedStatus.Error);
|
||||||
|
|
||||||
|
Log.Logger.Information("Book counts. {@DebugInfo}", new { total = results.Count, booksFullyBackedUp, booksDownloadedOnly, booksNoProgress, booksError });
|
||||||
|
|
||||||
|
var boolResults = libraryBooks
|
||||||
|
.AsParallel()
|
||||||
|
.Where(lb => lb.Book.HasPdf())
|
||||||
|
.Select(lb => Pdf_Status(lb.Book))
|
||||||
|
.ToList();
|
||||||
|
var pdfsDownloaded = boolResults.Count(r => r == LiberatedStatus.Liberated);
|
||||||
|
var pdfsNotDownloaded = boolResults.Count(r => r == LiberatedStatus.NotLiberated);
|
||||||
|
|
||||||
|
Log.Logger.Information("PDF counts. {@DebugInfo}", new { total = boolResults.Count, pdfsDownloaded, pdfsNotDownloaded });
|
||||||
|
|
||||||
|
return new(booksFullyBackedUp, booksDownloadedOnly, booksNoProgress, booksError, pdfsDownloaded, pdfsNotDownloaded);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -100,6 +100,9 @@ namespace ApplicationServices
|
|||||||
|
|
||||||
[Name("Content Type")]
|
[Name("Content Type")]
|
||||||
public string ContentType { get; set; }
|
public string ContentType { get; set; }
|
||||||
|
|
||||||
|
[Name("Audio Format")]
|
||||||
|
public string AudioFormat { get; set; }
|
||||||
}
|
}
|
||||||
public static class LibToDtos
|
public static class LibToDtos
|
||||||
{
|
{
|
||||||
@@ -132,7 +135,8 @@ namespace ApplicationServices
|
|||||||
MyLibationTags = a.Book.UserDefinedItem.Tags,
|
MyLibationTags = a.Book.UserDefinedItem.Tags,
|
||||||
BookStatus = a.Book.UserDefinedItem.BookStatus.ToString(),
|
BookStatus = a.Book.UserDefinedItem.BookStatus.ToString(),
|
||||||
PdfStatus = a.Book.UserDefinedItem.PdfStatus.ToString(),
|
PdfStatus = a.Book.UserDefinedItem.PdfStatus.ToString(),
|
||||||
ContentType = a.Book.ContentType.ToString()
|
ContentType = a.Book.ContentType.ToString(),
|
||||||
|
AudioFormat = a.Book.AudioFormat.ToString()
|
||||||
}).ToList();
|
}).ToList();
|
||||||
}
|
}
|
||||||
public static class LibraryExporter
|
public static class LibraryExporter
|
||||||
@@ -176,33 +180,34 @@ namespace ApplicationServices
|
|||||||
var row = sheet.CreateRow(rowIndex);
|
var row = sheet.CreateRow(rowIndex);
|
||||||
|
|
||||||
var columns = new[] {
|
var columns = new[] {
|
||||||
nameof (ExportDto.Account),
|
nameof(ExportDto.Account),
|
||||||
nameof (ExportDto.DateAdded),
|
nameof(ExportDto.DateAdded),
|
||||||
nameof (ExportDto.AudibleProductId),
|
nameof(ExportDto.AudibleProductId),
|
||||||
nameof (ExportDto.Locale),
|
nameof(ExportDto.Locale),
|
||||||
nameof (ExportDto.Title),
|
nameof(ExportDto.Title),
|
||||||
nameof (ExportDto.AuthorNames),
|
nameof(ExportDto.AuthorNames),
|
||||||
nameof (ExportDto.NarratorNames),
|
nameof(ExportDto.NarratorNames),
|
||||||
nameof (ExportDto.LengthInMinutes),
|
nameof(ExportDto.LengthInMinutes),
|
||||||
nameof (ExportDto.Description),
|
nameof(ExportDto.Description),
|
||||||
nameof (ExportDto.Publisher),
|
nameof(ExportDto.Publisher),
|
||||||
nameof (ExportDto.HasPdf),
|
nameof(ExportDto.HasPdf),
|
||||||
nameof (ExportDto.SeriesNames),
|
nameof(ExportDto.SeriesNames),
|
||||||
nameof (ExportDto.SeriesOrder),
|
nameof(ExportDto.SeriesOrder),
|
||||||
nameof (ExportDto.CommunityRatingOverall),
|
nameof(ExportDto.CommunityRatingOverall),
|
||||||
nameof (ExportDto.CommunityRatingPerformance),
|
nameof(ExportDto.CommunityRatingPerformance),
|
||||||
nameof (ExportDto.CommunityRatingStory),
|
nameof(ExportDto.CommunityRatingStory),
|
||||||
nameof (ExportDto.PictureId),
|
nameof(ExportDto.PictureId),
|
||||||
nameof (ExportDto.IsAbridged),
|
nameof(ExportDto.IsAbridged),
|
||||||
nameof (ExportDto.DatePublished),
|
nameof(ExportDto.DatePublished),
|
||||||
nameof (ExportDto.CategoriesNames),
|
nameof(ExportDto.CategoriesNames),
|
||||||
nameof (ExportDto.MyRatingOverall),
|
nameof(ExportDto.MyRatingOverall),
|
||||||
nameof (ExportDto.MyRatingPerformance),
|
nameof(ExportDto.MyRatingPerformance),
|
||||||
nameof (ExportDto.MyRatingStory),
|
nameof(ExportDto.MyRatingStory),
|
||||||
nameof (ExportDto.MyLibationTags),
|
nameof(ExportDto.MyLibationTags),
|
||||||
nameof (ExportDto.BookStatus),
|
nameof(ExportDto.BookStatus),
|
||||||
nameof (ExportDto.PdfStatus),
|
nameof(ExportDto.PdfStatus),
|
||||||
nameof (ExportDto.ContentType)
|
nameof(ExportDto.ContentType),
|
||||||
|
nameof(ExportDto.AudioFormat)
|
||||||
};
|
};
|
||||||
var col = 0;
|
var col = 0;
|
||||||
foreach (var c in columns)
|
foreach (var c in columns)
|
||||||
@@ -268,6 +273,7 @@ namespace ApplicationServices
|
|||||||
row.CreateCell(col++).SetCellValue(dto.BookStatus);
|
row.CreateCell(col++).SetCellValue(dto.BookStatus);
|
||||||
row.CreateCell(col++).SetCellValue(dto.PdfStatus);
|
row.CreateCell(col++).SetCellValue(dto.PdfStatus);
|
||||||
row.CreateCell(col++).SetCellValue(dto.ContentType);
|
row.CreateCell(col++).SetCellValue(dto.ContentType);
|
||||||
|
row.CreateCell(col++).SetCellValue(dto.AudioFormat);
|
||||||
|
|
||||||
rowIndex++;
|
rowIndex++;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,198 @@
|
|||||||
|
using AudibleApi.Common;
|
||||||
|
using CsvHelper;
|
||||||
|
using DataLayer;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
using NPOI.XSSF.UserModel;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace ApplicationServices
|
||||||
|
{
|
||||||
|
public static class RecordExporter
|
||||||
|
{
|
||||||
|
public static void ToXlsx(string saveFilePath, IEnumerable<IRecord> records)
|
||||||
|
{
|
||||||
|
if (!records.Any())
|
||||||
|
return;
|
||||||
|
|
||||||
|
using var workbook = new XSSFWorkbook();
|
||||||
|
var sheet = workbook.CreateSheet("Records");
|
||||||
|
|
||||||
|
var detailSubtotalFont = workbook.CreateFont();
|
||||||
|
detailSubtotalFont.IsBold = true;
|
||||||
|
|
||||||
|
var detailSubtotalCellStyle = workbook.CreateCellStyle();
|
||||||
|
detailSubtotalCellStyle.SetFont(detailSubtotalFont);
|
||||||
|
|
||||||
|
// headers
|
||||||
|
var rowIndex = 0;
|
||||||
|
var row = sheet.CreateRow(rowIndex);
|
||||||
|
|
||||||
|
var columns = new List<string>
|
||||||
|
{
|
||||||
|
nameof(Type.Name),
|
||||||
|
nameof(IRecord.Created),
|
||||||
|
nameof(IRecord.Start) + "_ms",
|
||||||
|
};
|
||||||
|
|
||||||
|
if (records.OfType<IAnnotation>().Any())
|
||||||
|
{
|
||||||
|
columns.Add(nameof(IAnnotation.AnnotationId));
|
||||||
|
columns.Add(nameof(IAnnotation.LastModified));
|
||||||
|
}
|
||||||
|
if (records.OfType<IRangeAnnotation>().Any())
|
||||||
|
{
|
||||||
|
columns.Add(nameof(IRangeAnnotation.End) + "_ms");
|
||||||
|
columns.Add(nameof(IRangeAnnotation.Text));
|
||||||
|
}
|
||||||
|
if (records.OfType<Clip>().Any())
|
||||||
|
columns.Add(nameof(Clip.Title));
|
||||||
|
|
||||||
|
var col = 0;
|
||||||
|
foreach (var c in columns)
|
||||||
|
{
|
||||||
|
var cell = row.CreateCell(col++);
|
||||||
|
cell.SetCellValue(c);
|
||||||
|
cell.CellStyle = detailSubtotalCellStyle;
|
||||||
|
}
|
||||||
|
|
||||||
|
var dateFormat = workbook.CreateDataFormat();
|
||||||
|
var dateStyle = workbook.CreateCellStyle();
|
||||||
|
dateStyle.DataFormat = dateFormat.GetFormat("MM/dd/yyyy HH:mm:ss");
|
||||||
|
|
||||||
|
// Add data rows
|
||||||
|
foreach (var record in records)
|
||||||
|
{
|
||||||
|
col = 0;
|
||||||
|
|
||||||
|
row = sheet.CreateRow(++rowIndex);
|
||||||
|
|
||||||
|
row.CreateCell(col++).SetCellValue(record.GetType().Name);
|
||||||
|
|
||||||
|
var dateCreatedCell = row.CreateCell(col++);
|
||||||
|
dateCreatedCell.CellStyle = dateStyle;
|
||||||
|
dateCreatedCell.SetCellValue(record.Created.DateTime);
|
||||||
|
|
||||||
|
row.CreateCell(col++).SetCellValue(record.Start.TotalMilliseconds);
|
||||||
|
|
||||||
|
if (record is IAnnotation annotation)
|
||||||
|
{
|
||||||
|
row.CreateCell(col++).SetCellValue(annotation.AnnotationId);
|
||||||
|
|
||||||
|
var lastModifiedCell = row.CreateCell(col++);
|
||||||
|
lastModifiedCell.CellStyle = dateStyle;
|
||||||
|
lastModifiedCell.SetCellValue(annotation.LastModified.DateTime);
|
||||||
|
|
||||||
|
if (annotation is IRangeAnnotation rangeAnnotation)
|
||||||
|
{
|
||||||
|
row.CreateCell(col++).SetCellValue(rangeAnnotation.End.TotalMilliseconds);
|
||||||
|
row.CreateCell(col++).SetCellValue(rangeAnnotation.Text);
|
||||||
|
|
||||||
|
if (rangeAnnotation is Clip clip)
|
||||||
|
row.CreateCell(col++).SetCellValue(clip.Title);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
using var fileData = new System.IO.FileStream(saveFilePath, System.IO.FileMode.Create);
|
||||||
|
workbook.Write(fileData);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void ToJson(string saveFilePath, LibraryBook libraryBook, IEnumerable<IRecord> records)
|
||||||
|
{
|
||||||
|
if (!records.Any())
|
||||||
|
return;
|
||||||
|
|
||||||
|
var recordsEx = extendRecords(records);
|
||||||
|
|
||||||
|
var recordsObj = new JObject
|
||||||
|
{
|
||||||
|
{ "title", libraryBook.Book.Title},
|
||||||
|
{ "asin", libraryBook.Book.AudibleProductId},
|
||||||
|
{ "exportTime", DateTime.Now},
|
||||||
|
{ "records", JArray.FromObject(recordsEx) }
|
||||||
|
};
|
||||||
|
|
||||||
|
System.IO.File.WriteAllText(saveFilePath, recordsObj.ToString(Newtonsoft.Json.Formatting.Indented));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void ToCsv(string saveFilePath, IEnumerable<IRecord> records)
|
||||||
|
{
|
||||||
|
if (!records.Any())
|
||||||
|
return;
|
||||||
|
|
||||||
|
using var writer = new System.IO.StreamWriter(saveFilePath);
|
||||||
|
using var csv = new CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture);
|
||||||
|
|
||||||
|
//Write headers for the present record type that has the most properties
|
||||||
|
if (records.OfType<Clip>().Any())
|
||||||
|
csv.WriteHeader(typeof(ClipEx));
|
||||||
|
else if (records.OfType<Note>().Any())
|
||||||
|
csv.WriteHeader(typeof(NoteEx));
|
||||||
|
else if (records.OfType<Bookmark>().Any())
|
||||||
|
csv.WriteHeader(typeof(BookmarkEx));
|
||||||
|
else
|
||||||
|
csv.WriteHeader(typeof(LastHeardEx));
|
||||||
|
|
||||||
|
var recordsEx = extendRecords(records);
|
||||||
|
|
||||||
|
csv.NextRecord();
|
||||||
|
csv.WriteRecords(recordsEx.OfType<ClipEx>());
|
||||||
|
csv.WriteRecords(recordsEx.OfType<NoteEx>());
|
||||||
|
csv.WriteRecords(recordsEx.OfType<BookmarkEx>());
|
||||||
|
csv.WriteRecords(recordsEx.OfType<LastHeardEx>());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IEnumerable<IRecordEx> extendRecords(IEnumerable<IRecord> records)
|
||||||
|
=> records
|
||||||
|
.Select<IRecord, IRecordEx>(
|
||||||
|
r => r switch
|
||||||
|
{
|
||||||
|
Clip c => new ClipEx(nameof(Clip), c),
|
||||||
|
Note n => new NoteEx(nameof(Note), n),
|
||||||
|
Bookmark b => new BookmarkEx(nameof(Bookmark), b),
|
||||||
|
LastHeard l => new LastHeardEx(nameof(LastHeard), l),
|
||||||
|
_ => throw new InvalidOperationException(),
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
private interface IRecordEx { string Type { get; } }
|
||||||
|
|
||||||
|
private record LastHeardEx : LastHeard, IRecordEx
|
||||||
|
{
|
||||||
|
public string Type { get; }
|
||||||
|
public LastHeardEx(string type, LastHeard original) : base(original)
|
||||||
|
{
|
||||||
|
Type = type;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private record BookmarkEx : Bookmark, IRecordEx
|
||||||
|
{
|
||||||
|
public string Type { get; }
|
||||||
|
public BookmarkEx(string type, Bookmark original) : base(original)
|
||||||
|
{
|
||||||
|
Type = type;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private record NoteEx : Note, IRecordEx
|
||||||
|
{
|
||||||
|
public string Type { get; }
|
||||||
|
public NoteEx(string type, Note original) : base(original)
|
||||||
|
{
|
||||||
|
Type = type;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private record ClipEx : Clip, IRecordEx
|
||||||
|
{
|
||||||
|
public string Type { get; }
|
||||||
|
public ClipEx(string type, Clip original) : base(original)
|
||||||
|
{
|
||||||
|
Type = type;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
using DataLayer;
|
using DataLayer;
|
||||||
using LibationSearchEngine;
|
using LibationSearchEngine;
|
||||||
|
|
||||||
@@ -7,40 +9,12 @@ namespace ApplicationServices
|
|||||||
{
|
{
|
||||||
public static class SearchEngineCommands
|
public static class SearchEngineCommands
|
||||||
{
|
{
|
||||||
public static void FullReIndex(SearchEngine engine = null)
|
#region Search
|
||||||
{
|
public static SearchResultSet Search(string searchString) => performSafeQuery(e =>
|
||||||
engine ??= new SearchEngine();
|
|
||||||
var library = DbContexts.GetLibrary_Flat_NoTracking();
|
|
||||||
engine.CreateNewIndex(library);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static SearchResultSet Search(string searchString) => performSearchEngineFunc_safe(e =>
|
|
||||||
e.Search(searchString)
|
e.Search(searchString)
|
||||||
);
|
);
|
||||||
|
|
||||||
public static void UpdateBookTags(Book book) => performSearchEngineAction_safe(e =>
|
private static T performSafeQuery<T>(Func<SearchEngine, T> func)
|
||||||
e.UpdateTags(book.AudibleProductId, book.UserDefinedItem.Tags)
|
|
||||||
);
|
|
||||||
|
|
||||||
public static void UpdateLiberatedStatus(Book book) => performSearchEngineAction_safe(e =>
|
|
||||||
e.UpdateLiberatedStatus(book)
|
|
||||||
);
|
|
||||||
|
|
||||||
private static void performSearchEngineAction_safe(Action<SearchEngine> action)
|
|
||||||
{
|
|
||||||
var engine = new SearchEngine();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
action(engine);
|
|
||||||
}
|
|
||||||
catch (FileNotFoundException)
|
|
||||||
{
|
|
||||||
FullReIndex(engine);
|
|
||||||
action(engine);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static T performSearchEngineFunc_safe<T>(Func<SearchEngine, T> func)
|
|
||||||
{
|
{
|
||||||
var engine = new SearchEngine();
|
var engine = new SearchEngine();
|
||||||
try
|
try
|
||||||
@@ -49,9 +23,79 @@ namespace ApplicationServices
|
|||||||
}
|
}
|
||||||
catch (FileNotFoundException)
|
catch (FileNotFoundException)
|
||||||
{
|
{
|
||||||
FullReIndex(engine);
|
fullReIndex(engine);
|
||||||
return func(engine);
|
return func(engine);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
public static event EventHandler SearchEngineUpdated;
|
||||||
|
|
||||||
|
#region Update
|
||||||
|
private static bool isUpdating;
|
||||||
|
|
||||||
|
public static void UpdateBooks(IEnumerable<Book> books)
|
||||||
|
{
|
||||||
|
// Semi-arbitrary. At some point it's more worth it to do a full re-index than to do one offs.
|
||||||
|
// I did not benchmark before choosing the number here
|
||||||
|
if (books.Count() > 15)
|
||||||
|
FullReIndex();
|
||||||
|
else
|
||||||
|
{
|
||||||
|
foreach (var book in books)
|
||||||
|
UpdateUserDefinedItems(book);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void FullReIndex() => performSafeCommand(fullReIndex);
|
||||||
|
|
||||||
|
internal static void UpdateUserDefinedItems(Book book) => performSafeCommand(e =>
|
||||||
|
{
|
||||||
|
e.UpdateLiberatedStatus(book);
|
||||||
|
e.UpdateTags(book.AudibleProductId, book.UserDefinedItem.Tags);
|
||||||
|
e.UpdateUserRatings(book);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
private static void performSafeCommand(Action<SearchEngine> action)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
update(action);
|
||||||
|
}
|
||||||
|
catch (FileNotFoundException)
|
||||||
|
{
|
||||||
|
fullReIndex(new SearchEngine());
|
||||||
|
update(action);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void update(Action<SearchEngine> action)
|
||||||
|
{
|
||||||
|
if (action is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
// support nesting incl recursion
|
||||||
|
var prevIsUpdating = isUpdating;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
isUpdating = true;
|
||||||
|
|
||||||
|
action(new SearchEngine());
|
||||||
|
if (!prevIsUpdating)
|
||||||
|
SearchEngineUpdated?.Invoke(null, null);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
isUpdating = prevIsUpdating;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void fullReIndex(SearchEngine engine)
|
||||||
|
{
|
||||||
|
var library = DbContexts.GetLibrary_Flat_NoTracking();
|
||||||
|
engine.CreateNewIndex(library);
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using AudibleApi;
|
using AudibleApi;
|
||||||
using AudibleApi.Common;
|
using AudibleApi.Common;
|
||||||
using Dinah.Core;
|
using Dinah.Core;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Converters;
|
||||||
using Polly;
|
using Polly;
|
||||||
using Polly.Retry;
|
using Polly.Retry;
|
||||||
|
|
||||||
@@ -118,31 +122,43 @@ namespace AudibleUtilities
|
|||||||
private async Task<List<Item>> getItemsAsync(LibraryOptions libraryOptions, bool importEpisodes)
|
private async Task<List<Item>> getItemsAsync(LibraryOptions libraryOptions, bool importEpisodes)
|
||||||
{
|
{
|
||||||
var items = new List<Item>();
|
var items = new List<Item>();
|
||||||
#if DEBUG
|
|
||||||
//// this will not work for multi accounts
|
|
||||||
//var library_json = "library.json";
|
|
||||||
//library_json = System.IO.Path.GetFullPath(library_json);
|
|
||||||
//if (System.IO.File.Exists(library_json))
|
|
||||||
//{
|
|
||||||
// items = AudibleApi.Common.Converter.FromJson<List<Item>>(System.IO.File.ReadAllText(library_json));
|
|
||||||
//}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
Serilog.Log.Logger.Debug("Begin initial library scan");
|
Serilog.Log.Logger.Debug("Beginning library scan.");
|
||||||
|
|
||||||
if (!items.Any())
|
List<Task<List<Item>>> getChildEpisodesTasks = new();
|
||||||
items = await Api.GetAllLibraryItemsAsync(libraryOptions);
|
|
||||||
|
|
||||||
Serilog.Log.Logger.Debug("Initial library scan complete. Begin episode scan");
|
int count = 0, maxConcurrentEpisodeScans = 5;
|
||||||
|
using SemaphoreSlim concurrencySemaphore = new(maxConcurrentEpisodeScans);
|
||||||
|
|
||||||
await manageEpisodesAsync(items, importEpisodes);
|
await foreach (var item in Api.GetLibraryItemAsyncEnumerable(libraryOptions))
|
||||||
|
{
|
||||||
|
if ((item.IsEpisodes || item.IsSeriesParent) && importEpisodes)
|
||||||
|
{
|
||||||
|
//Get child episodes asynchronously and await all at the end
|
||||||
|
getChildEpisodesTasks.Add(getChildEpisodesAsync(concurrencySemaphore, item));
|
||||||
|
}
|
||||||
|
else if (!item.IsEpisodes && !item.IsSeriesParent)
|
||||||
|
items.Add(item);
|
||||||
|
|
||||||
Serilog.Log.Logger.Debug("Episode scan complete");
|
count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serilog.Log.Logger.Debug("Library scan complete. Found {count} books and series. Waiting on {getChildEpisodesTasksCount} series episode scans to complete.", count, getChildEpisodesTasks.Count);
|
||||||
|
|
||||||
|
//await and add all episodes from all parents
|
||||||
|
foreach (var epList in await Task.WhenAll(getChildEpisodesTasks))
|
||||||
|
items.AddRange(epList);
|
||||||
|
|
||||||
|
Serilog.Log.Logger.Debug("Completed library scan.");
|
||||||
|
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
//System.IO.File.WriteAllText(library_json, AudibleApi.Common.Converter.ToJson(items));
|
//// this will not work for multi accounts
|
||||||
|
//var library_json = "library.json";
|
||||||
|
//library_json = System.IO.Path.GetFullPath(library_json);
|
||||||
|
//if (System.IO.File.Exists(library_json))
|
||||||
|
// items = AudibleApi.Common.Converter.FromJson<List<Item>>(System.IO.File.ReadAllText(library_json));
|
||||||
|
//System.IO.File.WriteAllText(library_json, AudibleApi.Common.Converter.ToJson(items));
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
var validators = new List<IValidator>();
|
var validators = new List<IValidator>();
|
||||||
validators.AddRange(getValidators());
|
validators.AddRange(getValidators());
|
||||||
foreach (var v in validators)
|
foreach (var v in validators)
|
||||||
@@ -151,60 +167,88 @@ namespace AudibleUtilities
|
|||||||
if (exceptions is not null && exceptions.Any())
|
if (exceptions is not null && exceptions.Any())
|
||||||
throw new AggregateException(exceptions);
|
throw new AggregateException(exceptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
|
|
||||||
#region episodes and podcasts
|
private static List<IValidator> getValidators()
|
||||||
private async Task manageEpisodesAsync(List<Item> items, bool importEpisodes)
|
|
||||||
{
|
{
|
||||||
// add podcasts and episodes to list. If fail, don't let it de-rail the rest of the import
|
var type = typeof(IValidator);
|
||||||
try
|
var types = AppDomain.CurrentDomain.GetAssemblies()
|
||||||
{
|
.SelectMany(s => s.GetTypes())
|
||||||
// get parents
|
.Where(p => type.IsAssignableFrom(p) && !p.IsInterface);
|
||||||
var parents = items.Where(i => i.IsEpisodes).ToList();
|
|
||||||
#if DEBUG
|
|
||||||
//var parentsDebug = parents.Select(i => i.ToJson()).Aggregate((a, b) => $"{a}\r\n\r\n{b}");
|
|
||||||
//System.IO.File.WriteAllText("parents.json", parentsDebug);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (!parents.Any())
|
return types.Select(t => Activator.CreateInstance(t) as IValidator).ToList();
|
||||||
return;
|
|
||||||
|
|
||||||
Serilog.Log.Logger.Information($"{parents.Count} series of shows/podcasts found");
|
|
||||||
|
|
||||||
// remove episode parents. even if the following stuff fails, these will still be removed from the collection
|
|
||||||
items.RemoveAll(i => i.IsEpisodes);
|
|
||||||
|
|
||||||
if (importEpisodes)
|
|
||||||
{
|
|
||||||
// add children
|
|
||||||
var children = await getEpisodesAsync(parents);
|
|
||||||
Serilog.Log.Logger.Information($"{children.Count} episodes of shows/podcasts found");
|
|
||||||
items.AddRange(children);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Serilog.Log.Logger.Error(ex, "Error adding podcasts and episodes");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<List<Item>> getEpisodesAsync(List<Item> parents)
|
#region episodes and podcasts
|
||||||
|
|
||||||
|
private async Task<List<Item>> getChildEpisodesAsync(SemaphoreSlim concurrencySemaphore, Item parent)
|
||||||
{
|
{
|
||||||
var results = new List<Item>();
|
await concurrencySemaphore.WaitAsync();
|
||||||
|
|
||||||
foreach (var parent in parents)
|
try
|
||||||
{
|
{
|
||||||
var children = await getEpisodeChildrenAsync(parent);
|
Serilog.Log.Logger.Debug("Beginning episode scan for {parent}", parent);
|
||||||
|
|
||||||
// actual individual episode, not the parent of a series.
|
List<Item> children;
|
||||||
// for now I'm keeping it inside this method since it fits the work flow, incl. importEpisodes logic
|
|
||||||
if (!children.Any())
|
if (parent.IsEpisodes)
|
||||||
{
|
{
|
||||||
results.Add(parent);
|
//The 'parent' is a single episode that was added to the library.
|
||||||
continue;
|
//Get the episode's parent and add it to the database.
|
||||||
|
|
||||||
|
Serilog.Log.Logger.Debug("Supplied Parent is an episode. Beginning parent scan for {parent}", parent);
|
||||||
|
|
||||||
|
children = new() { parent };
|
||||||
|
|
||||||
|
var parentAsins = parent.Relationships
|
||||||
|
.Where(r => r.RelationshipToProduct == RelationshipToProduct.Parent)
|
||||||
|
.Select(p => p.Asin);
|
||||||
|
|
||||||
|
var seriesParents = await Api.GetCatalogProductsAsync(parentAsins, CatalogOptions.ResponseGroupOptions.ALL_OPTIONS);
|
||||||
|
|
||||||
|
int numSeriesParents = seriesParents.Count(p => p.IsSeriesParent);
|
||||||
|
if (numSeriesParents != 1)
|
||||||
|
{
|
||||||
|
//There should only ever be 1 top-level parent per episode. If not, log
|
||||||
|
//so we can figure out what to do about those special cases, and don't
|
||||||
|
//import the episode.
|
||||||
|
JsonSerializerSettings Settings = new()
|
||||||
|
{
|
||||||
|
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
|
||||||
|
DateParseHandling = DateParseHandling.None,
|
||||||
|
Converters =
|
||||||
|
{
|
||||||
|
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
|
||||||
|
},
|
||||||
|
};
|
||||||
|
Serilog.Log.Logger.Error($"Found {numSeriesParents} parents for {parent.Asin}\r\nEpisode Product:\r\n{JsonConvert.SerializeObject(parent, Formatting.None, Settings)}");
|
||||||
|
return new List<Item>();
|
||||||
|
}
|
||||||
|
|
||||||
|
var realParent = seriesParents.Single(p => p.IsSeriesParent);
|
||||||
|
realParent.PurchaseDate = parent.PurchaseDate;
|
||||||
|
|
||||||
|
Serilog.Log.Logger.Debug("Completed parent scan for {parent}", parent);
|
||||||
|
parent = realParent;
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
children = await getEpisodeChildrenAsync(parent);
|
||||||
|
if (!children.Any())
|
||||||
|
return new();
|
||||||
|
}
|
||||||
|
|
||||||
|
//A series parent will always have exactly 1 Series
|
||||||
|
parent.Series = new Series[]
|
||||||
|
{
|
||||||
|
new Series
|
||||||
|
{
|
||||||
|
Asin = parent.Asin,
|
||||||
|
Sequence = "-1",
|
||||||
|
Title = parent.TitleWithSubtitle
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
foreach (var child in children)
|
foreach (var child in children)
|
||||||
{
|
{
|
||||||
@@ -217,25 +261,22 @@ namespace AudibleUtilities
|
|||||||
{
|
{
|
||||||
Asin = parent.Asin,
|
Asin = parent.Asin,
|
||||||
// This should properly be Single() not FirstOrDefault(), but FirstOrDefault is defensive for malformed data from audible
|
// This should properly be Single() not FirstOrDefault(), but FirstOrDefault is defensive for malformed data from audible
|
||||||
Sequence = parent.Relationships.FirstOrDefault(r => r.Asin == child.Asin).Sort.ToString(),
|
Sequence = parent.Relationships.FirstOrDefault(r => r.Asin == child.Asin)?.Sort?.ToString() ?? "0",
|
||||||
Title = parent.TitleWithSubtitle
|
Title = parent.TitleWithSubtitle
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// overload (read: abuse) IsEpisodes flag
|
|
||||||
child.Relationships = new Relationship[]
|
|
||||||
{
|
|
||||||
new Relationship
|
|
||||||
{
|
|
||||||
RelationshipToProduct = RelationshipToProduct.Child,
|
|
||||||
RelationshipType = RelationshipType.Episode
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
results.AddRange(children);
|
children.Add(parent);
|
||||||
}
|
|
||||||
|
|
||||||
return results;
|
Serilog.Log.Logger.Debug("Completed episode scan for {parent}", parent);
|
||||||
|
|
||||||
|
return children;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
concurrencySemaphore.Release();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<List<Item>> getEpisodeChildrenAsync(Item parent)
|
private async Task<List<Item>> getEpisodeChildrenAsync(Item parent)
|
||||||
@@ -261,8 +302,8 @@ namespace AudibleUtilities
|
|||||||
{
|
{
|
||||||
childrenBatch = await Api.GetCatalogProductsAsync(idBatch, CatalogOptions.ResponseGroupOptions.ALL_OPTIONS);
|
childrenBatch = await Api.GetCatalogProductsAsync(idBatch, CatalogOptions.ResponseGroupOptions.ALL_OPTIONS);
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
//var childrenBatchDebug = childrenBatch.Select(i => i.ToJson()).Aggregate((a, b) => $"{a}\r\n\r\n{b}");
|
//var childrenBatchDebug = childrenBatch.Select(i => i.ToJson()).Aggregate((a, b) => $"{a}\r\n\r\n{b}");
|
||||||
//System.IO.File.WriteAllText($"children of {parent.Asin}.json", childrenBatchDebug);
|
//System.IO.File.WriteAllText($"children of {parent.Asin}.json", childrenBatchDebug);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -277,7 +318,7 @@ namespace AudibleUtilities
|
|||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serilog.Log.Logger.Debug($"Batch {i}: {childrenBatch.Count} results");
|
Serilog.Log.Logger.Debug($"Batch {i}: {childrenBatch.Count} results\t({{parent}})", parent);
|
||||||
// the service returned no results. probably indicates an error. stop running batches
|
// the service returned no results. probably indicates an error. stop running batches
|
||||||
if (!childrenBatch.Any())
|
if (!childrenBatch.Any())
|
||||||
break;
|
break;
|
||||||
@@ -295,22 +336,12 @@ namespace AudibleUtilities
|
|||||||
if (childrenIds.Count != results.Count)
|
if (childrenIds.Count != results.Count)
|
||||||
{
|
{
|
||||||
var ex = new ApplicationException($"Mis-match: Children defined by parent={childrenIds.Count}. Children returned by batches={results.Count}");
|
var ex = new ApplicationException($"Mis-match: Children defined by parent={childrenIds.Count}. Children returned by batches={results.Count}");
|
||||||
Serilog.Log.Logger.Error(ex, "Quantity of series episodes defined by parent does not match quantity returned by batch fetching.");
|
Serilog.Log.Logger.Error(ex, "{parent} - Quantity of series episodes defined by parent does not match quantity returned by batch fetching.", parent);
|
||||||
throw ex;
|
throw ex;
|
||||||
}
|
}
|
||||||
|
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
private static List<IValidator> getValidators()
|
|
||||||
{
|
|
||||||
var type = typeof(IValidator);
|
|
||||||
var types = AppDomain.CurrentDomain.GetAssemblies()
|
|
||||||
.SelectMany(s => s.GetTypes())
|
|
||||||
.Where(p => type.IsAssignableFrom(p) && !p.IsInterface);
|
|
||||||
|
|
||||||
return types.Select(t => Activator.CreateInstance(t) as IValidator).ToList();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,23 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net6.0-windows</TargetFramework>
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="AudibleApi" Version="2.8.1.1" />
|
<PackageReference Include="AudibleApi" Version="7.3.1.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\LibationFileManager\LibationFileManager.csproj" />
|
<ProjectReference Include="..\LibationFileManager\LibationFileManager.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using AudibleApi;
|
||||||
|
using AudibleApi.Authorization;
|
||||||
|
using Dinah.Core;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
|
||||||
|
namespace AudibleUtilities
|
||||||
|
{
|
||||||
|
public partial class Mkb79Auth : IIdentityMaintainer
|
||||||
|
{
|
||||||
|
[JsonProperty("website_cookies")]
|
||||||
|
private JObject _websiteCookies { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("adp_token")]
|
||||||
|
public string AdpToken { get; private set; }
|
||||||
|
|
||||||
|
[JsonProperty("access_token")]
|
||||||
|
public string AccessToken { get; private set; }
|
||||||
|
|
||||||
|
[JsonProperty("refresh_token")]
|
||||||
|
public string RefreshToken { get; private set; }
|
||||||
|
|
||||||
|
[JsonProperty("device_private_key")]
|
||||||
|
public string DevicePrivateKey { get; private set; }
|
||||||
|
|
||||||
|
[JsonProperty("store_authentication_cookie")]
|
||||||
|
private JObject _storeAuthenticationCookie { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("device_info")]
|
||||||
|
public DeviceInfo DeviceInfo { get; private set; }
|
||||||
|
|
||||||
|
[JsonProperty("customer_info")]
|
||||||
|
public CustomerInfo CustomerInfo { get; private set; }
|
||||||
|
|
||||||
|
[JsonProperty("expires")]
|
||||||
|
private double _expires { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("locale_code")]
|
||||||
|
public string LocaleCode { get; private set; }
|
||||||
|
|
||||||
|
[JsonProperty("activation_bytes")]
|
||||||
|
public string ActivationBytes { get; private set; }
|
||||||
|
|
||||||
|
[JsonIgnore]
|
||||||
|
public Dictionary<string, string> WebsiteCookies
|
||||||
|
{
|
||||||
|
get => _websiteCookies.ToObject<Dictionary<string, string>>();
|
||||||
|
private set => _websiteCookies = JObject.Parse(JsonConvert.SerializeObject(value, Converter.Settings));
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonIgnore]
|
||||||
|
public string StoreAuthenticationCookie
|
||||||
|
{
|
||||||
|
get => _storeAuthenticationCookie.ToObject<Dictionary<string, string>>()["cookie"];
|
||||||
|
private set => _storeAuthenticationCookie = JObject.Parse(JsonConvert.SerializeObject(new Dictionary<string, string>() { { "cookie", value } }, Converter.Settings));
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonIgnore]
|
||||||
|
public DateTime AccessTokenExpires
|
||||||
|
{
|
||||||
|
get => DateTimeOffset.FromUnixTimeMilliseconds((long)(_expires * 1000)).DateTime;
|
||||||
|
private set => _expires = new DateTimeOffset(value).ToUnixTimeMilliseconds() / 1000d;
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonIgnore] public ISystemDateTime SystemDateTime { get; } = new SystemDateTime();
|
||||||
|
[JsonIgnore] public Locale Locale => Localization.Get(LocaleCode);
|
||||||
|
[JsonIgnore] public string DeviceSerialNumber => DeviceInfo.DeviceSerialNumber;
|
||||||
|
[JsonIgnore] public string DeviceType => DeviceInfo.DeviceType;
|
||||||
|
[JsonIgnore] public string AmazonAccountId => CustomerInfo.UserId;
|
||||||
|
|
||||||
|
public Task<AccessToken> GetAccessTokenAsync()
|
||||||
|
=> Task.FromResult(new AccessToken(AccessToken, AccessTokenExpires));
|
||||||
|
|
||||||
|
public Task<AdpToken> GetAdpTokenAsync()
|
||||||
|
=> Task.FromResult(new AdpToken(AdpToken));
|
||||||
|
|
||||||
|
public Task<PrivateKey> GetPrivateKeyAsync()
|
||||||
|
=> Task.FromResult(new PrivateKey(DevicePrivateKey));
|
||||||
|
}
|
||||||
|
|
||||||
|
public partial class CustomerInfo
|
||||||
|
{
|
||||||
|
[JsonProperty("account_pool")]
|
||||||
|
public string AccountPool { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("user_id")]
|
||||||
|
public string UserId { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("home_region")]
|
||||||
|
public string HomeRegion { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("name")]
|
||||||
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("given_name")]
|
||||||
|
public string GivenName { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public partial class DeviceInfo
|
||||||
|
{
|
||||||
|
[JsonProperty("device_name")]
|
||||||
|
public string DeviceName { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("device_serial_number")]
|
||||||
|
public string DeviceSerialNumber { get; set; }
|
||||||
|
|
||||||
|
[JsonProperty("device_type")]
|
||||||
|
public string DeviceType { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public partial class Mkb79Auth
|
||||||
|
{
|
||||||
|
public static Mkb79Auth FromJson(string json)
|
||||||
|
=> JsonConvert.DeserializeObject<Mkb79Auth>(json, Converter.Settings);
|
||||||
|
|
||||||
|
public string ToJson()
|
||||||
|
=> JObject.Parse(JsonConvert.SerializeObject(this, Converter.Settings)).ToString(Formatting.Indented);
|
||||||
|
|
||||||
|
public async Task<Account> ToAccountAsync()
|
||||||
|
{
|
||||||
|
var refreshToken = new RefreshToken(RefreshToken);
|
||||||
|
|
||||||
|
var authorize = new Authorize(Locale);
|
||||||
|
var newToken = await authorize.RefreshAccessTokenAsync(refreshToken);
|
||||||
|
AccessToken = newToken.TokenValue;
|
||||||
|
AccessTokenExpires = newToken.Expires;
|
||||||
|
|
||||||
|
var api = new Api(this);
|
||||||
|
var email = await api.GetEmailAsync();
|
||||||
|
var account = new Account(email)
|
||||||
|
{
|
||||||
|
DecryptKey = ActivationBytes,
|
||||||
|
AccountName = $"{email} - {Locale.Name}",
|
||||||
|
IdentityTokens = new Identity(Locale)
|
||||||
|
};
|
||||||
|
|
||||||
|
account.IdentityTokens.Update(
|
||||||
|
await GetPrivateKeyAsync(),
|
||||||
|
await GetAdpTokenAsync(),
|
||||||
|
await GetAccessTokenAsync(),
|
||||||
|
refreshToken,
|
||||||
|
WebsiteCookies.Select(c => new KeyValuePair<string, string>(c.Key, c.Value)),
|
||||||
|
DeviceSerialNumber,
|
||||||
|
DeviceType,
|
||||||
|
AmazonAccountId,
|
||||||
|
DeviceInfo.DeviceName,
|
||||||
|
StoreAuthenticationCookie);
|
||||||
|
|
||||||
|
return account;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Mkb79Auth FromAccount(Account account)
|
||||||
|
=> new()
|
||||||
|
{
|
||||||
|
AccessToken = account.IdentityTokens.ExistingAccessToken.TokenValue,
|
||||||
|
ActivationBytes = string.IsNullOrEmpty(account.DecryptKey) ? null : account.DecryptKey,
|
||||||
|
AdpToken = account.IdentityTokens.AdpToken.Value,
|
||||||
|
CustomerInfo = new CustomerInfo
|
||||||
|
{
|
||||||
|
AccountPool = "Amazon",
|
||||||
|
GivenName = string.Empty,
|
||||||
|
HomeRegion = "NA",
|
||||||
|
Name = string.Empty,
|
||||||
|
UserId = account.IdentityTokens.AmazonAccountId
|
||||||
|
},
|
||||||
|
DeviceInfo = new DeviceInfo
|
||||||
|
{
|
||||||
|
DeviceName = account.IdentityTokens.DeviceName,
|
||||||
|
DeviceSerialNumber = account.IdentityTokens.DeviceSerialNumber,
|
||||||
|
DeviceType = account.IdentityTokens.DeviceType,
|
||||||
|
},
|
||||||
|
DevicePrivateKey = account.IdentityTokens.PrivateKey,
|
||||||
|
AccessTokenExpires = account.IdentityTokens.ExistingAccessToken.Expires,
|
||||||
|
LocaleCode = account.Locale.CountryCode,
|
||||||
|
RefreshToken = account.IdentityTokens.RefreshToken.Value,
|
||||||
|
StoreAuthenticationCookie = account.IdentityTokens.StoreAuthenticationCookie,
|
||||||
|
WebsiteCookies = new(account.IdentityTokens.Cookies.ToKeyValuePair()),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class Serialize
|
||||||
|
{
|
||||||
|
public static string ToJson(this Mkb79Auth self)
|
||||||
|
=> JObject.Parse(JsonConvert.SerializeObject(self, Converter.Settings)).ToString(Formatting.Indented);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class Converter
|
||||||
|
{
|
||||||
|
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
|
||||||
|
{
|
||||||
|
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
|
||||||
|
DateParseHandling = DateParseHandling.None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,11 +12,13 @@ namespace DataLayer.Configurations
|
|||||||
|
|
||||||
entity.OwnsOne(b => b.Rating);
|
entity.OwnsOne(b => b.Rating);
|
||||||
|
|
||||||
|
entity.Property(nameof(Book._audioFormat));
|
||||||
//
|
//
|
||||||
// CRUCIAL: ignore unmapped collections, even get-only
|
// CRUCIAL: ignore unmapped collections, even get-only
|
||||||
//
|
//
|
||||||
entity.Ignore(nameof(Book.Authors));
|
entity.Ignore(nameof(Book.Authors));
|
||||||
entity.Ignore(nameof(Book.Narrators));
|
entity.Ignore(nameof(Book.Narrators));
|
||||||
|
entity.Ignore(nameof(Book.AudioFormat));
|
||||||
//// these don't seem to matter
|
//// these don't seem to matter
|
||||||
//entity.Ignore(nameof(Book.AuthorNames));
|
//entity.Ignore(nameof(Book.AuthorNames));
|
||||||
//entity.Ignore(nameof(Book.NarratorNames));
|
//entity.Ignore(nameof(Book.NarratorNames));
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ namespace DataLayer.Configurations
|
|||||||
{
|
{
|
||||||
entity.HasKey(c => c.CategoryId);
|
entity.HasKey(c => c.CategoryId);
|
||||||
entity.HasIndex(c => c.AudibleCategoryId);
|
entity.HasIndex(c => c.AudibleCategoryId);
|
||||||
|
|
||||||
|
// seeds go here. examples in Dinah.EntityFrameworkCore.Tests\DbContextFactoryExample.cs
|
||||||
|
entity.HasData(Category.GetEmpty());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -17,6 +17,9 @@ namespace DataLayer.Configurations
|
|||||||
.Metadata
|
.Metadata
|
||||||
.FindNavigation(nameof(Contributor.BooksLink))
|
.FindNavigation(nameof(Contributor.BooksLink))
|
||||||
.SetPropertyAccessMode(PropertyAccessMode.Field);
|
.SetPropertyAccessMode(PropertyAccessMode.Field);
|
||||||
|
|
||||||
|
// seeds go here. examples in Dinah.EntityFrameworkCore.Tests\DbContextFactoryExample.cs
|
||||||
|
entity.HasData(Contributor.GetEmpty());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,35 +1,38 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net6.0-windows</TargetFramework>
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
|
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
|
||||||
<ApplicationIcon />
|
|
||||||
<OutputType>Library</OutputType>
|
<OutputType>Library</OutputType>
|
||||||
<StartupObject />
|
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Dinah.EntityFrameworkCore" Version="4.0.1.1" />
|
<PackageReference Include="Dinah.Core" Version="7.2.0.1" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.5">
|
<PackageReference Include="Dinah.EntityFrameworkCore" Version="7.1.0.1" />
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.1">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.5" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.1" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.5">
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.1">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\LibationFileManager\LibationFileManager.csproj" />
|
<None Update="migrate.json">
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<None Update="appsettings.json">
|
|
||||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
</None>
|
</None>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace DataLayer
|
||||||
|
{
|
||||||
|
internal enum AudioFormatEnum : long
|
||||||
|
{
|
||||||
|
//Defining the enum this way ensures that when comparing:
|
||||||
|
//LC_128_44100_stereo > LC_64_44100_stereo > LC_64_22050_stereo > LC_64_22050_stereo
|
||||||
|
//This matches how audible interprets these codecs when specifying quality using AudibleApi.DownloadQuality
|
||||||
|
//I've never seen mono formats.
|
||||||
|
Unknown = 0,
|
||||||
|
LC_32_22050_stereo = (32L << 18) | (22050 << 2) | 2,
|
||||||
|
LC_64_22050_stereo = (64L << 18) | (22050 << 2) | 2,
|
||||||
|
LC_64_44100_stereo = (64L << 18) | (44100 << 2) | 2,
|
||||||
|
LC_128_44100_stereo = (128L << 18) | (44100 << 2) | 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AudioFormat : IComparable<AudioFormat>, IComparable
|
||||||
|
{
|
||||||
|
internal int AudioFormatID { get; private set; }
|
||||||
|
public int Bitrate { get; private init; }
|
||||||
|
public int SampleRate { get; private init; }
|
||||||
|
public int Channels { get; private init; }
|
||||||
|
public bool IsValid => Bitrate != 0 && SampleRate != 0 && Channels != 0;
|
||||||
|
|
||||||
|
public static AudioFormat FromString(string formatStr)
|
||||||
|
{
|
||||||
|
if (Enum.TryParse(formatStr, ignoreCase: true, out AudioFormatEnum enumVal))
|
||||||
|
return FromEnum(enumVal);
|
||||||
|
return FromEnum(AudioFormatEnum.Unknown);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static AudioFormat FromEnum(AudioFormatEnum enumVal)
|
||||||
|
{
|
||||||
|
var val = (long)enumVal;
|
||||||
|
|
||||||
|
return new()
|
||||||
|
{
|
||||||
|
Bitrate = (int)(val >> 18),
|
||||||
|
SampleRate = (int)(val >> 2) & ushort.MaxValue,
|
||||||
|
Channels = (int)(val & 3)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
internal AudioFormatEnum ToEnum()
|
||||||
|
{
|
||||||
|
var val = (AudioFormatEnum)(((long)Bitrate << 18) | ((long)SampleRate << 2) | (long)Channels);
|
||||||
|
|
||||||
|
return Enum.IsDefined(val) ?
|
||||||
|
val : AudioFormatEnum.Unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString()
|
||||||
|
=> IsValid ?
|
||||||
|
$"{Bitrate} Kbps, {SampleRate / 1000d:F1} kHz, {(Channels == 2 ? "Stereo" : Channels)}" :
|
||||||
|
"Unknown";
|
||||||
|
|
||||||
|
public int CompareTo(AudioFormat other) => ToEnum().CompareTo(other.ToEnum());
|
||||||
|
|
||||||
|
public int CompareTo(object obj) => CompareTo(obj as AudioFormat);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,8 +16,15 @@ namespace DataLayer
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// enum will be easier than bool to extend later
|
// enum will be easier than bool to extend later.
|
||||||
public enum ContentType { Unknown = 0, Product = 1, Episode = 2 }
|
public enum ContentType
|
||||||
|
{
|
||||||
|
Unknown = 0,
|
||||||
|
Product = 1,
|
||||||
|
Episode = 2,
|
||||||
|
Parent = 4,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public class Book
|
public class Book
|
||||||
{
|
{
|
||||||
@@ -32,6 +39,10 @@ namespace DataLayer
|
|||||||
public ContentType ContentType { get; private set; }
|
public ContentType ContentType { get; private set; }
|
||||||
public string Locale { get; private set; }
|
public string Locale { get; private set; }
|
||||||
|
|
||||||
|
internal AudioFormatEnum _audioFormat;
|
||||||
|
|
||||||
|
public AudioFormat AudioFormat { get => AudioFormat.FromEnum(_audioFormat); set => _audioFormat = value.ToEnum(); }
|
||||||
|
|
||||||
// mutable
|
// mutable
|
||||||
public string PictureId { get; set; }
|
public string PictureId { get; set; }
|
||||||
public string PictureLarge { get; set; }
|
public string PictureLarge { get; set; }
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ namespace DataLayer
|
|||||||
public DateTime DateAdded { get; private set; }
|
public DateTime DateAdded { get; private set; }
|
||||||
public string Account { get; private set; }
|
public string Account { get; private set; }
|
||||||
|
|
||||||
|
public bool IsDeleted { get; set; }
|
||||||
|
|
||||||
private LibraryBook() { }
|
private LibraryBook() { }
|
||||||
public LibraryBook(Book book, DateTime dateAdded, string account)
|
public LibraryBook(Book book, DateTime dateAdded, string account)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ namespace DataLayer
|
|||||||
public float StoryRating { get; private set; }
|
public float StoryRating { get; private set; }
|
||||||
|
|
||||||
private Rating() { }
|
private Rating() { }
|
||||||
internal Rating(float overallRating, float performanceRating, float storyRating)
|
public Rating(float overallRating, float performanceRating, float storyRating)
|
||||||
{
|
{
|
||||||
OverallRating = overallRating;
|
OverallRating = overallRating;
|
||||||
PerformanceRating = performanceRating;
|
PerformanceRating = performanceRating;
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using Dinah.Core;
|
using Dinah.Core;
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace DataLayer
|
namespace DataLayer
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -30,10 +30,6 @@ namespace DataLayer
|
|||||||
{
|
{
|
||||||
ArgumentValidator.EnsureNotNull(book, nameof(book));
|
ArgumentValidator.EnsureNotNull(book, nameof(book));
|
||||||
Book = book;
|
Book = book;
|
||||||
|
|
||||||
// import previously saved tags
|
|
||||||
ArgumentValidator.EnsureNotNullOrWhiteSpace(book.AudibleProductId, nameof(book.AudibleProductId));
|
|
||||||
Tags = LibationFileManager.TagsPersistence.GetTags(book.AudibleProductId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#region Tags
|
#region Tags
|
||||||
@@ -150,10 +146,19 @@ namespace DataLayer
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
public void SetPdfStatus(LiberatedStatus? pdfStatus)
|
||||||
|
{
|
||||||
|
// don't change whether pdf is actually available. if null, leave as null. if not null, only assign non-null
|
||||||
|
|
||||||
|
// null => non-null : only when adding a supplement
|
||||||
|
|
||||||
|
if (pdfStatus.HasValue && PdfStatus.HasValue)
|
||||||
|
PdfStatus = pdfStatus;
|
||||||
|
}
|
||||||
public LiberatedStatus? PdfStatus
|
public LiberatedStatus? PdfStatus
|
||||||
{
|
{
|
||||||
get => _pdfStatus;
|
get => _pdfStatus;
|
||||||
set
|
internal set
|
||||||
{
|
{
|
||||||
if (_pdfStatus != value)
|
if (_pdfStatus != value)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
using DataLayer.Configurations;
|
using DataLayer.Configurations;
|
||||||
using Dinah.EntityFrameworkCore;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace DataLayer
|
namespace DataLayer
|
||||||
{
|
{
|
||||||
public class LibationContext : InterceptableDbContext
|
public class LibationContext : DbContext
|
||||||
{
|
{
|
||||||
// IMPORTANT: USING DbSet<>
|
// IMPORTANT: USING DbSet<>
|
||||||
// ========================
|
// ========================
|
||||||
@@ -35,14 +34,6 @@ namespace DataLayer
|
|||||||
// see DesignTimeDbContextFactoryBase for info about ctors and connection strings/OnConfiguring()
|
// see DesignTimeDbContextFactoryBase for info about ctors and connection strings/OnConfiguring()
|
||||||
internal LibationContext(DbContextOptions options) : base(options) { }
|
internal LibationContext(DbContextOptions options) : base(options) { }
|
||||||
|
|
||||||
// called on each instantiation
|
|
||||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
|
||||||
{
|
|
||||||
AddInterceptor(new TagPersistenceInterceptor());
|
|
||||||
|
|
||||||
base.OnConfiguring(optionsBuilder);
|
|
||||||
}
|
|
||||||
|
|
||||||
// typically only called once per execution; NOT once per instantiation
|
// typically only called once per execution; NOT once per instantiation
|
||||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
{
|
{
|
||||||
@@ -56,15 +47,6 @@ namespace DataLayer
|
|||||||
modelBuilder.ApplyConfiguration(new SeriesBookConfig());
|
modelBuilder.ApplyConfiguration(new SeriesBookConfig());
|
||||||
modelBuilder.ApplyConfiguration(new CategoryConfig());
|
modelBuilder.ApplyConfiguration(new CategoryConfig());
|
||||||
|
|
||||||
// seeds go here. examples in Dinah.EntityFrameworkCore.Tests\DbContextFactoryExample.cs
|
|
||||||
|
|
||||||
modelBuilder
|
|
||||||
.Entity<Category>()
|
|
||||||
.HasData(Category.GetEmpty());
|
|
||||||
modelBuilder
|
|
||||||
.Entity<Contributor>()
|
|
||||||
.HasData(Contributor.GetEmpty());
|
|
||||||
|
|
||||||
// views are now supported via "keyless entity types" (instead of "entity types" or the prev "query types"):
|
// views are now supported via "keyless entity types" (instead of "entity types" or the prev "query types"):
|
||||||
// https://docs.microsoft.com/en-us/ef/core/modeling/keyless-entity-types
|
// https://docs.microsoft.com/en-us/ef/core/modeling/keyless-entity-types
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,397 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using DataLayer;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace DataLayer.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(LibationContext))]
|
||||||
|
[Migration("20220624214932_AddAudioFormat")]
|
||||||
|
partial class AddAudioFormat
|
||||||
|
{
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder.HasAnnotation("ProductVersion", "6.0.6");
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Book", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("BookId")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("AudibleProductId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<int>("CategoryId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<int>("ContentType")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<DateTime?>("DatePublished")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<bool>("IsAbridged")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<int>("LengthInMinutes")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Locale")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("PictureId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("PictureLarge")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Title")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<long>("_audioFormat")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.HasKey("BookId");
|
||||||
|
|
||||||
|
b.HasIndex("AudibleProductId");
|
||||||
|
|
||||||
|
b.HasIndex("CategoryId");
|
||||||
|
|
||||||
|
b.ToTable("Books");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.BookContributor", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("BookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<int>("ContributorId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<int>("Role")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<byte>("Order")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.HasKey("BookId", "ContributorId", "Role");
|
||||||
|
|
||||||
|
b.HasIndex("BookId");
|
||||||
|
|
||||||
|
b.HasIndex("ContributorId");
|
||||||
|
|
||||||
|
b.ToTable("BookContributor");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Category", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("CategoryId")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("AudibleCategoryId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<int?>("ParentCategoryCategoryId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.HasKey("CategoryId");
|
||||||
|
|
||||||
|
b.HasIndex("AudibleCategoryId");
|
||||||
|
|
||||||
|
b.HasIndex("ParentCategoryCategoryId");
|
||||||
|
|
||||||
|
b.ToTable("Categories");
|
||||||
|
|
||||||
|
b.HasData(
|
||||||
|
new
|
||||||
|
{
|
||||||
|
CategoryId = -1,
|
||||||
|
AudibleCategoryId = "",
|
||||||
|
Name = ""
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Contributor", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("ContributorId")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("AudibleContributorId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("ContributorId");
|
||||||
|
|
||||||
|
b.HasIndex("Name");
|
||||||
|
|
||||||
|
b.ToTable("Contributors");
|
||||||
|
|
||||||
|
b.HasData(
|
||||||
|
new
|
||||||
|
{
|
||||||
|
ContributorId = -1,
|
||||||
|
Name = ""
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.LibraryBook", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("BookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Account")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime>("DateAdded")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("BookId");
|
||||||
|
|
||||||
|
b.ToTable("LibraryBooks");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Series", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("SeriesId")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("AudibleSeriesId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("SeriesId");
|
||||||
|
|
||||||
|
b.HasIndex("AudibleSeriesId");
|
||||||
|
|
||||||
|
b.ToTable("Series");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.SeriesBook", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("SeriesId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<int>("BookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Order")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("SeriesId", "BookId");
|
||||||
|
|
||||||
|
b.HasIndex("BookId");
|
||||||
|
|
||||||
|
b.HasIndex("SeriesId");
|
||||||
|
|
||||||
|
b.ToTable("SeriesBook");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Book", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("DataLayer.Category", "Category")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("CategoryId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.OwnsOne("DataLayer.Rating", "Rating", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<int>("BookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b1.Property<float>("OverallRating")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b1.Property<float>("PerformanceRating")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b1.Property<float>("StoryRating")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b1.HasKey("BookId");
|
||||||
|
|
||||||
|
b1.ToTable("Books");
|
||||||
|
|
||||||
|
b1.WithOwner()
|
||||||
|
.HasForeignKey("BookId");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.OwnsMany("DataLayer.Supplement", "Supplements", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<int>("SupplementId")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b1.Property<int>("BookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b1.Property<string>("Url")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b1.HasKey("SupplementId");
|
||||||
|
|
||||||
|
b1.HasIndex("BookId");
|
||||||
|
|
||||||
|
b1.ToTable("Supplement");
|
||||||
|
|
||||||
|
b1.WithOwner("Book")
|
||||||
|
.HasForeignKey("BookId");
|
||||||
|
|
||||||
|
b1.Navigation("Book");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.OwnsOne("DataLayer.UserDefinedItem", "UserDefinedItem", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<int>("BookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b1.Property<int>("BookStatus")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b1.Property<int?>("PdfStatus")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b1.Property<string>("Tags")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b1.HasKey("BookId");
|
||||||
|
|
||||||
|
b1.ToTable("UserDefinedItem", (string)null);
|
||||||
|
|
||||||
|
b1.WithOwner("Book")
|
||||||
|
.HasForeignKey("BookId");
|
||||||
|
|
||||||
|
b1.OwnsOne("DataLayer.Rating", "Rating", b2 =>
|
||||||
|
{
|
||||||
|
b2.Property<int>("UserDefinedItemBookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b2.Property<float>("OverallRating")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b2.Property<float>("PerformanceRating")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b2.Property<float>("StoryRating")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b2.HasKey("UserDefinedItemBookId");
|
||||||
|
|
||||||
|
b2.ToTable("UserDefinedItem");
|
||||||
|
|
||||||
|
b2.WithOwner()
|
||||||
|
.HasForeignKey("UserDefinedItemBookId");
|
||||||
|
});
|
||||||
|
|
||||||
|
b1.Navigation("Book");
|
||||||
|
|
||||||
|
b1.Navigation("Rating");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.Navigation("Category");
|
||||||
|
|
||||||
|
b.Navigation("Rating");
|
||||||
|
|
||||||
|
b.Navigation("Supplements");
|
||||||
|
|
||||||
|
b.Navigation("UserDefinedItem");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.BookContributor", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("DataLayer.Book", "Book")
|
||||||
|
.WithMany("ContributorsLink")
|
||||||
|
.HasForeignKey("BookId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("DataLayer.Contributor", "Contributor")
|
||||||
|
.WithMany("BooksLink")
|
||||||
|
.HasForeignKey("ContributorId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Book");
|
||||||
|
|
||||||
|
b.Navigation("Contributor");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Category", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("DataLayer.Category", "ParentCategory")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("ParentCategoryCategoryId");
|
||||||
|
|
||||||
|
b.Navigation("ParentCategory");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.LibraryBook", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("DataLayer.Book", "Book")
|
||||||
|
.WithOne()
|
||||||
|
.HasForeignKey("DataLayer.LibraryBook", "BookId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Book");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.SeriesBook", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("DataLayer.Book", "Book")
|
||||||
|
.WithMany("SeriesLink")
|
||||||
|
.HasForeignKey("BookId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("DataLayer.Series", "Series")
|
||||||
|
.WithMany("BooksLink")
|
||||||
|
.HasForeignKey("SeriesId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Book");
|
||||||
|
|
||||||
|
b.Navigation("Series");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Book", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("ContributorsLink");
|
||||||
|
|
||||||
|
b.Navigation("SeriesLink");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Contributor", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("BooksLink");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Series", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("BooksLink");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace DataLayer.Migrations
|
||||||
|
{
|
||||||
|
public partial class AddAudioFormat : Migration
|
||||||
|
{
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<long>(
|
||||||
|
name: "_audioFormat",
|
||||||
|
table: "Books",
|
||||||
|
type: "INTEGER",
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: 0L);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "_audioFormat",
|
||||||
|
table: "Books");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+401
@@ -0,0 +1,401 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using DataLayer;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace DataLayer.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(LibationContext))]
|
||||||
|
[Migration("20221214205106_LibraryBookIsDeleted")]
|
||||||
|
partial class LibraryBookIsDeleted
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder.HasAnnotation("ProductVersion", "7.0.0");
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Book", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("BookId")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("AudibleProductId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<int>("CategoryId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<int>("ContentType")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<DateTime?>("DatePublished")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<bool>("IsAbridged")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<int>("LengthInMinutes")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Locale")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("PictureId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("PictureLarge")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Title")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<long>("_audioFormat")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.HasKey("BookId");
|
||||||
|
|
||||||
|
b.HasIndex("AudibleProductId");
|
||||||
|
|
||||||
|
b.HasIndex("CategoryId");
|
||||||
|
|
||||||
|
b.ToTable("Books");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.BookContributor", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("BookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<int>("ContributorId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<int>("Role")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<byte>("Order")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.HasKey("BookId", "ContributorId", "Role");
|
||||||
|
|
||||||
|
b.HasIndex("BookId");
|
||||||
|
|
||||||
|
b.HasIndex("ContributorId");
|
||||||
|
|
||||||
|
b.ToTable("BookContributor");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Category", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("CategoryId")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("AudibleCategoryId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<int?>("ParentCategoryCategoryId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.HasKey("CategoryId");
|
||||||
|
|
||||||
|
b.HasIndex("AudibleCategoryId");
|
||||||
|
|
||||||
|
b.HasIndex("ParentCategoryCategoryId");
|
||||||
|
|
||||||
|
b.ToTable("Categories");
|
||||||
|
|
||||||
|
b.HasData(
|
||||||
|
new
|
||||||
|
{
|
||||||
|
CategoryId = -1,
|
||||||
|
AudibleCategoryId = "",
|
||||||
|
Name = ""
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Contributor", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("ContributorId")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("AudibleContributorId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("ContributorId");
|
||||||
|
|
||||||
|
b.HasIndex("Name");
|
||||||
|
|
||||||
|
b.ToTable("Contributors");
|
||||||
|
|
||||||
|
b.HasData(
|
||||||
|
new
|
||||||
|
{
|
||||||
|
ContributorId = -1,
|
||||||
|
Name = ""
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.LibraryBook", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("BookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Account")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime>("DateAdded")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<bool>("IsDeleted")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.HasKey("BookId");
|
||||||
|
|
||||||
|
b.ToTable("LibraryBooks");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Series", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("SeriesId")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("AudibleSeriesId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("SeriesId");
|
||||||
|
|
||||||
|
b.HasIndex("AudibleSeriesId");
|
||||||
|
|
||||||
|
b.ToTable("Series");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.SeriesBook", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("SeriesId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<int>("BookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("Order")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("SeriesId", "BookId");
|
||||||
|
|
||||||
|
b.HasIndex("BookId");
|
||||||
|
|
||||||
|
b.HasIndex("SeriesId");
|
||||||
|
|
||||||
|
b.ToTable("SeriesBook");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Book", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("DataLayer.Category", "Category")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("CategoryId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.OwnsOne("DataLayer.Rating", "Rating", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<int>("BookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b1.Property<float>("OverallRating")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b1.Property<float>("PerformanceRating")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b1.Property<float>("StoryRating")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b1.HasKey("BookId");
|
||||||
|
|
||||||
|
b1.ToTable("Books");
|
||||||
|
|
||||||
|
b1.WithOwner()
|
||||||
|
.HasForeignKey("BookId");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.OwnsMany("DataLayer.Supplement", "Supplements", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<int>("SupplementId")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b1.Property<int>("BookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b1.Property<string>("Url")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b1.HasKey("SupplementId");
|
||||||
|
|
||||||
|
b1.HasIndex("BookId");
|
||||||
|
|
||||||
|
b1.ToTable("Supplement");
|
||||||
|
|
||||||
|
b1.WithOwner("Book")
|
||||||
|
.HasForeignKey("BookId");
|
||||||
|
|
||||||
|
b1.Navigation("Book");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.OwnsOne("DataLayer.UserDefinedItem", "UserDefinedItem", b1 =>
|
||||||
|
{
|
||||||
|
b1.Property<int>("BookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b1.Property<int>("BookStatus")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b1.Property<int?>("PdfStatus")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b1.Property<string>("Tags")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b1.HasKey("BookId");
|
||||||
|
|
||||||
|
b1.ToTable("UserDefinedItem", (string)null);
|
||||||
|
|
||||||
|
b1.WithOwner("Book")
|
||||||
|
.HasForeignKey("BookId");
|
||||||
|
|
||||||
|
b1.OwnsOne("DataLayer.Rating", "Rating", b2 =>
|
||||||
|
{
|
||||||
|
b2.Property<int>("UserDefinedItemBookId")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b2.Property<float>("OverallRating")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b2.Property<float>("PerformanceRating")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b2.Property<float>("StoryRating")
|
||||||
|
.HasColumnType("REAL");
|
||||||
|
|
||||||
|
b2.HasKey("UserDefinedItemBookId");
|
||||||
|
|
||||||
|
b2.ToTable("UserDefinedItem");
|
||||||
|
|
||||||
|
b2.WithOwner()
|
||||||
|
.HasForeignKey("UserDefinedItemBookId");
|
||||||
|
});
|
||||||
|
|
||||||
|
b1.Navigation("Book");
|
||||||
|
|
||||||
|
b1.Navigation("Rating");
|
||||||
|
});
|
||||||
|
|
||||||
|
b.Navigation("Category");
|
||||||
|
|
||||||
|
b.Navigation("Rating");
|
||||||
|
|
||||||
|
b.Navigation("Supplements");
|
||||||
|
|
||||||
|
b.Navigation("UserDefinedItem");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.BookContributor", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("DataLayer.Book", "Book")
|
||||||
|
.WithMany("ContributorsLink")
|
||||||
|
.HasForeignKey("BookId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("DataLayer.Contributor", "Contributor")
|
||||||
|
.WithMany("BooksLink")
|
||||||
|
.HasForeignKey("ContributorId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Book");
|
||||||
|
|
||||||
|
b.Navigation("Contributor");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Category", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("DataLayer.Category", "ParentCategory")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("ParentCategoryCategoryId");
|
||||||
|
|
||||||
|
b.Navigation("ParentCategory");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.LibraryBook", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("DataLayer.Book", "Book")
|
||||||
|
.WithOne()
|
||||||
|
.HasForeignKey("DataLayer.LibraryBook", "BookId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Book");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.SeriesBook", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("DataLayer.Book", "Book")
|
||||||
|
.WithMany("SeriesLink")
|
||||||
|
.HasForeignKey("BookId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("DataLayer.Series", "Series")
|
||||||
|
.WithMany("BooksLink")
|
||||||
|
.HasForeignKey("SeriesId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Book");
|
||||||
|
|
||||||
|
b.Navigation("Series");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Book", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("ContributorsLink");
|
||||||
|
|
||||||
|
b.Navigation("SeriesLink");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Contributor", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("BooksLink");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("DataLayer.Series", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("BooksLink");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace DataLayer.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class LibraryBookIsDeleted : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<bool>(
|
||||||
|
name: "IsDeleted",
|
||||||
|
table: "LibraryBooks",
|
||||||
|
type: "INTEGER",
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "IsDeleted",
|
||||||
|
table: "LibraryBooks");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,7 +15,7 @@ namespace DataLayer.Migrations
|
|||||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||||
{
|
{
|
||||||
#pragma warning disable 612, 618
|
#pragma warning disable 612, 618
|
||||||
modelBuilder.HasAnnotation("ProductVersion", "6.0.4");
|
modelBuilder.HasAnnotation("ProductVersion", "7.0.0");
|
||||||
|
|
||||||
modelBuilder.Entity("DataLayer.Book", b =>
|
modelBuilder.Entity("DataLayer.Book", b =>
|
||||||
{
|
{
|
||||||
@@ -56,6 +56,9 @@ namespace DataLayer.Migrations
|
|||||||
b.Property<string>("Title")
|
b.Property<string>("Title")
|
||||||
.HasColumnType("TEXT");
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<long>("_audioFormat")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
b.HasKey("BookId");
|
b.HasKey("BookId");
|
||||||
|
|
||||||
b.HasIndex("AudibleProductId");
|
b.HasIndex("AudibleProductId");
|
||||||
@@ -157,6 +160,9 @@ namespace DataLayer.Migrations
|
|||||||
b.Property<DateTime>("DateAdded")
|
b.Property<DateTime>("DateAdded")
|
||||||
.HasColumnType("TEXT");
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<bool>("IsDeleted")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
b.HasKey("BookId");
|
b.HasKey("BookId");
|
||||||
|
|
||||||
b.ToTable("LibraryBooks");
|
b.ToTable("LibraryBooks");
|
||||||
|
|||||||
@@ -35,5 +35,17 @@ namespace DataLayer
|
|||||||
.Include(b => b.SeriesLink).ThenInclude(sb => sb.Series)
|
.Include(b => b.SeriesLink).ThenInclude(sb => sb.Series)
|
||||||
.Include(b => b.ContributorsLink).ThenInclude(c => c.Contributor)
|
.Include(b => b.ContributorsLink).ThenInclude(c => c.Contributor)
|
||||||
.Include(b => b.Category).ThenInclude(c => c.ParentCategory);
|
.Include(b => b.Category).ThenInclude(c => c.ParentCategory);
|
||||||
|
|
||||||
|
public static bool IsProduct(this Book book)
|
||||||
|
=> book.ContentType is not ContentType.Episode and not ContentType.Parent;
|
||||||
|
|
||||||
|
public static bool IsEpisodeChild(this Book book)
|
||||||
|
=> book.ContentType is ContentType.Episode;
|
||||||
|
|
||||||
|
public static bool IsEpisodeParent(this Book book)
|
||||||
|
=> book.ContentType is ContentType.Parent;
|
||||||
|
public static bool HasLiberated(this Book book)
|
||||||
|
=> book.UserDefinedItem.BookStatus is LiberatedStatus.Liberated ||
|
||||||
|
book.UserDefinedItem.PdfStatus is not null and LiberatedStatus.Liberated;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15,11 +15,13 @@ namespace DataLayer
|
|||||||
// .GetLibrary()
|
// .GetLibrary()
|
||||||
// .ToList();
|
// .ToList();
|
||||||
|
|
||||||
public static List<LibraryBook> GetLibrary_Flat_NoTracking(this LibationContext context)
|
public static List<LibraryBook> GetLibrary_Flat_NoTracking(this LibationContext context, bool includeParents = false)
|
||||||
=> context
|
=> context
|
||||||
.LibraryBooks
|
.LibraryBooks
|
||||||
.AsNoTrackingWithIdentityResolution()
|
.AsNoTrackingWithIdentityResolution()
|
||||||
.GetLibrary()
|
.GetLibrary()
|
||||||
|
.AsEnumerable()
|
||||||
|
.Where(lb => !lb.Book.IsEpisodeParent() || includeParents)
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
public static LibraryBook GetLibraryBook_Flat_NoTracking(this LibationContext context, string productId)
|
public static LibraryBook GetLibraryBook_Flat_NoTracking(this LibationContext context, string productId)
|
||||||
@@ -35,10 +37,78 @@ namespace DataLayer
|
|||||||
|
|
||||||
/// <summary>This is still IQueryable. YOU MUST CALL ToList() YOURSELF</summary>
|
/// <summary>This is still IQueryable. YOU MUST CALL ToList() YOURSELF</summary>
|
||||||
public static IQueryable<LibraryBook> GetLibrary(this IQueryable<LibraryBook> library)
|
public static IQueryable<LibraryBook> GetLibrary(this IQueryable<LibraryBook> library)
|
||||||
|
=> library
|
||||||
|
.Where(lb => !lb.IsDeleted)
|
||||||
|
.getLibrary();
|
||||||
|
|
||||||
|
public static List<LibraryBook> GetDeletedLibraryBooks(this LibationContext context)
|
||||||
|
=> context
|
||||||
|
.LibraryBooks
|
||||||
|
.AsNoTrackingWithIdentityResolution()
|
||||||
|
.Where(lb => lb.IsDeleted)
|
||||||
|
.getLibrary()
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
/// <summary>This is still IQueryable. YOU MUST CALL ToList() YOURSELF</summary>
|
||||||
|
private static IQueryable<LibraryBook> getLibrary(this IQueryable<LibraryBook> library)
|
||||||
=> library
|
=> library
|
||||||
// owned items are always loaded. eg: book.UserDefinedItem, book.Supplements
|
// owned items are always loaded. eg: book.UserDefinedItem, book.Supplements
|
||||||
.Include(le => le.Book).ThenInclude(b => b.SeriesLink).ThenInclude(sb => sb.Series)
|
.Include(le => le.Book).ThenInclude(b => b.SeriesLink).ThenInclude(sb => sb.Series)
|
||||||
.Include(le => le.Book).ThenInclude(b => b.ContributorsLink).ThenInclude(c => c.Contributor)
|
.Include(le => le.Book).ThenInclude(b => b.ContributorsLink).ThenInclude(c => c.Contributor)
|
||||||
.Include(le => le.Book).ThenInclude(b => b.Category).ThenInclude(c => c.ParentCategory);
|
.Include(le => le.Book).ThenInclude(b => b.Category).ThenInclude(c => c.ParentCategory);
|
||||||
|
|
||||||
|
public static IEnumerable<LibraryBook> ParentedEpisodes(this IEnumerable<LibraryBook> libraryBooks)
|
||||||
|
=> libraryBooks.Where(lb => lb.Book.IsEpisodeParent()).SelectMany(libraryBooks.FindChildren);
|
||||||
|
|
||||||
|
public static IEnumerable<LibraryBook> FindOrphanedEpisodes(this IEnumerable<LibraryBook> libraryBooks)
|
||||||
|
=> libraryBooks
|
||||||
|
.Where(lb => lb.Book.IsEpisodeChild())
|
||||||
|
.ExceptBy(
|
||||||
|
libraryBooks
|
||||||
|
.ParentedEpisodes()
|
||||||
|
.Select(ge => ge.Book.AudibleProductId), ge => ge.Book.AudibleProductId);
|
||||||
|
|
||||||
|
#nullable enable
|
||||||
|
public static LibraryBook? FindSeriesParent(this IEnumerable<LibraryBook> libraryBooks, LibraryBook seriesEpisode)
|
||||||
|
{
|
||||||
|
if (seriesEpisode.Book.SeriesLink is null) return null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//Parent books will always have exactly 1 SeriesBook due to how
|
||||||
|
//they are imported in ApiExtended.getChildEpisodesAsync()
|
||||||
|
return libraryBooks.FirstOrDefault(
|
||||||
|
lb =>
|
||||||
|
lb.Book.IsEpisodeParent() &&
|
||||||
|
seriesEpisode.Book.SeriesLink.Any(
|
||||||
|
s => s.Series.AudibleSeriesId == lb.Book.SeriesLink.Single().Series.AudibleSeriesId));
|
||||||
|
}
|
||||||
|
catch (System.Exception ex)
|
||||||
|
{
|
||||||
|
Serilog.Log.Error(ex, "Query error in {0}", nameof(FindSeriesParent));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
public static IEnumerable<LibraryBook> FindChildren(this IEnumerable<LibraryBook> bookList, LibraryBook parent)
|
||||||
|
=> bookList
|
||||||
|
.Where(
|
||||||
|
lb =>
|
||||||
|
lb.Book.IsEpisodeChild() &&
|
||||||
|
lb.Book.SeriesLink?
|
||||||
|
.Any(
|
||||||
|
s =>
|
||||||
|
s.Series.AudibleSeriesId == parent.Book.AudibleProductId
|
||||||
|
) == true
|
||||||
|
).ToList();
|
||||||
|
|
||||||
|
public static IEnumerable<LibraryBook> UnLiberated(this IEnumerable<LibraryBook> bookList)
|
||||||
|
=> bookList
|
||||||
|
.Where(
|
||||||
|
lb =>
|
||||||
|
lb.Book.UserDefinedItem.BookStatus is LiberatedStatus.NotLiberated or LiberatedStatus.PartialDownload
|
||||||
|
|| lb.Book.UserDefinedItem.PdfStatus is LiberatedStatus.NotLiberated or LiberatedStatus.PartialDownload
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using Dinah.Core.Collections.Generic;
|
|
||||||
using Dinah.EntityFrameworkCore;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace DataLayer
|
|
||||||
{
|
|
||||||
internal class TagPersistenceInterceptor : IDbInterceptor
|
|
||||||
{
|
|
||||||
public void Executed(DbContext context) { }
|
|
||||||
|
|
||||||
public void Executing(DbContext context)
|
|
||||||
{
|
|
||||||
var tagsCollection
|
|
||||||
= context
|
|
||||||
.ChangeTracker
|
|
||||||
.Entries()
|
|
||||||
.Where(e => e.State.In(EntityState.Modified, EntityState.Added))
|
|
||||||
.Select(e => e.Entity as UserDefinedItem)
|
|
||||||
.Where(udi => udi is not null)
|
|
||||||
// do NOT filter out entires with blank tags. blank is the valid way to show the absence of tags
|
|
||||||
.Select(t => (t.Book.AudibleProductId, t.Tags))
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
LibationFileManager.TagsPersistence.Save(tagsCollection);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"ConnectionStrings": {
|
|
||||||
"// this connection string is ONLY used for DataLayer's Migrations. this appsettings.json file is NOT used at all by application; it is overwritten": "",
|
|
||||||
"LibationContext": "Data Source=LibationContext.db;Foreign Keys=False;"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"ConnectionStrings": {
|
||||||
|
"LibationContext": "Data Source=LibationContext.db;Foreign Keys=False;"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -75,7 +75,7 @@ namespace DtoImporterService
|
|||||||
{
|
{
|
||||||
var item = importItem.DtoItem;
|
var item = importItem.DtoItem;
|
||||||
|
|
||||||
var contentType = item.IsEpisodes ? DataLayer.ContentType.Episode : DataLayer.ContentType.Product;
|
var contentType = GetContentType(item);
|
||||||
|
|
||||||
// absence of authors is very rare, but possible
|
// absence of authors is very rare, but possible
|
||||||
if (!item.Authors?.Any() ?? true)
|
if (!item.Authors?.Any() ?? true)
|
||||||
@@ -84,7 +84,8 @@ namespace DtoImporterService
|
|||||||
// nested logic is required so order of names is retained. else, contributors may appear in the order they were inserted into the db
|
// nested logic is required so order of names is retained. else, contributors may appear in the order they were inserted into the db
|
||||||
var authors = item
|
var authors = item
|
||||||
.Authors
|
.Authors
|
||||||
.Select(a => contributorImporter.Cache[a.Name])
|
.DistinctBy(a => a.Name)
|
||||||
|
.Select(a => contributorImporter.Cache[a.Name])
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
var narrators
|
var narrators
|
||||||
@@ -94,14 +95,16 @@ namespace DtoImporterService
|
|||||||
// nested logic is required so order of names is retained. else, contributors may appear in the order they were inserted into the db
|
// nested logic is required so order of names is retained. else, contributors may appear in the order they were inserted into the db
|
||||||
: item
|
: item
|
||||||
.Narrators
|
.Narrators
|
||||||
.Select(n => contributorImporter.Cache[n.Name])
|
.DistinctBy(a => a.Name)
|
||||||
|
.Select(n => contributorImporter.Cache[n.Name])
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
// categories are laid out for a breadcrumb. category is 1st, subcategory is 2nd
|
// categories are laid out for a breadcrumb. category is 1st, subcategory is 2nd
|
||||||
// absence of categories is also possible
|
// absence of categories is also possible
|
||||||
|
|
||||||
// CATEGORY HACK: only use the 1st 2 categories
|
// CATEGORY HACK: only use the 1st 2 categories
|
||||||
// (real impl: var lastCategory = item.Categories.LastOrDefault()?.CategoryId ?? "";)
|
// after we support full arbitrary-depth category trees and multiple categories per book, the real impl will be something like this
|
||||||
|
// var lastCategory = item.Categories.LastOrDefault()?.CategoryId ?? "";
|
||||||
var lastCategory
|
var lastCategory
|
||||||
= item.Categories.Length == 0 ? ""
|
= item.Categories.Length == 0 ? ""
|
||||||
: item.Categories.Length == 1 ? item.Categories[0].CategoryId
|
: item.Categories.Length == 1 ? item.Categories[0].CategoryId
|
||||||
@@ -161,6 +164,9 @@ namespace DtoImporterService
|
|||||||
{
|
{
|
||||||
var item = importItem.DtoItem;
|
var item = importItem.DtoItem;
|
||||||
|
|
||||||
|
var codec = item.AvailableCodecs?.Max(f => AudioFormat.FromString(f.EnhancedCodec)) ?? new AudioFormat();
|
||||||
|
book.AudioFormat = codec;
|
||||||
|
|
||||||
// set/update book-specific info which may have changed
|
// set/update book-specific info which may have changed
|
||||||
if (item.PictureId is not null)
|
if (item.PictureId is not null)
|
||||||
book.PictureId = item.PictureId;
|
book.PictureId = item.PictureId;
|
||||||
@@ -184,5 +190,15 @@ namespace DtoImporterService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static DataLayer.ContentType GetContentType(Item item)
|
||||||
|
{
|
||||||
|
if (item.IsEpisodes)
|
||||||
|
return DataLayer.ContentType.Episode;
|
||||||
|
else if (item.IsSeriesParent)
|
||||||
|
return DataLayer.ContentType.Parent;
|
||||||
|
else
|
||||||
|
return DataLayer.ContentType.Product;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -91,7 +91,7 @@ namespace DtoImporterService
|
|||||||
return hash.Count;
|
return hash.Count;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Contributor addContributor(string name, string id = null)
|
private Contributor addContributor(string name, string id = null)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -108,6 +108,6 @@ namespace DtoImporterService
|
|||||||
Serilog.Log.Logger.Error(ex, "Error adding contributor. {@DebugInfo}", new { name, id });
|
Serilog.Log.Logger.Error(ex, "Error adding contributor. {@DebugInfo}", new { name, id });
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,15 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net6.0-windows</TargetFramework>
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ namespace DtoImporterService
|
|||||||
protected ItemsImporterBase(LibationContext context) : base(context) { }
|
protected ItemsImporterBase(LibationContext context) : base(context) { }
|
||||||
|
|
||||||
protected abstract IValidator Validator { get; }
|
protected abstract IValidator Validator { get; }
|
||||||
public sealed override IEnumerable<Exception> Validate(IEnumerable<ImportItem> importItems)
|
public sealed override IEnumerable<Exception> Validate(IEnumerable<ImportItem> importItems)
|
||||||
=> Validator.Validate(importItems.Select(i => i.DtoItem));
|
=> Validator.Validate(importItems.Select(i => i.DtoItem));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -49,7 +49,7 @@ namespace DtoImporterService
|
|||||||
// just use the first
|
// just use the first
|
||||||
var hash = newItems.ToDictionarySafe(dto => dto.DtoItem.ProductId);
|
var hash = newItems.ToDictionarySafe(dto => dto.DtoItem.ProductId);
|
||||||
foreach (var kvp in hash)
|
foreach (var kvp in hash)
|
||||||
{
|
{
|
||||||
var newItem = kvp.Value;
|
var newItem = kvp.Value;
|
||||||
|
|
||||||
var libraryBook = new LibraryBook(
|
var libraryBook = new LibraryBook(
|
||||||
|
|||||||
@@ -1,16 +1,44 @@
|
|||||||
using System;
|
using LibationFileManager;
|
||||||
|
using NAudio.Lame;
|
||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace FileLiberator
|
namespace FileLiberator
|
||||||
{
|
{
|
||||||
public abstract class AudioDecodable : Processable
|
public abstract class AudioDecodable : Processable
|
||||||
{
|
{
|
||||||
public event EventHandler<Action<byte[]>> RequestCoverArt;
|
public delegate byte[] RequestCoverArtHandler(object sender, EventArgs eventArgs);
|
||||||
|
public event RequestCoverArtHandler RequestCoverArt;
|
||||||
public event EventHandler<string> TitleDiscovered;
|
public event EventHandler<string> TitleDiscovered;
|
||||||
public event EventHandler<string> AuthorsDiscovered;
|
public event EventHandler<string> AuthorsDiscovered;
|
||||||
public event EventHandler<string> NarratorsDiscovered;
|
public event EventHandler<string> NarratorsDiscovered;
|
||||||
public event EventHandler<byte[]> CoverImageDiscovered;
|
public event EventHandler<byte[]> CoverImageDiscovered;
|
||||||
public abstract void Cancel();
|
public abstract Task CancelAsync();
|
||||||
|
|
||||||
|
protected LameConfig GetLameOptions(Configuration config)
|
||||||
|
{
|
||||||
|
LameConfig lameConfig = new();
|
||||||
|
lameConfig.Mode = MPEGMode.Mono;
|
||||||
|
|
||||||
|
if (config.LameTargetBitrate)
|
||||||
|
{
|
||||||
|
if (config.LameConstantBitrate)
|
||||||
|
lameConfig.BitRate = config.LameBitrate;
|
||||||
|
else
|
||||||
|
{
|
||||||
|
lameConfig.ABRRateKbps = config.LameBitrate;
|
||||||
|
lameConfig.VBR = VBRMode.ABR;
|
||||||
|
lameConfig.WriteVBRTag = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
lameConfig.VBR = VBRMode.Default;
|
||||||
|
lameConfig.VBRQuality = config.LameVBRQuality;
|
||||||
|
lameConfig.WriteVBRTag = true;
|
||||||
|
}
|
||||||
|
return lameConfig;
|
||||||
|
}
|
||||||
protected void OnTitleDiscovered(string title) => OnTitleDiscovered(null, title);
|
protected void OnTitleDiscovered(string title) => OnTitleDiscovered(null, title);
|
||||||
protected void OnTitleDiscovered(object _, string title)
|
protected void OnTitleDiscovered(object _, string title)
|
||||||
{
|
{
|
||||||
@@ -32,10 +60,10 @@ namespace FileLiberator
|
|||||||
NarratorsDiscovered?.Invoke(this, narrators);
|
NarratorsDiscovered?.Invoke(this, narrators);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void OnRequestCoverArt(Action<byte[]> setCoverArtDel)
|
protected byte[] OnRequestCoverArt()
|
||||||
{
|
{
|
||||||
Serilog.Log.Logger.Debug("Event fired {@DebugInfo}", new { Name = nameof(RequestCoverArt) });
|
Serilog.Log.Logger.Debug("Event fired {@DebugInfo}", new { Name = nameof(RequestCoverArt) });
|
||||||
RequestCoverArt?.Invoke(this, setCoverArtDel);
|
return RequestCoverArt?.Invoke(this, new());
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void OnCoverImageDiscovered(byte[] coverImage)
|
protected void OnCoverImageDiscovered(byte[] coverImage)
|
||||||
|
|||||||
@@ -1,56 +1,57 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using DataLayer;
|
using DataLayer;
|
||||||
using Dinah.Core;
|
|
||||||
using FileManager;
|
|
||||||
using LibationFileManager;
|
using LibationFileManager;
|
||||||
|
|
||||||
namespace FileLiberator
|
namespace FileLiberator
|
||||||
{
|
{
|
||||||
public static class AudioFileStorageExt
|
public static class AudioFileStorageExt
|
||||||
{
|
{
|
||||||
private class MultipartRenamer
|
/// <summary>
|
||||||
{
|
/// DownloadDecryptBook:
|
||||||
private LibraryBook libraryBook { get; }
|
/// File path for where to move files into.
|
||||||
|
/// Path: directory nested inside of Books directory
|
||||||
|
/// File name: n/a
|
||||||
|
/// </summary>
|
||||||
|
public static string GetDestinationDirectory(this AudioFileStorage _, LibraryBook libraryBook)
|
||||||
|
{
|
||||||
|
if (libraryBook.Book.IsEpisodeChild() && Configuration.Instance.SavePodcastsToParentFolder)
|
||||||
|
{
|
||||||
|
var series = libraryBook.Book.SeriesLink.SingleOrDefault();
|
||||||
|
if (series is not null)
|
||||||
|
{
|
||||||
|
var seriesParent = ApplicationServices.DbContexts.GetContext().GetLibraryBook_Flat_NoTracking(series.Series.AudibleSeriesId);
|
||||||
|
|
||||||
internal MultipartRenamer(LibraryBook libraryBook) => this.libraryBook = libraryBook;
|
if (seriesParent is not null)
|
||||||
|
{
|
||||||
|
var baseDir = Templates.Folder.GetFilename(seriesParent.ToDto());
|
||||||
|
return Templates.Folder.GetFilename(libraryBook.ToDto(), baseDir);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal string MultipartFilename(AaxDecrypter.MultiConvertFileProperties props)
|
return Templates.Folder.GetFilename(libraryBook.ToDto());
|
||||||
=> Templates.ChapterFile.GetFilename(libraryBook.ToDto(), props);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public static Func<AaxDecrypter.MultiConvertFileProperties, string> CreateMultipartRenamerFunc(this AudioFileStorage _, LibraryBook libraryBook)
|
/// <summary>
|
||||||
=> new MultipartRenamer(libraryBook).MultipartFilename;
|
/// DownloadDecryptBook:
|
||||||
|
/// Path: in progress directory.
|
||||||
|
/// File name: final file name.
|
||||||
|
/// </summary>
|
||||||
|
public static string GetInProgressFilename(this AudioFileStorage _, LibraryBook libraryBook, string extension)
|
||||||
|
=> Templates.File.GetFilename(libraryBook.ToDto(), AudibleFileStorage.DecryptInProgressDirectory, extension, returnFirstExisting: true);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// DownloadDecryptBook:
|
/// PDF: audio file does not exist
|
||||||
/// File path for where to move files into.
|
/// </summary>
|
||||||
/// Path: directory nested inside of Books directory
|
public static string GetBooksDirectoryFilename(this AudioFileStorage _, LibraryBook libraryBook, string extension)
|
||||||
/// File name: n/a
|
=> Templates.File.GetFilename(libraryBook.ToDto(), AudibleFileStorage.BooksDirectory, extension);
|
||||||
/// </summary>
|
|
||||||
public static string GetDestinationDirectory(this AudioFileStorage _, LibraryBook libraryBook)
|
|
||||||
=> Templates.Folder.GetFilename(libraryBook.ToDto());
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// DownloadDecryptBook:
|
/// PDF: audio file already exists
|
||||||
/// Path: in progress directory.
|
/// </summary>
|
||||||
/// File name: final file name.
|
public static string GetCustomDirFilename(this AudioFileStorage _, LibraryBook libraryBook, string dirFullPath, string extension)
|
||||||
/// </summary>
|
=> Templates.File.GetFilename(libraryBook.ToDto(), dirFullPath, extension);
|
||||||
public static string GetInProgressFilename(this AudioFileStorage _, LibraryBook libraryBook, string extension)
|
}
|
||||||
=> Templates.File.GetFilename(libraryBook.ToDto(), AudibleFileStorage.DecryptInProgressDirectory, extension, returnFirstExisting: true);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// PDF: audio file does not exist
|
|
||||||
/// </summary>
|
|
||||||
public static string GetBooksDirectoryFilename(this AudioFileStorage _, LibraryBook libraryBook, string extension)
|
|
||||||
=> Templates.File.GetFilename(libraryBook.ToDto(), AudibleFileStorage.BooksDirectory, extension);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// PDF: audio file already exists
|
|
||||||
/// </summary>
|
|
||||||
public static string GetCustomDirFilename(this AudioFileStorage _, LibraryBook libraryBook, string dirFullPath, string extension)
|
|
||||||
=> Templates.File.GetFilename(libraryBook.ToDto(), dirFullPath, extension);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using AAXClean;
|
using AAXClean;
|
||||||
using AAXClean.Codecs;
|
using AAXClean.Codecs;
|
||||||
using DataLayer;
|
using DataLayer;
|
||||||
using Dinah.Core;
|
|
||||||
using Dinah.Core.ErrorHandling;
|
using Dinah.Core.ErrorHandling;
|
||||||
using Dinah.Core.Net.Http;
|
using Dinah.Core.Net.Http;
|
||||||
using FileManager;
|
using FileManager;
|
||||||
@@ -12,82 +12,102 @@ using LibationFileManager;
|
|||||||
|
|
||||||
namespace FileLiberator
|
namespace FileLiberator
|
||||||
{
|
{
|
||||||
public class ConvertToMp3 : AudioDecodable
|
public class ConvertToMp3 : AudioDecodable
|
||||||
{
|
{
|
||||||
private Mp4File m4bBook;
|
public override string Name => "Convert to Mp3";
|
||||||
|
private Mp4File m4bBook;
|
||||||
|
|
||||||
private long fileSize;
|
private long fileSize;
|
||||||
private static string Mp3FileName(string m4bPath) => Path.ChangeExtension(m4bPath ?? "", ".mp3");
|
private static string Mp3FileName(string m4bPath) => Path.ChangeExtension(m4bPath ?? "", ".mp3");
|
||||||
|
|
||||||
public override void Cancel() => m4bBook?.Cancel();
|
public override Task CancelAsync() => m4bBook?.CancelAsync() ?? Task.CompletedTask;
|
||||||
|
|
||||||
public override bool Validate(LibraryBook libraryBook)
|
public static bool ValidateMp3(LibraryBook libraryBook)
|
||||||
{
|
{
|
||||||
var path = AudibleFileStorage.Audio.GetPath(libraryBook.Book.AudibleProductId);
|
var paths = AudibleFileStorage.Audio.GetPaths(libraryBook.Book.AudibleProductId);
|
||||||
return path?.ToLower()?.EndsWith(".m4b") == true && !File.Exists(Mp3FileName(path));
|
return paths.Any(path => path?.ToString()?.ToLower()?.EndsWith(".m4b") == true && !File.Exists(Mp3FileName(path)));
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task<StatusHandler> ProcessAsync(LibraryBook libraryBook)
|
public override bool Validate(LibraryBook libraryBook) => ValidateMp3(libraryBook);
|
||||||
{
|
|
||||||
OnBegin(libraryBook);
|
|
||||||
|
|
||||||
OnStreamingBegin($"Begin converting {libraryBook} to mp3");
|
public override async Task<StatusHandler> ProcessAsync(LibraryBook libraryBook)
|
||||||
|
{
|
||||||
|
OnBegin(libraryBook);
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var m4bPath = AudibleFileStorage.Audio.GetPath(libraryBook.Book.AudibleProductId);
|
var m4bPaths = AudibleFileStorage.Audio.GetPaths(libraryBook.Book.AudibleProductId);
|
||||||
m4bBook = new Mp4File(m4bPath, FileAccess.Read);
|
|
||||||
m4bBook.ConversionProgressUpdate += M4bBook_ConversionProgressUpdate;
|
|
||||||
|
|
||||||
fileSize = m4bBook.InputStream.Length;
|
foreach (var m4bPath in m4bPaths)
|
||||||
|
{
|
||||||
|
var proposedMp3Path = Mp3FileName(m4bPath);
|
||||||
|
if (File.Exists(proposedMp3Path) || !File.Exists(m4bPath)) continue;
|
||||||
|
|
||||||
OnTitleDiscovered(m4bBook.AppleTags.Title);
|
m4bBook = await Task.Run(() => new Mp4File(m4bPath, FileAccess.Read));
|
||||||
OnAuthorsDiscovered(m4bBook.AppleTags.FirstAuthor);
|
m4bBook.ConversionProgressUpdate += M4bBook_ConversionProgressUpdate;
|
||||||
OnNarratorsDiscovered(m4bBook.AppleTags.Narrator);
|
|
||||||
OnCoverImageDiscovered(m4bBook.AppleTags.Cover);
|
|
||||||
|
|
||||||
using var mp3File = File.OpenWrite(Path.GetTempFileName());
|
fileSize = m4bBook.InputStream.Length;
|
||||||
|
|
||||||
var result = await Task.Run(() => m4bBook.ConvertToMp3(mp3File));
|
OnTitleDiscovered(m4bBook.AppleTags.Title);
|
||||||
m4bBook.InputStream.Close();
|
OnAuthorsDiscovered(m4bBook.AppleTags.FirstAuthor);
|
||||||
mp3File.Close();
|
OnNarratorsDiscovered(m4bBook.AppleTags.Narrator);
|
||||||
|
OnCoverImageDiscovered(m4bBook.AppleTags.Cover);
|
||||||
|
|
||||||
var proposedMp3Path = Mp3FileName(m4bPath);
|
var config = Configuration.Instance;
|
||||||
var realMp3Path = FileUtility.SaferMoveToValidPath(mp3File.Name, proposedMp3Path);
|
var lameConfig = GetLameOptions(config);
|
||||||
OnFileCreated(libraryBook, realMp3Path);
|
|
||||||
|
|
||||||
var statusHandler = new StatusHandler();
|
//Finishing configuring lame encoder.
|
||||||
|
AaxDecrypter.MpegUtil.ConfigureLameOptions(
|
||||||
|
m4bBook,
|
||||||
|
lameConfig,
|
||||||
|
config.LameDownsampleMono,
|
||||||
|
config.LameMatchSourceBR);
|
||||||
|
|
||||||
if (result == ConversionResult.Failed)
|
using var mp3File = File.OpenWrite(Path.GetTempFileName());
|
||||||
statusHandler.AddError("Conversion failed");
|
var result = await m4bBook.ConvertToMp3Async(mp3File, lameConfig);
|
||||||
|
m4bBook.InputStream.Close();
|
||||||
|
mp3File.Close();
|
||||||
|
|
||||||
return statusHandler;
|
if (result == ConversionResult.Failed)
|
||||||
}
|
{
|
||||||
finally
|
FileUtility.SaferDelete(mp3File.Name);
|
||||||
{
|
return new StatusHandler { "Conversion failed" };
|
||||||
OnStreamingCompleted($"Completed converting to mp3: {libraryBook.Book.Title}");
|
}
|
||||||
OnCompleted(libraryBook);
|
else if (result == ConversionResult.Cancelled)
|
||||||
}
|
{
|
||||||
}
|
FileUtility.SaferDelete(mp3File.Name);
|
||||||
|
return new StatusHandler { "Cancelled" };
|
||||||
|
}
|
||||||
|
|
||||||
private void M4bBook_ConversionProgressUpdate(object sender, ConversionProgressEventArgs e)
|
var realMp3Path = FileUtility.SaferMoveToValidPath(mp3File.Name, proposedMp3Path, Configuration.Instance.ReplacementCharacters);
|
||||||
{
|
OnFileCreated(libraryBook, realMp3Path);
|
||||||
var duration = m4bBook.Duration;
|
}
|
||||||
var remainingSecsToProcess = (duration - e.ProcessPosition).TotalSeconds;
|
return new StatusHandler();
|
||||||
var estTimeRemaining = remainingSecsToProcess / e.ProcessSpeed;
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
OnCompleted(libraryBook);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (double.IsNormal(estTimeRemaining))
|
private void M4bBook_ConversionProgressUpdate(object sender, ConversionProgressEventArgs e)
|
||||||
OnStreamingTimeRemaining(TimeSpan.FromSeconds(estTimeRemaining));
|
{
|
||||||
|
var duration = m4bBook.Duration;
|
||||||
|
var remainingSecsToProcess = (duration - e.ProcessPosition).TotalSeconds;
|
||||||
|
var estTimeRemaining = remainingSecsToProcess / e.ProcessSpeed;
|
||||||
|
|
||||||
double progressPercent = 100 * e.ProcessPosition.TotalSeconds / duration.TotalSeconds;
|
if (double.IsNormal(estTimeRemaining))
|
||||||
|
OnStreamingTimeRemaining(TimeSpan.FromSeconds(estTimeRemaining));
|
||||||
|
|
||||||
OnStreamingProgressChanged(
|
double progressPercent = 100 * e.ProcessPosition.TotalSeconds / duration.TotalSeconds;
|
||||||
new DownloadProgress
|
|
||||||
{
|
OnStreamingProgressChanged(
|
||||||
ProgressPercentage = progressPercent,
|
new DownloadProgress
|
||||||
BytesReceived = (long)(fileSize * progressPercent),
|
{
|
||||||
TotalBytesToReceive = fileSize
|
ProgressPercentage = progressPercent,
|
||||||
});
|
BytesReceived = (long)(fileSize * progressPercent),
|
||||||
}
|
TotalBytesToReceive = fileSize
|
||||||
}
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,7 @@ using System.IO;
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using AaxDecrypter;
|
using AaxDecrypter;
|
||||||
|
using ApplicationServices;
|
||||||
using AudibleApi;
|
using AudibleApi;
|
||||||
using DataLayer;
|
using DataLayer;
|
||||||
using Dinah.Core;
|
using Dinah.Core;
|
||||||
@@ -15,11 +16,12 @@ namespace FileLiberator
|
|||||||
{
|
{
|
||||||
public class DownloadDecryptBook : AudioDecodable
|
public class DownloadDecryptBook : AudioDecodable
|
||||||
{
|
{
|
||||||
|
public override string Name => "Download & Decrypt";
|
||||||
private AudiobookDownloadBase abDownloader;
|
private AudiobookDownloadBase abDownloader;
|
||||||
|
|
||||||
public override bool Validate(LibraryBook libraryBook) => !libraryBook.Book.Audio_Exists();
|
public override bool Validate(LibraryBook libraryBook) => !libraryBook.Book.Audio_Exists();
|
||||||
|
|
||||||
public override void Cancel() => abDownloader?.Cancel();
|
public override Task CancelAsync() => abDownloader?.CancelAsync() ?? Task.CompletedTask;
|
||||||
|
|
||||||
public override async Task<StatusHandler> ProcessAsync(LibraryBook libraryBook)
|
public override async Task<StatusHandler> ProcessAsync(LibraryBook libraryBook)
|
||||||
{
|
{
|
||||||
@@ -65,21 +67,26 @@ namespace FileLiberator
|
|||||||
foreach (var tmpFile in entries.Where(f => f.FileType != FileType.AAXC))
|
foreach (var tmpFile in entries.Where(f => f.FileType != FileType.AAXC))
|
||||||
FileUtility.SaferDelete(tmpFile.Path);
|
FileUtility.SaferDelete(tmpFile.Path);
|
||||||
|
|
||||||
return new StatusHandler { "Decrypt failed" };
|
return abDownloader?.IsCanceled == true ?
|
||||||
|
new StatusHandler { "Cancelled" } :
|
||||||
|
new StatusHandler { "Decrypt failed" };
|
||||||
}
|
}
|
||||||
|
|
||||||
// moves new files from temp dir to final dest
|
// moves new files from temp dir to final dest.
|
||||||
var movedAudioFile = moveFilesToBooksDir(libraryBook, entries);
|
// This could take a few seconds if moving hundreds of files.
|
||||||
|
var finalStorageDir = await Task.Run(() => moveFilesToBooksDir(libraryBook, entries));
|
||||||
|
|
||||||
// decrypt failed
|
// decrypt failed
|
||||||
if (!movedAudioFile)
|
if (finalStorageDir is null)
|
||||||
return new StatusHandler { "Cannot find final audio file after decryption" };
|
return new StatusHandler { "Cannot find final audio file after decryption" };
|
||||||
|
|
||||||
if (Configuration.Instance.DownloadCoverArt)
|
if (Configuration.Instance.DownloadCoverArt)
|
||||||
DownloadCoverArt(libraryBook);
|
downloadCoverArt(libraryBook);
|
||||||
|
|
||||||
libraryBook.Book.UserDefinedItem.BookStatus = LiberatedStatus.Liberated;
|
// contains logic to check for config setting and OS
|
||||||
ApplicationServices.LibraryCommands.UpdateUserDefinedItem(libraryBook.Book);
|
WindowsDirectory.SetCoverAsFolderIcon(pictureId: libraryBook.Book.PictureId, directory: finalStorageDir);
|
||||||
|
|
||||||
|
libraryBook.Book.UpdateBookStatus(LiberatedStatus.Liberated);
|
||||||
|
|
||||||
return new StatusHandler();
|
return new StatusHandler();
|
||||||
}
|
}
|
||||||
@@ -91,57 +98,45 @@ namespace FileLiberator
|
|||||||
|
|
||||||
private async Task<bool> downloadAudiobookAsync(LibraryBook libraryBook)
|
private async Task<bool> downloadAudiobookAsync(LibraryBook libraryBook)
|
||||||
{
|
{
|
||||||
OnStreamingBegin($"Begin decrypting {libraryBook}");
|
var config = Configuration.Instance;
|
||||||
|
|
||||||
try
|
downloadValidation(libraryBook);
|
||||||
|
|
||||||
|
var api = await libraryBook.GetApiAsync();
|
||||||
|
var contentLic = await api.GetDownloadLicenseAsync(libraryBook.Book.AudibleProductId);
|
||||||
|
using var dlOptions = BuildDownloadOptions(libraryBook, config, contentLic);
|
||||||
|
|
||||||
|
var outFileName = AudibleFileStorage.Audio.GetInProgressFilename(libraryBook, dlOptions.OutputFormat.ToString().ToLower());
|
||||||
|
var cacheDir = AudibleFileStorage.DownloadsInProgressDirectory;
|
||||||
|
|
||||||
|
if (contentLic.DrmType != AudibleApi.Common.DrmType.Adrm)
|
||||||
|
abDownloader = new UnencryptedAudiobookDownloader(outFileName, cacheDir, dlOptions);
|
||||||
|
else
|
||||||
{
|
{
|
||||||
var config = Configuration.Instance;
|
AaxcDownloadConvertBase converter
|
||||||
|
= config.SplitFilesByChapter ?
|
||||||
|
new AaxcDownloadMultiConverter(outFileName, cacheDir, dlOptions) :
|
||||||
|
new AaxcDownloadSingleConverter(outFileName, cacheDir, dlOptions);
|
||||||
|
|
||||||
downloadValidation(libraryBook);
|
if (config.AllowLibationFixup)
|
||||||
|
converter.RetrievedMetadata += (_, tags) => tags.Generes = string.Join(", ", libraryBook.Book.CategoriesNames());
|
||||||
|
|
||||||
var api = await libraryBook.GetApiAsync();
|
abDownloader = converter;
|
||||||
var contentLic = await api.GetDownloadLicenseAsync(libraryBook.Book.AudibleProductId);
|
|
||||||
var audiobookDlLic = BuildDownloadOptions(config, contentLic);
|
|
||||||
|
|
||||||
var outFileName = AudibleFileStorage.Audio.GetInProgressFilename(libraryBook, audiobookDlLic.OutputFormat.ToString().ToLower());
|
|
||||||
var cacheDir = AudibleFileStorage.DownloadsInProgressDirectory;
|
|
||||||
|
|
||||||
if (contentLic.DrmType != AudibleApi.Common.DrmType.Adrm)
|
|
||||||
abDownloader = new UnencryptedAudiobookDownloader(outFileName, cacheDir, audiobookDlLic);
|
|
||||||
else
|
|
||||||
{
|
|
||||||
AaxcDownloadConvertBase converter
|
|
||||||
= config.SplitFilesByChapter ? new AaxcDownloadMultiConverter(
|
|
||||||
outFileName, cacheDir, audiobookDlLic,
|
|
||||||
AudibleFileStorage.Audio.CreateMultipartRenamerFunc(libraryBook))
|
|
||||||
: new AaxcDownloadSingleConverter(outFileName, cacheDir, audiobookDlLic);
|
|
||||||
|
|
||||||
if (config.AllowLibationFixup)
|
|
||||||
converter.RetrievedMetadata += (_, tags) => tags.Generes = string.Join(", ", libraryBook.Book.CategoriesNames());
|
|
||||||
|
|
||||||
abDownloader = converter;
|
|
||||||
}
|
|
||||||
|
|
||||||
abDownloader.DecryptProgressUpdate += OnStreamingProgressChanged;
|
|
||||||
abDownloader.DecryptTimeRemaining += OnStreamingTimeRemaining;
|
|
||||||
abDownloader.RetrievedTitle += OnTitleDiscovered;
|
|
||||||
abDownloader.RetrievedAuthors += OnAuthorsDiscovered;
|
|
||||||
abDownloader.RetrievedNarrators += OnNarratorsDiscovered;
|
|
||||||
abDownloader.RetrievedCoverArt += AaxcDownloader_RetrievedCoverArt;
|
|
||||||
abDownloader.FileCreated += (_, path) => OnFileCreated(libraryBook, path);
|
|
||||||
|
|
||||||
// REAL WORK DONE HERE
|
|
||||||
var success = await Task.Run(abDownloader.Run);
|
|
||||||
|
|
||||||
return success;
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
OnStreamingCompleted($"Completed downloading and decrypting {libraryBook.Book.Title}");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
abDownloader.DecryptProgressUpdate += OnStreamingProgressChanged;
|
||||||
|
abDownloader.DecryptTimeRemaining += OnStreamingTimeRemaining;
|
||||||
|
abDownloader.RetrievedTitle += OnTitleDiscovered;
|
||||||
|
abDownloader.RetrievedAuthors += OnAuthorsDiscovered;
|
||||||
|
abDownloader.RetrievedNarrators += OnNarratorsDiscovered;
|
||||||
|
abDownloader.RetrievedCoverArt += AaxcDownloader_RetrievedCoverArt;
|
||||||
|
abDownloader.FileCreated += (_, path) => OnFileCreated(libraryBook, path);
|
||||||
|
|
||||||
|
// REAL WORK DONE HERE
|
||||||
|
return await abDownloader.RunAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static DownloadOptions BuildDownloadOptions(Configuration config, AudibleApi.Common.ContentLicense contentLic)
|
private DownloadOptions BuildDownloadOptions(LibraryBook libraryBook, Configuration config, AudibleApi.Common.ContentLicense contentLic)
|
||||||
{
|
{
|
||||||
//I assume if ContentFormat == "MPEG" that the delivered file is an unencrypted mp3.
|
//I assume if ContentFormat == "MPEG" that the delivered file is an unencrypted mp3.
|
||||||
//I also assume that if DrmType != Adrm, the file will be an mp3.
|
//I also assume that if DrmType != Adrm, the file will be an mp3.
|
||||||
@@ -152,10 +147,14 @@ namespace FileLiberator
|
|||||||
var outputFormat = !encrypted || (config.AllowLibationFixup && config.DecryptToLossy) ?
|
var outputFormat = !encrypted || (config.AllowLibationFixup && config.DecryptToLossy) ?
|
||||||
OutputFormat.Mp3 : OutputFormat.M4b;
|
OutputFormat.Mp3 : OutputFormat.M4b;
|
||||||
|
|
||||||
var audiobookDlLic = new DownloadOptions
|
long chapterStartMs = config.StripAudibleBrandAudio ?
|
||||||
|
contentLic.ContentMetadata.ChapterInfo.BrandIntroDurationMs : 0;
|
||||||
|
|
||||||
|
var dlOptions = new DownloadOptions
|
||||||
(
|
(
|
||||||
contentLic?.ContentMetadata?.ContentUrl?.OfflineUrl,
|
libraryBook,
|
||||||
Resources.USER_AGENT
|
contentLic?.ContentMetadata?.ContentUrl?.OfflineUrl,
|
||||||
|
Resources.USER_AGENT
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
AudibleKey = contentLic?.Voucher?.Key,
|
AudibleKey = contentLic?.Voucher?.Key,
|
||||||
@@ -166,54 +165,156 @@ namespace FileLiberator
|
|||||||
StripUnabridged = config.AllowLibationFixup && config.StripUnabridged,
|
StripUnabridged = config.AllowLibationFixup && config.StripUnabridged,
|
||||||
Downsample = config.AllowLibationFixup && config.LameDownsampleMono,
|
Downsample = config.AllowLibationFixup && config.LameDownsampleMono,
|
||||||
MatchSourceBitrate = config.AllowLibationFixup && config.LameMatchSourceBR && config.LameTargetBitrate,
|
MatchSourceBitrate = config.AllowLibationFixup && config.LameMatchSourceBR && config.LameTargetBitrate,
|
||||||
CreateCueSheet = config.CreateCueSheet
|
CreateCueSheet = config.CreateCueSheet,
|
||||||
|
DownloadClipsBookmarks = config.DownloadClipsBookmarks,
|
||||||
|
DownloadSpeedBps = config.DownloadSpeedLimit,
|
||||||
|
LameConfig = GetLameOptions(config),
|
||||||
|
ChapterInfo = new AAXClean.ChapterInfo(TimeSpan.FromMilliseconds(chapterStartMs)),
|
||||||
|
FixupFile = config.AllowLibationFixup
|
||||||
};
|
};
|
||||||
|
|
||||||
if (config.AllowLibationFixup || outputFormat == OutputFormat.Mp3)
|
var chapters = flattenChapters(contentLic.ContentMetadata.ChapterInfo.Chapters).OrderBy(c => c.StartOffsetMs).ToList();
|
||||||
|
|
||||||
|
if (config.MergeOpeningAndEndCredits)
|
||||||
|
combineCredits(chapters);
|
||||||
|
|
||||||
|
for (int i = 0; i < chapters.Count; i++)
|
||||||
{
|
{
|
||||||
|
var chapter = chapters[i];
|
||||||
|
long chapLenMs = chapter.LengthMs;
|
||||||
|
|
||||||
long startMs = audiobookDlLic.TrimOutputToChapterLength ?
|
if (i == 0)
|
||||||
contentLic.ContentMetadata.ChapterInfo.BrandIntroDurationMs : 0;
|
chapLenMs -= chapterStartMs;
|
||||||
|
|
||||||
audiobookDlLic.ChapterInfo = new AAXClean.ChapterInfo(TimeSpan.FromMilliseconds(startMs));
|
if (config.StripAudibleBrandAudio && i == chapters.Count - 1)
|
||||||
|
chapLenMs -= contentLic.ContentMetadata.ChapterInfo.BrandOutroDurationMs;
|
||||||
|
|
||||||
for (int i = 0; i < contentLic.ContentMetadata.ChapterInfo.Chapters.Length; i++)
|
dlOptions.ChapterInfo.AddChapter(chapter.Title, TimeSpan.FromMilliseconds(chapLenMs));
|
||||||
{
|
|
||||||
var chapter = contentLic.ContentMetadata.ChapterInfo.Chapters[i];
|
|
||||||
long chapLenMs = chapter.LengthMs;
|
|
||||||
|
|
||||||
if (i == 0)
|
|
||||||
chapLenMs -= startMs;
|
|
||||||
|
|
||||||
if (config.StripAudibleBrandAudio && i == contentLic.ContentMetadata.ChapterInfo.Chapters.Length - 1)
|
|
||||||
chapLenMs -= contentLic.ContentMetadata.ChapterInfo.BrandOutroDurationMs;
|
|
||||||
|
|
||||||
audiobookDlLic.ChapterInfo.AddChapter(chapter.Title, TimeSpan.FromMilliseconds(chapLenMs));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
audiobookDlLic.LameConfig = new();
|
return dlOptions;
|
||||||
audiobookDlLic.LameConfig.Mode = NAudio.Lame.MPEGMode.Mono;
|
}
|
||||||
|
|
||||||
if (config.LameTargetBitrate)
|
/*
|
||||||
{
|
|
||||||
if (config.LameConstantBitrate)
|
Flatten Audible's new hierarchical chapters, combining children into parents.
|
||||||
audiobookDlLic.LameConfig.BitRate = config.LameBitrate;
|
|
||||||
|
Audible may deliver chapters like this:
|
||||||
|
|
||||||
|
00:00 - 00:10 Opening Credits
|
||||||
|
00:10 - 00:12 Book 1
|
||||||
|
00:12 - 00:14 | Part 1
|
||||||
|
00:14 - 01:40 | | Chapter 1
|
||||||
|
01:40 - 03:20 | | Chapter 2
|
||||||
|
03:20 - 03:22 | Part 2
|
||||||
|
03:22 - 05:00 | | Chapter 3
|
||||||
|
05:00 - 06:40 | | Chapter 4
|
||||||
|
06:40 - 06:42 Book 2
|
||||||
|
06:42 - 06:44 | Part 3
|
||||||
|
06:44 - 08:20 | | Chapter 5
|
||||||
|
08:20 - 10:00 | | Chapter 6
|
||||||
|
10:00 - 10:02 | Part 4
|
||||||
|
10:02 - 11:40 | | Chapter 7
|
||||||
|
11:40 - 13:20 | | Chapter 8
|
||||||
|
13:20 - 13:30 End Credits
|
||||||
|
|
||||||
|
And flattenChapters will combine them into this:
|
||||||
|
|
||||||
|
00:00 - 00:10 Opening Credits
|
||||||
|
00:10 - 01:40 Book 1: Part 1: Chapter 1
|
||||||
|
01:40 - 03:20 Book 1: Part 1: Chapter 2
|
||||||
|
03:20 - 05:00 Book 1: Part 2: Chapter 3
|
||||||
|
05:00 - 06:40 Book 1: Part 2: Chapter 4
|
||||||
|
06:40 - 08:20 Book 2: Part 3: Chapter 5
|
||||||
|
08:20 - 10:00 Book 2: Part 3: Chapter 6
|
||||||
|
10:00 - 11:40 Book 2: Part 4: Chapter 7
|
||||||
|
11:40 - 13:20 Book 2: Part 4: Chapter 8
|
||||||
|
13:20 - 13:40 End Credits
|
||||||
|
|
||||||
|
However, if one of the parent chapters is longer than 10000 milliseconds, it's kept as its own
|
||||||
|
chapter. A duration longer than a few seconds implies that the chapter contains more than just
|
||||||
|
the narrator saying the chapter title, so it should probably be preserved as a separate chapter.
|
||||||
|
Using the example above, if "Book 1" was 15 seconds long and "Part 3" was 20 seconds long:
|
||||||
|
|
||||||
|
00:00 - 00:10 Opening Credits
|
||||||
|
00:10 - 00:25 Book 1
|
||||||
|
00:25 - 00:27 | Part 1
|
||||||
|
00:27 - 01:40 | | Chapter 1
|
||||||
|
01:40 - 03:20 | | Chapter 2
|
||||||
|
03:20 - 03:22 | Part 2
|
||||||
|
03:22 - 05:00 | | Chapter 3
|
||||||
|
05:00 - 06:40 | | Chapter 4
|
||||||
|
06:40 - 06:42 Book 2
|
||||||
|
06:42 - 07:02 | Part 3
|
||||||
|
07:02 - 08:20 | | Chapter 5
|
||||||
|
08:20 - 10:00 | | Chapter 6
|
||||||
|
10:00 - 10:02 | Part 4
|
||||||
|
10:02 - 11:40 | | Chapter 7
|
||||||
|
11:40 - 13:20 | | Chapter 8
|
||||||
|
13:20 - 13:30 End Credits
|
||||||
|
|
||||||
|
then flattenChapters will combine them into this:
|
||||||
|
|
||||||
|
00:00 - 00:10 Opening Credits
|
||||||
|
00:10 - 00:25 Book 1
|
||||||
|
00:25 - 01:40 Book 1: Part 1: Chapter 1
|
||||||
|
01:40 - 03:20 Book 1: Part 1: Chapter 2
|
||||||
|
03:20 - 05:00 Book 1: Part 2: Chapter 3
|
||||||
|
05:00 - 06:40 Book 1: Part 2: Chapter 4
|
||||||
|
06:40 - 07:02 Book 2: Part 3
|
||||||
|
07:02 - 08:20 Book 2: Part 3: Chapter 5
|
||||||
|
08:20 - 10:00 Book 2: Part 3: Chapter 6
|
||||||
|
10:00 - 11:40 Book 2: Part 4: Chapter 7
|
||||||
|
11:40 - 13:20 Book 2: Part 4: Chapter 8
|
||||||
|
13:20 - 13:40 End Credits
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
public static List<AudibleApi.Common.Chapter> flattenChapters(IList<AudibleApi.Common.Chapter> chapters, string titleConcat = ": ")
|
||||||
|
{
|
||||||
|
List<AudibleApi.Common.Chapter> chaps = new();
|
||||||
|
|
||||||
|
foreach (var c in chapters)
|
||||||
|
{
|
||||||
|
if (c.Chapters is not null)
|
||||||
|
{
|
||||||
|
if (c.LengthMs < 10000)
|
||||||
|
{
|
||||||
|
c.Chapters[0].StartOffsetMs = c.StartOffsetMs;
|
||||||
|
c.Chapters[0].StartOffsetSec = c.StartOffsetSec;
|
||||||
|
c.Chapters[0].LengthMs += c.LengthMs;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
chaps.Add(c);
|
||||||
|
|
||||||
|
var children = flattenChapters(c.Chapters);
|
||||||
|
|
||||||
|
foreach (var child in children)
|
||||||
|
child.Title = $"{c.Title}{titleConcat}{child.Title}";
|
||||||
|
|
||||||
|
chaps.AddRange(children);
|
||||||
|
c.Chapters = null;
|
||||||
|
}
|
||||||
else
|
else
|
||||||
{
|
chaps.Add(c);
|
||||||
audiobookDlLic.LameConfig.ABRRateKbps = config.LameBitrate;
|
|
||||||
audiobookDlLic.LameConfig.VBR = NAudio.Lame.VBRMode.ABR;
|
|
||||||
audiobookDlLic.LameConfig.WriteVBRTag = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
audiobookDlLic.LameConfig.VBR = NAudio.Lame.VBRMode.Default;
|
|
||||||
audiobookDlLic.LameConfig.VBRQuality = config.LameVBRQuality;
|
|
||||||
audiobookDlLic.LameConfig.WriteVBRTag = true;
|
|
||||||
}
|
}
|
||||||
|
return chaps;
|
||||||
|
}
|
||||||
|
|
||||||
return audiobookDlLic;
|
public static void combineCredits(IList<AudibleApi.Common.Chapter> chapters)
|
||||||
|
{
|
||||||
|
if (chapters.Count > 1 && chapters[0].Title == "Opening Credits")
|
||||||
|
{
|
||||||
|
chapters[1].StartOffsetMs = chapters[0].StartOffsetMs;
|
||||||
|
chapters[1].StartOffsetSec = chapters[0].StartOffsetSec;
|
||||||
|
chapters[1].LengthMs += chapters[0].LengthMs;
|
||||||
|
chapters.RemoveAt(0);
|
||||||
|
}
|
||||||
|
if (chapters.Count > 1 && chapters[^1].Title == "End Credits")
|
||||||
|
{
|
||||||
|
chapters[^2].LengthMs += chapters[^1].LengthMs;
|
||||||
|
chapters.Remove(chapters[^1]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void downloadValidation(LibraryBook libraryBook)
|
private static void downloadValidation(LibraryBook libraryBook)
|
||||||
@@ -243,12 +344,12 @@ namespace FileLiberator
|
|||||||
if (e is not null)
|
if (e is not null)
|
||||||
OnCoverImageDiscovered(e);
|
OnCoverImageDiscovered(e);
|
||||||
else if (Configuration.Instance.AllowLibationFixup)
|
else if (Configuration.Instance.AllowLibationFixup)
|
||||||
OnRequestCoverArt(abDownloader.SetCoverArt);
|
abDownloader.SetCoverArt(OnRequestCoverArt());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Move new files to 'Books' directory</summary>
|
/// <summary>Move new files to 'Books' directory</summary>
|
||||||
/// <returns>True if audiobook file(s) were successfully created and can be located on disk. Else false.</returns>
|
/// <returns>Return directory if audiobook file(s) were successfully created and can be located on disk. Else null.</returns>
|
||||||
private static bool moveFilesToBooksDir(LibraryBook libraryBook, List<FilePathCache.CacheEntry> entries)
|
private static string moveFilesToBooksDir(LibraryBook libraryBook, List<FilePathCache.CacheEntry> entries)
|
||||||
{
|
{
|
||||||
// create final directory. move each file into it
|
// create final directory. move each file into it
|
||||||
var destinationDir = AudibleFileStorage.Audio.GetDestinationDirectory(libraryBook);
|
var destinationDir = AudibleFileStorage.Audio.GetDestinationDirectory(libraryBook);
|
||||||
@@ -256,56 +357,51 @@ namespace FileLiberator
|
|||||||
|
|
||||||
FilePathCache.CacheEntry getFirstAudio() => entries.FirstOrDefault(f => f.FileType == FileType.Audio);
|
FilePathCache.CacheEntry getFirstAudio() => entries.FirstOrDefault(f => f.FileType == FileType.Audio);
|
||||||
|
|
||||||
if (getFirstAudio() == default)
|
if (getFirstAudio() == default)
|
||||||
return false;
|
return null;
|
||||||
|
|
||||||
for (var i = 0; i < entries.Count; i++)
|
for (var i = 0; i < entries.Count; i++)
|
||||||
{
|
{
|
||||||
var entry = entries[i];
|
var entry = entries[i];
|
||||||
|
|
||||||
var realDest = FileUtility.SaferMoveToValidPath(entry.Path, Path.Combine(destinationDir, Path.GetFileName(entry.Path)));
|
var realDest = FileUtility.SaferMoveToValidPath(entry.Path, Path.Combine(destinationDir, Path.GetFileName(entry.Path)), Configuration.Instance.ReplacementCharacters);
|
||||||
FilePathCache.Insert(libraryBook.Book.AudibleProductId, realDest);
|
FilePathCache.Insert(libraryBook.Book.AudibleProductId, realDest);
|
||||||
|
|
||||||
// propogate corrected path. Must update cache with corrected path. Also want updated path for cue file (after this for-loop)
|
// propagate corrected path. Must update cache with corrected path. Also want updated path for cue file (after this for-loop)
|
||||||
entries[i] = entry with { Path = realDest };
|
entries[i] = entry with { Path = realDest };
|
||||||
}
|
}
|
||||||
|
|
||||||
var cue = entries.FirstOrDefault(f => f.FileType == FileType.Cue);
|
var cue = entries.FirstOrDefault(f => f.FileType == FileType.Cue);
|
||||||
if (cue != default)
|
if (cue != default)
|
||||||
Cue.UpdateFileName(cue.Path, getFirstAudio().Path);
|
Cue.UpdateFileName(cue.Path, getFirstAudio().Path);
|
||||||
|
|
||||||
AudibleFileStorage.Audio.Refresh();
|
AudibleFileStorage.Audio.Refresh();
|
||||||
|
|
||||||
return true;
|
return destinationDir;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void DownloadCoverArt(LibraryBook libraryBook)
|
private static void downloadCoverArt(LibraryBook libraryBook)
|
||||||
{
|
{
|
||||||
var destinationDir = AudibleFileStorage.Audio.GetDestinationDirectory(libraryBook);
|
var coverPath = "[null]";
|
||||||
var coverPath = AudibleFileStorage.Audio.GetBooksDirectoryFilename(libraryBook, ".jpg");
|
|
||||||
coverPath = Path.Combine(destinationDir, Path.GetFileName(coverPath));
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (File.Exists(coverPath))
|
var destinationDir = AudibleFileStorage.Audio.GetDestinationDirectory(libraryBook);
|
||||||
|
coverPath = AudibleFileStorage.Audio.GetBooksDirectoryFilename(libraryBook, ".jpg");
|
||||||
|
coverPath = Path.Combine(destinationDir, Path.GetFileName(coverPath));
|
||||||
|
|
||||||
|
if (File.Exists(coverPath))
|
||||||
FileUtility.SaferDelete(coverPath);
|
FileUtility.SaferDelete(coverPath);
|
||||||
|
|
||||||
(string picId, PictureSize size) = libraryBook.Book.PictureLarge is null ?
|
var picBytes = PictureStorage.GetPictureSynchronously(new(libraryBook.Book.PictureLarge ?? libraryBook.Book.PictureId, PictureSize.Native));
|
||||||
(libraryBook.Book.PictureId, PictureSize.Native) :
|
|
||||||
(libraryBook.Book.PictureLarge, PictureSize.Native);
|
|
||||||
|
|
||||||
var picBytes = PictureStorage.GetPictureSynchronously(new PictureDefinition(picId, size));
|
|
||||||
|
|
||||||
if (picBytes.Length > 0)
|
if (picBytes.Length > 0)
|
||||||
File.WriteAllBytes(coverPath, picBytes);
|
File.WriteAllBytes(coverPath, picBytes);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
//Failure to download cover art should not be
|
//Failure to download cover art should not be considered a failure to download the book
|
||||||
//considered a failure to download the book
|
|
||||||
Serilog.Log.Logger.Error(ex, $"Error downloading cover art of {libraryBook.Book.AudibleProductId} to {coverPath} catalog product.");
|
Serilog.Log.Logger.Error(ex, $"Error downloading cover art of {libraryBook.Book.AudibleProductId} to {coverPath} catalog product.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Net.Http;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using Dinah.Core.Net.Http;
|
|
||||||
|
|
||||||
namespace FileLiberator
|
|
||||||
{
|
|
||||||
// currently only used to download the .zip flies for upgrade
|
|
||||||
public class DownloadFile : Streamable
|
|
||||||
{
|
|
||||||
public async Task<string> PerformDownloadFileAsync(string downloadUrl, string proposedDownloadFilePath)
|
|
||||||
{
|
|
||||||
var client = new HttpClient();
|
|
||||||
|
|
||||||
var progress = new Progress<DownloadProgress>(OnStreamingProgressChanged);
|
|
||||||
|
|
||||||
OnStreamingBegin(proposedDownloadFilePath);
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var actualDownloadedFilePath = await client.DownloadFileAsync(downloadUrl, proposedDownloadFilePath, progress);
|
|
||||||
OnFileCreated("Upgrade", actualDownloadedFilePath);
|
|
||||||
return actualDownloadedFilePath;
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
OnStreamingCompleted(proposedDownloadFilePath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
using AaxDecrypter;
|
||||||
|
using AAXClean;
|
||||||
|
using Dinah.Core;
|
||||||
|
using DataLayer;
|
||||||
|
using LibationFileManager;
|
||||||
|
using FileManager;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using ApplicationServices;
|
||||||
|
|
||||||
|
namespace FileLiberator
|
||||||
|
{
|
||||||
|
public class DownloadOptions : IDownloadOptions, IDisposable
|
||||||
|
{
|
||||||
|
public event EventHandler<long> DownloadSpeedChanged;
|
||||||
|
public LibraryBook LibraryBook { get; }
|
||||||
|
public LibraryBookDto LibraryBookDto { get; }
|
||||||
|
public string DownloadUrl { get; }
|
||||||
|
public string UserAgent { get; }
|
||||||
|
public string AudibleKey { get; init; }
|
||||||
|
public string AudibleIV { get; init; }
|
||||||
|
public AaxDecrypter.OutputFormat OutputFormat { get; init; }
|
||||||
|
public bool TrimOutputToChapterLength { get; init; }
|
||||||
|
public bool RetainEncryptedFile { get; init; }
|
||||||
|
public bool StripUnabridged { get; init; }
|
||||||
|
public bool CreateCueSheet { get; init; }
|
||||||
|
public bool DownloadClipsBookmarks { get; init; }
|
||||||
|
public long DownloadSpeedBps { get; init; }
|
||||||
|
public ChapterInfo ChapterInfo { get; init; }
|
||||||
|
public bool FixupFile { get; init; }
|
||||||
|
public NAudio.Lame.LameConfig LameConfig { get; init; }
|
||||||
|
public bool Downsample { get; init; }
|
||||||
|
public bool MatchSourceBitrate { get; init; }
|
||||||
|
public ReplacementCharacters ReplacementCharacters => Configuration.Instance.ReplacementCharacters;
|
||||||
|
|
||||||
|
public string GetMultipartFileName(MultiConvertFileProperties props)
|
||||||
|
=> Templates.ChapterFile.GetFilename(LibraryBookDto, props);
|
||||||
|
|
||||||
|
public string GetMultipartTitleName(MultiConvertFileProperties props)
|
||||||
|
=> Templates.ChapterTitle.GetTitle(LibraryBookDto, props);
|
||||||
|
|
||||||
|
public async Task<string> SaveClipsAndBookmarks(string fileName)
|
||||||
|
{
|
||||||
|
if (DownloadClipsBookmarks)
|
||||||
|
{
|
||||||
|
var format = Configuration.Instance.ClipsBookmarksFileFormat;
|
||||||
|
|
||||||
|
var formatExtension = format.ToString().ToLowerInvariant();
|
||||||
|
var filePath = Path.ChangeExtension(fileName, formatExtension);
|
||||||
|
|
||||||
|
var api = await LibraryBook.GetApiAsync();
|
||||||
|
var records = await api.GetRecordsAsync(LibraryBook.Book.AudibleProductId);
|
||||||
|
|
||||||
|
switch(format)
|
||||||
|
{
|
||||||
|
case Configuration.ClipBookmarkFormat.CSV:
|
||||||
|
RecordExporter.ToCsv(filePath, records);
|
||||||
|
break;
|
||||||
|
case Configuration.ClipBookmarkFormat.Xlsx:
|
||||||
|
RecordExporter.ToXlsx(filePath, records);
|
||||||
|
break;
|
||||||
|
case Configuration.ClipBookmarkFormat.Json:
|
||||||
|
RecordExporter.ToJson(filePath, LibraryBook, records);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return filePath;
|
||||||
|
}
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly IDisposable cancellation;
|
||||||
|
public void Dispose() => cancellation?.Dispose();
|
||||||
|
|
||||||
|
public DownloadOptions(LibraryBook libraryBook, string downloadUrl, string userAgent)
|
||||||
|
{
|
||||||
|
LibraryBook = ArgumentValidator.EnsureNotNull(libraryBook, nameof(libraryBook));
|
||||||
|
DownloadUrl = ArgumentValidator.EnsureNotNullOrEmpty(downloadUrl, nameof(downloadUrl));
|
||||||
|
UserAgent = ArgumentValidator.EnsureNotNullOrEmpty(userAgent, nameof(userAgent));
|
||||||
|
// no null/empty check for key/iv. unencrypted files do not have them
|
||||||
|
|
||||||
|
LibraryBookDto = LibraryBook.ToDto();
|
||||||
|
|
||||||
|
cancellation =
|
||||||
|
Configuration.Instance
|
||||||
|
.ObservePropertyChanged<long>(
|
||||||
|
nameof(Configuration.DownloadSpeedLimit),
|
||||||
|
newVal => DownloadSpeedChanged?.Invoke(this, newVal));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ using System.IO;
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using ApplicationServices;
|
||||||
using DataLayer;
|
using DataLayer;
|
||||||
using Dinah.Core.ErrorHandling;
|
using Dinah.Core.ErrorHandling;
|
||||||
using Dinah.Core.Net.Http;
|
using Dinah.Core.Net.Http;
|
||||||
@@ -14,6 +15,7 @@ namespace FileLiberator
|
|||||||
{
|
{
|
||||||
public class DownloadPdf : Processable
|
public class DownloadPdf : Processable
|
||||||
{
|
{
|
||||||
|
public override string Name => "Download Pdf";
|
||||||
public override bool Validate(LibraryBook libraryBook)
|
public override bool Validate(LibraryBook libraryBook)
|
||||||
=> !string.IsNullOrWhiteSpace(getdownloadUrl(libraryBook))
|
=> !string.IsNullOrWhiteSpace(getdownloadUrl(libraryBook))
|
||||||
&& !libraryBook.Book.PDF_Exists();
|
&& !libraryBook.Book.PDF_Exists();
|
||||||
@@ -22,22 +24,30 @@ namespace FileLiberator
|
|||||||
{
|
{
|
||||||
OnBegin(libraryBook);
|
OnBegin(libraryBook);
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var proposedDownloadFilePath = getProposedDownloadFilePath(libraryBook);
|
var proposedDownloadFilePath = getProposedDownloadFilePath(libraryBook);
|
||||||
var actualDownloadedFilePath = await downloadPdfAsync(libraryBook, proposedDownloadFilePath);
|
var actualDownloadedFilePath = await downloadPdfAsync(libraryBook, proposedDownloadFilePath);
|
||||||
var result = verifyDownload(actualDownloadedFilePath);
|
var result = verifyDownload(actualDownloadedFilePath);
|
||||||
|
|
||||||
libraryBook.Book.UserDefinedItem.PdfStatus = result.IsSuccess ? LiberatedStatus.Liberated : LiberatedStatus.NotLiberated;
|
libraryBook.Book.UpdatePdfStatus(result.IsSuccess ? LiberatedStatus.Liberated : LiberatedStatus.NotLiberated);
|
||||||
ApplicationServices.LibraryCommands.UpdateUserDefinedItem(libraryBook.Book);
|
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Serilog.Log.Logger.Error(ex, "Error downloading PDF");
|
||||||
|
|
||||||
|
var result = new StatusHandler();
|
||||||
|
result.AddError($"Error downloading PDF. See log for details. Error summary: {ex.Message}");
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
OnCompleted(libraryBook);
|
OnCompleted(libraryBook);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string getProposedDownloadFilePath(LibraryBook libraryBook)
|
private static string getProposedDownloadFilePath(LibraryBook libraryBook)
|
||||||
{
|
{
|
||||||
@@ -56,27 +66,18 @@ namespace FileLiberator
|
|||||||
|
|
||||||
private async Task<string> downloadPdfAsync(LibraryBook libraryBook, string proposedDownloadFilePath)
|
private async Task<string> downloadPdfAsync(LibraryBook libraryBook, string proposedDownloadFilePath)
|
||||||
{
|
{
|
||||||
OnStreamingBegin(proposedDownloadFilePath);
|
var api = await libraryBook.GetApiAsync();
|
||||||
|
var downloadUrl = await api.GetPdfDownloadLinkAsync(libraryBook.Book.AudibleProductId);
|
||||||
|
|
||||||
try
|
var progress = new Progress<DownloadProgress>(OnStreamingProgressChanged);
|
||||||
{
|
|
||||||
var api = await libraryBook.GetApiAsync();
|
|
||||||
var downloadUrl = await api.GetPdfDownloadLinkAsync(libraryBook.Book.AudibleProductId);
|
|
||||||
|
|
||||||
var progress = new Progress<DownloadProgress>(OnStreamingProgressChanged);
|
var client = new HttpClient();
|
||||||
|
|
||||||
var client = new HttpClient();
|
var actualDownloadedFilePath = await client.DownloadFileAsync(downloadUrl, proposedDownloadFilePath, progress);
|
||||||
|
OnFileCreated(libraryBook, actualDownloadedFilePath);
|
||||||
|
|
||||||
var actualDownloadedFilePath = await client.DownloadFileAsync(downloadUrl, proposedDownloadFilePath, progress);
|
OnStatusUpdate(actualDownloadedFilePath);
|
||||||
OnFileCreated(libraryBook, actualDownloadedFilePath);
|
return actualDownloadedFilePath;
|
||||||
|
|
||||||
OnStatusUpdate(actualDownloadedFilePath);
|
|
||||||
return actualDownloadedFilePath;
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
OnStreamingCompleted(proposedDownloadFilePath);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static StatusHandler verifyDownload(string actualDownloadedFilePath)
|
private static StatusHandler verifyDownload(string actualDownloadedFilePath)
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net6.0-windows</TargetFramework>
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@@ -11,4 +11,13 @@
|
|||||||
<ProjectReference Include="..\AudibleUtilities\AudibleUtilities.csproj" />
|
<ProjectReference Include="..\AudibleUtilities\AudibleUtilities.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -5,16 +5,22 @@ using System.Threading.Tasks;
|
|||||||
using DataLayer;
|
using DataLayer;
|
||||||
using Dinah.Core;
|
using Dinah.Core;
|
||||||
using Dinah.Core.ErrorHandling;
|
using Dinah.Core.ErrorHandling;
|
||||||
|
using Dinah.Core.Net.Http;
|
||||||
using LibationFileManager;
|
using LibationFileManager;
|
||||||
|
|
||||||
namespace FileLiberator
|
namespace FileLiberator
|
||||||
{
|
{
|
||||||
public abstract class Processable : Streamable
|
public abstract class Processable
|
||||||
{
|
{
|
||||||
|
public abstract string Name { get; }
|
||||||
public event EventHandler<LibraryBook> Begin;
|
public event EventHandler<LibraryBook> Begin;
|
||||||
|
|
||||||
/// <summary>General string message to display. DON'T rely on this for success, failure, or control logic</summary>
|
/// <summary>General string message to display. DON'T rely on this for success, failure, or control logic</summary>
|
||||||
public event EventHandler<string> StatusUpdate;
|
public event EventHandler<string> StatusUpdate;
|
||||||
|
/// <summary>Fired when a file is successfully saved to disk</summary>
|
||||||
|
public event EventHandler<(string id, string path)> FileCreated;
|
||||||
|
public event EventHandler<DownloadProgress> StreamingProgressChanged;
|
||||||
|
public event EventHandler<TimeSpan> StreamingTimeRemaining;
|
||||||
|
|
||||||
public event EventHandler<LibraryBook> Completed;
|
public event EventHandler<LibraryBook> Completed;
|
||||||
|
|
||||||
@@ -28,7 +34,7 @@ namespace FileLiberator
|
|||||||
public IEnumerable<LibraryBook> GetValidLibraryBooks(IEnumerable<LibraryBook> library)
|
public IEnumerable<LibraryBook> GetValidLibraryBooks(IEnumerable<LibraryBook> library)
|
||||||
=> library.Where(libraryBook =>
|
=> library.Where(libraryBook =>
|
||||||
Validate(libraryBook)
|
Validate(libraryBook)
|
||||||
&& (libraryBook.Book.ContentType != ContentType.Episode || LibationFileManager.Configuration.Instance.DownloadEpisodes)
|
&& (!libraryBook.Book.IsEpisodeChild() || Configuration.Instance.DownloadEpisodes)
|
||||||
);
|
);
|
||||||
|
|
||||||
public async Task<StatusHandler> ProcessSingleAsync(LibraryBook libraryBook, bool validate)
|
public async Task<StatusHandler> ProcessSingleAsync(LibraryBook libraryBook, bool validate)
|
||||||
@@ -68,6 +74,23 @@ namespace FileLiberator
|
|||||||
StatusUpdate?.Invoke(this, statusUpdate);
|
StatusUpdate?.Invoke(this, statusUpdate);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected void OnFileCreated(LibraryBook libraryBook, string path)
|
||||||
|
{
|
||||||
|
Serilog.Log.Logger.Information("File created {@DebugInfo}", new { Name = nameof(FileCreated), libraryBook.Book.AudibleProductId, path });
|
||||||
|
FilePathCache.Insert(libraryBook.Book.AudibleProductId, path);
|
||||||
|
FileCreated?.Invoke(this, (libraryBook.Book.AudibleProductId, path));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void OnStreamingProgressChanged(DownloadProgress progress)
|
||||||
|
=> OnStreamingProgressChanged(null, progress);
|
||||||
|
protected void OnStreamingProgressChanged(object _, DownloadProgress progress)
|
||||||
|
=> StreamingProgressChanged?.Invoke(this, progress);
|
||||||
|
|
||||||
|
protected void OnStreamingTimeRemaining(TimeSpan timeRemaining)
|
||||||
|
=> OnStreamingTimeRemaining(null, timeRemaining);
|
||||||
|
protected void OnStreamingTimeRemaining(object _, TimeSpan timeRemaining)
|
||||||
|
=> StreamingTimeRemaining?.Invoke(this, timeRemaining);
|
||||||
|
|
||||||
protected void OnCompleted(LibraryBook libraryBook)
|
protected void OnCompleted(LibraryBook libraryBook)
|
||||||
{
|
{
|
||||||
Serilog.Log.Logger.Debug("Event fired {@DebugInfo}", new { Name = nameof(Completed), Book = libraryBook.LogFriendly() });
|
Serilog.Log.Logger.Debug("Event fired {@DebugInfo}", new { Name = nameof(Completed), Book = libraryBook.LogFriendly() });
|
||||||
|
|||||||
@@ -1,47 +0,0 @@
|
|||||||
using System;
|
|
||||||
using Dinah.Core.Net.Http;
|
|
||||||
|
|
||||||
namespace FileLiberator
|
|
||||||
{
|
|
||||||
public abstract class Streamable
|
|
||||||
{
|
|
||||||
public event EventHandler<string> StreamingBegin;
|
|
||||||
public event EventHandler<DownloadProgress> StreamingProgressChanged;
|
|
||||||
public event EventHandler<TimeSpan> StreamingTimeRemaining;
|
|
||||||
public event EventHandler<string> StreamingCompleted;
|
|
||||||
/// <summary>Fired when a file is successfully saved to disk</summary>
|
|
||||||
public event EventHandler<(string id, string path)> FileCreated;
|
|
||||||
|
|
||||||
protected void OnStreamingBegin(string filePath)
|
|
||||||
{
|
|
||||||
Serilog.Log.Logger.Debug("Event fired {@DebugInfo}", new { Name = nameof(StreamingBegin), Message = filePath });
|
|
||||||
StreamingBegin?.Invoke(this, filePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void OnStreamingProgressChanged(DownloadProgress progress) => OnStreamingProgressChanged(null, progress);
|
|
||||||
protected void OnStreamingProgressChanged(object _, DownloadProgress progress)
|
|
||||||
{
|
|
||||||
StreamingProgressChanged?.Invoke(this, progress);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void OnStreamingTimeRemaining(TimeSpan timeRemaining) => OnStreamingTimeRemaining(null, timeRemaining);
|
|
||||||
protected void OnStreamingTimeRemaining(object _, TimeSpan timeRemaining)
|
|
||||||
{
|
|
||||||
StreamingTimeRemaining?.Invoke(this, timeRemaining);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void OnStreamingCompleted(string filePath)
|
|
||||||
{
|
|
||||||
Serilog.Log.Logger.Debug("Event fired {@DebugInfo}", new { Name = nameof(StreamingCompleted), Message = filePath });
|
|
||||||
StreamingCompleted?.Invoke(this, filePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void OnFileCreated(DataLayer.LibraryBook libraryBook, string path) => OnFileCreated(libraryBook.Book.AudibleProductId, path);
|
|
||||||
protected void OnFileCreated(string id, string path)
|
|
||||||
{
|
|
||||||
Serilog.Log.Logger.Information("File created {@DebugInfo}", new { Name = nameof(FileCreated), id, path });
|
|
||||||
LibationFileManager.FilePathCache.Insert(id, path);
|
|
||||||
FileCreated?.Invoke(this, (id, path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -31,13 +31,18 @@ namespace FileLiberator
|
|||||||
AudibleProductId = libraryBook.Book.AudibleProductId,
|
AudibleProductId = libraryBook.Book.AudibleProductId,
|
||||||
Title = libraryBook.Book.Title ?? "",
|
Title = libraryBook.Book.Title ?? "",
|
||||||
Locale = libraryBook.Book.Locale,
|
Locale = libraryBook.Book.Locale,
|
||||||
|
YearPublished = libraryBook.Book.DatePublished?.Year,
|
||||||
|
|
||||||
Authors = libraryBook.Book.Authors.Select(c => c.Name).ToList(),
|
Authors = libraryBook.Book.Authors.Select(c => c.Name).ToList(),
|
||||||
|
|
||||||
Narrators = libraryBook.Book.Narrators.Select(c => c.Name).ToList(),
|
Narrators = libraryBook.Book.Narrators.Select(c => c.Name).ToList(),
|
||||||
|
|
||||||
SeriesName = libraryBook.Book.SeriesLink.FirstOrDefault()?.Series.Name,
|
SeriesName = libraryBook.Book.SeriesLink.FirstOrDefault()?.Series.Name,
|
||||||
SeriesNumber = libraryBook.Book.SeriesLink.FirstOrDefault()?.Order
|
SeriesNumber = libraryBook.Book.SeriesLink.FirstOrDefault()?.Order,
|
||||||
|
|
||||||
|
BitRate = libraryBook.Book.AudioFormat.Bitrate,
|
||||||
|
SampleRate = libraryBook.Book.AudioFormat.SampleRate,
|
||||||
|
Channels = libraryBook.Book.AudioFormat.Channels,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,7 +12,7 @@ namespace FileManager
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class BackgroundFileSystem
|
public class BackgroundFileSystem
|
||||||
{
|
{
|
||||||
public string RootDirectory { get; private set; }
|
public LongPath RootDirectory { get; private set; }
|
||||||
public string SearchPattern { get; private set; }
|
public string SearchPattern { get; private set; }
|
||||||
public SearchOption SearchOption { get; private set; }
|
public SearchOption SearchOption { get; private set; }
|
||||||
|
|
||||||
@@ -21,9 +21,9 @@ namespace FileManager
|
|||||||
private Task backgroundScanner { get; set; }
|
private Task backgroundScanner { get; set; }
|
||||||
|
|
||||||
private object fsCacheLocker { get; } = new();
|
private object fsCacheLocker { get; } = new();
|
||||||
private List<string> fsCache { get; } = new();
|
private List<LongPath> fsCache { get; } = new();
|
||||||
|
|
||||||
public BackgroundFileSystem(string rootDirectory, string searchPattern, SearchOption searchOptions)
|
public BackgroundFileSystem(LongPath rootDirectory, string searchPattern, SearchOption searchOptions)
|
||||||
{
|
{
|
||||||
RootDirectory = rootDirectory;
|
RootDirectory = rootDirectory;
|
||||||
SearchPattern = searchPattern;
|
SearchPattern = searchPattern;
|
||||||
@@ -32,12 +32,18 @@ namespace FileManager
|
|||||||
Init();
|
Init();
|
||||||
}
|
}
|
||||||
|
|
||||||
public string FindFile(System.Text.RegularExpressions.Regex regex)
|
public LongPath FindFile(System.Text.RegularExpressions.Regex regex)
|
||||||
{
|
{
|
||||||
lock (fsCacheLocker)
|
lock (fsCacheLocker)
|
||||||
return fsCache.FirstOrDefault(s => regex.IsMatch(s));
|
return fsCache.FirstOrDefault(s => regex.IsMatch(s));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<LongPath> FindFiles(System.Text.RegularExpressions.Regex regex)
|
||||||
|
{
|
||||||
|
lock (fsCacheLocker)
|
||||||
|
return fsCache.Where(s => regex.IsMatch(s)).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
public void RefreshFiles()
|
public void RefreshFiles()
|
||||||
{
|
{
|
||||||
lock (fsCacheLocker)
|
lock (fsCacheLocker)
|
||||||
@@ -73,8 +79,13 @@ namespace FileManager
|
|||||||
//Stop raising events
|
//Stop raising events
|
||||||
fileSystemWatcher?.Dispose();
|
fileSystemWatcher?.Dispose();
|
||||||
|
|
||||||
//Calling CompleteAdding() will cause background scanner to terminate.
|
try
|
||||||
directoryChangesEvents?.CompleteAdding();
|
{
|
||||||
|
//Calling CompleteAdding() will cause background scanner to terminate.
|
||||||
|
directoryChangesEvents?.CompleteAdding();
|
||||||
|
}
|
||||||
|
// if directoryChangesEvents is non-null and isDisposed, this exception is thrown. there's no other way to check >:(
|
||||||
|
catch (ObjectDisposedException) { }
|
||||||
|
|
||||||
//Wait for background scanner to terminate before reinitializing.
|
//Wait for background scanner to terminate before reinitializing.
|
||||||
backgroundScanner?.Wait();
|
backgroundScanner?.Wait();
|
||||||
@@ -124,28 +135,33 @@ namespace FileManager
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void RemovePath(string path)
|
private void RemovePath(LongPath path)
|
||||||
{
|
{
|
||||||
var pathsToRemove = fsCache.Where(p => p.StartsWith(path)).ToArray();
|
path = path.LongPathName;
|
||||||
|
var pathsToRemove = fsCache.Where(p => ((string)p).StartsWith(path)).ToArray();
|
||||||
|
|
||||||
foreach (var p in pathsToRemove)
|
foreach (var p in pathsToRemove)
|
||||||
fsCache.Remove(p);
|
fsCache.Remove(p);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void AddPath(string path)
|
private void AddPath(LongPath path)
|
||||||
{
|
{
|
||||||
if (!File.Exists(path)) return;
|
path = path.LongPathName;
|
||||||
|
if (!File.Exists(path) && !Directory.Exists(path))
|
||||||
|
return;
|
||||||
if (File.GetAttributes(path).HasFlag(FileAttributes.Directory))
|
if (File.GetAttributes(path).HasFlag(FileAttributes.Directory))
|
||||||
AddUniqueFiles(FileUtility.SaferEnumerateFiles(path, SearchPattern, SearchOption));
|
AddUniqueFiles(FileUtility.SaferEnumerateFiles(path, SearchPattern, SearchOption));
|
||||||
else
|
else
|
||||||
AddUniqueFile(path);
|
AddUniqueFile(path);
|
||||||
}
|
}
|
||||||
private void AddUniqueFiles(IEnumerable<string> newFiles)
|
|
||||||
|
private void AddUniqueFiles(IEnumerable<LongPath> newFiles)
|
||||||
{
|
{
|
||||||
foreach (var file in newFiles)
|
foreach (var file in newFiles)
|
||||||
AddUniqueFile(file);
|
AddUniqueFile(file);
|
||||||
}
|
}
|
||||||
private void AddUniqueFile(string newFile)
|
|
||||||
|
private void AddUniqueFile(LongPath newFile)
|
||||||
{
|
{
|
||||||
if (!fsCache.Contains(newFile))
|
if (!fsCache.Contains(newFile))
|
||||||
fsCache.Add(newFile);
|
fsCache.Add(newFile);
|
||||||
|
|||||||
@@ -1,12 +1,20 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net6.0</TargetFramework>
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Dinah.Core" Version="4.2.0.1" />
|
<PackageReference Include="Dinah.Core" Version="7.2.0.1" />
|
||||||
<PackageReference Include="Polly" Version="7.2.3" />
|
<PackageReference Include="Polly" Version="7.2.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -1,64 +1,119 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using Dinah.Core;
|
using System.Text;
|
||||||
|
|
||||||
namespace FileManager
|
namespace FileManager
|
||||||
{
|
{
|
||||||
/// <summary>Get valid filename. Advanced features incl. parameterized template</summary>
|
/// <summary>Get valid filename. Advanced features incl. parameterized template</summary>
|
||||||
public class FileNamingTemplate
|
public class FileNamingTemplate : NamingTemplate
|
||||||
{
|
{
|
||||||
/// <summary>Proposed full file path. May contain optional html-styled template tags. Eg: <name></summary>
|
/// <param name="template">Proposed file name with optional html-styled template tags.</param>
|
||||||
public string Template { get; }
|
public FileNamingTemplate(string template) : base(template) { }
|
||||||
|
|
||||||
/// <param name="template">Proposed file name with optional html-styled template tags.</param>
|
/// <summary>Generate a valid path for this file or directory</summary>
|
||||||
public FileNamingTemplate(string template) => Template = ArgumentValidator.EnsureNotNullOrWhiteSpace(template, nameof(template));
|
public LongPath GetFilePath(ReplacementCharacters replacements, bool returnFirstExisting = false)
|
||||||
|
{
|
||||||
|
string fileName =
|
||||||
|
Template.EndsWith(Path.DirectorySeparatorChar) || Template.EndsWith(Path.AltDirectorySeparatorChar) ?
|
||||||
|
FileUtility.RemoveLastCharacter(Template) :
|
||||||
|
Template;
|
||||||
|
|
||||||
/// <summary>Optional step 1: Replace html-styled template tags with parameters. Eg {"name", "Bill Gates"} => /<name>/ => /Bill Gates/</summary>
|
List<string> pathParts = new();
|
||||||
public Dictionary<string, object> ParameterReplacements { get; } = new Dictionary<string, object>();
|
|
||||||
|
|
||||||
/// <summary>Convenience method</summary>
|
var paramReplacements = ParameterReplacements.ToDictionary(r => $"<{formatKey(r.Key)}>", r => formatValue(r.Value, replacements));
|
||||||
public void AddParameterReplacement(string key, object value)
|
|
||||||
// using .Add() instead of "[key] = value" will make unintended overwriting throw exception
|
|
||||||
=> ParameterReplacements.Add(key, value);
|
|
||||||
|
|
||||||
/// <summary>If set, truncate each parameter replacement to this many characters. Default 50</summary>
|
while (!string.IsNullOrEmpty(fileName))
|
||||||
public int? ParameterMaxSize { get; set; } = 50;
|
{
|
||||||
|
var file = Path.GetFileName(fileName);
|
||||||
|
|
||||||
/// <summary>Optional step 2: Replace all illegal characters with this. Default=<see cref="string.Empty"/></summary>
|
if (Path.IsPathRooted(Template) && file == string.Empty)
|
||||||
public string IllegalCharacterReplacements { get; set; }
|
{
|
||||||
|
pathParts.Add(fileName);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
pathParts.Add(file);
|
||||||
|
fileName = Path.GetDirectoryName(fileName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Generate a valid path for this file or directory</summary>
|
pathParts.Reverse();
|
||||||
public string GetFilePath(bool returnFirstExisting = false)
|
var fileNamePart = pathParts[^1];
|
||||||
{
|
pathParts.Remove(fileNamePart);
|
||||||
var filename = Template;
|
|
||||||
|
|
||||||
foreach (var r in ParameterReplacements)
|
var fileExtension = Path.GetExtension(fileNamePart);
|
||||||
filename = filename.Replace($"<{formatKey(r.Key)}>", formatValue(r.Value));
|
fileNamePart = fileNamePart[..^fileExtension.Length];
|
||||||
|
|
||||||
return FileUtility.GetValidFilename(filename, IllegalCharacterReplacements, returnFirstExisting);
|
LongPath directory = Path.Join(pathParts.Select(p => replaceFileName(p, paramReplacements, LongPath.MaxFilenameLength)).ToArray());
|
||||||
}
|
|
||||||
|
|
||||||
private static string formatKey(string key)
|
//If file already exists, GetValidFilename will append " (n)" to the filename.
|
||||||
=> key
|
//This could cause the filename length to exceed MaxFilenameLength, so reduce
|
||||||
.Replace("<", "")
|
//allowable filename length by 5 chars, allowing for up to 99 duplicates.
|
||||||
.Replace(">", "");
|
return FileUtility
|
||||||
|
.GetValidFilename(
|
||||||
|
Path.Join(directory, replaceFileName(fileNamePart, paramReplacements, LongPath.MaxFilenameLength - fileExtension.Length - 5)) + fileExtension,
|
||||||
|
replacements,
|
||||||
|
returnFirstExisting
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private string formatValue(object value)
|
private static string replaceFileName(string filename, Dictionary<string,string> paramReplacements, int maxFilenameLength)
|
||||||
{
|
{
|
||||||
if (value is null)
|
List<StringBuilder> filenameParts = new();
|
||||||
return "";
|
//Build the filename in parts, replacing replacement parameters with
|
||||||
|
//their values, and storing the parts in a list.
|
||||||
|
while (!string.IsNullOrEmpty(filename))
|
||||||
|
{
|
||||||
|
int openIndex = filename.IndexOf('<');
|
||||||
|
int closeIndex = filename.IndexOf('>');
|
||||||
|
|
||||||
// Other illegal characters will be taken care of later. Must take care of slashes now so params can't introduce new folders.
|
if (openIndex == 0 && closeIndex > 0)
|
||||||
// Esp important for file templates.
|
{
|
||||||
var val = value
|
var key = filename[..(closeIndex + 1)];
|
||||||
.ToString()
|
|
||||||
.Replace($"{System.IO.Path.DirectorySeparatorChar}", IllegalCharacterReplacements)
|
if (paramReplacements.ContainsKey(key))
|
||||||
.Replace($"{System.IO.Path.AltDirectorySeparatorChar}", IllegalCharacterReplacements);
|
filenameParts.Add(new StringBuilder(paramReplacements[key]));
|
||||||
return
|
else
|
||||||
ParameterMaxSize.HasValue && ParameterMaxSize.Value > 0
|
filenameParts.Add(new StringBuilder(key));
|
||||||
? val.Truncate(ParameterMaxSize.Value)
|
|
||||||
: val;
|
filename = filename[(closeIndex + 1)..];
|
||||||
}
|
}
|
||||||
}
|
else if (openIndex > 0 && closeIndex > openIndex)
|
||||||
|
{
|
||||||
|
var other = filename[..openIndex];
|
||||||
|
filenameParts.Add(new StringBuilder(other));
|
||||||
|
filename = filename[openIndex..];
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
filenameParts.Add(new StringBuilder(filename));
|
||||||
|
filename = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Remove 1 character from the end of the longest filename part until
|
||||||
|
//the total filename is less than max filename length
|
||||||
|
while (filenameParts.Sum(p => LongPath.GetFilesystemStringLength(p)) > maxFilenameLength)
|
||||||
|
{
|
||||||
|
int maxLength = filenameParts.Max(p => p.Length);
|
||||||
|
var maxEntry = filenameParts.First(p => p.Length == maxLength);
|
||||||
|
|
||||||
|
maxEntry.Remove(maxLength - 1, 1);
|
||||||
|
}
|
||||||
|
return string.Join("", filenameParts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string formatValue(object value, ReplacementCharacters replacements)
|
||||||
|
{
|
||||||
|
if (value is null)
|
||||||
|
return "";
|
||||||
|
|
||||||
|
// Other illegal characters will be taken care of later. Must take care of slashes now so params can't introduce new folders.
|
||||||
|
// Esp important for file templates.
|
||||||
|
return replacements.ReplaceFilenameChars(value.ToString());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+198
-219
@@ -6,267 +6,246 @@ using System.Text.RegularExpressions;
|
|||||||
using Dinah.Core;
|
using Dinah.Core;
|
||||||
using Polly;
|
using Polly;
|
||||||
using Polly.Retry;
|
using Polly.Retry;
|
||||||
|
using Dinah.Core.Collections.Generic;
|
||||||
|
|
||||||
namespace FileManager
|
namespace FileManager
|
||||||
{
|
{
|
||||||
public static class FileUtility
|
public static class FileUtility
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// "txt" => ".txt"
|
|
||||||
/// <br />".txt" => ".txt"
|
|
||||||
/// <br />null or whitespace => ""
|
|
||||||
/// </summary>
|
|
||||||
public static string GetStandardizedExtension(string extension)
|
|
||||||
=> string.IsNullOrWhiteSpace(extension)
|
|
||||||
? (extension ?? "")?.Trim()
|
|
||||||
: '.' + extension.Trim().Trim('.');
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Return position with correct number of leading zeros.
|
|
||||||
/// <br />- 2 of 9 => "2"
|
|
||||||
/// <br />- 2 of 90 => "02"
|
|
||||||
/// <br />- 2 of 900 => "002"
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="position">position in sequence. The 'x' in 'x of y'</param>
|
|
||||||
/// <param name="total">total qty in sequence. The 'y' in 'x of y'</param>
|
|
||||||
public static string GetSequenceFormatted(int position, int total)
|
|
||||||
{
|
|
||||||
ArgumentValidator.EnsureGreaterThan(position, nameof(position), 0);
|
|
||||||
ArgumentValidator.EnsureGreaterThan(total, nameof(total), 0);
|
|
||||||
if (position > total)
|
|
||||||
throw new ArgumentException($"{position} may not be greater than {total}");
|
|
||||||
|
|
||||||
return position.ToString().PadLeft(total.ToString().Length, '0');
|
/// <summary>
|
||||||
}
|
/// "txt" => ".txt"
|
||||||
|
/// <br />".txt" => ".txt"
|
||||||
|
/// <br />null or whitespace => ""
|
||||||
|
/// </summary>
|
||||||
|
public static string GetStandardizedExtension(string extension)
|
||||||
|
=> string.IsNullOrWhiteSpace(extension)
|
||||||
|
? (extension ?? "")?.Trim()
|
||||||
|
: '.' + extension.Trim().Trim('.');
|
||||||
|
|
||||||
private const int MAX_FILENAME_LENGTH = 255;
|
/// <summary>
|
||||||
private const int MAX_DIRECTORY_LENGTH = 247;
|
/// Return position with correct number of leading zeros.
|
||||||
|
/// <br />- 2 of 9 => "2"
|
||||||
|
/// <br />- 2 of 90 => "02"
|
||||||
|
/// <br />- 2 of 900 => "002"
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="position">position in sequence. The 'x' in 'x of y'</param>
|
||||||
|
/// <param name="total">total qty in sequence. The 'y' in 'x of y'</param>
|
||||||
|
public static string GetSequenceFormatted(int position, int total)
|
||||||
|
{
|
||||||
|
ArgumentValidator.EnsureGreaterThan(position, nameof(position), 0);
|
||||||
|
ArgumentValidator.EnsureGreaterThan(total, nameof(total), 0);
|
||||||
|
if (position > total)
|
||||||
|
throw new ArgumentException($"{position} may not be greater than {total}");
|
||||||
|
|
||||||
/// <summary>
|
return position.ToString().PadLeft(total.ToString().Length, '0');
|
||||||
/// Ensure valid file name path:
|
}
|
||||||
/// <br/>- remove invalid chars
|
|
||||||
/// <br/>- ensure uniqueness
|
|
||||||
/// <br/>- enforce max file length
|
|
||||||
/// </summary>
|
|
||||||
public static string GetValidFilename(string path, string illegalCharacterReplacements = "", bool returnFirstExisting = false)
|
|
||||||
{
|
|
||||||
ArgumentValidator.EnsureNotNull(path, nameof(path));
|
|
||||||
|
|
||||||
// remove invalid chars
|
|
||||||
path = GetSafePath(path, illegalCharacterReplacements);
|
|
||||||
|
|
||||||
// ensure uniqueness and check lengths
|
/// <summary>
|
||||||
var dir = Path.GetDirectoryName(path);
|
/// Ensure valid file name path:
|
||||||
dir = dir.Truncate(MAX_DIRECTORY_LENGTH);
|
/// <br/>- remove invalid chars
|
||||||
|
/// <br/>- ensure uniqueness
|
||||||
|
/// <br/>- enforce max file length
|
||||||
|
/// </summary>
|
||||||
|
public static LongPath GetValidFilename(LongPath path, ReplacementCharacters replacements, bool returnFirstExisting = false)
|
||||||
|
{
|
||||||
|
ArgumentValidator.EnsureNotNull(path, nameof(path));
|
||||||
|
|
||||||
var filename = Path.GetFileNameWithoutExtension(path);
|
// remove invalid chars
|
||||||
var fileStem = Path.Combine(dir, filename);
|
path = GetSafePath(path, replacements);
|
||||||
|
|
||||||
var extension = Path.GetExtension(path);
|
// ensure uniqueness and check lengths
|
||||||
|
var dir = Path.GetDirectoryName(path);
|
||||||
|
dir = dir?.TruncateFilename(LongPath.MaxDirectoryLength) ?? string.Empty;
|
||||||
|
|
||||||
var fullfilename = fileStem.Truncate(MAX_FILENAME_LENGTH - extension.Length) + extension;
|
var extension = Path.GetExtension(path);
|
||||||
|
|
||||||
fullfilename = removeInvalidWhitespace(fullfilename);
|
var filename = Path.GetFileNameWithoutExtension(path).TruncateFilename(LongPath.MaxFilenameLength - extension.Length);
|
||||||
|
var fileStem = Path.Combine(dir, filename);
|
||||||
|
|
||||||
var i = 0;
|
|
||||||
while (File.Exists(fullfilename) && !returnFirstExisting)
|
|
||||||
{
|
|
||||||
var increm = $" ({++i})";
|
|
||||||
fullfilename = fileStem.Truncate(MAX_FILENAME_LENGTH - increm.Length - extension.Length) + increm + extension;
|
|
||||||
}
|
|
||||||
|
|
||||||
return fullfilename;
|
var fullfilename = fileStem.TruncateFilename(LongPath.MaxPathLength - extension.Length) + extension;
|
||||||
}
|
|
||||||
|
|
||||||
// GetInvalidFileNameChars contains everything in GetInvalidPathChars plus ':', '*', '?', '\\', '/'
|
fullfilename = removeInvalidWhitespace(fullfilename);
|
||||||
|
|
||||||
/// <summary>Use with file name, not full path. Valid path charaters which are invalid file name characters will be replaced: ':', '\\', '/'</summary>
|
var i = 0;
|
||||||
public static string GetSafeFileName(string str, string illegalCharacterReplacements = "")
|
while (File.Exists(fullfilename) && !returnFirstExisting)
|
||||||
=> string.Join(illegalCharacterReplacements ?? "", str.Split(Path.GetInvalidFileNameChars()));
|
{
|
||||||
|
var increm = $" ({++i})";
|
||||||
|
fullfilename = fileStem.TruncateFilename(LongPath.MaxPathLength - increm.Length - extension.Length) + increm + extension;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Use with full path, not file name. Valid path charaters which are invalid file name characters will be retained: '\\', '/'</summary>
|
return fullfilename;
|
||||||
public static string GetSafePath(string path, string illegalCharacterReplacements = "")
|
}
|
||||||
{
|
|
||||||
ArgumentValidator.EnsureNotNull(path, nameof(path));
|
|
||||||
|
|
||||||
path = replaceInvalidChars(path, illegalCharacterReplacements);
|
/// <summary>Use with full path, not file name. Valid path characters which are invalid file name characters will be retained: '\\', '/'</summary>
|
||||||
path = standardizeSlashes(path);
|
public static LongPath GetSafePath(LongPath path, ReplacementCharacters replacements)
|
||||||
path = replaceColons(path, illegalCharacterReplacements);
|
{
|
||||||
path = removeDoubleSlashes(path);
|
ArgumentValidator.EnsureNotNull(path, nameof(path));
|
||||||
|
|
||||||
return path;
|
var pathNoPrefix = path.PathWithoutPrefix;
|
||||||
}
|
|
||||||
|
|
||||||
private static char[] invalidChars { get; } = Path.GetInvalidPathChars().Union(new[] {
|
pathNoPrefix = replacements.ReplacePathChars(pathNoPrefix);
|
||||||
'*', '?',
|
pathNoPrefix = removeDoubleSlashes(pathNoPrefix);
|
||||||
// these are weird. If you run Path.GetInvalidPathChars() in Visual Studio's "C# Interactive", then these characters are included.
|
|
||||||
// In live code, Path.GetInvalidPathChars() does not include them
|
|
||||||
'"', '<', '>'
|
|
||||||
}).ToArray();
|
|
||||||
private static string replaceInvalidChars(string path, string illegalCharacterReplacements)
|
|
||||||
=> string.Join(illegalCharacterReplacements ?? "", path.Split(invalidChars));
|
|
||||||
|
|
||||||
private static string standardizeSlashes(string path)
|
return pathNoPrefix;
|
||||||
=> path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
|
}
|
||||||
|
|
||||||
private static string replaceColons(string path, string illegalCharacterReplacements)
|
private static string removeDoubleSlashes(string path)
|
||||||
{
|
{
|
||||||
// replace all colons except within the first 2 chars
|
if (path.Length < 2)
|
||||||
var builder = new System.Text.StringBuilder();
|
return path;
|
||||||
for (var i = 0; i < path.Length; i++)
|
|
||||||
{
|
|
||||||
var c = path[i];
|
|
||||||
if (i >= 2 && c == ':')
|
|
||||||
builder.Append(illegalCharacterReplacements);
|
|
||||||
else
|
|
||||||
builder.Append(c);
|
|
||||||
}
|
|
||||||
return builder.ToString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string removeDoubleSlashes(string path)
|
// exception: don't try to condense the initial dbl bk slashes in a path. eg: \\192.168.0.1
|
||||||
{
|
|
||||||
if (path.Length < 2)
|
|
||||||
return path;
|
|
||||||
|
|
||||||
// exception: don't try to condense the initial dbl bk slashes in a path. eg: \\192.168.0.1
|
var remainder = path[1..];
|
||||||
|
var dblSeparator = $"{Path.DirectorySeparatorChar}{Path.DirectorySeparatorChar}";
|
||||||
|
while (remainder.Contains(dblSeparator))
|
||||||
|
remainder = remainder.Replace(dblSeparator, $"{Path.DirectorySeparatorChar}");
|
||||||
|
|
||||||
var remainder = path[1..];
|
return path[0] + remainder;
|
||||||
var dblSeparator = $"{Path.DirectorySeparatorChar}{Path.DirectorySeparatorChar}";
|
}
|
||||||
while (remainder.Contains(dblSeparator))
|
|
||||||
remainder = remainder.Replace(dblSeparator, $"{Path.DirectorySeparatorChar}");
|
|
||||||
|
|
||||||
return path[0] + remainder;
|
private static string removeInvalidWhitespace_pattern { get; } = $@"[\s\.]*\{Path.DirectorySeparatorChar}\s*";
|
||||||
}
|
private static Regex removeInvalidWhitespace_regex { get; } = new(removeInvalidWhitespace_pattern, RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
|
||||||
|
|
||||||
private static string removeInvalidWhitespace_pattern { get; } = $@"[\s\.]*\{Path.DirectorySeparatorChar}\s*";
|
/// <summary>no part of the path may begin or end in whitespace</summary>
|
||||||
private static Regex removeInvalidWhitespace_regex { get; } = new(removeInvalidWhitespace_pattern, RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
|
private static string removeInvalidWhitespace(string fullfilename)
|
||||||
|
{
|
||||||
|
// no whitespace at beginning or end
|
||||||
|
// replace whitespace around path slashes
|
||||||
|
// regex (with space added for clarity)
|
||||||
|
// \s* \\ \s* => \
|
||||||
|
// no ending dots. beginning dots are valid
|
||||||
|
|
||||||
/// <summary>no part of the path may begin or end in whitespace</summary>
|
// regex is easier by ending with separator
|
||||||
private static string removeInvalidWhitespace(string fullfilename)
|
fullfilename += Path.DirectorySeparatorChar;
|
||||||
{
|
fullfilename = removeInvalidWhitespace_regex.Replace(fullfilename, Path.DirectorySeparatorChar.ToString());
|
||||||
// no whitespace at beginning or end
|
// take separator back off
|
||||||
// replace whitespace around path slashes
|
fullfilename = RemoveLastCharacter(fullfilename);
|
||||||
// regex (with space added for clarity)
|
|
||||||
// \s* \\ \s* => \
|
|
||||||
// no ending dots. beginning dots are valid
|
|
||||||
|
|
||||||
// regex is easier by ending with separator
|
fullfilename = removeDoubleSlashes(fullfilename);
|
||||||
fullfilename += Path.DirectorySeparatorChar;
|
return fullfilename;
|
||||||
fullfilename = removeInvalidWhitespace_regex.Replace(fullfilename, Path.DirectorySeparatorChar.ToString());
|
}
|
||||||
// take seperator back off
|
|
||||||
fullfilename = RemoveLastCharacter(fullfilename);
|
|
||||||
|
|
||||||
fullfilename = removeDoubleSlashes(fullfilename);
|
public static string RemoveLastCharacter(this string str) => string.IsNullOrEmpty(str) ? str : str[..^1];
|
||||||
return fullfilename;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static string RemoveLastCharacter(this string str) => string.IsNullOrEmpty(str) ? str : str[..^1];
|
public static string TruncateFilename(this string filenameStr, int limit)
|
||||||
|
{
|
||||||
|
if (LongPath.IsWindows) return filenameStr.Truncate(limit);
|
||||||
|
|
||||||
/// <summary>
|
int index = filenameStr.Length;
|
||||||
/// Move file.
|
|
||||||
/// <br/>- Ensure valid file name path: remove invalid chars, ensure uniqueness, enforce max file length
|
|
||||||
/// <br/>- Perform <see cref="SaferMove"/>
|
|
||||||
/// <br/>- Return valid path
|
|
||||||
/// </summary>
|
|
||||||
public static string SaferMoveToValidPath(string source, string destination)
|
|
||||||
{
|
|
||||||
destination = GetValidFilename(destination);
|
|
||||||
SaferMove(source, destination);
|
|
||||||
return destination;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int maxRetryAttempts { get; } = 3;
|
while (index > 0 && System.Text.Encoding.UTF8.GetByteCount(filenameStr, 0, index) > limit)
|
||||||
private static TimeSpan pauseBetweenFailures { get; } = TimeSpan.FromMilliseconds(100);
|
index--;
|
||||||
private static RetryPolicy retryPolicy { get; } =
|
|
||||||
Policy
|
|
||||||
.Handle<Exception>()
|
|
||||||
.WaitAndRetry(maxRetryAttempts, i => pauseBetweenFailures);
|
|
||||||
|
|
||||||
/// <summary>Delete file. No error when source does not exist. Retry up to 3 times before throwing exception.</summary>
|
return filenameStr[..index];
|
||||||
public static void SaferDelete(string source)
|
}
|
||||||
=> retryPolicy.Execute(() =>
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (!File.Exists(source))
|
|
||||||
{
|
|
||||||
Serilog.Log.Logger.Debug("No file to delete: {@DebugText}", new { source });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Serilog.Log.Logger.Debug("Attempt to delete file: {@DebugText}", new { source });
|
/// <summary>
|
||||||
File.Delete(source);
|
/// Move file.
|
||||||
Serilog.Log.Logger.Information("File successfully deleted: {@DebugText}", new { source });
|
/// <br/>- Ensure valid file name path: remove invalid chars, ensure uniqueness, enforce max file length
|
||||||
}
|
/// <br/>- Perform <see cref="SaferMove"/>
|
||||||
catch (Exception e)
|
/// <br/>- Return valid path
|
||||||
{
|
/// </summary>
|
||||||
Serilog.Log.Logger.Error(e, "Failed to delete file: {@DebugText}", new { source });
|
public static string SaferMoveToValidPath(LongPath source, LongPath destination, ReplacementCharacters replacements)
|
||||||
throw;
|
{
|
||||||
}
|
destination = GetValidFilename(destination, replacements);
|
||||||
});
|
SaferMove(source, destination);
|
||||||
|
return destination;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Move file. No error when source does not exist. Retry up to 3 times before throwing exception.</summary>
|
private static int maxRetryAttempts { get; } = 3;
|
||||||
public static void SaferMove(string source, string destination)
|
private static TimeSpan pauseBetweenFailures { get; } = TimeSpan.FromMilliseconds(100);
|
||||||
=> retryPolicy.Execute(() =>
|
private static RetryPolicy retryPolicy { get; } =
|
||||||
{
|
Policy
|
||||||
try
|
.Handle<Exception>()
|
||||||
{
|
.WaitAndRetry(maxRetryAttempts, i => pauseBetweenFailures);
|
||||||
if (!File.Exists(source))
|
|
||||||
{
|
|
||||||
Serilog.Log.Logger.Debug("No file to move: {@DebugText}", new { source });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
SaferDelete(destination);
|
/// <summary>Delete file. No error when source does not exist. Retry up to 3 times before throwing exception.</summary>
|
||||||
|
public static void SaferDelete(LongPath source)
|
||||||
|
=> retryPolicy.Execute(() =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!File.Exists(source))
|
||||||
|
{
|
||||||
|
Serilog.Log.Logger.Debug("No file to delete: {@DebugText}", new { source });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
var dir = Path.GetDirectoryName(destination);
|
Serilog.Log.Logger.Debug("Attempt to delete file: {@DebugText}", new { source });
|
||||||
Serilog.Log.Logger.Debug("Attempt to create directory: {@DebugText}", new { dir });
|
File.Delete(source);
|
||||||
Directory.CreateDirectory(dir);
|
Serilog.Log.Logger.Information("File successfully deleted: {@DebugText}", new { source });
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Serilog.Log.Logger.Error(e, "Failed to delete file: {@DebugText}", new { source });
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
Serilog.Log.Logger.Debug("Attempt to move file: {@DebugText}", new { source, destination });
|
/// <summary>Move file. No error when source does not exist. Retry up to 3 times before throwing exception.</summary>
|
||||||
File.Move(source, destination);
|
public static void SaferMove(LongPath source, LongPath destination)
|
||||||
Serilog.Log.Logger.Information("File successfully moved: {@DebugText}", new { source, destination });
|
=> retryPolicy.Execute(() =>
|
||||||
}
|
{
|
||||||
catch (Exception e)
|
try
|
||||||
{
|
{
|
||||||
Serilog.Log.Logger.Error(e, "Failed to move file: {@DebugText}", new { source, destination });
|
if (!File.Exists(source))
|
||||||
throw;
|
{
|
||||||
}
|
Serilog.Log.Logger.Debug("No file to move: {@DebugText}", new { source });
|
||||||
});
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
SaferDelete(destination);
|
||||||
/// A safer way to get all the files in a directory and sub directory without crashing on UnauthorizedException or PathTooLongException
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="rootPath">Starting directory</param>
|
|
||||||
/// <param name="patternMatch">Filename pattern match</param>
|
|
||||||
/// <param name="searchOption">Search subdirectories or only top level directory for files</param>
|
|
||||||
/// <returns>List of files</returns>
|
|
||||||
public static IEnumerable<string> SaferEnumerateFiles(string path, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly)
|
|
||||||
{
|
|
||||||
var foundFiles = Enumerable.Empty<string>();
|
|
||||||
|
|
||||||
if (searchOption == SearchOption.AllDirectories)
|
var dir = Path.GetDirectoryName(destination);
|
||||||
{
|
Serilog.Log.Logger.Debug("Attempt to create directory: {@DebugText}", new { dir });
|
||||||
try
|
Directory.CreateDirectory(dir);
|
||||||
{
|
|
||||||
IEnumerable<string> subDirs = Directory.EnumerateDirectories(path);
|
|
||||||
// Add files in subdirectories recursively to the list
|
|
||||||
foreach (string dir in subDirs)
|
|
||||||
foundFiles = foundFiles.Concat(SaferEnumerateFiles(dir, searchPattern, searchOption));
|
|
||||||
}
|
|
||||||
catch (UnauthorizedAccessException) { }
|
|
||||||
catch (PathTooLongException) { }
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
Serilog.Log.Logger.Debug("Attempt to move file: {@DebugText}", new { source, destination });
|
||||||
{
|
File.Move(source, destination);
|
||||||
// Add files from the current directory
|
Serilog.Log.Logger.Information("File successfully moved: {@DebugText}", new { source, destination });
|
||||||
foundFiles = foundFiles.Concat(Directory.EnumerateFiles(path, searchPattern));
|
}
|
||||||
}
|
catch (Exception e)
|
||||||
catch (UnauthorizedAccessException) { }
|
{
|
||||||
|
Serilog.Log.Logger.Error(e, "Failed to move file: {@DebugText}", new { source, destination });
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
return foundFiles;
|
/// <summary>
|
||||||
}
|
/// A safer way to get all the files in a directory and sub directory without crashing on UnauthorizedException or PathTooLongException
|
||||||
}
|
/// </summary>
|
||||||
|
/// <param name="rootPath">Starting directory</param>
|
||||||
|
/// <param name="patternMatch">Filename pattern match</param>
|
||||||
|
/// <param name="searchOption">Search subdirectories or only top level directory for files</param>
|
||||||
|
/// <returns>List of files</returns>
|
||||||
|
public static IEnumerable<LongPath> SaferEnumerateFiles(LongPath path, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly)
|
||||||
|
{
|
||||||
|
var foundFiles = Enumerable.Empty<LongPath>();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (searchOption == SearchOption.AllDirectories)
|
||||||
|
{
|
||||||
|
IEnumerable<LongPath> subDirs = Directory.EnumerateDirectories(path).Select(p => (LongPath)p);
|
||||||
|
// Add files in subdirectories recursively to the list
|
||||||
|
foreach (string dir in subDirs)
|
||||||
|
foundFiles = foundFiles.Concat(SaferEnumerateFiles(dir, searchPattern, searchOption));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add files from the current directory
|
||||||
|
foundFiles = foundFiles.Concat(Directory.EnumerateFiles(path, searchPattern).Select(f => (LongPath)f));
|
||||||
|
}
|
||||||
|
catch (UnauthorizedAccessException) { }
|
||||||
|
catch (PathTooLongException) { }
|
||||||
|
// Symbolic links will result in DirectoryNotFoundException. Ohter logical directories might also. Just skip them. Don't want to risk (or have to handle) infinite recursion
|
||||||
|
catch (DirectoryNotFoundException) { }
|
||||||
|
|
||||||
|
return foundFiles;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace FileManager
|
||||||
|
{
|
||||||
|
public class LongPath
|
||||||
|
{
|
||||||
|
//https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd
|
||||||
|
|
||||||
|
public const int MaxFilenameLength = 255;
|
||||||
|
public static readonly int MaxDirectoryLength;
|
||||||
|
public static readonly int MaxPathLength;
|
||||||
|
private const int WIN_MAX_PATH = 260;
|
||||||
|
private const string WIN_LONG_PATH_PREFIX = @"\\?\";
|
||||||
|
internal static readonly bool IsWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
|
||||||
|
internal static readonly bool IsLinux = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
|
||||||
|
internal static readonly bool IsOSX = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
|
||||||
|
|
||||||
|
public string Path { get; }
|
||||||
|
|
||||||
|
static LongPath()
|
||||||
|
{
|
||||||
|
if (IsWindows)
|
||||||
|
{
|
||||||
|
MaxPathLength = short.MaxValue;
|
||||||
|
MaxDirectoryLength = MaxPathLength - 13;
|
||||||
|
}
|
||||||
|
else if (IsOSX)
|
||||||
|
{
|
||||||
|
MaxPathLength = 1024;
|
||||||
|
MaxDirectoryLength = MaxPathLength - MaxFilenameLength;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
MaxPathLength = 4096;
|
||||||
|
MaxDirectoryLength = MaxPathLength - MaxFilenameLength;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private LongPath(string path)
|
||||||
|
{
|
||||||
|
if (IsWindows && path.Length > MaxPathLength)
|
||||||
|
throw new System.IO.PathTooLongException($"Path exceeds {MaxPathLength} character limit. ({path})");
|
||||||
|
if (!IsWindows && Encoding.UTF8.GetByteCount(path) > MaxPathLength)
|
||||||
|
throw new System.IO.PathTooLongException($"Path exceeds {MaxPathLength} byte limit. ({path})");
|
||||||
|
|
||||||
|
Path = path;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Filename limits on NTFS and FAT filesystems are based on characters,
|
||||||
|
//but on ext* filesystems they're based on bytes. The ext* filesystems
|
||||||
|
//don't care about encoding, so how unicode characters are encoded is
|
||||||
|
///a choice made by the linux kernel. As best as I can tell, pretty
|
||||||
|
//much everyone uses UTF-8.
|
||||||
|
public static int GetFilesystemStringLength(StringBuilder filename)
|
||||||
|
=> LongPath.IsWindows ?
|
||||||
|
filename.Length
|
||||||
|
: Encoding.UTF8.GetByteCount(filename.ToString());
|
||||||
|
|
||||||
|
public static implicit operator LongPath(string path)
|
||||||
|
{
|
||||||
|
if (!IsWindows) return new LongPath(path);
|
||||||
|
|
||||||
|
if (path is null) return null;
|
||||||
|
|
||||||
|
//File I/O functions in the Windows API convert "/" to "\" as part of converting
|
||||||
|
//the name to an NT-style name, except when using the "\\?\" prefix
|
||||||
|
path = path.Replace(System.IO.Path.AltDirectorySeparatorChar, System.IO.Path.DirectorySeparatorChar);
|
||||||
|
|
||||||
|
if (path.StartsWith(WIN_LONG_PATH_PREFIX))
|
||||||
|
return new LongPath(path);
|
||||||
|
else if ((path.Length > 2 && path[1] == ':') || path.StartsWith(@"UNC\"))
|
||||||
|
return new LongPath(WIN_LONG_PATH_PREFIX + path);
|
||||||
|
else if (path.StartsWith(@"\\"))
|
||||||
|
//The "\\?\" prefix can also be used with paths constructed according to the
|
||||||
|
//universal naming convention (UNC). To specify such a path using UNC, use
|
||||||
|
//the "\\?\UNC\" prefix.
|
||||||
|
return new LongPath(WIN_LONG_PATH_PREFIX + @"UNC\" + path.Substring(2));
|
||||||
|
else
|
||||||
|
{
|
||||||
|
//These prefixes are not used as part of the path itself. They indicate that
|
||||||
|
//the path should be passed to the system with minimal modification, which
|
||||||
|
//means that you cannot use forward slashes to represent path separators, or
|
||||||
|
//a period to represent the current directory, or double dots to represent the
|
||||||
|
//parent directory. Because you cannot use the "\\?\" prefix with a relative
|
||||||
|
//path, relative paths are always limited to a total of MAX_PATH characters.
|
||||||
|
if (path.Length > WIN_MAX_PATH)
|
||||||
|
throw new System.IO.PathTooLongException();
|
||||||
|
return new LongPath(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static implicit operator string(LongPath path) => path?.Path;
|
||||||
|
|
||||||
|
[JsonIgnore]
|
||||||
|
public string ShortPathName
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (!IsWindows) return Path;
|
||||||
|
|
||||||
|
//Short Path names are useful for navigating to the file in windows explorer,
|
||||||
|
//which will not recognize paths longer than MAX_PATH. Short path names are not
|
||||||
|
//always enabled on every volume. So to check if a volume enables short path
|
||||||
|
//names (aka 8dot3 names), run the following command from an elevated command
|
||||||
|
//prompt:
|
||||||
|
//
|
||||||
|
// fsutil 8dot3name query c:
|
||||||
|
//
|
||||||
|
//It will say:
|
||||||
|
//
|
||||||
|
// "Based on the above settings, 8dot3 name creation is [enabled/disabled] on c:"
|
||||||
|
//
|
||||||
|
//To enable short names on a volume on the system, run the following command
|
||||||
|
//from an elevated command prompt:
|
||||||
|
//
|
||||||
|
// fsutil 8dot3name set c: 0
|
||||||
|
//
|
||||||
|
//or for all volumes on the system:
|
||||||
|
//
|
||||||
|
// fsutil 8dot3name set 0
|
||||||
|
//
|
||||||
|
//Note that after enabling 8dot3 names on a volume, they will only be available
|
||||||
|
//for newly-created entries in ther file system. Existing entries made while
|
||||||
|
//8dot3 names were disabled will not be reachable by short paths.
|
||||||
|
|
||||||
|
if (Path is null) return null;
|
||||||
|
|
||||||
|
StringBuilder shortPathBuffer = new(MaxPathLength);
|
||||||
|
GetShortPathName(Path, shortPathBuffer, MaxPathLength);
|
||||||
|
return shortPathBuffer.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonIgnore]
|
||||||
|
public string LongPathName
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (!IsWindows) return Path;
|
||||||
|
if (Path is null) return null;
|
||||||
|
|
||||||
|
StringBuilder longPathBuffer = new(MaxPathLength);
|
||||||
|
GetLongPathName(Path, longPathBuffer, MaxPathLength);
|
||||||
|
return longPathBuffer.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonIgnore]
|
||||||
|
public string PathWithoutPrefix
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (!IsWindows) return Path;
|
||||||
|
return
|
||||||
|
Path?.StartsWith(WIN_LONG_PATH_PREFIX) == true ? Path.Remove(0, WIN_LONG_PATH_PREFIX.Length)
|
||||||
|
:Path;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString() => Path;
|
||||||
|
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||||
|
private static extern int GetShortPathName([MarshalAs(UnmanagedType.LPWStr)] string path, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder shortPath, int shortPathLength);
|
||||||
|
|
||||||
|
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||||
|
private static extern int GetLongPathName([MarshalAs(UnmanagedType.LPWStr)] string lpszShortPath, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpszLongPath, int cchBuffer);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace FileManager
|
||||||
|
{
|
||||||
|
public class MetadataNamingTemplate : NamingTemplate
|
||||||
|
{
|
||||||
|
public MetadataNamingTemplate(string template) : base(template) { }
|
||||||
|
|
||||||
|
public string GetTagContents()
|
||||||
|
{
|
||||||
|
var tagValue = Template;
|
||||||
|
|
||||||
|
foreach (var r in ParameterReplacements)
|
||||||
|
tagValue = tagValue.Replace($"<{formatKey(r.Key)}>", r.Value?.ToString() ?? "");
|
||||||
|
|
||||||
|
return tagValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using Dinah.Core;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace FileManager
|
||||||
|
{
|
||||||
|
public class NamingTemplate
|
||||||
|
{
|
||||||
|
/// <summary>Proposed full name. May contain optional html-styled template tags. Eg: <name></summary>
|
||||||
|
public string Template { get; }
|
||||||
|
|
||||||
|
/// <param name="template">Proposed file name with optional html-styled template tags.</param>
|
||||||
|
public NamingTemplate(string template) => Template = ArgumentValidator.EnsureNotNullOrWhiteSpace(template, nameof(template));
|
||||||
|
|
||||||
|
/// <summary>Optional step 1: Replace html-styled template tags with parameters. Eg {"name", "Bill Gates"} => /<name>/ => /Bill Gates/</summary>
|
||||||
|
public Dictionary<string, object> ParameterReplacements { get; } = new Dictionary<string, object>();
|
||||||
|
|
||||||
|
/// <summary>Convenience method</summary>
|
||||||
|
public void AddParameterReplacement(string key, object value)
|
||||||
|
// using .Add() instead of "[key] = value" will make unintended overwriting throw exception
|
||||||
|
=> ParameterReplacements.Add(key, value);
|
||||||
|
|
||||||
|
protected static string formatKey(string key)
|
||||||
|
=> key
|
||||||
|
.Replace("<", "")
|
||||||
|
.Replace(">", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -49,10 +49,22 @@ namespace FileManager
|
|||||||
public T GetNonString<T>(string propertyName)
|
public T GetNonString<T>(string propertyName)
|
||||||
{
|
{
|
||||||
var obj = GetObject(propertyName);
|
var obj = GetObject(propertyName);
|
||||||
|
|
||||||
if (obj is null) return default;
|
if (obj is null) return default;
|
||||||
if (obj is JValue jValue) return jValue.Value<T>();
|
if (obj.GetType().IsAssignableTo(typeof(T))) return (T)obj;
|
||||||
if (obj is JObject jObject) return jObject.ToObject<T>();
|
if (obj is JObject jObject) return jObject.ToObject<T>();
|
||||||
return (T)obj;
|
if (obj is JValue jValue)
|
||||||
|
{
|
||||||
|
if (jValue.Type == JTokenType.String && typeof(T).IsAssignableTo(typeof(Enum)))
|
||||||
|
{
|
||||||
|
return
|
||||||
|
Enum.TryParse(typeof(T), jValue.Value<string>(), out var enumVal)
|
||||||
|
? (T)enumVal
|
||||||
|
: Enum.GetValues(typeof(T)).Cast<T>().First();
|
||||||
|
}
|
||||||
|
return jValue.Value<T>();
|
||||||
|
}
|
||||||
|
throw new InvalidCastException($"{obj.GetType()} is not convertible to {typeof(T)}");
|
||||||
}
|
}
|
||||||
|
|
||||||
public object GetObject(string propertyName)
|
public object GetObject(string propertyName)
|
||||||
@@ -179,6 +191,7 @@ namespace FileManager
|
|||||||
}
|
}
|
||||||
catch (Exception exDebug)
|
catch (Exception exDebug)
|
||||||
{
|
{
|
||||||
|
Serilog.Log.Logger.Debug(exDebug, "Silent failure");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,343 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace FileManager
|
||||||
|
{
|
||||||
|
public record Replacement
|
||||||
|
{
|
||||||
|
public const int FIXED_COUNT = 6;
|
||||||
|
|
||||||
|
internal const char QUOTE_MARK = '"';
|
||||||
|
[JsonIgnore] public bool Mandatory { get; set; }
|
||||||
|
[JsonProperty] public char CharacterToReplace { get; private set; }
|
||||||
|
[JsonProperty] public string ReplacementString { get; private set; }
|
||||||
|
[JsonProperty] public string Description { get; set; }
|
||||||
|
public override string ToString() => $"{CharacterToReplace} → {ReplacementString} ({Description})";
|
||||||
|
|
||||||
|
public Replacement(char charToReplace, string replacementString, string description)
|
||||||
|
{
|
||||||
|
CharacterToReplace = charToReplace;
|
||||||
|
ReplacementString = replacementString;
|
||||||
|
Description = description;
|
||||||
|
}
|
||||||
|
private Replacement(char charToReplace, string replacementString, string description, bool mandatory)
|
||||||
|
: this(charToReplace, replacementString, description)
|
||||||
|
{
|
||||||
|
Mandatory = mandatory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Update(char charToReplace, string replacementString, string description)
|
||||||
|
{
|
||||||
|
ReplacementString = replacementString;
|
||||||
|
|
||||||
|
if (!Mandatory)
|
||||||
|
{
|
||||||
|
CharacterToReplace = charToReplace;
|
||||||
|
Description = description;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Replacement OtherInvalid(string replacement) => new(default, replacement, "All other invalid characters", true);
|
||||||
|
public static Replacement FilenameForwardSlash(string replacement) => new('/', replacement, "Forward Slash (Filename Only)", true);
|
||||||
|
public static Replacement FilenameBackSlash(string replacement) => new('\\', replacement, "Back Slash (Filename Only)", true);
|
||||||
|
public static Replacement OpenQuote(string replacement) => new('"', replacement, "Open Quote", true);
|
||||||
|
public static Replacement CloseQuote(string replacement) => new('"', replacement, "Close Quote", true);
|
||||||
|
public static Replacement OtherQuote(string replacement) => new('"', replacement, "Other Quote", true);
|
||||||
|
public static Replacement Colon(string replacement) => new(':', replacement, "Colon");
|
||||||
|
public static Replacement Asterisk(string replacement) => new('*', replacement, "Asterisk");
|
||||||
|
public static Replacement QuestionMark(string replacement) => new('?', replacement, "Question Mark");
|
||||||
|
public static Replacement OpenAngleBracket(string replacement) => new('<', replacement, "Open Angle Bracket");
|
||||||
|
public static Replacement CloseAngleBracket(string replacement) => new('>', replacement, "Close Angle Bracket");
|
||||||
|
public static Replacement Pipe(string replacement) => new('|', replacement, "Vertical Line");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonConverter(typeof(ReplacementCharactersConverter))]
|
||||||
|
public class ReplacementCharacters
|
||||||
|
{
|
||||||
|
public override bool Equals(object obj)
|
||||||
|
{
|
||||||
|
if (obj is ReplacementCharacters second && Replacements.Count == second.Replacements.Count)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < Replacements.Count; i++)
|
||||||
|
if (Replacements[i] != second.Replacements[i])
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
public override int GetHashCode() => Replacements.GetHashCode();
|
||||||
|
|
||||||
|
public static readonly ReplacementCharacters Default
|
||||||
|
= IsWindows
|
||||||
|
? new()
|
||||||
|
{
|
||||||
|
Replacements = new Replacement[]
|
||||||
|
{
|
||||||
|
Replacement.OtherInvalid("_"),
|
||||||
|
Replacement.FilenameForwardSlash("∕"),
|
||||||
|
Replacement.FilenameBackSlash(""),
|
||||||
|
Replacement.OpenQuote("“"),
|
||||||
|
Replacement.CloseQuote("”"),
|
||||||
|
Replacement.OtherQuote("""),
|
||||||
|
Replacement.OpenAngleBracket("<"),
|
||||||
|
Replacement.CloseAngleBracket(">"),
|
||||||
|
Replacement.Colon("꞉"),
|
||||||
|
Replacement.Asterisk("✱"),
|
||||||
|
Replacement.QuestionMark("?"),
|
||||||
|
Replacement.Pipe("⏐"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: new()
|
||||||
|
{
|
||||||
|
Replacements = new Replacement[]
|
||||||
|
{
|
||||||
|
Replacement.OtherInvalid("_"),
|
||||||
|
Replacement.FilenameForwardSlash("∕"),
|
||||||
|
Replacement.FilenameBackSlash("\\"),
|
||||||
|
Replacement.OpenQuote("“"),
|
||||||
|
Replacement.CloseQuote("”"),
|
||||||
|
Replacement.OtherQuote("\"")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
public static readonly ReplacementCharacters LoFiDefault
|
||||||
|
= IsWindows
|
||||||
|
? new()
|
||||||
|
{
|
||||||
|
Replacements = new Replacement[]
|
||||||
|
{
|
||||||
|
Replacement.OtherInvalid("_"),
|
||||||
|
Replacement.FilenameForwardSlash("_"),
|
||||||
|
Replacement.FilenameBackSlash("_"),
|
||||||
|
Replacement.OpenQuote("'"),
|
||||||
|
Replacement.CloseQuote("'"),
|
||||||
|
Replacement.OtherQuote("'"),
|
||||||
|
Replacement.OpenAngleBracket("{"),
|
||||||
|
Replacement.CloseAngleBracket("}"),
|
||||||
|
Replacement.Colon("-"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: new ()
|
||||||
|
{
|
||||||
|
Replacements = new Replacement[]
|
||||||
|
{
|
||||||
|
Replacement.OtherInvalid("_"),
|
||||||
|
Replacement.FilenameForwardSlash("_"),
|
||||||
|
Replacement.FilenameBackSlash("\\"),
|
||||||
|
Replacement.OpenQuote("\""),
|
||||||
|
Replacement.CloseQuote("\""),
|
||||||
|
Replacement.OtherQuote("\"")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
public static readonly ReplacementCharacters Barebones
|
||||||
|
= IsWindows
|
||||||
|
? new ()
|
||||||
|
{
|
||||||
|
Replacements = new Replacement[]
|
||||||
|
{
|
||||||
|
Replacement.OtherInvalid("_"),
|
||||||
|
Replacement.FilenameForwardSlash("_"),
|
||||||
|
Replacement.FilenameBackSlash("_"),
|
||||||
|
Replacement.OpenQuote("_"),
|
||||||
|
Replacement.CloseQuote("_"),
|
||||||
|
Replacement.OtherQuote("_")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: new ()
|
||||||
|
{
|
||||||
|
Replacements = new Replacement[]
|
||||||
|
{
|
||||||
|
Replacement.OtherInvalid("_"),
|
||||||
|
Replacement.FilenameForwardSlash("_"),
|
||||||
|
Replacement.FilenameBackSlash("\\"),
|
||||||
|
Replacement.OpenQuote("\""),
|
||||||
|
Replacement.CloseQuote("\""),
|
||||||
|
Replacement.OtherQuote("\"")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
private static bool IsWindows => Environment.OSVersion.Platform is PlatformID.Win32NT;
|
||||||
|
|
||||||
|
private static readonly char[] invalidPathChars = Path.GetInvalidFileNameChars().Except(new[] {
|
||||||
|
Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar
|
||||||
|
}).ToArray();
|
||||||
|
|
||||||
|
private static readonly char[] invalidSlashes = Path.GetInvalidFileNameChars().Intersect(new[] {
|
||||||
|
Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar
|
||||||
|
}).ToArray();
|
||||||
|
|
||||||
|
public IReadOnlyList<Replacement> Replacements { get; init; }
|
||||||
|
private string DefaultReplacement => Replacements[0].ReplacementString;
|
||||||
|
private Replacement ForwardSlash => Replacements[1];
|
||||||
|
private Replacement BackSlash => Replacements[2];
|
||||||
|
private string OpenQuote => Replacements[3].ReplacementString;
|
||||||
|
private string CloseQuote => Replacements[4].ReplacementString;
|
||||||
|
private string OtherQuote => Replacements[5].ReplacementString;
|
||||||
|
|
||||||
|
private string GetFilenameCharReplacement(char toReplace, char preceding, char succeding)
|
||||||
|
{
|
||||||
|
if (toReplace == ForwardSlash.CharacterToReplace)
|
||||||
|
return ForwardSlash.ReplacementString;
|
||||||
|
else if (toReplace == BackSlash.CharacterToReplace)
|
||||||
|
return BackSlash.ReplacementString;
|
||||||
|
else return GetPathCharReplacement(toReplace, preceding, succeding);
|
||||||
|
}
|
||||||
|
private string GetPathCharReplacement(char toReplace, char preceding, char succeding)
|
||||||
|
{
|
||||||
|
if (toReplace == Replacement.QUOTE_MARK)
|
||||||
|
{
|
||||||
|
if (
|
||||||
|
preceding == default ||
|
||||||
|
(
|
||||||
|
!char.IsLetter(preceding) &&
|
||||||
|
!char.IsNumber(preceding) &&
|
||||||
|
(char.IsLetter(succeding) || char.IsNumber(succeding))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return OpenQuote;
|
||||||
|
else if (
|
||||||
|
succeding == default ||
|
||||||
|
(
|
||||||
|
!char.IsLetter(succeding) &&
|
||||||
|
!char.IsNumber(succeding) &&
|
||||||
|
(char.IsLetter(preceding) || char.IsNumber(preceding))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return CloseQuote;
|
||||||
|
else
|
||||||
|
return OtherQuote;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!IsWindows && toReplace == BackSlash.CharacterToReplace)
|
||||||
|
return BackSlash.ReplacementString;
|
||||||
|
|
||||||
|
//Replace any other non-mandatory characters
|
||||||
|
for (int i = Replacement.FIXED_COUNT; i < Replacements.Count; i++)
|
||||||
|
{
|
||||||
|
var r = Replacements[i];
|
||||||
|
if (r.CharacterToReplace == toReplace)
|
||||||
|
return r.ReplacementString;
|
||||||
|
}
|
||||||
|
return DefaultReplacement;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool ContainsInvalidPathChar(string path)
|
||||||
|
=> path.Any(c => invalidPathChars.Contains(c));
|
||||||
|
public static bool ContainsInvalidFilenameChar(string path)
|
||||||
|
=> ContainsInvalidPathChar(path) || path.Any(c => invalidSlashes.Contains(c));
|
||||||
|
|
||||||
|
public string ReplaceFilenameChars(string fileName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(fileName)) return string.Empty;
|
||||||
|
var builder = new System.Text.StringBuilder();
|
||||||
|
for (var i = 0; i < fileName.Length; i++)
|
||||||
|
{
|
||||||
|
var c = fileName[i];
|
||||||
|
|
||||||
|
if (invalidPathChars.Contains(c)
|
||||||
|
|| invalidSlashes.Contains(c)
|
||||||
|
|| Replacements.Any(r => r.CharacterToReplace == c) /* Replace any other legal characters that they user wants. */ )
|
||||||
|
{
|
||||||
|
char preceding = i > 0 ? fileName[i - 1] : default;
|
||||||
|
char succeeding = i < fileName.Length - 1 ? fileName[i + 1] : default;
|
||||||
|
builder.Append(GetFilenameCharReplacement(c, preceding, succeeding));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
builder.Append(c);
|
||||||
|
}
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public string ReplacePathChars(string pathStr)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(pathStr)) return string.Empty;
|
||||||
|
|
||||||
|
var builder = new System.Text.StringBuilder();
|
||||||
|
for (var i = 0; i < pathStr.Length; i++)
|
||||||
|
{
|
||||||
|
var c = pathStr[i];
|
||||||
|
|
||||||
|
if (
|
||||||
|
(
|
||||||
|
invalidPathChars.Contains(c)
|
||||||
|
|| ( // Replace any other legal characters that they user wants.
|
||||||
|
c != Path.DirectorySeparatorChar
|
||||||
|
&& c != Path.AltDirectorySeparatorChar
|
||||||
|
&& Replacements.Any(r => r.CharacterToReplace == c)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
&& !( // replace all colons except drive letter designator on Windows
|
||||||
|
c == ':'
|
||||||
|
&& i == 1
|
||||||
|
&& Path.IsPathRooted(pathStr)
|
||||||
|
&& IsWindows
|
||||||
|
)
|
||||||
|
)
|
||||||
|
{
|
||||||
|
char preceding = i > 0 ? pathStr[i - 1] : default;
|
||||||
|
char succeeding = i < pathStr.Length - 1 ? pathStr[i + 1] : default;
|
||||||
|
builder.Append(GetPathCharReplacement(c, preceding, succeeding));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
builder.Append(c);
|
||||||
|
}
|
||||||
|
return builder.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#region JSON Converter
|
||||||
|
internal class ReplacementCharactersConverter : JsonConverter
|
||||||
|
{
|
||||||
|
public override bool CanConvert(Type objectType)
|
||||||
|
=> objectType == typeof(ReplacementCharacters);
|
||||||
|
|
||||||
|
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
||||||
|
{
|
||||||
|
var jObj = JObject.Load(reader);
|
||||||
|
var replaceArr = jObj[nameof(Replacement)];
|
||||||
|
IReadOnlyList<Replacement> dict = replaceArr
|
||||||
|
.ToObject<Replacement[]>().ToList();
|
||||||
|
|
||||||
|
//Ensure that the first 6 replacements are for the expected chars and that all replacement strings are valid.
|
||||||
|
//If not, reset to default.
|
||||||
|
|
||||||
|
for (int i = 0; i < Replacement.FIXED_COUNT; i++)
|
||||||
|
{
|
||||||
|
if (dict.Count < Replacement.FIXED_COUNT
|
||||||
|
|| dict[i].CharacterToReplace != ReplacementCharacters.Barebones.Replacements[i].CharacterToReplace
|
||||||
|
|| dict[i].Description != ReplacementCharacters.Barebones.Replacements[i].Description)
|
||||||
|
{
|
||||||
|
dict = ReplacementCharacters.Default.Replacements;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
//First FIXED_COUNT are mandatory
|
||||||
|
dict[i].Mandatory = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ReplacementCharacters { Replacements = dict };
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
||||||
|
{
|
||||||
|
ReplacementCharacters replacements = (ReplacementCharacters)value;
|
||||||
|
|
||||||
|
var propertyNames = replacements.Replacements
|
||||||
|
.Select(JObject.FromObject).ToList();
|
||||||
|
|
||||||
|
var prop = new JProperty(nameof(Replacement), new JArray(propertyNames));
|
||||||
|
|
||||||
|
var obj = new JObject();
|
||||||
|
obj.AddFirst(prop);
|
||||||
|
obj.WriteTo(writer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<Application xmlns="https://github.com/avaloniaui"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
xmlns:local="using:HangoverAvalonia"
|
||||||
|
x:Class="HangoverAvalonia.App">
|
||||||
|
<Application.DataTemplates>
|
||||||
|
<local:ViewLocator/>
|
||||||
|
</Application.DataTemplates>
|
||||||
|
|
||||||
|
<Application.Styles>
|
||||||
|
<FluentTheme Mode="Light"/>
|
||||||
|
</Application.Styles>
|
||||||
|
</Application>
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
using Avalonia;
|
||||||
|
using Avalonia.Controls.ApplicationLifetimes;
|
||||||
|
using Avalonia.Markup.Xaml;
|
||||||
|
using HangoverAvalonia.ViewModels;
|
||||||
|
using HangoverAvalonia.Views;
|
||||||
|
|
||||||
|
namespace HangoverAvalonia
|
||||||
|
{
|
||||||
|
public partial class App : Application
|
||||||
|
{
|
||||||
|
public override void Initialize()
|
||||||
|
{
|
||||||
|
AvaloniaXamlLoader.Load(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnFrameworkInitializationCompleted()
|
||||||
|
{
|
||||||
|
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||||
|
{
|
||||||
|
var mainWindow = new MainWindow
|
||||||
|
{
|
||||||
|
DataContext = new MainVM(),
|
||||||
|
};
|
||||||
|
desktop.MainWindow = mainWindow;
|
||||||
|
mainWindow.OnLoad();
|
||||||
|
}
|
||||||
|
|
||||||
|
base.OnFrameworkInitializationCompleted();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 133 KiB |
@@ -0,0 +1,30 @@
|
|||||||
|
<UserControl xmlns="https://github.com/avaloniaui"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||||
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
|
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
|
||||||
|
x:Class="HangoverAvalonia.Controls.CheckedListBox">
|
||||||
|
|
||||||
|
<UserControl.Resources>
|
||||||
|
<RecyclePool x:Key="RecyclePool" />
|
||||||
|
<DataTemplate x:Key="queuedBook">
|
||||||
|
<CheckBox HorizontalAlignment="Stretch" Margin="10,0,0,0" Content="{Binding Item}" IsChecked="{Binding IsChecked, Mode=TwoWay}" />
|
||||||
|
</DataTemplate>
|
||||||
|
<RecyclingElementFactory x:Key="elementFactory" RecyclePool="{StaticResource RecyclePool}">
|
||||||
|
<RecyclingElementFactory.Templates>
|
||||||
|
<StaticResource x:Key="queuedBook" ResourceKey="queuedBook" />
|
||||||
|
</RecyclingElementFactory.Templates>
|
||||||
|
</RecyclingElementFactory>
|
||||||
|
</UserControl.Resources>
|
||||||
|
|
||||||
|
<ScrollViewer
|
||||||
|
Name="scroller"
|
||||||
|
HorizontalScrollBarVisibility="Disabled"
|
||||||
|
VerticalScrollBarVisibility="Auto">
|
||||||
|
<ItemsRepeater IsVisible="True"
|
||||||
|
VerticalCacheLength="1.2"
|
||||||
|
HorizontalCacheLength="1"
|
||||||
|
Items="{Binding CheckboxItems}"
|
||||||
|
ItemTemplate="{StaticResource elementFactory}" />
|
||||||
|
</ScrollViewer>
|
||||||
|
</UserControl>
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
using Avalonia;
|
||||||
|
using Avalonia.Collections;
|
||||||
|
using Avalonia.Controls;
|
||||||
|
using HangoverAvalonia.ViewModels;
|
||||||
|
using ReactiveUI;
|
||||||
|
using System;
|
||||||
|
using System.Collections;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.ComponentModel;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace HangoverAvalonia.Controls
|
||||||
|
{
|
||||||
|
public partial class CheckedListBox : UserControl
|
||||||
|
{
|
||||||
|
public event EventHandler<ItemCheckEventArgs> ItemCheck;
|
||||||
|
|
||||||
|
public static readonly StyledProperty<IEnumerable> ItemsProperty =
|
||||||
|
AvaloniaProperty.Register<CheckedListBox, IEnumerable>(nameof(Items));
|
||||||
|
|
||||||
|
public IEnumerable Items { get => GetValue(ItemsProperty); set => SetValue(ItemsProperty, value); }
|
||||||
|
private CheckedListBoxViewModel _viewModel = new();
|
||||||
|
|
||||||
|
public IEnumerable<object> CheckedItems =>
|
||||||
|
_viewModel
|
||||||
|
.CheckboxItems
|
||||||
|
.Where(i => i.IsChecked)
|
||||||
|
.Select(i => i.Item);
|
||||||
|
|
||||||
|
public void SetItemChecked(int i, bool isChecked) => _viewModel.CheckboxItems[i].IsChecked = isChecked;
|
||||||
|
public void SetItemChecked(object item, bool isChecked)
|
||||||
|
{
|
||||||
|
var obj = _viewModel.CheckboxItems.SingleOrDefault(i => i.Item == item);
|
||||||
|
if (obj is not null)
|
||||||
|
obj.IsChecked = isChecked;
|
||||||
|
}
|
||||||
|
|
||||||
|
public CheckedListBox()
|
||||||
|
{
|
||||||
|
InitializeComponent();
|
||||||
|
scroller.DataContext = _viewModel;
|
||||||
|
_viewModel.CheckedChanged += _viewModel_CheckedChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void _viewModel_CheckedChanged(object sender, CheckBoxViewModel e)
|
||||||
|
{
|
||||||
|
var args = new ItemCheckEventArgs { Item = e.Item, ItemIndex = _viewModel.CheckboxItems.IndexOf(e), IsChecked = e.IsChecked };
|
||||||
|
ItemCheck?.Invoke(this, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
|
||||||
|
{
|
||||||
|
if (change.Property.Name == nameof(Items) && Items != null)
|
||||||
|
_viewModel.SetItems(Items);
|
||||||
|
base.OnPropertyChanged(change);
|
||||||
|
}
|
||||||
|
|
||||||
|
public class CheckedListBoxViewModel : ViewModelBase
|
||||||
|
{
|
||||||
|
public event EventHandler<CheckBoxViewModel> CheckedChanged;
|
||||||
|
public AvaloniaList<CheckBoxViewModel> CheckboxItems { get; private set; }
|
||||||
|
|
||||||
|
public void SetItems(IEnumerable items)
|
||||||
|
{
|
||||||
|
UnsubscribeFromItems(CheckboxItems);
|
||||||
|
CheckboxItems = new(items.OfType<object>().Select(o => new CheckBoxViewModel { Item = o }));
|
||||||
|
SubscribeToItems(CheckboxItems);
|
||||||
|
this.RaisePropertyChanged(nameof(CheckboxItems));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubscribeToItems(IEnumerable objects)
|
||||||
|
{
|
||||||
|
foreach (var i in objects.OfType<INotifyPropertyChanged>())
|
||||||
|
i.PropertyChanged += I_PropertyChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UnsubscribeFromItems(AvaloniaList<CheckBoxViewModel> objects)
|
||||||
|
{
|
||||||
|
if (objects is null) return;
|
||||||
|
|
||||||
|
foreach (var i in objects)
|
||||||
|
i.PropertyChanged -= I_PropertyChanged;
|
||||||
|
}
|
||||||
|
private void I_PropertyChanged(object sender, PropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
CheckedChanged?.Invoke(this, (CheckBoxViewModel)sender);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public class CheckBoxViewModel : ViewModelBase
|
||||||
|
{
|
||||||
|
private bool _isChecked;
|
||||||
|
public bool IsChecked { get => _isChecked; set => this.RaiseAndSetIfChanged(ref _isChecked, value); }
|
||||||
|
private object _bookText;
|
||||||
|
public object Item { get => _bookText; set => this.RaiseAndSetIfChanged(ref _bookText, value); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ItemCheckEventArgs : EventArgs
|
||||||
|
{
|
||||||
|
public int ItemIndex { get; init; }
|
||||||
|
public bool IsChecked { get; init; }
|
||||||
|
public object Item { get; init; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>WinExe</OutputType>
|
||||||
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
|
<!--Avalonia doesen't support TrimMode=link currently,but we are working on that https://github.com/AvaloniaUI/Avalonia/issues/6892 -->
|
||||||
|
<TrimMode>copyused</TrimMode>
|
||||||
|
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
||||||
|
<IsPublishable>true</IsPublishable>
|
||||||
|
<AssemblyName>Hangover</AssemblyName>
|
||||||
|
<PublishReadyToRun>true</PublishReadyToRun>
|
||||||
|
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
|
||||||
|
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
|
||||||
|
<StartupObject />
|
||||||
|
<IsPublishable>true</IsPublishable>
|
||||||
|
|
||||||
|
<PublishReadyToRun>true</PublishReadyToRun>
|
||||||
|
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
|
||||||
|
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
|
||||||
|
|
||||||
|
<ApplicationIcon>hangover.ico</ApplicationIcon>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<!--
|
||||||
|
HACK FOR COMPILER BUG 2021-09-14. Hopefully will be fixed in future versions
|
||||||
|
- Not using SatelliteResourceLanguages will load all language packs: works
|
||||||
|
- Specifying 'en' semicolon 1 more should load 1 language pack: works
|
||||||
|
- Specifying only 'en' should load no language packs: broken, still loads all
|
||||||
|
-->
|
||||||
|
<SatelliteResourceLanguages>en;es</SatelliteResourceLanguages>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
|
<OutputPath>..\bin\Avalonia\Debug</OutputPath>
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||||
|
<OutputPath>..\bin\Avalonia\Release</OutputPath>
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<AvaloniaResource Include="Assets\**" />
|
||||||
|
<AvaloniaXaml Remove="Models\**" />
|
||||||
|
<Compile Remove="Models\**" />
|
||||||
|
<EmbeddedResource Remove="Models\**" />
|
||||||
|
<None Remove="Models\**" />
|
||||||
|
<None Remove=".gitignore" />
|
||||||
|
<None Remove="Assets\hangover.ico" />
|
||||||
|
<None Remove="hangover.ico" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Update="ViewModels\MainVM.*.cs">
|
||||||
|
<DependentUpon>MainVM.cs</DependentUpon>
|
||||||
|
</Compile>
|
||||||
|
<Compile Update="Views\MainWindow.*.cs">
|
||||||
|
<DependentUpon>MainWindow.axaml</DependentUpon>
|
||||||
|
</Compile>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<AvaloniaResource Include="hangover.ico" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<!--This helps with theme dll-s trimming.
|
||||||
|
If you will publish your application in self-contained mode with p:PublishTrimmed=true and it will use Fluent theme Default theme will be trimmed from the output and vice versa.
|
||||||
|
https://github.com/AvaloniaUI/Avalonia/issues/5593 -->
|
||||||
|
<TrimmableAssembly Include="Avalonia.Themes.Fluent" />
|
||||||
|
<TrimmableAssembly Include="Avalonia.Themes.Default" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
|
||||||
|
<PackageReference Include="Avalonia" Version="11.0.0-preview4" />
|
||||||
|
<PackageReference Include="Avalonia.Desktop" Version="11.0.0-preview4" />
|
||||||
|
<!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
|
||||||
|
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.0.0-preview4" />
|
||||||
|
<PackageReference Include="Avalonia.ReactiveUI" Version="11.0.0-preview4" />
|
||||||
|
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.0.0-preview4" />
|
||||||
|
<PackageReference Include="XamlNameReferenceGenerator" Version="1.5.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\HangoverBase\HangoverBase.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
|
||||||
|
<Target Name="SpicNSpan" AfterTargets="Clean">
|
||||||
|
<!-- Remove obj folder -->
|
||||||
|
<RemoveDir Directories="$(BaseIntermediateOutputPath)" />
|
||||||
|
<!-- Remove bin folder -->
|
||||||
|
<RemoveDir Directories="$(BaseOutputPath)" />
|
||||||
|
</Target>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
using Avalonia;
|
||||||
|
using Avalonia.ReactiveUI;
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace HangoverAvalonia
|
||||||
|
{
|
||||||
|
internal class Program
|
||||||
|
{
|
||||||
|
// Initialization code. Don't use any Avalonia, third-party APIs or any
|
||||||
|
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
|
||||||
|
// yet and stuff might break.
|
||||||
|
[STAThread]
|
||||||
|
public static void Main(string[] args) => BuildAvaloniaApp()
|
||||||
|
.StartWithClassicDesktopLifetime(args);
|
||||||
|
|
||||||
|
// Avalonia configuration, don't remove; also used by visual designer.
|
||||||
|
public static AppBuilder BuildAvaloniaApp()
|
||||||
|
=> AppBuilder.Configure<App>()
|
||||||
|
.UsePlatformDetect()
|
||||||
|
.LogToTrace()
|
||||||
|
.UseReactiveUI();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!--
|
||||||
|
https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||||
|
-->
|
||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<Configuration>Release</Configuration>
|
||||||
|
<Platform>Any CPU</Platform>
|
||||||
|
<PublishDir>..\bin\Publish\Linux-chardonnay</PublishDir>
|
||||||
|
<PublishProtocol>FileSystem</PublishProtocol>
|
||||||
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
|
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
|
||||||
|
<SelfContained>true</SelfContained>
|
||||||
|
<PublishSingleFile>false</PublishSingleFile>
|
||||||
|
<PublishTrimmed>false</PublishTrimmed>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
||||||
Loaded 100 of 516 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user