mirror of
https://github.com/seanmorley15/AdventureLog.git
synced 2025-07-19 12:59:36 +02:00
Compare commits
758 commits
Author | SHA1 | Date | |
---|---|---|---|
|
4e96e529f4 | ||
|
cadea118d3 | ||
|
7a17e0e1d8 | ||
|
6516bc56ef | ||
|
a6b39f64d6 | ||
|
36f9022872 | ||
|
3b0ccdb6d3 | ||
|
9964398e25 | ||
|
df24316837 | ||
|
63e8e96d52 | ||
|
08cd3912c7 | ||
|
eef8c92e82 | ||
|
3306b799df | ||
|
8b108c5797 | ||
|
93a489a778 | ||
|
44ea7dff0c | ||
|
7ec4e5d0f5 | ||
|
380fe1364f | ||
|
69631848cf | ||
|
7f285f2b1d | ||
|
4f7d408460 | ||
|
aed76a5689 | ||
|
a556c49147 | ||
|
ea4b6bd715 | ||
|
2fb1548f9f | ||
|
be8ac67161 | ||
|
0636f0ec8c | ||
|
09ffb6cdff | ||
|
930c98a607 | ||
|
cee9345bf1 | ||
|
ced1f94473 | ||
|
da65235277 | ||
|
ab5082317e | ||
|
c2074c1581 | ||
|
977843cbc6 | ||
|
b0e8000cf8 | ||
|
b5931c6c23 | ||
|
151c76dbd1 | ||
|
d4c76f8718 | ||
|
badeac867d | ||
|
a99553ba0d | ||
|
14eb4ca802 | ||
|
7eb96bcc2a | ||
|
24cf3f844d | ||
|
c60ced09c4 | ||
|
05db98f968 | ||
|
3f9a6767bd | ||
|
f6b9802ba7 | ||
|
71ff217323 | ||
|
ef5dca79e5 | ||
|
d9070e68bb | ||
|
f72fb50eb0 | ||
|
b59dcade3b | ||
|
164627b35b | ||
|
3f89fad67f | ||
|
871e265001 | ||
|
2cab28e921 | ||
|
8a46bd7ed3 | ||
|
f36de76501 | ||
|
55f501d939 | ||
|
0037d037cf | ||
|
19baf6ab35 | ||
|
20cdc2405f | ||
|
297eb2916a | ||
|
27a27545ca | ||
|
06a5bb06b3 | ||
|
c0f2d060db | ||
|
2d7b6c85c9 | ||
|
5d0132a2a8 | ||
|
39c664ab1a | ||
|
d91a4fbe98 | ||
|
90624664f4 | ||
|
5f9d0cd207 | ||
|
36a2e59d52 | ||
|
af5be0bc8f | ||
|
16840a6040 | ||
|
ebee6f52e8 | ||
|
9d817a5ce9 | ||
|
6fdfb86297 | ||
|
c0c91c8472 | ||
|
d6ab4e9f64 | ||
|
4f342425ab | ||
|
6c338b8c0f | ||
|
2f7103f5f3 | ||
|
d0c1ecd394 | ||
|
cf108ecd3a | ||
|
50a80a8116 | ||
|
442a7724a0 | ||
|
b336a24401 | ||
|
45e195a84e | ||
|
937db00226 | ||
|
0838a41156 | ||
|
06787bccf6 | ||
|
f95afdc35c | ||
|
c159e176b3 | ||
|
b50447b1a2 | ||
|
92f9bf6908 | ||
|
48df9ee56d | ||
|
64bfda6bf0 | ||
|
8f1c60a440 | ||
|
806efd71bf | ||
|
e89f2a947e | ||
|
724aec1f3a | ||
|
514ee85767 | ||
|
53d370297e | ||
|
ae16c12251 | ||
|
4e8024051c | ||
|
9d69935f22 | ||
|
787ac4a8b3 | ||
|
81006af027 | ||
|
3acfc9f228 | ||
|
8be723b9ad | ||
|
a7128756bd | ||
|
d41d46f15d | ||
|
0adfdfa62f | ||
|
fa52af8ad1 | ||
|
6be4acb196 | ||
|
9df0338c3d | ||
|
069bcfb58a | ||
|
1551fba9ab | ||
|
56b8b55b84 | ||
|
57aa2c9916 | ||
|
37866660d3 | ||
|
d34a9001c0 | ||
|
bcd1f02131 | ||
|
f2246921d4 | ||
|
575669aedf | ||
|
9eaaadc0f2 | ||
|
3f6aa67b3f | ||
|
5e6d5305cc | ||
|
4fb25f63fd | ||
|
40f54529a4 | ||
|
7707ac7769 | ||
|
b25bf4af27 | ||
|
f355ba48e2 | ||
|
e56335d30f | ||
|
c123231bab | ||
|
9e304f81fe | ||
|
1997f164b8 | ||
|
c0b9013576 | ||
|
ce9faa28f8 | ||
|
68ba3c4b4d | ||
|
042d034594 | ||
|
ec2b285d50 | ||
|
03c76adc6d | ||
|
4404064263 | ||
|
7fddca6fb0 | ||
|
809cf98169 | ||
|
d3d74f9f35 | ||
|
e856a57498 | ||
|
0d5792a99a | ||
|
2ccb8f5e0b | ||
|
0d800e8986 | ||
|
3d9f4545a1 | ||
|
0a7db8985d | ||
|
c828f86570 | ||
|
a1062e72cf | ||
|
84cd136401 | ||
|
ac32f9ac5b | ||
|
d52e302e9b | ||
|
14e71626f6 | ||
|
f96b6f5f65 | ||
|
5dfe39468a | ||
|
a991f54d0a | ||
|
274dafc47d | ||
|
5f19670ed9 | ||
|
bd9f3fc494 | ||
|
d87d0e807f | ||
|
8b41a0f5a4 | ||
|
9435ccfa5a | ||
|
890332f4b6 | ||
|
049c229799 | ||
|
f15d7bfd1e | ||
|
7c3c139e61 | ||
|
1ff116ed00 | ||
|
b0e8c025fc | ||
|
feeb682e14 | ||
|
6de737bbf8 | ||
|
6ca674ff7e | ||
|
908d31a4a3 | ||
|
4af80eb584 | ||
|
d9d754a87c | ||
|
abc2d86dcf | ||
|
330fabb3e0 | ||
|
8538aa0b7c | ||
|
c9fa1d55f7 | ||
|
ab189c8aff | ||
|
1323d91e32 | ||
|
b30d6df964 | ||
|
89c4f1058a | ||
|
13bc748d0d | ||
|
c6177c5a05 | ||
|
e9c333642f | ||
|
07c0c36ab8 | ||
|
b712d10d7e | ||
|
a5e44d29e6 | ||
|
a91018d792 | ||
|
9f86688fe9 | ||
|
4ce7ed7045 | ||
|
b74fe90512 | ||
|
73c664e549 | ||
|
5e1f17fe2e | ||
|
f3f75368df | ||
|
ab12a2e7d8 | ||
|
cbb8c6283b | ||
|
0af0218a34 | ||
|
04f9227ae6 | ||
|
3caebd37dd | ||
|
311e2847cb | ||
|
2c50ca0b1a | ||
|
bbad7b890c | ||
|
5c109bbbaf | ||
|
c93d4865ce | ||
|
8d0490fd81 | ||
|
77be046f19 | ||
|
827b150965 | ||
|
7442bd70cd | ||
|
645cc9728b | ||
|
d99ca18e1c | ||
|
39104b3fef | ||
|
5bdadd0f88 | ||
|
f1f1cda799 | ||
|
f31db982ce | ||
|
f6097a2d60 | ||
|
5f7bf52758 | ||
|
911ce67d9f | ||
|
932036bc8b | ||
|
cd494fefee | ||
|
5136122ed9 | ||
|
e40ea028d0 | ||
|
56bbbb0ffb | ||
|
228f79dbc3 | ||
|
e44c153f9b | ||
|
3a8776c000 | ||
|
b8aa96b5b3 | ||
|
be0e56728a | ||
|
85b4db87ec | ||
|
c12f94855d | ||
|
6942f5e1bb | ||
|
7499722867 | ||
|
1ea4022e80 | ||
|
a8502884dc | ||
|
b29461f29d | ||
|
983a038420 | ||
|
233d2be63f | ||
|
64377c0300 | ||
|
0f36f34bfb | ||
|
ea85c5fc5a | ||
|
9a825e56e4 | ||
|
9043ee9565 | ||
|
a11400fa98 | ||
|
44a260b5b6 | ||
|
49f7bf27e8 | ||
|
dd01ada61e | ||
|
a974c8c275 | ||
|
988cdc12e6 | ||
|
548d43b563 | ||
|
23426012af | ||
|
2b031f51ac | ||
|
d7496df100 | ||
|
6f489b2734 | ||
|
a09b3f379f | ||
|
937c3c6a68 | ||
|
43b8275fc1 | ||
|
3b5240dffe | ||
|
d2933854ff | ||
|
0ce101594f | ||
|
b166058d36 | ||
|
15d34c88dc | ||
|
af2778ff61 | ||
|
2982a4044d | ||
|
658764fb58 | ||
|
847193a0ae | ||
|
8531855f46 | ||
|
af8a9acbae | ||
|
8041f67ba1 | ||
|
cd833884e8 | ||
|
47c219affd | ||
|
cde293c4bd | ||
|
04c3402e14 | ||
|
b4c5e22662 | ||
|
7d5750049b | ||
|
16a7772003 | ||
|
731b7e9db1 | ||
|
ca4ef79837 | ||
|
13d3b24ec2 | ||
|
113d41ca30 | ||
|
b71109fd09 | ||
|
a3cd940065 | ||
|
6eebd5b70a | ||
|
44ede92b92 | ||
|
fe25f8e2c8 | ||
|
794df82ec6 | ||
|
db63b6e7d8 | ||
|
4ccfa6e42c | ||
|
f79b06f6b3 | ||
|
1042a3edcc | ||
|
771579ef3d | ||
|
dbd417ca87 | ||
|
6e1fbbfc3a | ||
|
76ee4c73e0 | ||
|
c402dff9a7 | ||
|
f554bb8777 | ||
|
876c5e83b4 | ||
|
1dc8e10758 | ||
|
9fd2a142cb | ||
|
6eb57d1d6e | ||
|
6f720a154f | ||
|
585f050a30 | ||
|
3b6d437f29 | ||
|
b82e4b6f0d | ||
|
4e543fad55 | ||
|
eb541225bd | ||
|
a38828eb45 | ||
|
9adf1d158a | ||
|
ea61b5e67a | ||
|
189cd0ee69 | ||
|
c2fc249c92 | ||
|
a640934370 | ||
|
7fbcf170d0 | ||
|
d26d3a2128 | ||
|
50a732b4d7 | ||
|
d9a88b644f | ||
|
b7d6d6af56 | ||
|
4db72d9719 | ||
|
eaab1f8a7c | ||
|
ed76c1426e | ||
|
a16df1640d | ||
|
fee6c66eab | ||
|
6d3b4c1e8e | ||
|
4759ff71a1 | ||
|
7a63e1227f | ||
|
689d2af21c | ||
|
3e0639e6f7 | ||
|
3c9aec4bfb | ||
|
b1068d27b0 | ||
|
d5311bb71e | ||
|
00e4ec64ae | ||
|
b61083f7df | ||
|
d80805a181 | ||
|
ea36b104b6 | ||
|
232e01bf8f | ||
|
1c15e85986 | ||
|
7cea432353 | ||
|
a7513d6c06 | ||
|
b4496508dd | ||
|
2713b3640f | ||
|
670e499d8f | ||
|
16fc9bc70e | ||
|
577eb9cceb | ||
|
af33acec66 | ||
|
00f0fc9acf | ||
|
d31b95289d | ||
|
b5d6788c11 | ||
|
9e5e2456fa | ||
|
60b5bbb3c8 | ||
|
299b190f69 | ||
|
cf4691beaf | ||
|
68924d7ecc | ||
|
1351f26ba0 | ||
|
57db1e088f | ||
|
cbcf2a70d7 | ||
|
d4f9abd158 | ||
|
a899579a02 | ||
|
d2cb862103 | ||
|
d1f50dfa17 | ||
|
271cba9abc | ||
|
921e756aef | ||
|
f7ff8f30b0 | ||
|
9b54af8d40 | ||
|
5f344cad83 | ||
|
a00d2abe0d | ||
|
e93909e7ea | ||
|
8ea8043beb | ||
|
9c3a52ae85 | ||
|
ad5fb02ebb | ||
|
ed1e24252c | ||
|
df60184f23 | ||
|
da9c2ba80a | ||
|
5b42e8b372 | ||
|
28b2a918e8 | ||
|
4da34032e9 | ||
|
dc169d1046 | ||
|
659c56f02d | ||
|
bdb17a3177 | ||
|
7d71c84fd2 | ||
|
c1807826d0 | ||
|
341de6daea | ||
|
9cdd502264 | ||
|
cc6a98d23b | ||
|
94fca45af0 | ||
|
c7d34f6c48 | ||
|
08bfeac837 | ||
|
aaacacbd60 | ||
|
bc08362a4c | ||
|
85b55660f9 | ||
|
6d80969fdc | ||
|
defd97fc02 | ||
|
afdc894f23 | ||
|
41cc47d631 | ||
|
145627b1eb | ||
|
896c537791 | ||
|
b68e2dedaa | ||
|
db077b5fd7 | ||
|
697851e210 | ||
|
3468e82b04 | ||
|
680a2378d9 | ||
|
f5dc0ceb0a | ||
|
d326d38329 | ||
|
6a5bfbda2d | ||
|
37fca9ba1d | ||
|
abaee8c9c4 | ||
|
6b090096d6 | ||
|
8fef53fd24 | ||
|
8fee537d8b | ||
|
69967b759f | ||
|
f04a6e30a7 | ||
|
9e66c67c62 | ||
|
12a6429812 | ||
|
0eb4bc706a | ||
|
6ea0e07775 | ||
|
d5fe7eeff8 | ||
|
1447a948c2 | ||
|
10230e926c | ||
|
3f30819d25 | ||
|
6e28e5234e | ||
|
1b3cf6ab39 | ||
|
f9cf92041d | ||
|
64d2bdebce | ||
|
30c58ca118 | ||
|
25edec460b | ||
|
1f3abf7f32 | ||
|
94c3e3d363 | ||
|
a88e59869e | ||
|
3ccd078508 | ||
|
e9538b707f | ||
|
e0fa62c1ea | ||
|
aa216f5688 | ||
|
433599dc20 | ||
|
f7e183f9a3 | ||
|
f10e171a8e | ||
|
d60945d5b7 | ||
|
9132ef39ec | ||
|
8f6e655378 | ||
|
1a7643b8a7 | ||
|
fcec4a420c | ||
|
75162bbf7b | ||
|
ae8617a9fb | ||
|
8af53f8f01 | ||
|
a508dd8d96 | ||
|
8f1f2e139a | ||
|
e9084db832 | ||
|
6289c7e305 | ||
|
0cee4c386d | ||
|
f4450b6a38 | ||
|
5b4092ba6c | ||
|
2b78021155 | ||
|
9ceee13edc | ||
|
f56abd2312 | ||
|
62efa2478e | ||
|
0588555707 | ||
|
bcbe7657ad | ||
|
5f1a611671 | ||
|
21345e0971 | ||
|
b4c9cd1f27 | ||
|
92a52d65f2 | ||
|
2c1b540c20 | ||
|
743774dbca | ||
|
5cce76274a | ||
|
16cdda2b82 | ||
|
611509a289 | ||
|
af4026300b | ||
|
ab2ad829f2 | ||
|
ce87afeeb9 | ||
|
5965b82780 | ||
|
4a1e51e12a | ||
|
7be21fcace | ||
|
c084a40cab | ||
|
b16b1a1e44 | ||
|
69673fb5ef | ||
|
b023078e04 | ||
|
f6605bc1bf | ||
|
e8f2c7ea81 | ||
|
187f4c0a4f | ||
|
ef44836328 | ||
|
96ff727b57 | ||
|
a8e84be28e | ||
|
4c84ac0979 | ||
|
62d2fd7c6a | ||
|
609f68b10d | ||
|
4a36fbb4c1 | ||
|
145a3f00c5 | ||
|
062111d7fe | ||
|
ec3ada986d | ||
|
a010afcc43 | ||
|
563373dd54 | ||
|
a766a07ea1 | ||
|
f27453824a | ||
|
ac37bc98c4 | ||
|
53d500b7d5 | ||
|
9a7667fd62 | ||
|
7f2c3c33a5 | ||
|
6252f3cf14 | ||
|
6413b9a985 | ||
|
3b5b5d83b9 | ||
|
0f828dd0bf | ||
|
32125efed4 | ||
|
1f7d75acfc | ||
|
30f1eaef1c | ||
|
af1d43ddf3 | ||
|
b04a8b8a9e | ||
|
fa60db1d93 | ||
|
e8f3674101 | ||
|
cd06f838b0 | ||
|
377420226e | ||
|
5cccadad15 | ||
|
3bde752234 | ||
|
2cd60adc8c | ||
|
2221b1dad9 | ||
|
88d62eb869 | ||
|
76ee4a7290 | ||
|
a50f051079 | ||
|
ef996cd302 | ||
|
ae3c43f7c8 | ||
|
b1a3379604 | ||
|
1e48152e1a | ||
|
de8764499b | ||
|
013a2cc751 | ||
|
22790ae7c0 | ||
|
abe870506f | ||
|
80cec30fda | ||
|
44810e6343 | ||
|
a883d4104d | ||
|
f670fbc93a | ||
|
548702890d | ||
|
a5aa09ed7b | ||
|
e19781d7ac | ||
|
59b41c01df | ||
|
128c33d9a1 | ||
|
a9c2af9649 | ||
|
4fdc16da58 | ||
|
604cfa05b3 | ||
|
3d22621a26 | ||
|
9e4846a66a | ||
|
a4df852744 | ||
|
56244329f5 | ||
|
230a786d6e | ||
|
259f2e75c2 | ||
|
82a1134019 | ||
|
50e0d4a34e | ||
|
3a024e1e18 | ||
|
57e367d112 | ||
|
6651557738 | ||
|
c6fa603a93 | ||
|
991efa8d08 | ||
|
73036dcef8 | ||
|
eea87e59a5 | ||
|
386014db92 | ||
|
81b60d6021 | ||
|
cee9f16cf5 | ||
|
5d12d103fc | ||
|
67f6af8ca3 | ||
|
15fd15ba40 | ||
|
dc89743569 | ||
|
66ce80226e | ||
|
79db20a903 | ||
|
d5ff2fc6b7 | ||
|
fd7f285c57 | ||
|
b5ac66a1cc | ||
|
bc6cf42b8e | ||
|
8716efb613 | ||
|
7cf634def8 | ||
|
697c40fca0 | ||
|
5d3ec181a0 | ||
|
46e3e91679 | ||
|
8f7551f4be | ||
|
df2ce01910 | ||
|
f7c998ab58 | ||
|
c3782cc9d7 | ||
|
c11395cbd6 | ||
|
c9dd5fe33d | ||
|
d6eb4edddd | ||
|
c3fddb1889 | ||
|
7c68dc839a | ||
|
57f2bdb8ba | ||
|
dd08a6fe24 | ||
|
4de6fa675f | ||
|
7d609d01ea | ||
|
e0296543b6 | ||
|
edc5fdf1cc | ||
|
f3c3e19d51 | ||
|
54c859b2a8 | ||
|
6cf17ce56e | ||
|
c77b3573d4 | ||
|
febbdfa252 | ||
|
148568fca4 | ||
|
10dbafd1ee | ||
|
c966b73eba | ||
|
0c27f4b8a4 | ||
|
4839edde7b | ||
|
c0fd91ef8d | ||
|
0376709325 | ||
|
9bf0849b92 | ||
|
1b54f8ed69 | ||
|
7b7db1c530 | ||
|
673a56c6a0 | ||
|
54d7a1a229 | ||
|
2ccbf4be83 | ||
|
0272c6b076 | ||
|
f7742ca37d | ||
|
2f321517a6 | ||
|
57f3be0938 | ||
|
914028ea2f | ||
|
6a00a2ed55 | ||
|
91a51515dd | ||
|
56a4292f4f | ||
|
64105808b5 | ||
|
ca66b85838 | ||
|
d44cb06e31 | ||
|
f0603f7dbd | ||
|
0616fe19f3 | ||
|
a39e22b0a8 | ||
|
82040d5c85 | ||
|
88dbd41b92 | ||
|
21d8b376b3 | ||
|
dc29f48ab2 | ||
|
4ecad7f46d | ||
|
0a2b172405 | ||
|
6ba047d2a5 | ||
|
50dc0424a9 | ||
|
84566b8ec1 | ||
|
c65fcc2558 | ||
|
b86c7258e7 | ||
|
1f4a02467b | ||
|
aecb3ca70e | ||
|
2d24cb8aba | ||
|
0d9c063c58 | ||
|
f119e6fdc2 | ||
|
53dc57453c | ||
|
9bc20be70e | ||
|
bde2e6a82d | ||
|
7defdac3a8 | ||
|
0878008a05 | ||
|
0b08dfbab9 | ||
|
888bde042e | ||
|
335b5c2498 | ||
|
9f9e4fd12e | ||
|
30e2606a2f | ||
|
df0d49298f | ||
|
2ea3637c4b | ||
|
84c013fa11 | ||
|
f618c24a7b | ||
|
39991c1877 | ||
|
483c297af8 | ||
|
66713ea76d | ||
|
ec4935ecdd | ||
|
173c6183b3 | ||
|
f5a0f388b7 | ||
|
9d2f83d4b6 | ||
|
7a3ec33fa7 | ||
|
958e9de84e | ||
|
06f0b93dd5 | ||
|
734208d869 | ||
|
fd3c30f540 | ||
|
6963fd858e | ||
|
74ff1b0b7f | ||
|
4dbcd96581 | ||
|
def642960c | ||
|
d20de4aeed | ||
|
a0aae8c237 | ||
|
02f534662b | ||
|
477e76a0af | ||
|
f878167a36 | ||
|
adf45ff557 | ||
|
ce0b82acb7 | ||
|
17d8784d8c | ||
|
d7baf6961e | ||
|
b1ec7dc815 | ||
|
8e5a20ec62 | ||
|
736ede2417 | ||
|
a6630b7de2 | ||
|
9b28d9a315 | ||
|
86d213bb8b | ||
|
129c76078e | ||
|
42f07dc2fb | ||
|
ae92fc2027 | ||
|
4a7f720773 | ||
|
0ea948c62c | ||
|
c3f37b66d0 | ||
|
954c154add | ||
|
10a0963a1e | ||
|
f16a7f1e94 | ||
|
39fce5ace7 | ||
|
0a7704aade | ||
|
adb92a1d41 | ||
|
bde33260fa | ||
|
3dc193d098 | ||
|
742cb9dd94 | ||
|
6132b1c0d6 | ||
|
efd19da10b | ||
|
98e545be6f | ||
|
add691b678 | ||
|
b32c780266 | ||
|
c7207ccf52 | ||
|
bcba4f4425 | ||
|
2c3fb41e5c | ||
|
04b332e031 | ||
|
de45296dc1 | ||
|
c27bf4baba | ||
|
87928932c2 | ||
|
6eff9f6456 | ||
|
44c0ffc1d7 | ||
|
40cb5daa07 | ||
|
9c6e11b16d | ||
|
9ac4a8f4e9 | ||
|
7cd869a507 | ||
|
7988ba4d68 | ||
|
3df124b250 | ||
|
c0aaec1436 | ||
|
4bbbc10097 | ||
|
172f07acca | ||
|
6137411b84 | ||
|
07263c5697 | ||
|
e6c5bc9ca8 | ||
|
b60455b50a | ||
|
a7a49227c4 | ||
|
25ed72afbc | ||
|
727daf0cfd | ||
|
9d42dbac98 | ||
|
83d06fc0a4 | ||
|
05076a6732 | ||
|
fcd2d27221 | ||
|
5011829e6e | ||
|
4f40d0de63 | ||
|
8068fe93f7 | ||
|
91c0ec8c07 | ||
|
6cf62cfb82 | ||
|
6f8864a13d | ||
|
6daacabc1b | ||
|
ae70c96ddc | ||
|
5435208d3e | ||
|
f03c74cd74 | ||
|
de873c9eb5 | ||
|
ef3f2aee10 | ||
|
78ab387055 | ||
|
874a384477 | ||
|
075257c846 | ||
|
1e67de6e14 | ||
|
0a8ff18560 | ||
|
e22e175ae5 | ||
|
53cfd276f2 | ||
|
fdf4f07156 | ||
|
f34d533dc6 | ||
|
c084f348d9 | ||
|
792d9bcda2 | ||
|
a9b42439cc | ||
|
8175daf773 | ||
|
3a66a433ca |
417 changed files with 39930 additions and 272672 deletions
47
.env.example
Normal file
47
.env.example
Normal file
|
@ -0,0 +1,47 @@
|
|||
# 🌐 Frontend
|
||||
PUBLIC_SERVER_URL=http://server:8000 # PLEASE DON'T CHANGE :) - Should be the service name of the backend with port 8000, even if you change the port in the backend service. Only change if you are using a custom more complex setup.
|
||||
ORIGIN=http://localhost:8015
|
||||
BODY_SIZE_LIMIT=Infinity
|
||||
FRONTEND_PORT=8015
|
||||
|
||||
# 🐘 PostgreSQL Database
|
||||
PGHOST=db
|
||||
POSTGRES_DB=database
|
||||
POSTGRES_USER=adventure
|
||||
POSTGRES_PASSWORD=changeme123
|
||||
|
||||
# 🔒 Django Backend
|
||||
SECRET_KEY=changeme123
|
||||
DJANGO_ADMIN_USERNAME=admin
|
||||
DJANGO_ADMIN_PASSWORD=admin
|
||||
DJANGO_ADMIN_EMAIL=admin@example.com
|
||||
PUBLIC_URL=http://localhost:8016 # Match the outward port, used for the creation of image urls
|
||||
CSRF_TRUSTED_ORIGINS=http://localhost:8016,http://localhost:8015
|
||||
DEBUG=False
|
||||
FRONTEND_URL=http://localhost:8015 # Used for email generation. This should be the url of the frontend
|
||||
BACKEND_PORT=8016
|
||||
|
||||
# Optional: use Google Maps integration
|
||||
# https://adventurelog.app/docs/configuration/google_maps_integration.html
|
||||
# GOOGLE_MAPS_API_KEY=your_google_maps_api_key
|
||||
|
||||
# Optional: disable registration
|
||||
# https://adventurelog.app/docs/configuration/disable_registration.html
|
||||
DISABLE_REGISTRATION=False
|
||||
# DISABLE_REGISTRATION_MESSAGE=Registration is disabled for this instance of AdventureLog.
|
||||
|
||||
# Optional: Use email
|
||||
# https://adventurelog.app/docs/configuration/email.html
|
||||
# EMAIL_BACKEND=email
|
||||
# EMAIL_HOST=smtp.gmail.com
|
||||
# EMAIL_USE_TLS=True
|
||||
# EMAIL_PORT=587
|
||||
# EMAIL_USE_SSL=False
|
||||
# EMAIL_HOST_USER=user
|
||||
# EMAIL_HOST_PASSWORD=password
|
||||
# DEFAULT_FROM_EMAIL=user@example.com
|
||||
|
||||
# Optional: Use Umami for analytics
|
||||
# https://adventurelog.app/docs/configuration/analytics.html
|
||||
# PUBLIC_UMAMI_SRC=https://cloud.umami.is/script.js # If you are using the hosted version of Umami
|
||||
# PUBLIC_UMAMI_WEBSITE_ID=
|
16
.github/.docker-compose-database.yml
vendored
Normal file
16
.github/.docker-compose-database.yml
vendored
Normal file
|
@ -0,0 +1,16 @@
|
|||
services:
|
||||
db:
|
||||
image: postgis/postgis:15-3.3
|
||||
container_name: adventurelog-db
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "127.0.0.1:5432:5432"
|
||||
environment:
|
||||
POSTGRES_DB: database
|
||||
POSTGRES_USER: adventure
|
||||
POSTGRES_PASSWORD: changeme123
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data/
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
1
.github/CODEOWNERS
vendored
Normal file
1
.github/CODEOWNERS
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
* @seanmorley15
|
1
.github/FUNDING.yml
vendored
1
.github/FUNDING.yml
vendored
|
@ -1 +1,2 @@
|
|||
github: seanmorley15
|
||||
buy_me_a_coffee: seanmorley15
|
||||
|
|
2
.github/ISSUE_TEMPLATE/bug_report.md
vendored
2
.github/ISSUE_TEMPLATE/bug_report.md
vendored
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
name: Bug report
|
||||
about: "Detailed bug reports help me diagnose and fix bugs quicker! Thanks!"
|
||||
about: Detailed bug reports help me diagnose and fix bugs quicker! Thanks!
|
||||
title: "[BUG]"
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
|
15
.github/ISSUE_TEMPLATE/deployment-issue.md
vendored
Normal file
15
.github/ISSUE_TEMPLATE/deployment-issue.md
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
---
|
||||
name: Deployment Issue
|
||||
about: Request help deploying AdventureLog on your machine. The more details, the
|
||||
better I can help!
|
||||
title: "[DEPLOYMENT]"
|
||||
labels: deployment
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
## Explain your issue
|
||||
|
||||
## Provide an **obfuscated** `docker-compose.yml`
|
||||
|
||||
## Provide any necessary logs from the containers and browser
|
46
.github/workflows/backend-beta.yml
vendored
Normal file
46
.github/workflows/backend-beta.yml
vendored
Normal file
|
@ -0,0 +1,46 @@
|
|||
name: Upload beta backend image to GHCR and Docker Hub
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- development
|
||||
paths:
|
||||
- "backend/**"
|
||||
|
||||
env:
|
||||
IMAGE_NAME: "adventurelog-backend"
|
||||
|
||||
jobs:
|
||||
upload:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.ACCESS_TOKEN }}
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: set lower case owner name
|
||||
run: |
|
||||
echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV}
|
||||
env:
|
||||
OWNER: "${{ github.repository_owner }}"
|
||||
|
||||
- name: Build Docker images
|
||||
run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:beta -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:beta ./backend
|
64
.github/workflows/backend-test.yml
vendored
Normal file
64
.github/workflows/backend-test.yml
vendored
Normal file
|
@ -0,0 +1,64 @@
|
|||
name: Test Backend
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'backend/server/**'
|
||||
- '.github/workflows/backend-test.yml'
|
||||
push:
|
||||
paths:
|
||||
- 'backend/server/**'
|
||||
- '.github/workflows/backend-test.yml'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: set up python 3.12
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: install dependencies
|
||||
run: |
|
||||
sudo apt update -q
|
||||
sudo apt install -y -q \
|
||||
python3-gdal
|
||||
|
||||
- name: start database
|
||||
run: |
|
||||
docker compose -f .github/.docker-compose-database.yml up -d
|
||||
|
||||
- name: install python libreries
|
||||
working-directory: backend/server
|
||||
run: |
|
||||
pip install -r requirements.txt
|
||||
|
||||
- name: run server
|
||||
working-directory: backend/server
|
||||
env:
|
||||
PGHOST: "127.0.0.1"
|
||||
PGDATABASE: "database"
|
||||
PGUSER: "adventure"
|
||||
PGPASSWORD: "changeme123"
|
||||
SECRET_KEY: "changeme123"
|
||||
DJANGO_ADMIN_USERNAME: "admin"
|
||||
DJANGO_ADMIN_PASSWORD: "admin"
|
||||
DJANGO_ADMIN_EMAIL: "admin@example.com"
|
||||
PUBLIC_URL: "http://localhost:8000"
|
||||
CSRF_TRUSTED_ORIGINS: "http://localhost:5173,http://localhost:8000"
|
||||
DEBUG: "True"
|
||||
FRONTEND_URL: "http://localhost:5173"
|
||||
run: |
|
||||
python manage.py migrate
|
||||
python manage.py runserver &
|
||||
|
||||
- name: wait for backend to boot
|
||||
run: >
|
||||
curl -fisS --retry 60 --retry-delay 1 --retry-all-errors
|
||||
http://localhost:8000/
|
46
.github/workflows/cdn-beta.yml
vendored
Normal file
46
.github/workflows/cdn-beta.yml
vendored
Normal file
|
@ -0,0 +1,46 @@
|
|||
name: Upload beta CDN image to GHCR and Docker Hub
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- development
|
||||
paths:
|
||||
- "cdn/**"
|
||||
|
||||
env:
|
||||
IMAGE_NAME: "adventurelog-cdn"
|
||||
|
||||
jobs:
|
||||
upload:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.ACCESS_TOKEN }}
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: set lower case owner name
|
||||
run: |
|
||||
echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV}
|
||||
env:
|
||||
OWNER: "${{ github.repository_owner }}"
|
||||
|
||||
- name: Build Docker images
|
||||
run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:beta -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:beta ./cdn
|
46
.github/workflows/cdn-latest.yml
vendored
Normal file
46
.github/workflows/cdn-latest.yml
vendored
Normal file
|
@ -0,0 +1,46 @@
|
|||
name: Upload latest CDN image to GHCR and Docker Hub
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "cdn/**"
|
||||
|
||||
env:
|
||||
IMAGE_NAME: "adventurelog-cdn"
|
||||
|
||||
jobs:
|
||||
upload:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.ACCESS_TOKEN }}
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: set lower case owner name
|
||||
run: |
|
||||
echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV}
|
||||
env:
|
||||
OWNER: "${{ github.repository_owner }}"
|
||||
|
||||
- name: Build Docker images
|
||||
run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:latest -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:latest ./cdn
|
43
.github/workflows/cdn-release.yml
vendored
Normal file
43
.github/workflows/cdn-release.yml
vendored
Normal file
|
@ -0,0 +1,43 @@
|
|||
name: Upload the tagged release CDN image to GHCR and Docker Hub
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [released]
|
||||
|
||||
env:
|
||||
IMAGE_NAME: "adventurelog-cdn"
|
||||
|
||||
jobs:
|
||||
upload:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.ACCESS_TOKEN }}
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: set lower case owner name
|
||||
run: |
|
||||
echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV}
|
||||
env:
|
||||
OWNER: "${{ github.repository_owner }}"
|
||||
|
||||
- name: Build Docker images
|
||||
run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:${{ github.event.release.tag_name }} -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:${{ github.event.release.tag_name }} ./cdn
|
46
.github/workflows/frontend-beta.yml
vendored
Normal file
46
.github/workflows/frontend-beta.yml
vendored
Normal file
|
@ -0,0 +1,46 @@
|
|||
name: Upload beta frontend image to GHCR and Docker Hub
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- development
|
||||
paths:
|
||||
- "frontend/**"
|
||||
|
||||
env:
|
||||
IMAGE_NAME: "adventurelog-frontend"
|
||||
|
||||
jobs:
|
||||
upload:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.ACCESS_TOKEN }}
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: set lower case owner name
|
||||
run: |
|
||||
echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV}
|
||||
env:
|
||||
OWNER: "${{ github.repository_owner }}"
|
||||
|
||||
- name: Build Docker images
|
||||
run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:beta -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:beta ./frontend
|
32
.github/workflows/frontend-test.yml
vendored
Normal file
32
.github/workflows/frontend-test.yml
vendored
Normal file
|
@ -0,0 +1,32 @@
|
|||
name: Test Frontend
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "frontend/**"
|
||||
- ".github/workflows/frontend-test.yml"
|
||||
push:
|
||||
paths:
|
||||
- "frontend/**"
|
||||
- ".github/workflows/frontend-test.yml"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
|
||||
- name: install dependencies
|
||||
working-directory: frontend
|
||||
run: npm i
|
||||
|
||||
- name: build frontend
|
||||
working-directory: frontend
|
||||
run: npm run build
|
3
.gitignore
vendored
3
.gitignore
vendored
|
@ -1,2 +1,5 @@
|
|||
# Ignore everything in the .venv folder
|
||||
.venv/
|
||||
.vscode/settings.json
|
||||
.pnpm-store/
|
||||
.env
|
||||
|
|
6
.vscode/extensions.json
vendored
Normal file
6
.vscode/extensions.json
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"recommendations": [
|
||||
"lokalise.i18n-ally",
|
||||
"svelte.svelte-vscode"
|
||||
]
|
||||
}
|
39
.vscode/settings.json
vendored
39
.vscode/settings.json
vendored
|
@ -1,3 +1,40 @@
|
|||
{
|
||||
"git.ignoreLimitWarning": true
|
||||
"git.ignoreLimitWarning": true,
|
||||
"i18n-ally.localesPaths": [
|
||||
"frontend/src/locales",
|
||||
"backend/server/backend/lib/python3.12/site-packages/allauth/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/dj_rest_auth/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/rest_framework/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/rest_framework_simplejwt/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/django/conf/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/django/contrib/messages",
|
||||
"backend/server/backend/lib/python3.12/site-packages/allauth/templates/account/messages",
|
||||
"backend/server/backend/lib/python3.12/site-packages/allauth/templates/mfa/messages",
|
||||
"backend/server/backend/lib/python3.12/site-packages/allauth/templates/socialaccount/messages",
|
||||
"backend/server/backend/lib/python3.12/site-packages/allauth/templates/usersessions/messages",
|
||||
"backend/server/backend/lib/python3.12/site-packages/django/contrib/admindocs/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/django/contrib/auth/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/django/contrib/admin/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/django/contrib/contenttypes/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/django/contrib/flatpages/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/django/contrib/humanize/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/django/contrib/gis/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/django/contrib/redirects/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/django/contrib/postgres/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/django/contrib/sessions/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/django/contrib/sites/locale",
|
||||
"backend/server/backend/lib/python3.12/site-packages/rest_framework/templates/rest_framework/docs/langs"
|
||||
],
|
||||
"i18n-ally.keystyle": "nested",
|
||||
"i18n-ally.keysInUse": [
|
||||
"navbar.themes.dim",
|
||||
"navbar.themes.northernLights",
|
||||
"navbar.themes.aqua",
|
||||
"navbar.themes.aestheticDark",
|
||||
"navbar.themes.aestheticLight",
|
||||
"navbar.themes.forest",
|
||||
"navbar.themes.night",
|
||||
"navbar.themes.dark",
|
||||
"navbar.themes.light"
|
||||
]
|
||||
}
|
||||
|
|
|
@ -1,91 +1,50 @@
|
|||
# Contributing to AdventureLog
|
||||
|
||||
When contributing to this repository, please first discuss the change you wish to make via issue,
|
||||
email, or any other method with the owners of this repository before making a change.
|
||||
|
||||
Please note we have a code of conduct, please follow it in all your interactions with the project.
|
||||
We’re excited to have you contribute to AdventureLog! To ensure that this community remains welcoming and productive for all users and developers, please follow this simple Code of Conduct.
|
||||
|
||||
## Pull Request Process
|
||||
|
||||
1. Please make sure you create an issue first for your change so you can link any pull requests to this issue. There should be a clear relationship between pull requests and issues.
|
||||
2. Update the README.md with details of changes to the interface, this includes new environment
|
||||
variables, exposed ports, useful file locations and container parameters.
|
||||
3. Increase the version numbers in any examples files and the README.md to the new version that this
|
||||
Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/).
|
||||
4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you
|
||||
do not have permission to do that, you may request the second reviewer to merge it for you.
|
||||
1. **Open an Issue First**: Discuss any changes or features you plan to implement by opening an issue. This helps to clarify your idea and ensures there’s a shared understanding.
|
||||
2. **Document Changes**: If your changes impact the user interface, add new environment variables, or introduce new container configurations, make sure to update the documentation accordingly. The documentation is located in the `documentation` folder.
|
||||
3. **Pull Request**: Submit a pull request with your changes. Make sure to reference the issue you opened in the description.
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
### Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, gender identity and expression, level of experience,
|
||||
nationality, personal appearance, race, religion, or sexual identity and
|
||||
orientation.
|
||||
At AdventureLog, we are committed to creating a community that fosters adventure, exploration, and innovation. We encourage diverse participation and strive to maintain a space where everyone feels welcome to contribute, regardless of their background or experience level. We ask that you contribute with respect and kindness, making sure to prioritize collaboration and mutual growth.
|
||||
|
||||
### Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
In order to maintain a positive environment, we encourage the following behaviors:
|
||||
|
||||
- Using welcoming and inclusive language
|
||||
- Being respectful of differing viewpoints and experiences
|
||||
- Gracefully accepting constructive criticism
|
||||
- Focusing on what is best for the community
|
||||
- Showing empathy towards other community members
|
||||
- **Inclusivity**: Use welcoming and inclusive language that fosters collaboration across all perspectives and experiences.
|
||||
- **Respect**: Respect differing opinions and engage with empathy, understanding that each person’s perspective is valuable.
|
||||
- **Constructive Feedback**: Offer feedback that helps improve the project and allows contributors to grow from it.
|
||||
- **Adventure Spirit**: Bring the same sense of curiosity, discovery, and positivity that drives AdventureLog into all interactions with the community.
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
- The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
- Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
- Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
- Personal attacks, trolling, or any form of harassment.
|
||||
- Insensitive or discriminatory language, including sexualized comments or imagery.
|
||||
- Spamming or misusing project spaces for personal gain.
|
||||
- Publishing or using others’ private information without permission.
|
||||
- Anything else that could be seen as disrespectful or unprofessional in a collaborative environment.
|
||||
|
||||
### Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
As maintainers of AdventureLog, we are committed to enforcing this Code of Conduct and taking corrective action when necessary. This may involve moderating comments, pulling code, or banning users who engage in harmful behaviors.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
We strive to foster a community that balances open collaboration with respect for all contributors.
|
||||
|
||||
### Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
This Code of Conduct applies in all spaces related to AdventureLog. This includes our GitHub repository, discussions, documentation, social media accounts, and events—both online and in person.
|
||||
|
||||
### Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at [INSERT EMAIL ADDRESS]. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
If you experience or witness unacceptable behavior, please report it to the project team at `contact@adventurelog.app`. All reports will be confidential and handled swiftly. The maintainers will investigate the issue and take appropriate action as needed.
|
||||
|
||||
### Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at [http://contributor-covenant.org/version/1/4][version]
|
||||
|
||||
[homepage]: http://contributor-covenant.org
|
||||
[version]: http://contributor-covenant.org/version/1/4/
|
||||
This Code of Conduct is inspired by the [Contributor Covenant](http://contributor-covenant.org), version 1.4, and adapted to fit the unique spirit of AdventureLog.
|
||||
|
|
2
LICENSE
2
LICENSE
|
@ -1,5 +1,5 @@
|
|||
AdventureLog: Self-hostable travel tracker and trip planner.
|
||||
Copyright (C) 2024 Sean Morley
|
||||
Copyright (C) 2023-2025 Sean Morley
|
||||
Contact: contact@seanmorley.com
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
|
|
233
README.md
233
README.md
|
@ -1,161 +1,150 @@
|
|||
# AdventureLog: Embark, Explore, Remember. 🌍
|
||||
<div align="center">
|
||||
|
||||
### _"Never forget an adventure with AdventureLog - Your ultimate travel companion!"_
|
||||
<img src="brand/adventurelog.png" alt="logo" width="200" height="auto" />
|
||||
<h1>AdventureLog</h1>
|
||||
|
||||
[](https://www.buymeacoffee.com/seanmorley15)
|
||||
<p>
|
||||
The ultimate travel companion for the modern-day explorer.
|
||||
</p>
|
||||
|
||||
**Documentation can be found [here](https://docs.adventurelog.app).**
|
||||
<h4>
|
||||
<a href="https://demo.adventurelog.app">View Demo</a>
|
||||
<span> · </span>
|
||||
<a href="https://adventurelog.app">Documentation</a>
|
||||
<span> · </span>
|
||||
<a href="https://discord.gg/wRbQ9Egr8C">Discord</a>
|
||||
<span> · </span>
|
||||
<a href="https://buymeacoffee.com/seanmorley15">Support 💖</a>
|
||||
</h4>
|
||||
</div>
|
||||
|
||||
**Join the AdventureLog Community Discord Server [here](https://discord.gg/wRbQ9Egr8C).**
|
||||
<br />
|
||||
|
||||
<!-- Table of Contents -->
|
||||
|
||||
# Table of Contents
|
||||
|
||||
- [Installation](#installation)
|
||||
- [Docker 🐋](#docker-)
|
||||
- [Prerequisites](#prerequisites)
|
||||
- [Getting Started](#getting-started)
|
||||
- [Configuration](#configuration)
|
||||
- [Frontend Container (web)](#frontend-container-web)
|
||||
- [Backend Container (server)](#backend-container-server)
|
||||
- [Proxy Container (nginx) Configuration](#proxy-container-nginx-configuration)
|
||||
- [Running the Containers](#running-the-containers)
|
||||
- [Screenshots 🖼️](#screenshots)
|
||||
- [About AdventureLog](#about-adventurelog)
|
||||
- [Attribution](#attribution)
|
||||
- [About the Project](#-about-the-project)
|
||||
- [Screenshots](#-screenshots)
|
||||
- [Tech Stack](#-tech-stack)
|
||||
- [Features](#-features)
|
||||
- [Roadmap](#-roadmap)
|
||||
- [Contributing](#-contributing)
|
||||
- [License](#-license)
|
||||
- [Contact](#-contact)
|
||||
- [Acknowledgements](#-acknowledgements)
|
||||
|
||||
# Installation
|
||||
<!-- About the Project -->
|
||||
|
||||
# Docker 🐋
|
||||
## ⭐ About the Project
|
||||
|
||||
Docker is the preferred way to run AdventureLog on your local machine. It is a lightweight containerization technology that allows you to run applications in isolated environments called containers.
|
||||
**Note**: This guide mainly focuses on installation with a linux based host machine, but the steps are similar for other operating systems.
|
||||
Starting from a simple idea of tracking travel locations (called adventures), AdventureLog has grown into a full-fledged travel companion. With AdventureLog, you can log your adventures, keep track of where you've been on the world map, plan your next trip collaboratively, and share your experiences with friends and family.
|
||||
|
||||
## Prerequisites
|
||||
AdventureLog was created to solve a problem: the lack of a modern, open-source, user-friendly travel companion. Many existing travel apps are either too complex, too expensive, or too closed-off to be useful for the average traveler. AdventureLog aims to be the opposite: simple, beautiful, and open to everyone.
|
||||
|
||||
- Docker installed on your machine/server. You can learn how to download it [here](https://docs.docker.com/engine/install/).
|
||||
<!-- Screenshots -->
|
||||
|
||||
## Getting Started
|
||||
### 📷 Screenshots
|
||||
|
||||
Get the `docker-compose.yml` file from the AdventureLog repository. You can download it from [here](https://github.com/seanmorley15/AdventureLog/blob/main/docker-compose.yml) or run this command to download it directly to your machine:
|
||||
<div align="center">
|
||||
<img src="./brand/screenshots/adventures.png" alt="Adventures" />
|
||||
<p>Displays the adventures you have visited and the ones you plan to embark on. You can also filter and sort the adventures.</p>
|
||||
<img src="./brand/screenshots/details.png" alt="Adventure Details" />
|
||||
<p>Shows specific details about an adventure, including the name, date, location, description, and rating.</p>
|
||||
<img src="./brand/screenshots/edit.png" alt="Edit Modal" />
|
||||
<img src="./brand/screenshots/map.png" alt="Adventure Details" />
|
||||
<p>View all of your adventures on a map, with the ability to filter by visit status and add new ones by click on the map</p>
|
||||
<img src="./brand/screenshots/dashboard.png" alt="Dashboard" />
|
||||
<p>Displays a summary of your adventures, including your world travel stats.</p>
|
||||
<img src="./brand/screenshots/itinerary.png" alt="Itinerary" />
|
||||
<p>Plan your adventures and travel itinerary with a list of activities and a map view. View your trip in a variety of ways, including an itinerary list, a map view, and a calendar view.</p>
|
||||
<img src="./brand/screenshots/countries.png" alt="Countries" />
|
||||
<p>Lists all the countries you have visited and plan to visit, with the ability to filter by visit status.</p>
|
||||
<img src="./brand/screenshots/regions.png" alt="Regions" />
|
||||
<p>Displays the regions for a specific country, includes a map view to visually select regions.</p>
|
||||
</div>
|
||||
|
||||
```bash
|
||||
wget https://raw.githubusercontent.com/seanmorley15/AdventureLog/main/docker-compose.yml
|
||||
```
|
||||
<!-- TechStack -->
|
||||
|
||||
## Configuration
|
||||
### 🚀 Tech Stack
|
||||
|
||||
Here is a summary of the configuration options available in the `docker-compose.yml` file:
|
||||
<details>
|
||||
<summary>Client</summary>
|
||||
<ul>
|
||||
<li><a href="https://svelte.dev/">SvelteKit</a></li>
|
||||
<li><a href="https://tailwindcss.com/">TailwindCSS</a></li>
|
||||
<li><a href="https://daisyui.com/">DaisyUI</a></li>
|
||||
<li><a href="https://github.com/dimfeld/svelte-maplibre/">Svelte MapLibre</a></li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<!-- make a table with colum name, is required, other -->
|
||||
<details>
|
||||
<summary>Server</summary>
|
||||
<ul>
|
||||
<li><a href="https://www.djangoproject.com/">Django</a></li>
|
||||
<li><a href="https://postgis.net/">PostGIS</a></li>
|
||||
<li><a href="https://www.django-rest-framework.org/">Django REST Framework</a></li>
|
||||
<li><a href="https://allauth.org/">AllAuth</a></li>
|
||||
</ul>
|
||||
</details>
|
||||
<!-- Features -->
|
||||
|
||||
### Frontend Container (web)
|
||||
### 🎯 Features
|
||||
|
||||
| Name | Required | Description | Default Value |
|
||||
| ------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
|
||||
| `PUBLIC_SERVER_URL` | Yes | What the frontend SSR server uses to connect to the backend. | http://server:8000 |
|
||||
| `ORIGIN` | Sometimes | Not needed if using HTTPS. If not, set it to the domain of what you will acess the app from. | http://localhost:8080 |
|
||||
| `BODY_SIZE_LIMIT` | Yes | Used to set the maximum upload size to the server. Should be changed to prevent someone from uploading too much! Custom values must be set in **kiliobytes**. | Infinity |
|
||||
- **Track Your Adventures** 🌍: Log your adventures and keep track of where you've been on the world map.
|
||||
- Adventures can store a variety of information, including the location, date, and description.
|
||||
- Adventures can be sorted into custom categories for easy organization.
|
||||
- Adventures can be marked as private or public, allowing you to share your adventures with friends and family.
|
||||
- Keep track of the countries and regions you've visited with the world travel book.
|
||||
- **Plan Your Next Trip** 📃: Take the guesswork out of planning your next adventure with an easy-to-use itinerary planner.
|
||||
- Itineraries can be created for any number of days and can include multiple destinations.
|
||||
- Itineraries include many planning features like flight information, notes, checklists, and links to external resources.
|
||||
- Itineraries can be shared with friends and family for collaborative planning.
|
||||
- **Share Your Experiences** 📸: Share your adventures with friends and family and collaborate on trips together.
|
||||
- Adventures and itineraries can be shared via a public link or directly with other AdventureLog users.
|
||||
- Collaborators can view and edit shared itineraries (collections), making planning a breeze.
|
||||
|
||||
### Backend Container (server)
|
||||
<!-- Roadmap -->
|
||||
|
||||
| Name | Required | Description | Default Value |
|
||||
| ----------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
|
||||
| `PGHOST` | Yes | Databse host. | db |
|
||||
| `PGDATABASE` | Yes | Database. | database |
|
||||
| `PGUSER` | Yes | Database user. | adventure |
|
||||
| `PGPASSWORD` | Yes | Database password. | changeme123 |
|
||||
| `DJANGO_ADMIN_USERNAME` | Yes | Default username. | admin |
|
||||
| `DJANGO_ADMIN_PASSWORD` | Yes | Default password, change after inital login. | admin |
|
||||
| `DJANGO_ADMIN_EMAIL` | Yes | Default user's email. | admin@example.com |
|
||||
| `PUBLIC_URL` | Yes | This is the publically accessible url to the **nginx** container. You should be able to acess nginx from this url where you access your app. | http://127.0.0.1:81 |
|
||||
| `CSRF_TRUSTED_ORIGINS` | Yes | Need to be changed to the orgins where you use your backend server and frontend. These values are comma seperated. | Needs to be changed. |
|
||||
| `FRONTEND_URL` | Yes | This is the publically accessible url to the **frontend** container. This link should be accessable for all users. Used for email generation. | http://localhost:3000 |
|
||||
## 🧭 Roadmap
|
||||
|
||||
### Proxy Container (nginx) Configuration
|
||||
The AdventureLog Roadmap can be found [here](https://github.com/users/seanmorley15/projects/5)
|
||||
|
||||
In order to use media files in a production environment, you need to configure the `nginx` container to serve the media files. The container is already in the docker compose file but you need to do a few things to make it work.
|
||||
<!-- Contributing -->
|
||||
|
||||
1. Create a directory called `proxy` in the same directory as the `docker-compose.yml` file.
|
||||
2. Create a file called `nginx.conf` in the `proxy` directory.
|
||||
3. Add the following configuration to the `nginx.conf` file:
|
||||
## 👋 Contributing
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
<a href="https://github.com/seanmorley15/AdventureLog/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=seanmorley15/AdventureLog" />
|
||||
</a>
|
||||
|
||||
location /media/ {
|
||||
alias /app/media/;
|
||||
}
|
||||
}
|
||||
```
|
||||
Contributions are always welcome!
|
||||
|
||||
## Running the Containers
|
||||
See `contributing.md` for ways to get started.
|
||||
|
||||
To start the containers, run the following command:
|
||||
<!-- License -->
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
## 📃 License
|
||||
|
||||
Enjoy AdventureLog! 🎉
|
||||
Distributed under the GNU General Public License v3.0. See `LICENSE` for more information.
|
||||
|
||||
# Screenshots
|
||||
<!-- Contact -->
|
||||
|
||||

|
||||
Displaying the adventures you have visited and the ones you plan to embark on. You can also filter and sort the adventures.
|
||||
## 🤝 Contact
|
||||
|
||||

|
||||
Shows specific details about an adventure, including the name, date, location, description, and rating.
|
||||
Sean Morley - [website](https://seanmorley.com)
|
||||
|
||||

|
||||
Hi! I'm Sean, the creator of AdventureLog. I'm a college student and software developer with a passion for travel and adventure. I created AdventureLog to help people like me document their adventures and plan new ones effortlessly. As a student, I am always looking for more opportunities to learn and grow, so feel free to reach out via the contact on my website if you would like to collaborate or chat!
|
||||
|
||||

|
||||
View all of your adventures on a map, with the ability to filter by visit status and add new ones by click on the map.
|
||||
<!-- Acknowledgments -->
|
||||
|
||||

|
||||
## 💎 Acknowledgements
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
️
|
||||
|
||||
# About AdventureLog
|
||||
|
||||
AdventureLog is a Svelte Kit and Django application that utilizes a PostgreSQL database. Users can log the adventures they have experienced, as well as plan future ones. Key features include:
|
||||
|
||||
- Logging past adventures with fields like name, date, location, description, and rating.
|
||||
- Planning future adventures with similar fields.
|
||||
- Tagging different activity types for better organization.
|
||||
- Viewing countries, regions, and marking visited regions.
|
||||
|
||||
AdventureLog aims to be your ultimate travel companion, helping you document your adventures and plan new ones effortlessly.
|
||||
|
||||
AdventureLog is licensed under the GNU General Public License v3.0.
|
||||
|
||||
<!-- ## Screenshots 🖼️
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
## Roadmap 🛣️
|
||||
|
||||
- Improved mobile device support
|
||||
- Password reset functionality
|
||||
- Improved error handling
|
||||
- Handling of adventure cards with variable width -->
|
||||
|
||||
# Attribution
|
||||
|
||||
- Logo Design by [redtechtiger](https://github.com/redtechtiger)
|
||||
- Logo Design by [nordtektiger](https://github.com/nordtektiger)
|
||||
- WorldTravel Dataset [dr5hn/countries-states-cities-database](https://github.com/dr5hn/countries-states-cities-database)
|
||||
- [Mexico GEOJSON](https://cartographyvectors.com/map/784-mexico-with-states)
|
||||
- [Japan GEOJSON](https://cartographyvectors.com/map/361-japan)
|
||||
- [Ireland GEOJSON](https://cartographyvectors.com/map/1399-ireland-provinces)
|
||||
- [Sweden GEOJSON](https://cartographyvectors.com/map/1521-sweden-with-regions)
|
||||
- [Switzerland GEOJSON](https://cartographyvectors.com/map/1522-switzerland-with-regions)
|
||||
- [Iceland GEOJSON](https://cartographyvectors.com/map/1453-iceland-with-regions)
|
||||
- [Austria GEOJSON](https://github.com/codeforgermany/click_that_hood/blob/main/public/data/austria-states.geojson)
|
||||
|
||||
### Top Supporters 💖
|
||||
|
||||
- [Veymax](https://x.com/veymax)
|
||||
- [nebriv](https://github.com/nebriv)
|
||||
- [Victor Butler](https://x.com/victor_butler)
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
http://github.com/iMerica/dj-rest-auth/contributors
|
|
@ -1,33 +1,60 @@
|
|||
# Dockerfile
|
||||
# Use the official Python slim image as the base image
|
||||
FROM python:3.13-slim
|
||||
|
||||
FROM python:3.10-slim
|
||||
|
||||
LABEL Developers="Sean Morley"
|
||||
# Metadata labels for the AdventureLog image
|
||||
LABEL maintainer="Sean Morley" \
|
||||
version="v0.10.0" \
|
||||
description="AdventureLog — the ultimate self-hosted travel companion." \
|
||||
org.opencontainers.image.title="AdventureLog" \
|
||||
org.opencontainers.image.description="AdventureLog is a self-hosted travel companion that helps you plan, track, and share your adventures." \
|
||||
org.opencontainers.image.version="v0.10.0" \
|
||||
org.opencontainers.image.authors="Sean Morley" \
|
||||
org.opencontainers.image.url="https://raw.githubusercontent.com/seanmorley15/AdventureLog/refs/heads/main/brand/banner.png" \
|
||||
org.opencontainers.image.source="https://github.com/seanmorley15/AdventureLog" \
|
||||
org.opencontainers.image.vendor="Sean Morley" \
|
||||
org.opencontainers.image.created="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" \
|
||||
org.opencontainers.image.licenses="GPL-3.0"
|
||||
|
||||
# Set environment variables
|
||||
ENV PYTHONDONTWRITEBYTECODE 1
|
||||
ENV PYTHONUNBUFFERED 1
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
# Set the working directory
|
||||
WORKDIR /code
|
||||
|
||||
# Install system dependencies
|
||||
# Install system dependencies (Nginx included)
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y git postgresql-client gdal-bin libgdal-dev \
|
||||
&& apt-get clean
|
||||
&& apt-get install -y git postgresql-client gdal-bin libgdal-dev nginx supervisor \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python dependencies
|
||||
COPY ./server/requirements.txt /code/
|
||||
RUN pip install --upgrade pip
|
||||
RUN pip install -r requirements.txt
|
||||
RUN pip install --upgrade pip \
|
||||
&& pip install -r requirements.txt
|
||||
|
||||
# Create necessary directories
|
||||
RUN mkdir -p /code/static /code/media
|
||||
# RUN mkdir -p /code/staticfiles /code/media
|
||||
|
||||
# Copy the Django project code into the Docker image
|
||||
COPY ./server /code/
|
||||
|
||||
# Copy Nginx configuration
|
||||
COPY ./nginx.conf /etc/nginx/nginx.conf
|
||||
|
||||
# Copy Supervisor configuration
|
||||
COPY ./supervisord.conf /etc/supervisor/conf.d/supervisord.conf
|
||||
|
||||
# Collect static files
|
||||
RUN python3 manage.py collectstatic --noinput --verbosity 2
|
||||
|
||||
# Set the entrypoint script
|
||||
COPY ./entrypoint.sh /code/entrypoint.sh
|
||||
RUN chmod +x /code/entrypoint.sh
|
||||
ENTRYPOINT ["/code/entrypoint.sh"]
|
||||
|
||||
# Expose ports for NGINX and Gunicorn
|
||||
EXPOSE 80 8000
|
||||
|
||||
# Command to start Supervisor (which starts Nginx and Gunicorn)
|
||||
CMD ["supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
|
||||
|
|
|
@ -1,21 +0,0 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 iMerica https://github.com/iMerica/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
|
@ -1,5 +0,0 @@
|
|||
include AUTHORS
|
||||
include LICENSE
|
||||
include MANIFEST.in
|
||||
include README.md
|
||||
graft dj_rest_auth
|
|
@ -1,4 +0,0 @@
|
|||
# AdventureLog Django Backend
|
||||
A demo of a possible AdventureLog 2.0 version using Django as the backend with a REST API.
|
||||
|
||||
Based of django-rest-framework and dj-rest-auth.
|
|
@ -1,10 +1,32 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Function to check PostgreSQL availability
|
||||
check_postgres() {
|
||||
PGPASSWORD=$PGPASSWORD psql -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -c '\q' >/dev/null 2>&1
|
||||
# Helper to get the first non-empty environment variable
|
||||
get_env() {
|
||||
for var in "$@"; do
|
||||
value="${!var}"
|
||||
if [ -n "$value" ]; then
|
||||
echo "$value"
|
||||
return
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
check_postgres() {
|
||||
local db_host
|
||||
local db_user
|
||||
local db_name
|
||||
local db_pass
|
||||
|
||||
db_host=$(get_env PGHOST)
|
||||
db_user=$(get_env PGUSER POSTGRES_USER)
|
||||
db_name=$(get_env PGDATABASE POSTGRES_DB)
|
||||
db_pass=$(get_env PGPASSWORD POSTGRES_PASSWORD)
|
||||
|
||||
PGPASSWORD="$db_pass" psql -h "$db_host" -U "$db_user" -d "$db_name" -c '\q' >/dev/null 2>&1
|
||||
}
|
||||
|
||||
|
||||
# Wait for PostgreSQL to become available
|
||||
until check_postgres; do
|
||||
>&2 echo "PostgreSQL is unavailable - sleeping"
|
||||
|
@ -20,21 +42,50 @@ done
|
|||
python manage.py migrate
|
||||
|
||||
# Create superuser if environment variables are set and there are no users present at all.
|
||||
if [ -n "$DJANGO_ADMIN_USERNAME" ] && [ -n "$DJANGO_ADMIN_PASSWORD" ]; then
|
||||
if [ -n "$DJANGO_ADMIN_USERNAME" ] && [ -n "$DJANGO_ADMIN_PASSWORD" ] && [ -n "$DJANGO_ADMIN_EMAIL" ]; then
|
||||
echo "Creating superuser..."
|
||||
python manage.py shell << EOF
|
||||
from django.contrib.auth import get_user_model
|
||||
from allauth.account.models import EmailAddress
|
||||
|
||||
User = get_user_model()
|
||||
if User.objects.count() == 0:
|
||||
User.objects.create_superuser('$DJANGO_ADMIN_USERNAME', '$DJANGO_ADMIN_EMAIL', '$DJANGO_ADMIN_PASSWORD')
|
||||
|
||||
# Check if the user already exists
|
||||
if not User.objects.filter(username='$DJANGO_ADMIN_USERNAME').exists():
|
||||
# Create the superuser
|
||||
superuser = User.objects.create_superuser(
|
||||
username='$DJANGO_ADMIN_USERNAME',
|
||||
email='$DJANGO_ADMIN_EMAIL',
|
||||
password='$DJANGO_ADMIN_PASSWORD'
|
||||
)
|
||||
print("Superuser created successfully.")
|
||||
|
||||
# Create the EmailAddress object for AllAuth
|
||||
EmailAddress.objects.create(
|
||||
user=superuser,
|
||||
email='$DJANGO_ADMIN_EMAIL',
|
||||
verified=True,
|
||||
primary=True
|
||||
)
|
||||
print("EmailAddress object created successfully for AllAuth.")
|
||||
else:
|
||||
print("Superuser already exists.")
|
||||
EOF
|
||||
fi
|
||||
|
||||
|
||||
# Sync the countries and world travel regions
|
||||
# Sync the countries and world travel regions
|
||||
python manage.py download-countries
|
||||
if [ $? -eq 137 ]; then
|
||||
>&2 echo "WARNING: The download-countries command was interrupted. This is likely due to lack of memory allocated to the container or the host. Please try again with more memory."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Start Django server
|
||||
python manage.py runserver 0.0.0.0:8000
|
||||
cat /code/adventurelog.txt
|
||||
|
||||
# Start Gunicorn in foreground
|
||||
exec gunicorn main.wsgi:application \
|
||||
--bind [::]:8000 \
|
||||
--workers 2 \
|
||||
--timeout 120
|
||||
|
|
42
backend/nginx.conf
Normal file
42
backend/nginx.conf
Normal file
|
@ -0,0 +1,42 @@
|
|||
worker_processes 1;
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
sendfile on;
|
||||
keepalive_timeout 65;
|
||||
client_max_body_size 100M;
|
||||
# The backend is running in the same container, so reference localhost
|
||||
upstream django {
|
||||
server 127.0.0.1:8000; # Use localhost to point to Gunicorn running internally
|
||||
}
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
location / {
|
||||
proxy_pass http://django; # Forward to the upstream block
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
location /static/ {
|
||||
alias /code/staticfiles/; # Serve static files directly
|
||||
}
|
||||
# Serve protected media files with X-Accel-Redirect
|
||||
location /protectedMedia/ {
|
||||
internal; # Only internal requests are allowed
|
||||
alias /code/media/; # This should match Django MEDIA_ROOT
|
||||
try_files $uri =404; # Return a 404 if the file doesn't exist
|
||||
|
||||
# Security headers for all protected files
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'none'; object-src 'none'; base-uri 'none'" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header X-Frame-Options SAMEORIGIN always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -21,3 +21,16 @@ EMAIL_BACKEND='console'
|
|||
# EMAIL_HOST_USER='user'
|
||||
# EMAIL_HOST_PASSWORD='password'
|
||||
# DEFAULT_FROM_EMAIL='user@example.com'
|
||||
|
||||
# GOOGLE_MAPS_API_KEY='key'
|
||||
|
||||
|
||||
# ------------------- #
|
||||
# For Developers to start a Demo Database
|
||||
# docker run --name adventurelog-development -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=admin -e POSTGRES_DB=adventurelog -p 5432:5432 -d postgis/postgis:15-3.3
|
||||
|
||||
# PGHOST='localhost'
|
||||
# PGDATABASE='adventurelog'
|
||||
# PGUSER='admin'
|
||||
# PGPASSWORD='admin'
|
||||
# ------------------- #
|
9
backend/server/achievements/admin.py
Normal file
9
backend/server/achievements/admin.py
Normal file
|
@ -0,0 +1,9 @@
|
|||
from django.contrib import admin
|
||||
from allauth.account.decorators import secure_admin_login
|
||||
from achievements.models import Achievement, UserAchievement
|
||||
|
||||
admin.autodiscover()
|
||||
admin.site.login = secure_admin_login(admin.site.login)
|
||||
|
||||
admin.site.register(Achievement)
|
||||
admin.site.register(UserAchievement)
|
6
backend/server/achievements/apps.py
Normal file
6
backend/server/achievements/apps.py
Normal file
|
@ -0,0 +1,6 @@
|
|||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class AchievementsConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'achievements'
|
0
backend/server/achievements/management/__init__.py
Normal file
0
backend/server/achievements/management/__init__.py
Normal file
|
@ -0,0 +1,66 @@
|
|||
import json
|
||||
from django.core.management.base import BaseCommand
|
||||
from achievements.models import Achievement
|
||||
|
||||
US_STATE_CODES = [
|
||||
'US-AL', 'US-AK', 'US-AZ', 'US-AR', 'US-CA', 'US-CO', 'US-CT', 'US-DE',
|
||||
'US-FL', 'US-GA', 'US-HI', 'US-ID', 'US-IL', 'US-IN', 'US-IA', 'US-KS',
|
||||
'US-KY', 'US-LA', 'US-ME', 'US-MD', 'US-MA', 'US-MI', 'US-MN', 'US-MS',
|
||||
'US-MO', 'US-MT', 'US-NE', 'US-NV', 'US-NH', 'US-NJ', 'US-NM', 'US-NY',
|
||||
'US-NC', 'US-ND', 'US-OH', 'US-OK', 'US-OR', 'US-PA', 'US-RI', 'US-SC',
|
||||
'US-SD', 'US-TN', 'US-TX', 'US-UT', 'US-VT', 'US-VA', 'US-WA', 'US-WV',
|
||||
'US-WI', 'US-WY'
|
||||
]
|
||||
|
||||
ACHIEVEMENTS = [
|
||||
{
|
||||
"name": "First Adventure",
|
||||
"key": "achievements.first_adventure",
|
||||
"type": "adventure_count",
|
||||
"description": "Log your first adventure!",
|
||||
"condition": {"type": "adventure_count", "value": 1},
|
||||
},
|
||||
{
|
||||
"name": "Explorer",
|
||||
"key": "achievements.explorer",
|
||||
"type": "adventure_count",
|
||||
"description": "Log 10 adventures.",
|
||||
"condition": {"type": "adventure_count", "value": 10},
|
||||
},
|
||||
{
|
||||
"name": "Globetrotter",
|
||||
"key": "achievements.globetrotter",
|
||||
"type": "country_count",
|
||||
"description": "Visit 5 different countries.",
|
||||
"condition": {"type": "country_count", "value": 5},
|
||||
},
|
||||
{
|
||||
"name": "American Dream",
|
||||
"key": "achievements.american_dream",
|
||||
"type": "country_count",
|
||||
"description": "Visit all 50 states in the USA.",
|
||||
"condition": {"type": "country_count", "items": US_STATE_CODES},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Seeds the database with predefined achievements"
|
||||
|
||||
def handle(self, *args, **kwargs):
|
||||
for achievement_data in ACHIEVEMENTS:
|
||||
achievement, created = Achievement.objects.update_or_create(
|
||||
name=achievement_data["name"],
|
||||
defaults={
|
||||
"description": achievement_data["description"],
|
||||
"condition": json.dumps(achievement_data["condition"]),
|
||||
"type": achievement_data["type"],
|
||||
"key": achievement_data["key"],
|
||||
},
|
||||
)
|
||||
if created:
|
||||
self.stdout.write(self.style.SUCCESS(f"✅ Created: {achievement.name}"))
|
||||
else:
|
||||
self.stdout.write(self.style.WARNING(f"🔄 Updated: {achievement.name}"))
|
34
backend/server/achievements/models.py
Normal file
34
backend/server/achievements/models.py
Normal file
|
@ -0,0 +1,34 @@
|
|||
import uuid
|
||||
from django.db import models
|
||||
from django.contrib.auth import get_user_model
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
VALID_ACHIEVEMENT_TYPES = [
|
||||
"adventure_count",
|
||||
"country_count",
|
||||
]
|
||||
|
||||
class Achievement(models.Model):
|
||||
"""Stores all possible achievements"""
|
||||
name = models.CharField(max_length=255, unique=True)
|
||||
key = models.CharField(max_length=255, unique=True, default='achievements.other') # Used for frontend lookups, e.g. "achievements.first_adventure"
|
||||
type = models.CharField(max_length=255, choices=[(tag, tag) for tag in VALID_ACHIEVEMENT_TYPES], default='adventure_count') # adventure_count, country_count, etc.
|
||||
description = models.TextField()
|
||||
icon = models.ImageField(upload_to="achievements/", null=True, blank=True)
|
||||
condition = models.JSONField() # Stores rules like {"type": "adventure_count", "value": 10}
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
class UserAchievement(models.Model):
|
||||
"""Tracks which achievements a user has earned"""
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
||||
achievement = models.ForeignKey(Achievement, on_delete=models.CASCADE)
|
||||
earned_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
unique_together = ("user", "achievement") # Prevent duplicates
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.user.username} - {self.achievement.name}"
|
3
backend/server/achievements/tests.py
Normal file
3
backend/server/achievements/tests.py
Normal file
|
@ -0,0 +1,3 @@
|
|||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
3
backend/server/achievements/views.py
Normal file
3
backend/server/achievements/views.py
Normal file
|
@ -0,0 +1,3 @@
|
|||
from django.shortcuts import render
|
||||
|
||||
# Create your views here.
|
7
backend/server/adventurelog.txt
Normal file
7
backend/server/adventurelog.txt
Normal file
|
@ -0,0 +1,7 @@
|
|||
█████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗████████╗██╗ ██╗██████╗ ███████╗██╗ ██████╗ ██████╗
|
||||
██╔══██╗██╔══██╗██║ ██║██╔════╝████╗ ██║╚══██╔══╝██║ ██║██╔══██╗██╔════╝██║ ██╔═══██╗██╔════╝
|
||||
███████║██║ ██║██║ ██║█████╗ ██╔██╗ ██║ ██║ ██║ ██║██████╔╝█████╗ ██║ ██║ ██║██║ ███╗
|
||||
██╔══██║██║ ██║╚██╗ ██╔╝██╔══╝ ██║╚██╗██║ ██║ ██║ ██║██╔══██╗██╔══╝ ██║ ██║ ██║██║ ██║
|
||||
██║ ██║██████╔╝ ╚████╔╝ ███████╗██║ ╚████║ ██║ ╚██████╔╝██║ ██║███████╗███████╗╚██████╔╝╚██████╔╝
|
||||
╚═╝ ╚═╝╚═════╝ ╚═══╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═════╝ ╚═════╝
|
||||
“The world is full of wonderful things you haven't seen yet. Don't ever give up on the chance of seeing them.” - J.K. Rowling
|
|
@ -1,14 +1,47 @@
|
|||
import os
|
||||
from django.contrib import admin
|
||||
from django.utils.html import mark_safe
|
||||
from .models import Adventure, Checklist, ChecklistItem, Collection, Transportation, Note, AdventureImage, Visit
|
||||
from worldtravel.models import Country, Region, VisitedRegion
|
||||
from .models import Adventure, Checklist, ChecklistItem, Collection, Transportation, Note, AdventureImage, Visit, Category, Attachment, Lodging
|
||||
from worldtravel.models import Country, Region, VisitedRegion, City, VisitedCity
|
||||
from allauth.account.decorators import secure_admin_login
|
||||
|
||||
admin.autodiscover()
|
||||
admin.site.login = secure_admin_login(admin.site.login)
|
||||
|
||||
@admin.action(description="Trigger geocoding")
|
||||
def trigger_geocoding(modeladmin, request, queryset):
|
||||
count = 0
|
||||
for adventure in queryset:
|
||||
try:
|
||||
adventure.save() # Triggers geocoding logic in your model
|
||||
count += 1
|
||||
except Exception as e:
|
||||
modeladmin.message_user(request, f"Error geocoding {adventure}: {e}", level='error')
|
||||
modeladmin.message_user(request, f"Geocoding triggered for {count} adventures.", level='success')
|
||||
|
||||
|
||||
|
||||
class AdventureAdmin(admin.ModelAdmin):
|
||||
list_display = ('name', 'type', 'user_id', 'is_public')
|
||||
list_filter = ('type', 'user_id', 'is_public')
|
||||
list_display = ('name', 'get_category', 'get_visit_count', 'user_id', 'is_public')
|
||||
list_filter = ( 'user_id', 'is_public')
|
||||
search_fields = ('name',)
|
||||
readonly_fields = ('city', 'region', 'country')
|
||||
actions = [trigger_geocoding]
|
||||
|
||||
def get_category(self, obj):
|
||||
if obj.category and obj.category.display_name and obj.category.icon:
|
||||
return obj.category.display_name + ' ' + obj.category.icon
|
||||
elif obj.category and obj.category.name:
|
||||
return obj.category.name
|
||||
else:
|
||||
return 'No Category'
|
||||
|
||||
get_category.short_description = 'Category'
|
||||
|
||||
def get_visit_count(self, obj):
|
||||
return obj.visits.count()
|
||||
|
||||
get_visit_count.short_description = 'Visit Count'
|
||||
|
||||
|
||||
class CountryAdmin(admin.ModelAdmin):
|
||||
|
@ -33,17 +66,27 @@ class RegionAdmin(admin.ModelAdmin):
|
|||
|
||||
number_of_visits.short_description = 'Number of Visits'
|
||||
|
||||
class CityAdmin(admin.ModelAdmin):
|
||||
list_display = ('name', 'region', 'country')
|
||||
list_filter = ('region', 'region__country')
|
||||
search_fields = ('name', 'region__name', 'region__country__name')
|
||||
|
||||
def country(self, obj):
|
||||
return obj.region.country.name
|
||||
|
||||
country.short_description = 'Country'
|
||||
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth.admin import UserAdmin
|
||||
from users.models import CustomUser
|
||||
|
||||
class CustomUserAdmin(UserAdmin):
|
||||
model = CustomUser
|
||||
list_display = ['username', 'email', 'is_staff', 'is_active', 'image_display']
|
||||
list_display = ['username', 'is_staff', 'is_active', 'image_display']
|
||||
readonly_fields = ('uuid',)
|
||||
search_fields = ('username', 'email')
|
||||
search_fields = ('username',)
|
||||
fieldsets = UserAdmin.fieldsets + (
|
||||
(None, {'fields': ('profile_pic', 'uuid', 'public_profile')}),
|
||||
(None, {'fields': ('profile_pic', 'uuid', 'public_profile', 'disable_password')}),
|
||||
)
|
||||
def image_display(self, obj):
|
||||
if obj.profile_pic:
|
||||
|
@ -81,14 +124,14 @@ class VisitAdmin(admin.ModelAdmin):
|
|||
|
||||
image_display.short_description = 'Image Preview'
|
||||
|
||||
class CategoryAdmin(admin.ModelAdmin):
|
||||
list_display = ('name', 'user_id', 'display_name', 'icon')
|
||||
search_fields = ('name', 'display_name')
|
||||
|
||||
class CollectionAdmin(admin.ModelAdmin):
|
||||
def adventure_count(self, obj):
|
||||
return obj.adventure_set.count()
|
||||
|
||||
adventure_count.short_description = 'Adventure Count'
|
||||
|
||||
list_display = ('name', 'user_id', 'adventure_count', 'is_public')
|
||||
list_display = ('name', 'user_id', 'is_public')
|
||||
|
||||
admin.site.register(CustomUser, CustomUserAdmin)
|
||||
|
||||
|
@ -105,6 +148,11 @@ admin.site.register(Note)
|
|||
admin.site.register(Checklist)
|
||||
admin.site.register(ChecklistItem)
|
||||
admin.site.register(AdventureImage, AdventureImageAdmin)
|
||||
admin.site.register(Category, CategoryAdmin)
|
||||
admin.site.register(City, CityAdmin)
|
||||
admin.site.register(VisitedCity)
|
||||
admin.site.register(Attachment)
|
||||
admin.site.register(Lodging)
|
||||
|
||||
admin.site.site_header = 'AdventureLog Admin'
|
||||
admin.site.site_title = 'AdventureLog Admin Site'
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
from django.apps import AppConfig
|
||||
from django.conf import settings
|
||||
|
||||
class AdventuresConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'adventures'
|
||||
|
||||
def ready(self):
|
||||
import adventures.signals # Import signals when the app is ready
|
273
backend/server/adventures/geocoding.py
Normal file
273
backend/server/adventures/geocoding.py
Normal file
|
@ -0,0 +1,273 @@
|
|||
import requests
|
||||
import time
|
||||
import socket
|
||||
from worldtravel.models import Region, City, VisitedRegion, VisitedCity
|
||||
from django.conf import settings
|
||||
|
||||
# -----------------
|
||||
# SEARCHING
|
||||
def search_google(query):
|
||||
try:
|
||||
api_key = settings.GOOGLE_MAPS_API_KEY
|
||||
if not api_key:
|
||||
return {"error": "Missing Google Maps API key"}
|
||||
|
||||
# Updated to use the new Places API (New) endpoint
|
||||
url = "https://places.googleapis.com/v1/places:searchText"
|
||||
|
||||
headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Goog-Api-Key': api_key,
|
||||
'X-Goog-FieldMask': 'places.displayName.text,places.formattedAddress,places.location,places.types,places.rating,places.userRatingCount'
|
||||
}
|
||||
|
||||
payload = {
|
||||
"textQuery": query,
|
||||
"maxResultCount": 20 # Adjust as needed
|
||||
}
|
||||
|
||||
response = requests.post(url, json=payload, headers=headers, timeout=(2, 5))
|
||||
response.raise_for_status()
|
||||
|
||||
data = response.json()
|
||||
|
||||
# Check if we have places in the response
|
||||
places = data.get("places", [])
|
||||
if not places:
|
||||
return {"error": "No results found"}
|
||||
|
||||
results = []
|
||||
for place in places:
|
||||
location = place.get("location", {})
|
||||
types = place.get("types", [])
|
||||
primary_type = types[0] if types else None
|
||||
category = _extract_google_category(types)
|
||||
addresstype = _infer_addresstype(primary_type)
|
||||
|
||||
importance = None
|
||||
rating = place.get("rating")
|
||||
ratings_total = place.get("userRatingCount")
|
||||
if rating is not None and ratings_total:
|
||||
importance = round(float(rating) * ratings_total / 100, 2)
|
||||
|
||||
# Extract display name from the new API structure
|
||||
display_name_obj = place.get("displayName", {})
|
||||
name = display_name_obj.get("text") if display_name_obj else None
|
||||
|
||||
results.append({
|
||||
"lat": location.get("latitude"),
|
||||
"lon": location.get("longitude"),
|
||||
"name": name,
|
||||
"display_name": place.get("formattedAddress"),
|
||||
"type": primary_type,
|
||||
"category": category,
|
||||
"importance": importance,
|
||||
"addresstype": addresstype,
|
||||
"powered_by": "google",
|
||||
})
|
||||
|
||||
if results:
|
||||
results.sort(key=lambda r: r["importance"] if r["importance"] is not None else 0, reverse=True)
|
||||
|
||||
return results
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
return {"error": "Network error while contacting Google Maps", "details": str(e)}
|
||||
|
||||
except Exception as e:
|
||||
return {"error": "Unexpected error during Google search", "details": str(e)}
|
||||
|
||||
def _extract_google_category(types):
|
||||
# Basic category inference based on common place types
|
||||
if not types:
|
||||
return None
|
||||
if "restaurant" in types:
|
||||
return "food"
|
||||
if "lodging" in types:
|
||||
return "accommodation"
|
||||
if "park" in types or "natural_feature" in types:
|
||||
return "nature"
|
||||
if "museum" in types or "tourist_attraction" in types:
|
||||
return "attraction"
|
||||
if "locality" in types or "administrative_area_level_1" in types:
|
||||
return "region"
|
||||
return types[0] # fallback to first type
|
||||
|
||||
|
||||
def _infer_addresstype(type_):
|
||||
# Rough mapping of Google place types to OSM-style addresstypes
|
||||
mapping = {
|
||||
"locality": "city",
|
||||
"sublocality": "neighborhood",
|
||||
"administrative_area_level_1": "region",
|
||||
"administrative_area_level_2": "county",
|
||||
"country": "country",
|
||||
"premise": "building",
|
||||
"point_of_interest": "poi",
|
||||
"route": "road",
|
||||
"street_address": "address",
|
||||
}
|
||||
return mapping.get(type_, None)
|
||||
|
||||
|
||||
def search_osm(query):
|
||||
url = f"https://nominatim.openstreetmap.org/search?q={query}&format=jsonv2"
|
||||
headers = {'User-Agent': 'AdventureLog Server'}
|
||||
response = requests.get(url, headers=headers)
|
||||
data = response.json()
|
||||
|
||||
return [{
|
||||
"lat": item.get("lat"),
|
||||
"lon": item.get("lon"),
|
||||
"name": item.get("name"),
|
||||
"display_name": item.get("display_name"),
|
||||
"type": item.get("type"),
|
||||
"category": item.get("category"),
|
||||
"importance": item.get("importance"),
|
||||
"addresstype": item.get("addresstype"),
|
||||
"powered_by": "nominatim",
|
||||
} for item in data]
|
||||
|
||||
# -----------------
|
||||
# REVERSE GEOCODING
|
||||
# -----------------
|
||||
|
||||
def extractIsoCode(user, data):
|
||||
"""
|
||||
Extract the ISO code from the response data.
|
||||
Returns a dictionary containing the region name, country name, and ISO code if found.
|
||||
"""
|
||||
iso_code = None
|
||||
town_city_or_county = None
|
||||
display_name = None
|
||||
country_code = None
|
||||
city = None
|
||||
visited_city = None
|
||||
location_name = None
|
||||
|
||||
# town = None
|
||||
# city = None
|
||||
# county = None
|
||||
|
||||
if 'name' in data.keys():
|
||||
location_name = data['name']
|
||||
|
||||
if 'address' in data.keys():
|
||||
keys = data['address'].keys()
|
||||
for key in keys:
|
||||
if key.find("ISO") != -1:
|
||||
iso_code = data['address'][key]
|
||||
if 'town' in keys:
|
||||
town_city_or_county = data['address']['town']
|
||||
if 'county' in keys:
|
||||
town_city_or_county = data['address']['county']
|
||||
if 'city' in keys:
|
||||
town_city_or_county = data['address']['city']
|
||||
if not iso_code:
|
||||
return {"error": "No region found"}
|
||||
|
||||
region = Region.objects.filter(id=iso_code).first()
|
||||
visited_region = VisitedRegion.objects.filter(region=region, user_id=user).first()
|
||||
|
||||
region_visited = False
|
||||
city_visited = False
|
||||
country_code = iso_code[:2]
|
||||
|
||||
if region:
|
||||
if town_city_or_county:
|
||||
display_name = f"{town_city_or_county}, {region.name}, {country_code}"
|
||||
city = City.objects.filter(name__contains=town_city_or_county, region=region).first()
|
||||
visited_city = VisitedCity.objects.filter(city=city, user_id=user).first()
|
||||
|
||||
if visited_region:
|
||||
region_visited = True
|
||||
if visited_city:
|
||||
city_visited = True
|
||||
if region:
|
||||
return {"region_id": iso_code, "region": region.name, "country": region.country.name, "country_id": region.country.country_code, "region_visited": region_visited, "display_name": display_name, "city": city.name if city else None, "city_id": city.id if city else None, "city_visited": city_visited, 'location_name': location_name}
|
||||
return {"error": "No region found"}
|
||||
|
||||
def is_host_resolvable(hostname: str) -> bool:
|
||||
try:
|
||||
socket.gethostbyname(hostname)
|
||||
return True
|
||||
except socket.error:
|
||||
return False
|
||||
|
||||
def reverse_geocode(lat, lon, user):
|
||||
if getattr(settings, 'GOOGLE_MAPS_API_KEY', None):
|
||||
return reverse_geocode_google(lat, lon, user)
|
||||
return reverse_geocode_osm(lat, lon, user)
|
||||
|
||||
def reverse_geocode_osm(lat, lon, user):
|
||||
url = f"https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat={lat}&lon={lon}"
|
||||
headers = {'User-Agent': 'AdventureLog Server'}
|
||||
connect_timeout = 1
|
||||
read_timeout = 5
|
||||
|
||||
if not is_host_resolvable("nominatim.openstreetmap.org"):
|
||||
return {"error": "DNS resolution failed"}
|
||||
|
||||
try:
|
||||
response = requests.get(url, headers=headers, timeout=(connect_timeout, read_timeout))
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return extractIsoCode(user, data)
|
||||
except Exception:
|
||||
return {"error": "An internal error occurred while processing the request"}
|
||||
|
||||
def reverse_geocode_google(lat, lon, user):
|
||||
api_key = settings.GOOGLE_MAPS_API_KEY
|
||||
|
||||
# Updated to use the new Geocoding API endpoint (this one is still supported)
|
||||
# The Geocoding API is separate from Places API and still uses the old format
|
||||
url = "https://maps.googleapis.com/maps/api/geocode/json"
|
||||
params = {"latlng": f"{lat},{lon}", "key": api_key}
|
||||
|
||||
try:
|
||||
response = requests.get(url, params=params)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
if data.get("status") != "OK":
|
||||
return {"error": "Geocoding failed"}
|
||||
|
||||
# Convert Google schema to Nominatim-style for extractIsoCode
|
||||
first_result = data.get("results", [])[0]
|
||||
result_data = {
|
||||
"name": first_result.get("formatted_address"),
|
||||
"address": _parse_google_address_components(first_result.get("address_components", []))
|
||||
}
|
||||
return extractIsoCode(user, result_data)
|
||||
except Exception:
|
||||
return {"error": "An internal error occurred while processing the request"}
|
||||
|
||||
def _parse_google_address_components(components):
|
||||
parsed = {}
|
||||
country_code = None
|
||||
state_code = None
|
||||
|
||||
for comp in components:
|
||||
types = comp.get("types", [])
|
||||
long_name = comp.get("long_name")
|
||||
short_name = comp.get("short_name")
|
||||
|
||||
if "country" in types:
|
||||
parsed["country"] = long_name
|
||||
country_code = short_name
|
||||
parsed["ISO3166-1"] = short_name
|
||||
if "administrative_area_level_1" in types:
|
||||
parsed["state"] = long_name
|
||||
state_code = short_name
|
||||
if "administrative_area_level_2" in types:
|
||||
parsed["county"] = long_name
|
||||
if "locality" in types:
|
||||
parsed["city"] = long_name
|
||||
if "sublocality" in types:
|
||||
parsed["town"] = long_name
|
||||
|
||||
# Build composite ISO 3166-2 code like US-ME
|
||||
if country_code and state_code:
|
||||
parsed["ISO3166-2-lvl1"] = f"{country_code}-{state_code}"
|
||||
|
||||
return parsed
|
17
backend/server/adventures/managers.py
Normal file
17
backend/server/adventures/managers.py
Normal file
|
@ -0,0 +1,17 @@
|
|||
from django.db import models
|
||||
from django.db.models import Q
|
||||
|
||||
class AdventureManager(models.Manager):
|
||||
def retrieve_adventures(self, user, include_owned=False, include_shared=False, include_public=False):
|
||||
query = Q()
|
||||
|
||||
if include_owned:
|
||||
query |= Q(user_id=user)
|
||||
|
||||
if include_shared:
|
||||
query |= Q(collections__shared_with=user)
|
||||
|
||||
if include_public:
|
||||
query |= Q(is_public=True)
|
||||
|
||||
return self.filter(query).distinct()
|
|
@ -1,13 +1,40 @@
|
|||
class AppVersionMiddleware:
|
||||
from django.conf import settings
|
||||
from django.utils.deprecation import MiddlewareMixin
|
||||
import os
|
||||
|
||||
class OverrideHostMiddleware:
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
# Process request (if needed)
|
||||
public_url = os.getenv('PUBLIC_URL', None)
|
||||
if public_url:
|
||||
# Extract host and scheme
|
||||
scheme, host = public_url.split("://")
|
||||
request.META['HTTP_HOST'] = host
|
||||
request.META['wsgi.url_scheme'] = scheme
|
||||
|
||||
# Set X-Forwarded-Proto for Django
|
||||
request.META['HTTP_X_FORWARDED_PROTO'] = scheme
|
||||
|
||||
response = self.get_response(request)
|
||||
|
||||
# Add custom header to response
|
||||
# Replace with your app version
|
||||
response['X-AdventureLog-Version'] = '1.0.0'
|
||||
|
||||
return response
|
||||
|
||||
class XSessionTokenMiddleware(MiddlewareMixin):
|
||||
def process_request(self, request):
|
||||
session_token = request.headers.get('X-Session-Token')
|
||||
if session_token:
|
||||
request.COOKIES[settings.SESSION_COOKIE_NAME] = session_token
|
||||
|
||||
class DisableCSRFForSessionTokenMiddleware(MiddlewareMixin):
|
||||
def process_request(self, request):
|
||||
if 'X-Session-Token' in request.headers:
|
||||
setattr(request, '_dont_enforce_csrf_checks', True)
|
||||
|
||||
class DisableCSRFForMobileLoginSignup(MiddlewareMixin):
|
||||
def process_request(self, request):
|
||||
is_mobile = request.headers.get('X-Is-Mobile', '').lower() == 'true'
|
||||
is_login_or_signup = request.path in ['/auth/browser/v1/auth/login', '/auth/browser/v1/auth/signup']
|
||||
if is_mobile and is_login_or_signup:
|
||||
setattr(request, '_dont_enforce_csrf_checks', True)
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
# Generated by Django 5.0.8 on 2024-11-14 04:30
|
||||
|
||||
from django.conf import settings
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0010_collection_link'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Category',
|
||||
fields=[
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),
|
||||
('name', models.CharField(max_length=200)),
|
||||
('display_name', models.CharField(max_length=200)),
|
||||
('icon', models.CharField(default='🌍', max_length=200)),
|
||||
('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'verbose_name_plural': 'Categories',
|
||||
},
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='adventure',
|
||||
name='category',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='adventures.category'),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,59 @@
|
|||
from django.db import migrations
|
||||
|
||||
def migrate_categories(apps, schema_editor):
|
||||
# Use the historical models
|
||||
Adventure = apps.get_model('adventures', 'Adventure')
|
||||
Category = apps.get_model('adventures', 'Category')
|
||||
|
||||
ADVENTURE_TYPES = {
|
||||
'general': ('General', '🌍'),
|
||||
'outdoor': ('Outdoor', '🏞️'),
|
||||
'lodging': ('Lodging', '🛌'),
|
||||
'dining': ('Dining', '🍽️'),
|
||||
'activity': ('Activity', '🏄'),
|
||||
'attraction': ('Attraction', '🎢'),
|
||||
'shopping': ('Shopping', '🛍️'),
|
||||
'nightlife': ('Nightlife', '🌃'),
|
||||
'event': ('Event', '🎉'),
|
||||
'transportation': ('Transportation', '🚗'),
|
||||
'culture': ('Culture', '🎭'),
|
||||
'water_sports': ('Water Sports', '🚤'),
|
||||
'hiking': ('Hiking', '🥾'),
|
||||
'wildlife': ('Wildlife', '🦒'),
|
||||
'historical_sites': ('Historical Sites', '🏛️'),
|
||||
'music_concerts': ('Music & Concerts', '🎶'),
|
||||
'fitness': ('Fitness', '🏋️'),
|
||||
'art_museums': ('Art & Museums', '🎨'),
|
||||
'festivals': ('Festivals', '🎪'),
|
||||
'spiritual_journeys': ('Spiritual Journeys', '🧘♀️'),
|
||||
'volunteer_work': ('Volunteer Work', '🤝'),
|
||||
'other': ('Other', '❓'),
|
||||
}
|
||||
|
||||
adventures = Adventure.objects.all()
|
||||
for adventure in adventures:
|
||||
# Access the old 'type' field using __dict__ because it's not in the model anymore
|
||||
old_type = adventure.__dict__.get('type')
|
||||
if old_type in ADVENTURE_TYPES:
|
||||
category, created = Category.objects.get_or_create(
|
||||
name=old_type,
|
||||
user_id=adventure.user_id,
|
||||
defaults={
|
||||
'display_name': ADVENTURE_TYPES[old_type][0],
|
||||
'icon': ADVENTURE_TYPES[old_type][1],
|
||||
}
|
||||
)
|
||||
adventure.category = category
|
||||
adventure.save()
|
||||
else:
|
||||
print(f"Unknown type: {old_type}")
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0011_category_adventure_category'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(migrate_categories),
|
||||
]
|
|
@ -0,0 +1,23 @@
|
|||
# Generated by Django 5.0.8 on 2024-11-14 04:51
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0012_migrate_types_to_categories'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='adventure',
|
||||
name='type',
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='adventure',
|
||||
name='category',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='adventures.category'),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,19 @@
|
|||
# Generated by Django 5.0.8 on 2024-11-17 21:43
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0013_remove_adventure_type_alter_adventure_category'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterUniqueTogether(
|
||||
name='category',
|
||||
unique_together={('name', 'user_id')},
|
||||
),
|
||||
]
|
|
@ -0,0 +1,33 @@
|
|||
# Generated by Django 5.0.8 on 2024-12-19 17:16
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0014_alter_category_unique_together'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='transportation',
|
||||
name='destination_latitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='transportation',
|
||||
name='destination_longitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='transportation',
|
||||
name='origin_latitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='transportation',
|
||||
name='origin_longitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,20 @@
|
|||
# Generated by Django 5.0.8 on 2025-01-01 21:40
|
||||
|
||||
import adventures.models
|
||||
import django_resized.forms
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0015_transportation_destination_latitude_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='adventureimage',
|
||||
name='image',
|
||||
field=django_resized.forms.ResizedImageField(crop=None, force_format='WEBP', keep_meta=True, quality=75, scale=None, size=[1920, 1080], upload_to=adventures.models.PathAndRename('images/')),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,18 @@
|
|||
# Generated by Django 5.0.8 on 2025-01-03 04:05
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0016_alter_adventureimage_image'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='adventureimage',
|
||||
name='is_primary',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
26
backend/server/adventures/migrations/0018_attachment.py
Normal file
26
backend/server/adventures/migrations/0018_attachment.py
Normal file
|
@ -0,0 +1,26 @@
|
|||
# Generated by Django 5.0.8 on 2025-01-19 00:39
|
||||
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0017_adventureimage_is_primary'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Attachment',
|
||||
fields=[
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),
|
||||
('file', models.FileField(upload_to='attachments/')),
|
||||
('adventure', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='adventures.adventure')),
|
||||
('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
]
|
|
@ -0,0 +1,19 @@
|
|||
# Generated by Django 5.0.8 on 2025-01-19 22:17
|
||||
|
||||
import adventures.models
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0018_attachment'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='attachment',
|
||||
name='file',
|
||||
field=models.FileField(upload_to=adventures.models.PathAndRename('attachments/')),
|
||||
),
|
||||
]
|
19
backend/server/adventures/migrations/0020_attachment_name.py
Normal file
19
backend/server/adventures/migrations/0020_attachment_name.py
Normal file
|
@ -0,0 +1,19 @@
|
|||
# Generated by Django 5.0.8 on 2025-01-19 22:32
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0019_alter_attachment_file'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='attachment',
|
||||
name='name',
|
||||
field=models.CharField(default='', max_length=200),
|
||||
preserve_default=False,
|
||||
),
|
||||
]
|
|
@ -0,0 +1,18 @@
|
|||
# Generated by Django 5.0.8 on 2025-01-19 22:32
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0020_attachment_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='attachment',
|
||||
name='name',
|
||||
field=models.CharField(blank=True, max_length=200, null=True),
|
||||
),
|
||||
]
|
39
backend/server/adventures/migrations/0022_hotel.py
Normal file
39
backend/server/adventures/migrations/0022_hotel.py
Normal file
|
@ -0,0 +1,39 @@
|
|||
# Generated by Django 5.0.8 on 2025-02-02 15:36
|
||||
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0021_alter_attachment_name'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Hotel',
|
||||
fields=[
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),
|
||||
('name', models.CharField(max_length=200)),
|
||||
('description', models.TextField(blank=True, null=True)),
|
||||
('rating', models.FloatField(blank=True, null=True)),
|
||||
('link', models.URLField(blank=True, max_length=2083, null=True)),
|
||||
('check_in', models.DateTimeField(blank=True, null=True)),
|
||||
('check_out', models.DateTimeField(blank=True, null=True)),
|
||||
('reservation_number', models.CharField(blank=True, max_length=100, null=True)),
|
||||
('price', models.DecimalField(blank=True, decimal_places=2, max_digits=9, null=True)),
|
||||
('latitude', models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True)),
|
||||
('longitude', models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True)),
|
||||
('location', models.CharField(blank=True, max_length=200, null=True)),
|
||||
('is_public', models.BooleanField(default=False)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('collection', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='adventures.collection')),
|
||||
('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
]
|
|
@ -0,0 +1,43 @@
|
|||
# Generated by Django 5.0.8 on 2025-02-08 01:50
|
||||
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0022_hotel'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Lodging',
|
||||
fields=[
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),
|
||||
('name', models.CharField(max_length=200)),
|
||||
('type', models.CharField(choices=[('hotel', 'Hotel'), ('hostel', 'Hostel'), ('resort', 'Resort'), ('bnb', 'Bed & Breakfast'), ('campground', 'Campground'), ('cabin', 'Cabin'), ('apartment', 'Apartment'), ('house', 'House'), ('villa', 'Villa'), ('motel', 'Motel'), ('other', 'Other')], default='other', max_length=100)),
|
||||
('description', models.TextField(blank=True, null=True)),
|
||||
('rating', models.FloatField(blank=True, null=True)),
|
||||
('link', models.URLField(blank=True, max_length=2083, null=True)),
|
||||
('check_in', models.DateTimeField(blank=True, null=True)),
|
||||
('check_out', models.DateTimeField(blank=True, null=True)),
|
||||
('reservation_number', models.CharField(blank=True, max_length=100, null=True)),
|
||||
('price', models.DecimalField(blank=True, decimal_places=2, max_digits=9, null=True)),
|
||||
('latitude', models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True)),
|
||||
('longitude', models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True)),
|
||||
('location', models.CharField(blank=True, max_length=200, null=True)),
|
||||
('is_public', models.BooleanField(default=False)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('collection', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='adventures.collection')),
|
||||
('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.DeleteModel(
|
||||
name='Hotel',
|
||||
),
|
||||
]
|
|
@ -0,0 +1,19 @@
|
|||
# Generated by Django 5.0.8 on 2025-03-17 01:15
|
||||
|
||||
import adventures.models
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0023_lodging_delete_hotel'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='attachment',
|
||||
name='file',
|
||||
field=models.FileField(upload_to=adventures.models.PathAndRename('attachments/'), validators=[adventures.models.validate_file_extension]),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,23 @@
|
|||
# Generated by Django 5.0.8 on 2025-03-17 21:41
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0024_alter_attachment_file'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='visit',
|
||||
name='end_date',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='visit',
|
||||
name='start_date',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
]
|
18
backend/server/adventures/migrations/0026_visit_timezone.py
Normal file
18
backend/server/adventures/migrations/0026_visit_timezone.py
Normal file
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,30 @@
|
|||
# Generated by Django 5.0.11 on 2025-05-22 22:48
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0028_lodging_timezone'),
|
||||
('worldtravel', '0015_city_insert_id_country_insert_id_region_insert_id'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='adventure',
|
||||
name='city',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='worldtravel.city'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='adventure',
|
||||
name='country',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='worldtravel.country'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='adventure',
|
||||
name='region',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='worldtravel.region'),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,18 @@
|
|||
from django.db import migrations
|
||||
|
||||
def set_end_date_equal_to_start(apps, schema_editor):
|
||||
Visit = apps.get_model('adventures', 'Visit')
|
||||
for visit in Visit.objects.filter(end_date__isnull=True):
|
||||
if visit.start_date:
|
||||
visit.end_date = visit.start_date
|
||||
visit.save()
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0029_adventure_city_adventure_country_adventure_region'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(set_end_date_equal_to_start),
|
||||
]
|
|
@ -0,0 +1,31 @@
|
|||
# Generated by Django 5.2.1 on 2025-06-01 16:57
|
||||
|
||||
import adventures.models
|
||||
import django_resized.forms
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0030_set_end_date_equal_start'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='adventureimage',
|
||||
name='immich_id',
|
||||
field=models.CharField(blank=True, max_length=200, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='adventureimage',
|
||||
name='image',
|
||||
field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='WEBP', keep_meta=True, null=True, quality=75, scale=None, size=[1920, 1080], upload_to=adventures.models.PathAndRename('images/')),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='adventureimage',
|
||||
constraint=models.CheckConstraint(condition=models.Q(models.Q(('image__isnull', False), ('immich_id__isnull', True)), models.Q(('image__isnull', True), ('immich_id__isnull', False)), _connector='OR'), name='image_xor_immich_id'),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,17 @@
|
|||
# Generated by Django 5.2.1 on 2025-06-01 17:18
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0031_adventureimage_immich_id_alter_adventureimage_image_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveConstraint(
|
||||
model_name='adventureimage',
|
||||
name='image_xor_immich_id',
|
||||
),
|
||||
]
|
|
@ -0,0 +1,19 @@
|
|||
# Generated by Django 5.2.1 on 2025-06-02 02:31
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0032_remove_adventureimage_image_xor_immich_id'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddConstraint(
|
||||
model_name='adventureimage',
|
||||
constraint=models.UniqueConstraint(fields=('immich_id', 'user_id'), name='unique_immich_id_per_user'),
|
||||
),
|
||||
]
|
|
@ -0,0 +1,17 @@
|
|||
# Generated by Django 5.2.1 on 2025-06-02 02:44
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0033_adventureimage_unique_immich_id_per_user'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveConstraint(
|
||||
model_name='adventureimage',
|
||||
name='unique_immich_id_per_user',
|
||||
),
|
||||
]
|
|
@ -0,0 +1,59 @@
|
|||
# Generated by Django 5.2.1 on 2025-06-10 03:04
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
def migrate_collection_relationships(apps, schema_editor):
|
||||
"""
|
||||
Migrate existing ForeignKey relationships to ManyToMany relationships
|
||||
"""
|
||||
Adventure = apps.get_model('adventures', 'Adventure')
|
||||
|
||||
# Get all adventures that have a collection assigned
|
||||
adventures_with_collections = Adventure.objects.filter(collection__isnull=False)
|
||||
|
||||
for adventure in adventures_with_collections:
|
||||
# Add the existing collection to the new many-to-many field
|
||||
adventure.collections.add(adventure.collection_id)
|
||||
|
||||
|
||||
def reverse_migrate_collection_relationships(apps, schema_editor):
|
||||
"""
|
||||
Reverse migration - convert first collection back to ForeignKey
|
||||
Note: This will only preserve the first collection if an adventure has multiple
|
||||
"""
|
||||
Adventure = apps.get_model('adventures', 'Adventure')
|
||||
|
||||
for adventure in Adventure.objects.all():
|
||||
first_collection = adventure.collections.first()
|
||||
if first_collection:
|
||||
adventure.collection = first_collection
|
||||
adventure.save()
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('adventures', '0034_remove_adventureimage_unique_immich_id_per_user'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
# First, add the new ManyToMany field
|
||||
migrations.AddField(
|
||||
model_name='adventure',
|
||||
name='collections',
|
||||
field=models.ManyToManyField(blank=True, related_name='adventures', to='adventures.collection'),
|
||||
),
|
||||
|
||||
# Migrate existing data from old field to new field
|
||||
migrations.RunPython(
|
||||
migrate_collection_relationships,
|
||||
reverse_migrate_collection_relationships
|
||||
),
|
||||
|
||||
# Finally, remove the old ForeignKey field
|
||||
migrations.RemoveField(
|
||||
model_name='adventure',
|
||||
name='collection',
|
||||
),
|
||||
]
|
|
@ -1,10 +1,66 @@
|
|||
from django.core.exceptions import ValidationError
|
||||
import os
|
||||
from typing import Iterable
|
||||
import uuid
|
||||
from django.db import models
|
||||
|
||||
from django.utils.deconstruct import deconstructible
|
||||
from adventures.managers import AdventureManager
|
||||
import threading
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.postgres.fields import ArrayField
|
||||
from django.forms import ValidationError
|
||||
from django_resized import ResizedImageField
|
||||
from worldtravel.models import City, Country, Region, VisitedCity, VisitedRegion
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.utils import timezone
|
||||
|
||||
def background_geocode_and_assign(adventure_id: str):
|
||||
print(f"[Adventure Geocode Thread] Starting geocode for adventure {adventure_id}")
|
||||
try:
|
||||
adventure = Adventure.objects.get(id=adventure_id)
|
||||
if not (adventure.latitude and adventure.longitude):
|
||||
return
|
||||
|
||||
from adventures.geocoding import reverse_geocode # or wherever you defined it
|
||||
is_visited = adventure.is_visited_status()
|
||||
result = reverse_geocode(adventure.latitude, adventure.longitude, adventure.user_id)
|
||||
|
||||
if 'region_id' in result:
|
||||
region = Region.objects.filter(id=result['region_id']).first()
|
||||
if region:
|
||||
adventure.region = region
|
||||
if is_visited:
|
||||
VisitedRegion.objects.get_or_create(user_id=adventure.user_id, region=region)
|
||||
|
||||
if 'city_id' in result:
|
||||
city = City.objects.filter(id=result['city_id']).first()
|
||||
if city:
|
||||
adventure.city = city
|
||||
if is_visited:
|
||||
VisitedCity.objects.get_or_create(user_id=adventure.user_id, city=city)
|
||||
|
||||
if 'country_id' in result:
|
||||
country = Country.objects.filter(country_code=result['country_id']).first()
|
||||
if country:
|
||||
adventure.country = country
|
||||
|
||||
# Save updated location info
|
||||
# Save updated location info, skip geocode threading
|
||||
adventure.save(update_fields=["region", "city", "country"], _skip_geocode=True)
|
||||
|
||||
# print(f"[Adventure Geocode Thread] Successfully processed {adventure_id}: {adventure.name} - {adventure.latitude}, {adventure.longitude}")
|
||||
|
||||
except Exception as e:
|
||||
# Optional: log or print the error
|
||||
print(f"[Adventure Geocode Thread] Error processing {adventure_id}: {e}")
|
||||
|
||||
def validate_file_extension(value):
|
||||
import os
|
||||
from django.core.exceptions import ValidationError
|
||||
ext = os.path.splitext(value.name)[1] # [0] returns path+filename
|
||||
valid_extensions = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.txt', '.png', '.jpg', '.jpeg', '.gif', '.webp', '.mp4', '.mov', '.avi', '.mkv', '.mp3', '.wav', '.flac', '.ogg', '.m4a', '.wma', '.aac', '.opus', '.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz', '.zst', '.lz4', '.lzma', '.lzo', '.z', '.tar.gz', '.tar.bz2', '.tar.xz', '.tar.zst', '.tar.lz4', '.tar.lzma', '.tar.lzo', '.tar.z', '.gpx', '.md']
|
||||
if not ext.lower() in valid_extensions:
|
||||
raise ValidationError('Unsupported file extension.')
|
||||
|
||||
ADVENTURE_TYPES = [
|
||||
('general', 'General 🌍'),
|
||||
|
@ -31,6 +87,440 @@ ADVENTURE_TYPES = [
|
|||
('other', 'Other')
|
||||
]
|
||||
|
||||
TIMEZONES = [
|
||||
"Africa/Abidjan",
|
||||
"Africa/Accra",
|
||||
"Africa/Addis_Ababa",
|
||||
"Africa/Algiers",
|
||||
"Africa/Asmera",
|
||||
"Africa/Bamako",
|
||||
"Africa/Bangui",
|
||||
"Africa/Banjul",
|
||||
"Africa/Bissau",
|
||||
"Africa/Blantyre",
|
||||
"Africa/Brazzaville",
|
||||
"Africa/Bujumbura",
|
||||
"Africa/Cairo",
|
||||
"Africa/Casablanca",
|
||||
"Africa/Ceuta",
|
||||
"Africa/Conakry",
|
||||
"Africa/Dakar",
|
||||
"Africa/Dar_es_Salaam",
|
||||
"Africa/Djibouti",
|
||||
"Africa/Douala",
|
||||
"Africa/El_Aaiun",
|
||||
"Africa/Freetown",
|
||||
"Africa/Gaborone",
|
||||
"Africa/Harare",
|
||||
"Africa/Johannesburg",
|
||||
"Africa/Juba",
|
||||
"Africa/Kampala",
|
||||
"Africa/Khartoum",
|
||||
"Africa/Kigali",
|
||||
"Africa/Kinshasa",
|
||||
"Africa/Lagos",
|
||||
"Africa/Libreville",
|
||||
"Africa/Lome",
|
||||
"Africa/Luanda",
|
||||
"Africa/Lubumbashi",
|
||||
"Africa/Lusaka",
|
||||
"Africa/Malabo",
|
||||
"Africa/Maputo",
|
||||
"Africa/Maseru",
|
||||
"Africa/Mbabane",
|
||||
"Africa/Mogadishu",
|
||||
"Africa/Monrovia",
|
||||
"Africa/Nairobi",
|
||||
"Africa/Ndjamena",
|
||||
"Africa/Niamey",
|
||||
"Africa/Nouakchott",
|
||||
"Africa/Ouagadougou",
|
||||
"Africa/Porto-Novo",
|
||||
"Africa/Sao_Tome",
|
||||
"Africa/Tripoli",
|
||||
"Africa/Tunis",
|
||||
"Africa/Windhoek",
|
||||
"America/Adak",
|
||||
"America/Anchorage",
|
||||
"America/Anguilla",
|
||||
"America/Antigua",
|
||||
"America/Araguaina",
|
||||
"America/Argentina/La_Rioja",
|
||||
"America/Argentina/Rio_Gallegos",
|
||||
"America/Argentina/Salta",
|
||||
"America/Argentina/San_Juan",
|
||||
"America/Argentina/San_Luis",
|
||||
"America/Argentina/Tucuman",
|
||||
"America/Argentina/Ushuaia",
|
||||
"America/Aruba",
|
||||
"America/Asuncion",
|
||||
"America/Bahia",
|
||||
"America/Bahia_Banderas",
|
||||
"America/Barbados",
|
||||
"America/Belem",
|
||||
"America/Belize",
|
||||
"America/Blanc-Sablon",
|
||||
"America/Boa_Vista",
|
||||
"America/Bogota",
|
||||
"America/Boise",
|
||||
"America/Buenos_Aires",
|
||||
"America/Cambridge_Bay",
|
||||
"America/Campo_Grande",
|
||||
"America/Cancun",
|
||||
"America/Caracas",
|
||||
"America/Catamarca",
|
||||
"America/Cayenne",
|
||||
"America/Cayman",
|
||||
"America/Chicago",
|
||||
"America/Chihuahua",
|
||||
"America/Ciudad_Juarez",
|
||||
"America/Coral_Harbour",
|
||||
"America/Cordoba",
|
||||
"America/Costa_Rica",
|
||||
"America/Creston",
|
||||
"America/Cuiaba",
|
||||
"America/Curacao",
|
||||
"America/Danmarkshavn",
|
||||
"America/Dawson",
|
||||
"America/Dawson_Creek",
|
||||
"America/Denver",
|
||||
"America/Detroit",
|
||||
"America/Dominica",
|
||||
"America/Edmonton",
|
||||
"America/Eirunepe",
|
||||
"America/El_Salvador",
|
||||
"America/Fort_Nelson",
|
||||
"America/Fortaleza",
|
||||
"America/Glace_Bay",
|
||||
"America/Godthab",
|
||||
"America/Goose_Bay",
|
||||
"America/Grand_Turk",
|
||||
"America/Grenada",
|
||||
"America/Guadeloupe",
|
||||
"America/Guatemala",
|
||||
"America/Guayaquil",
|
||||
"America/Guyana",
|
||||
"America/Halifax",
|
||||
"America/Havana",
|
||||
"America/Hermosillo",
|
||||
"America/Indiana/Knox",
|
||||
"America/Indiana/Marengo",
|
||||
"America/Indiana/Petersburg",
|
||||
"America/Indiana/Tell_City",
|
||||
"America/Indiana/Vevay",
|
||||
"America/Indiana/Vincennes",
|
||||
"America/Indiana/Winamac",
|
||||
"America/Indianapolis",
|
||||
"America/Inuvik",
|
||||
"America/Iqaluit",
|
||||
"America/Jamaica",
|
||||
"America/Jujuy",
|
||||
"America/Juneau",
|
||||
"America/Kentucky/Monticello",
|
||||
"America/Kralendijk",
|
||||
"America/La_Paz",
|
||||
"America/Lima",
|
||||
"America/Los_Angeles",
|
||||
"America/Louisville",
|
||||
"America/Lower_Princes",
|
||||
"America/Maceio",
|
||||
"America/Managua",
|
||||
"America/Manaus",
|
||||
"America/Marigot",
|
||||
"America/Martinique",
|
||||
"America/Matamoros",
|
||||
"America/Mazatlan",
|
||||
"America/Mendoza",
|
||||
"America/Menominee",
|
||||
"America/Merida",
|
||||
"America/Metlakatla",
|
||||
"America/Mexico_City",
|
||||
"America/Miquelon",
|
||||
"America/Moncton",
|
||||
"America/Monterrey",
|
||||
"America/Montevideo",
|
||||
"America/Montserrat",
|
||||
"America/Nassau",
|
||||
"America/New_York",
|
||||
"America/Nome",
|
||||
"America/Noronha",
|
||||
"America/North_Dakota/Beulah",
|
||||
"America/North_Dakota/Center",
|
||||
"America/North_Dakota/New_Salem",
|
||||
"America/Ojinaga",
|
||||
"America/Panama",
|
||||
"America/Paramaribo",
|
||||
"America/Phoenix",
|
||||
"America/Port-au-Prince",
|
||||
"America/Port_of_Spain",
|
||||
"America/Porto_Velho",
|
||||
"America/Puerto_Rico",
|
||||
"America/Punta_Arenas",
|
||||
"America/Rankin_Inlet",
|
||||
"America/Recife",
|
||||
"America/Regina",
|
||||
"America/Resolute",
|
||||
"America/Rio_Branco",
|
||||
"America/Santarem",
|
||||
"America/Santiago",
|
||||
"America/Santo_Domingo",
|
||||
"America/Sao_Paulo",
|
||||
"America/Scoresbysund",
|
||||
"America/Sitka",
|
||||
"America/St_Barthelemy",
|
||||
"America/St_Johns",
|
||||
"America/St_Kitts",
|
||||
"America/St_Lucia",
|
||||
"America/St_Thomas",
|
||||
"America/St_Vincent",
|
||||
"America/Swift_Current",
|
||||
"America/Tegucigalpa",
|
||||
"America/Thule",
|
||||
"America/Tijuana",
|
||||
"America/Toronto",
|
||||
"America/Tortola",
|
||||
"America/Vancouver",
|
||||
"America/Whitehorse",
|
||||
"America/Winnipeg",
|
||||
"America/Yakutat",
|
||||
"Antarctica/Casey",
|
||||
"Antarctica/Davis",
|
||||
"Antarctica/DumontDUrville",
|
||||
"Antarctica/Macquarie",
|
||||
"Antarctica/Mawson",
|
||||
"Antarctica/McMurdo",
|
||||
"Antarctica/Palmer",
|
||||
"Antarctica/Rothera",
|
||||
"Antarctica/Syowa",
|
||||
"Antarctica/Troll",
|
||||
"Antarctica/Vostok",
|
||||
"Arctic/Longyearbyen",
|
||||
"Asia/Aden",
|
||||
"Asia/Almaty",
|
||||
"Asia/Amman",
|
||||
"Asia/Anadyr",
|
||||
"Asia/Aqtau",
|
||||
"Asia/Aqtobe",
|
||||
"Asia/Ashgabat",
|
||||
"Asia/Atyrau",
|
||||
"Asia/Baghdad",
|
||||
"Asia/Bahrain",
|
||||
"Asia/Baku",
|
||||
"Asia/Bangkok",
|
||||
"Asia/Barnaul",
|
||||
"Asia/Beirut",
|
||||
"Asia/Bishkek",
|
||||
"Asia/Brunei",
|
||||
"Asia/Calcutta",
|
||||
"Asia/Chita",
|
||||
"Asia/Colombo",
|
||||
"Asia/Damascus",
|
||||
"Asia/Dhaka",
|
||||
"Asia/Dili",
|
||||
"Asia/Dubai",
|
||||
"Asia/Dushanbe",
|
||||
"Asia/Famagusta",
|
||||
"Asia/Gaza",
|
||||
"Asia/Hebron",
|
||||
"Asia/Hong_Kong",
|
||||
"Asia/Hovd",
|
||||
"Asia/Irkutsk",
|
||||
"Asia/Jakarta",
|
||||
"Asia/Jayapura",
|
||||
"Asia/Jerusalem",
|
||||
"Asia/Kabul",
|
||||
"Asia/Kamchatka",
|
||||
"Asia/Karachi",
|
||||
"Asia/Katmandu",
|
||||
"Asia/Khandyga",
|
||||
"Asia/Krasnoyarsk",
|
||||
"Asia/Kuala_Lumpur",
|
||||
"Asia/Kuching",
|
||||
"Asia/Kuwait",
|
||||
"Asia/Macau",
|
||||
"Asia/Magadan",
|
||||
"Asia/Makassar",
|
||||
"Asia/Manila",
|
||||
"Asia/Muscat",
|
||||
"Asia/Nicosia",
|
||||
"Asia/Novokuznetsk",
|
||||
"Asia/Novosibirsk",
|
||||
"Asia/Omsk",
|
||||
"Asia/Oral",
|
||||
"Asia/Phnom_Penh",
|
||||
"Asia/Pontianak",
|
||||
"Asia/Pyongyang",
|
||||
"Asia/Qatar",
|
||||
"Asia/Qostanay",
|
||||
"Asia/Qyzylorda",
|
||||
"Asia/Rangoon",
|
||||
"Asia/Riyadh",
|
||||
"Asia/Saigon",
|
||||
"Asia/Sakhalin",
|
||||
"Asia/Samarkand",
|
||||
"Asia/Seoul",
|
||||
"Asia/Shanghai",
|
||||
"Asia/Singapore",
|
||||
"Asia/Srednekolymsk",
|
||||
"Asia/Taipei",
|
||||
"Asia/Tashkent",
|
||||
"Asia/Tbilisi",
|
||||
"Asia/Tehran",
|
||||
"Asia/Thimphu",
|
||||
"Asia/Tokyo",
|
||||
"Asia/Tomsk",
|
||||
"Asia/Ulaanbaatar",
|
||||
"Asia/Urumqi",
|
||||
"Asia/Ust-Nera",
|
||||
"Asia/Vientiane",
|
||||
"Asia/Vladivostok",
|
||||
"Asia/Yakutsk",
|
||||
"Asia/Yekaterinburg",
|
||||
"Asia/Yerevan",
|
||||
"Atlantic/Azores",
|
||||
"Atlantic/Bermuda",
|
||||
"Atlantic/Canary",
|
||||
"Atlantic/Cape_Verde",
|
||||
"Atlantic/Faeroe",
|
||||
"Atlantic/Madeira",
|
||||
"Atlantic/Reykjavik",
|
||||
"Atlantic/South_Georgia",
|
||||
"Atlantic/St_Helena",
|
||||
"Atlantic/Stanley",
|
||||
"Australia/Adelaide",
|
||||
"Australia/Brisbane",
|
||||
"Australia/Broken_Hill",
|
||||
"Australia/Darwin",
|
||||
"Australia/Eucla",
|
||||
"Australia/Hobart",
|
||||
"Australia/Lindeman",
|
||||
"Australia/Lord_Howe",
|
||||
"Australia/Melbourne",
|
||||
"Australia/Perth",
|
||||
"Australia/Sydney",
|
||||
"Europe/Amsterdam",
|
||||
"Europe/Andorra",
|
||||
"Europe/Astrakhan",
|
||||
"Europe/Athens",
|
||||
"Europe/Belgrade",
|
||||
"Europe/Berlin",
|
||||
"Europe/Bratislava",
|
||||
"Europe/Brussels",
|
||||
"Europe/Bucharest",
|
||||
"Europe/Budapest",
|
||||
"Europe/Busingen",
|
||||
"Europe/Chisinau",
|
||||
"Europe/Copenhagen",
|
||||
"Europe/Dublin",
|
||||
"Europe/Gibraltar",
|
||||
"Europe/Guernsey",
|
||||
"Europe/Helsinki",
|
||||
"Europe/Isle_of_Man",
|
||||
"Europe/Istanbul",
|
||||
"Europe/Jersey",
|
||||
"Europe/Kaliningrad",
|
||||
"Europe/Kiev",
|
||||
"Europe/Kirov",
|
||||
"Europe/Lisbon",
|
||||
"Europe/Ljubljana",
|
||||
"Europe/London",
|
||||
"Europe/Luxembourg",
|
||||
"Europe/Madrid",
|
||||
"Europe/Malta",
|
||||
"Europe/Mariehamn",
|
||||
"Europe/Minsk",
|
||||
"Europe/Monaco",
|
||||
"Europe/Moscow",
|
||||
"Europe/Oslo",
|
||||
"Europe/Paris",
|
||||
"Europe/Podgorica",
|
||||
"Europe/Prague",
|
||||
"Europe/Riga",
|
||||
"Europe/Rome",
|
||||
"Europe/Samara",
|
||||
"Europe/San_Marino",
|
||||
"Europe/Sarajevo",
|
||||
"Europe/Saratov",
|
||||
"Europe/Simferopol",
|
||||
"Europe/Skopje",
|
||||
"Europe/Sofia",
|
||||
"Europe/Stockholm",
|
||||
"Europe/Tallinn",
|
||||
"Europe/Tirane",
|
||||
"Europe/Ulyanovsk",
|
||||
"Europe/Vaduz",
|
||||
"Europe/Vatican",
|
||||
"Europe/Vienna",
|
||||
"Europe/Vilnius",
|
||||
"Europe/Volgograd",
|
||||
"Europe/Warsaw",
|
||||
"Europe/Zagreb",
|
||||
"Europe/Zurich",
|
||||
"Indian/Antananarivo",
|
||||
"Indian/Chagos",
|
||||
"Indian/Christmas",
|
||||
"Indian/Cocos",
|
||||
"Indian/Comoro",
|
||||
"Indian/Kerguelen",
|
||||
"Indian/Mahe",
|
||||
"Indian/Maldives",
|
||||
"Indian/Mauritius",
|
||||
"Indian/Mayotte",
|
||||
"Indian/Reunion",
|
||||
"Pacific/Apia",
|
||||
"Pacific/Auckland",
|
||||
"Pacific/Bougainville",
|
||||
"Pacific/Chatham",
|
||||
"Pacific/Easter",
|
||||
"Pacific/Efate",
|
||||
"Pacific/Enderbury",
|
||||
"Pacific/Fakaofo",
|
||||
"Pacific/Fiji",
|
||||
"Pacific/Funafuti",
|
||||
"Pacific/Galapagos",
|
||||
"Pacific/Gambier",
|
||||
"Pacific/Guadalcanal",
|
||||
"Pacific/Guam",
|
||||
"Pacific/Honolulu",
|
||||
"Pacific/Kiritimati",
|
||||
"Pacific/Kosrae",
|
||||
"Pacific/Kwajalein",
|
||||
"Pacific/Majuro",
|
||||
"Pacific/Marquesas",
|
||||
"Pacific/Midway",
|
||||
"Pacific/Nauru",
|
||||
"Pacific/Niue",
|
||||
"Pacific/Norfolk",
|
||||
"Pacific/Noumea",
|
||||
"Pacific/Pago_Pago",
|
||||
"Pacific/Palau",
|
||||
"Pacific/Pitcairn",
|
||||
"Pacific/Ponape",
|
||||
"Pacific/Port_Moresby",
|
||||
"Pacific/Rarotonga",
|
||||
"Pacific/Saipan",
|
||||
"Pacific/Tahiti",
|
||||
"Pacific/Tarawa",
|
||||
"Pacific/Tongatapu",
|
||||
"Pacific/Truk",
|
||||
"Pacific/Wake",
|
||||
"Pacific/Wallis"
|
||||
]
|
||||
|
||||
LODGING_TYPES = [
|
||||
('hotel', 'Hotel'),
|
||||
('hostel', 'Hostel'),
|
||||
('resort', 'Resort'),
|
||||
('bnb', 'Bed & Breakfast'),
|
||||
('campground', 'Campground'),
|
||||
('cabin', 'Cabin'),
|
||||
('apartment', 'Apartment'),
|
||||
('house', 'House'),
|
||||
('villa', 'Villa'),
|
||||
('motel', 'Motel'),
|
||||
('other', 'Other')
|
||||
]
|
||||
|
||||
TRANSPORTATION_TYPES = [
|
||||
('car', 'Car'),
|
||||
('plane', 'Plane'),
|
||||
|
@ -50,8 +540,9 @@ User = get_user_model()
|
|||
class Visit(models.Model):
|
||||
id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
|
||||
adventure = models.ForeignKey('Adventure', on_delete=models.CASCADE, related_name='visits')
|
||||
start_date = models.DateField(null=True, blank=True)
|
||||
end_date = models.DateField(null=True, blank=True)
|
||||
start_date = models.DateTimeField(null=True, blank=True)
|
||||
end_date = models.DateTimeField(null=True, blank=True)
|
||||
timezone = models.CharField(max_length=50, choices=[(tz, tz) for tz in TIMEZONES], null=True, blank=True)
|
||||
notes = models.TextField(blank=True, null=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
@ -68,7 +559,8 @@ class Adventure(models.Model):
|
|||
id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
|
||||
user_id = models.ForeignKey(
|
||||
User, on_delete=models.CASCADE, default=default_user_id)
|
||||
type = models.CharField(max_length=100, choices=ADVENTURE_TYPES, default='general')
|
||||
|
||||
category = models.ForeignKey('Category', on_delete=models.SET_NULL, blank=True, null=True)
|
||||
name = models.CharField(max_length=200)
|
||||
location = models.CharField(max_length=200, blank=True, null=True)
|
||||
activity_types = ArrayField(models.CharField(
|
||||
|
@ -77,28 +569,92 @@ class Adventure(models.Model):
|
|||
rating = models.FloatField(blank=True, null=True)
|
||||
link = models.URLField(blank=True, null=True, max_length=2083)
|
||||
is_public = models.BooleanField(default=False)
|
||||
|
||||
longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
|
||||
latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
|
||||
collection = models.ForeignKey('Collection', on_delete=models.CASCADE, blank=True, null=True)
|
||||
|
||||
city = models.ForeignKey(City, on_delete=models.SET_NULL, blank=True, null=True)
|
||||
region = models.ForeignKey(Region, on_delete=models.SET_NULL, blank=True, null=True)
|
||||
country = models.ForeignKey(Country, on_delete=models.SET_NULL, blank=True, null=True)
|
||||
|
||||
# Changed from ForeignKey to ManyToManyField
|
||||
collections = models.ManyToManyField('Collection', blank=True, related_name='adventures')
|
||||
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
# DEPRECATED FIELDS - TO BE REMOVED IN FUTURE VERSIONS
|
||||
# Migrations performed in this version will remove these fields
|
||||
# image = ResizedImageField(force_format="WEBP", quality=75, null=True, blank=True, upload_to='images/')
|
||||
# date = models.DateField(blank=True, null=True)
|
||||
# end_date = models.DateField(blank=True, null=True)
|
||||
objects = AdventureManager()
|
||||
|
||||
def clean(self):
|
||||
if self.date and self.end_date and self.date > self.end_date:
|
||||
raise ValidationError('The start date must be before the end date. Start date: ' + str(self.date) + ' End date: ' + str(self.end_date))
|
||||
if self.end_date and not self.date:
|
||||
raise ValidationError('Adventures must have an end date. Adventure: ' + self.name)
|
||||
if self.collection:
|
||||
if self.collection.is_public and not self.is_public:
|
||||
raise ValidationError('Adventures associated with a public collection must be public. Collection: ' + self.trip.name + ' Adventure: ' + self.name)
|
||||
if self.user_id != self.collection.user_id:
|
||||
raise ValidationError('Adventures must be associated with collections owned by the same user. Collection owner: ' + self.collection.user_id.username + ' Adventure owner: ' + self.user_id.username)
|
||||
def is_visited_status(self):
|
||||
current_date = timezone.now().date()
|
||||
for visit in self.visits.all():
|
||||
start_date = visit.start_date.date() if isinstance(visit.start_date, timezone.datetime) else visit.start_date
|
||||
end_date = visit.end_date.date() if isinstance(visit.end_date, timezone.datetime) else visit.end_date
|
||||
if start_date and end_date and (start_date <= current_date):
|
||||
return True
|
||||
elif start_date and not end_date and (start_date <= current_date):
|
||||
return True
|
||||
return False
|
||||
|
||||
def clean(self, skip_shared_validation=False):
|
||||
"""
|
||||
Validate model constraints.
|
||||
skip_shared_validation: Skip validation when called by shared users
|
||||
"""
|
||||
# Skip validation if this is a shared user update
|
||||
if skip_shared_validation:
|
||||
return
|
||||
|
||||
# Check collections after the instance is saved (in save method or separate validation)
|
||||
if self.pk: # Only check if the instance has been saved
|
||||
for collection in self.collections.all():
|
||||
if collection.is_public and not self.is_public:
|
||||
raise ValidationError(f'Adventures associated with a public collection must be public. Collection: {collection.name} Adventure: {self.name}')
|
||||
|
||||
# Only enforce same-user constraint for non-shared collections
|
||||
if self.user_id != collection.user_id:
|
||||
# Check if this is a shared collection scenario
|
||||
# Allow if the adventure owner has access to the collection through sharing
|
||||
if not collection.shared_with.filter(uuid=self.user_id.uuid).exists():
|
||||
raise ValidationError(f'Adventures must be associated with collections owned by the same user or shared collections. Collection owner: {collection.user_id.username} Adventure owner: {self.user_id.username}')
|
||||
|
||||
if self.category:
|
||||
if self.user_id != self.category.user_id:
|
||||
raise ValidationError(f'Adventures must be associated with categories owned by the same user. Category owner: {self.category.user_id.username} Adventure owner: {self.user_id.username}')
|
||||
|
||||
def save(self, force_insert=False, force_update=False, using=None, update_fields=None, _skip_geocode=False, _skip_shared_validation=False):
|
||||
if force_insert and force_update:
|
||||
raise ValueError("Cannot force both insert and updating in model saving.")
|
||||
|
||||
if not self.category:
|
||||
category, _ = Category.objects.get_or_create(
|
||||
user_id=self.user_id,
|
||||
name='general',
|
||||
defaults={'display_name': 'General', 'icon': '🌍'}
|
||||
)
|
||||
self.category = category
|
||||
|
||||
result = super().save(force_insert, force_update, using, update_fields)
|
||||
|
||||
# Validate collections after saving (since M2M relationships require saved instance)
|
||||
if self.pk:
|
||||
try:
|
||||
self.clean(skip_shared_validation=_skip_shared_validation)
|
||||
except ValidationError as e:
|
||||
# If validation fails, you might want to handle this differently
|
||||
# For now, we'll re-raise the error
|
||||
raise e
|
||||
|
||||
# ⛔ Skip threading if called from geocode background thread
|
||||
if _skip_geocode:
|
||||
return result
|
||||
|
||||
if self.latitude and self.longitude:
|
||||
thread = threading.Thread(target=background_geocode_and_assign, args=(str(self.id),))
|
||||
thread.daemon = True # Allows the thread to exit when the main program ends
|
||||
thread.start()
|
||||
|
||||
return result
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
@ -119,13 +675,13 @@ class Collection(models.Model):
|
|||
shared_with = models.ManyToManyField(User, related_name='shared_with', blank=True)
|
||||
link = models.URLField(blank=True, null=True, max_length=2083)
|
||||
|
||||
|
||||
# if connected adventures are private and collection is public, raise an error
|
||||
def clean(self):
|
||||
if self.is_public and self.pk: # Only check if the instance has a primary key
|
||||
for adventure in self.adventure_set.all():
|
||||
# Updated to use the new related_name 'adventures'
|
||||
for adventure in self.adventures.all():
|
||||
if not adventure.is_public:
|
||||
raise ValidationError('Public collections cannot be associated with private adventures. Collection: ' + self.name + ' Adventure: ' + adventure.name)
|
||||
raise ValidationError(f'Public collections cannot be associated with private adventures. Collection: {self.name} Adventure: {adventure.name}')
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
@ -142,8 +698,14 @@ class Transportation(models.Model):
|
|||
link = models.URLField(blank=True, null=True)
|
||||
date = models.DateTimeField(blank=True, null=True)
|
||||
end_date = models.DateTimeField(blank=True, null=True)
|
||||
start_timezone = models.CharField(max_length=50, choices=[(tz, tz) for tz in TIMEZONES], null=True, blank=True)
|
||||
end_timezone = models.CharField(max_length=50, choices=[(tz, tz) for tz in TIMEZONES], null=True, blank=True)
|
||||
flight_number = models.CharField(max_length=100, blank=True, null=True)
|
||||
from_location = models.CharField(max_length=200, blank=True, null=True)
|
||||
origin_latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
|
||||
origin_longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
|
||||
destination_latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
|
||||
destination_longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
|
||||
to_location = models.CharField(max_length=200, blank=True, null=True)
|
||||
is_public = models.BooleanField(default=False)
|
||||
collection = models.ForeignKey('Collection', on_delete=models.CASCADE, blank=True, null=True)
|
||||
|
@ -230,12 +792,118 @@ class ChecklistItem(models.Model):
|
|||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
@deconstructible
|
||||
class PathAndRename:
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
|
||||
def __call__(self, instance, filename):
|
||||
ext = filename.split('.')[-1]
|
||||
# Generate a new UUID for the filename
|
||||
filename = f"{uuid.uuid4()}.{ext}"
|
||||
return os.path.join(self.path, filename)
|
||||
|
||||
class AdventureImage(models.Model):
|
||||
id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
|
||||
user_id = models.ForeignKey(User, on_delete=models.CASCADE, default=default_user_id)
|
||||
image = ResizedImageField(
|
||||
force_format="WEBP",
|
||||
quality=75,
|
||||
upload_to=PathAndRename('images/'),
|
||||
blank=True,
|
||||
null=True,
|
||||
)
|
||||
immich_id = models.CharField(max_length=200, null=True, blank=True)
|
||||
adventure = models.ForeignKey(Adventure, related_name='images', on_delete=models.CASCADE)
|
||||
is_primary = models.BooleanField(default=False)
|
||||
|
||||
def clean(self):
|
||||
|
||||
# One of image or immich_id must be set, but not both
|
||||
has_image = bool(self.image and str(self.image).strip())
|
||||
has_immich_id = bool(self.immich_id and str(self.immich_id).strip())
|
||||
|
||||
if has_image and has_immich_id:
|
||||
raise ValidationError("Cannot have both image file and Immich ID. Please provide only one.")
|
||||
if not has_image and not has_immich_id:
|
||||
raise ValidationError("Must provide either an image file or an Immich ID.")
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
# Clean empty strings to None for proper database storage
|
||||
if not self.image:
|
||||
self.image = None
|
||||
if not self.immich_id or not str(self.immich_id).strip():
|
||||
self.immich_id = None
|
||||
|
||||
self.full_clean() # This calls clean() method
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
def __str__(self):
|
||||
return self.image.url if self.image else f"Immich ID: {self.immich_id or 'No image'}"
|
||||
|
||||
class Attachment(models.Model):
|
||||
id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
|
||||
user_id = models.ForeignKey(
|
||||
User, on_delete=models.CASCADE, default=default_user_id)
|
||||
image = ResizedImageField(force_format="WEBP", quality=75, upload_to='images/')
|
||||
adventure = models.ForeignKey(Adventure, related_name='images', on_delete=models.CASCADE)
|
||||
file = models.FileField(upload_to=PathAndRename('attachments/'),validators=[validate_file_extension])
|
||||
adventure = models.ForeignKey(Adventure, related_name='attachments', on_delete=models.CASCADE)
|
||||
name = models.CharField(max_length=200, null=True, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
return self.image.url
|
||||
return self.file.url
|
||||
|
||||
class Category(models.Model):
|
||||
id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
|
||||
user_id = models.ForeignKey(
|
||||
User, on_delete=models.CASCADE, default=default_user_id)
|
||||
name = models.CharField(max_length=200)
|
||||
display_name = models.CharField(max_length=200)
|
||||
icon = models.CharField(max_length=200, default='🌍')
|
||||
|
||||
class Meta:
|
||||
verbose_name_plural = 'Categories'
|
||||
unique_together = ['name', 'user_id']
|
||||
|
||||
def clean(self) -> None:
|
||||
self.name = self.name.lower().strip()
|
||||
|
||||
return super().clean()
|
||||
|
||||
|
||||
def __str__(self):
|
||||
return self.name + ' - ' + self.display_name + ' - ' + self.icon
|
||||
|
||||
class Lodging(models.Model):
|
||||
id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
|
||||
user_id = models.ForeignKey(
|
||||
User, on_delete=models.CASCADE, default=default_user_id)
|
||||
name = models.CharField(max_length=200)
|
||||
type = models.CharField(max_length=100, choices=LODGING_TYPES, default='other')
|
||||
description = models.TextField(blank=True, null=True)
|
||||
rating = models.FloatField(blank=True, null=True)
|
||||
link = models.URLField(blank=True, null=True, max_length=2083)
|
||||
check_in = models.DateTimeField(blank=True, null=True)
|
||||
check_out = models.DateTimeField(blank=True, null=True)
|
||||
timezone = models.CharField(max_length=50, choices=[(tz, tz) for tz in TIMEZONES], null=True, blank=True)
|
||||
reservation_number = models.CharField(max_length=100, blank=True, null=True)
|
||||
price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True)
|
||||
latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
|
||||
longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
|
||||
location = models.CharField(max_length=200, blank=True, null=True)
|
||||
is_public = models.BooleanField(default=False)
|
||||
collection = models.ForeignKey('Collection', on_delete=models.CASCADE, blank=True, null=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
def clean(self):
|
||||
if self.check_in and self.check_out and self.check_in > self.check_out:
|
||||
raise ValidationError('The start date must be before the end date. Start date: ' + str(self.check_in) + ' End date: ' + str(self.check_out))
|
||||
|
||||
if self.collection:
|
||||
if self.collection.is_public and not self.is_public:
|
||||
raise ValidationError('Lodging associated with a public collection must be public. Collection: ' + self.collection.name + ' Loging: ' + self.name)
|
||||
if self.user_id != self.collection.user_id:
|
||||
raise ValidationError('Lodging must be associated with collections owned by the same user. Collection owner: ' + self.collection.user_id.username + ' Lodging owner: ' + self.user_id.username)
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
|
@ -2,96 +2,99 @@ from rest_framework import permissions
|
|||
|
||||
class IsOwnerOrReadOnly(permissions.BasePermission):
|
||||
"""
|
||||
Custom permission to only allow owners of an object to edit it.
|
||||
Owners can edit, others have read-only access.
|
||||
"""
|
||||
|
||||
def has_object_permission(self, request, view, obj):
|
||||
# Read permissions are allowed to any request,
|
||||
# so we'll always allow GET, HEAD or OPTIONS requests.
|
||||
if request.method in permissions.SAFE_METHODS:
|
||||
return True
|
||||
|
||||
# Write permissions are only allowed to the owner of the object.
|
||||
# obj.user_id is FK to User, compare with request.user
|
||||
return obj.user_id == request.user
|
||||
|
||||
|
||||
class IsPublicReadOnly(permissions.BasePermission):
|
||||
"""
|
||||
Custom permission to only allow read-only access to public objects,
|
||||
and write access to the owner of the object.
|
||||
Read-only if public or owner, write only for owner.
|
||||
"""
|
||||
|
||||
def has_object_permission(self, request, view, obj):
|
||||
# Read permissions are allowed if the object is public
|
||||
if request.method in permissions.SAFE_METHODS:
|
||||
return obj.is_public or obj.user_id == request.user
|
||||
|
||||
# Write permissions are only allowed to the owner of the object
|
||||
return obj.user_id == request.user
|
||||
|
||||
|
||||
class CollectionShared(permissions.BasePermission):
|
||||
"""
|
||||
Custom permission to only allow read-only access to public objects,
|
||||
and write access to the owner of the object.
|
||||
Allow full access if user is in shared_with of collection(s) or owner,
|
||||
read-only if public or shared_with,
|
||||
write only if owner or shared_with.
|
||||
"""
|
||||
|
||||
def has_object_permission(self, request, view, obj):
|
||||
user = request.user
|
||||
if not user or not user.is_authenticated:
|
||||
# Anonymous: only read public
|
||||
return request.method in permissions.SAFE_METHODS and obj.is_public
|
||||
|
||||
# Read permissions are allowed if the object is shared with the user
|
||||
if obj.shared_with and obj.shared_with.filter(id=request.user.id).exists():
|
||||
# Check if user is in shared_with of any collections related to the obj
|
||||
# If obj is a Collection itself:
|
||||
if hasattr(obj, 'shared_with'):
|
||||
if obj.shared_with.filter(id=user.id).exists():
|
||||
return True
|
||||
|
||||
# Write permissions are allowed if the object is shared with the user
|
||||
if request.method not in permissions.SAFE_METHODS and obj.shared_with.filter(id=request.user.id).exists():
|
||||
# If obj is an Adventure (has collections M2M)
|
||||
if hasattr(obj, 'collections'):
|
||||
# Check if user is in shared_with of any related collection
|
||||
shared_collections = obj.collections.filter(shared_with=user)
|
||||
if shared_collections.exists():
|
||||
return True
|
||||
|
||||
# Read permissions are allowed if the object is public
|
||||
# Read permission if public or owner
|
||||
if request.method in permissions.SAFE_METHODS:
|
||||
return obj.is_public or obj.user_id == request.user
|
||||
return obj.is_public or obj.user_id == user
|
||||
|
||||
# Write permission only if owner or shared user via collections
|
||||
if obj.user_id == user:
|
||||
return True
|
||||
|
||||
if hasattr(obj, 'collections'):
|
||||
if obj.collections.filter(shared_with=user).exists():
|
||||
return True
|
||||
|
||||
# Default deny
|
||||
return False
|
||||
|
||||
# Write permissions are only allowed to the owner of the object
|
||||
return obj.user_id == request.user
|
||||
|
||||
class IsOwnerOrSharedWithFullAccess(permissions.BasePermission):
|
||||
"""
|
||||
Custom permission to allow:
|
||||
- Full access for shared users
|
||||
- Full access for owners
|
||||
- Read-only access for others on safe methods
|
||||
Full access for owners and users shared via collections,
|
||||
read-only for others if public.
|
||||
"""
|
||||
|
||||
def has_object_permission(self, request, view, obj):
|
||||
# Check if the object has a collection
|
||||
if hasattr(obj, 'collection') and obj.collection:
|
||||
# Allow all actions for shared users
|
||||
if request.user in obj.collection.shared_with.all():
|
||||
return True
|
||||
user = request.user
|
||||
if not user or not user.is_authenticated:
|
||||
return request.method in permissions.SAFE_METHODS and obj.is_public
|
||||
|
||||
# Always allow GET, HEAD, or OPTIONS requests (safe methods)
|
||||
# If safe method (read), allow if:
|
||||
if request.method in permissions.SAFE_METHODS:
|
||||
if obj.is_public:
|
||||
return True
|
||||
if obj.user_id == user:
|
||||
return True
|
||||
# If user in shared_with of any collection related to obj
|
||||
if hasattr(obj, 'collections') and obj.collections.filter(shared_with=user).exists():
|
||||
return True
|
||||
if hasattr(obj, 'collection') and obj.collection and obj.collection.shared_with.filter(id=user.id).exists():
|
||||
return True
|
||||
if hasattr(obj, 'shared_with') and obj.shared_with.filter(id=user.id).exists():
|
||||
return True
|
||||
return False
|
||||
|
||||
# For write methods, allow if owner or shared user
|
||||
if obj.user_id == user:
|
||||
return True
|
||||
if hasattr(obj, 'collections') and obj.collections.filter(shared_with=user).exists():
|
||||
return True
|
||||
if hasattr(obj, 'collection') and obj.collection and obj.collection.shared_with.filter(id=user.id).exists():
|
||||
return True
|
||||
if hasattr(obj, 'shared_with') and obj.shared_with.filter(id=user.id).exists():
|
||||
return True
|
||||
|
||||
# Allow all actions for the owner
|
||||
return obj.user_id == request.user
|
||||
|
||||
class IsPublicOrOwnerOrSharedWithFullAccess(permissions.BasePermission):
|
||||
"""
|
||||
Custom permission to allow:
|
||||
- Read-only access for public objects
|
||||
- Full access for shared users
|
||||
- Full access for owners
|
||||
"""
|
||||
|
||||
def has_object_permission(self, request, view, obj):
|
||||
# Allow read-only access for public objects
|
||||
if obj.is_public and request.method in permissions.SAFE_METHODS:
|
||||
return True
|
||||
|
||||
# Check if the object has a collection
|
||||
if hasattr(obj, 'collection') and obj.collection:
|
||||
# Allow all actions for shared users
|
||||
if request.user in obj.collection.shared_with.all():
|
||||
return True
|
||||
|
||||
# Allow all actions for the owner
|
||||
return obj.user_id == request.user
|
||||
return False
|
||||
|
|
|
@ -1,61 +1,236 @@
|
|||
from django.utils import timezone
|
||||
import os
|
||||
from .models import Adventure, AdventureImage, ChecklistItem, Collection, Note, Transportation, Checklist, Visit
|
||||
from .models import Adventure, AdventureImage, ChecklistItem, Collection, Note, Transportation, Checklist, Visit, Category, Attachment, Lodging
|
||||
from rest_framework import serializers
|
||||
from main.utils import CustomModelSerializer
|
||||
from users.serializers import CustomUserDetailsSerializer
|
||||
from worldtravel.serializers import CountrySerializer, RegionSerializer, CitySerializer
|
||||
from geopy.distance import geodesic
|
||||
from integrations.models import ImmichIntegration
|
||||
|
||||
class AdventureImageSerializer(serializers.ModelSerializer):
|
||||
|
||||
class AdventureImageSerializer(CustomModelSerializer):
|
||||
class Meta:
|
||||
model = AdventureImage
|
||||
fields = ['id', 'image', 'adventure']
|
||||
read_only_fields = ['id']
|
||||
fields = ['id', 'image', 'adventure', 'is_primary', 'user_id', 'immich_id']
|
||||
read_only_fields = ['id', 'user_id']
|
||||
|
||||
def to_representation(self, instance):
|
||||
# If immich_id is set, check for user integration once
|
||||
integration = None
|
||||
if instance.immich_id:
|
||||
integration = ImmichIntegration.objects.filter(user=instance.user_id).first()
|
||||
if not integration:
|
||||
return None # Skip if Immich image but no integration
|
||||
|
||||
# Base representation
|
||||
representation = super().to_representation(instance)
|
||||
|
||||
# Prepare public URL once
|
||||
public_url = os.environ.get('PUBLIC_URL', 'http://127.0.0.1:8000').rstrip('/').replace("'", "")
|
||||
|
||||
if instance.immich_id:
|
||||
# Use Immich integration URL
|
||||
representation['image'] = f"{public_url}/api/integrations/immich/{integration.id}/get/{instance.immich_id}"
|
||||
elif instance.image:
|
||||
# Use local image URL
|
||||
representation['image'] = f"{public_url}/media/{instance.image.name}"
|
||||
|
||||
return representation
|
||||
|
||||
class AttachmentSerializer(CustomModelSerializer):
|
||||
extension = serializers.SerializerMethodField()
|
||||
class Meta:
|
||||
model = Attachment
|
||||
fields = ['id', 'file', 'adventure', 'extension', 'name', 'user_id']
|
||||
read_only_fields = ['id', 'user_id']
|
||||
|
||||
def get_extension(self, obj):
|
||||
return obj.file.name.split('.')[-1]
|
||||
|
||||
def to_representation(self, instance):
|
||||
representation = super().to_representation(instance)
|
||||
if instance.image:
|
||||
if instance.file:
|
||||
public_url = os.environ.get('PUBLIC_URL', 'http://127.0.0.1:8000').rstrip('/')
|
||||
#print(public_url)
|
||||
# remove any ' from the url
|
||||
public_url = public_url.replace("'", "")
|
||||
representation['image'] = f"{public_url}/media/{instance.image.name}"
|
||||
representation['file'] = f"{public_url}/media/{instance.file.name}"
|
||||
return representation
|
||||
|
||||
class VisitSerializer(serializers.ModelSerializer):
|
||||
class CategorySerializer(serializers.ModelSerializer):
|
||||
num_adventures = serializers.SerializerMethodField()
|
||||
class Meta:
|
||||
model = Visit
|
||||
fields = ['id', 'start_date', 'end_date', 'notes']
|
||||
read_only_fields = ['id']
|
||||
model = Category
|
||||
fields = ['id', 'name', 'display_name', 'icon', 'num_adventures']
|
||||
read_only_fields = ['id', 'num_adventures']
|
||||
|
||||
class AdventureSerializer(serializers.ModelSerializer):
|
||||
images = AdventureImageSerializer(many=True, read_only=True)
|
||||
visits = VisitSerializer(many=True, read_only=False)
|
||||
class Meta:
|
||||
model = Adventure
|
||||
fields = ['id', 'user_id', 'name', 'description', 'rating', 'activity_types', 'location', 'is_public', 'collection', 'created_at', 'updated_at', 'images', 'link', 'type', 'longitude', 'latitude', 'visits']
|
||||
read_only_fields = ['id', 'created_at', 'updated_at', 'user_id']
|
||||
|
||||
def to_representation(self, instance):
|
||||
representation = super().to_representation(instance)
|
||||
return representation
|
||||
def validate_name(self, value):
|
||||
return value.lower()
|
||||
|
||||
def create(self, validated_data):
|
||||
visits_data = validated_data.pop('visits', [])
|
||||
user = self.context['request'].user
|
||||
validated_data['name'] = validated_data['name'].lower()
|
||||
return Category.objects.create(user_id=user, **validated_data)
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
for attr, value in validated_data.items():
|
||||
setattr(instance, attr, value)
|
||||
if 'name' in validated_data:
|
||||
instance.name = validated_data['name'].lower()
|
||||
instance.save()
|
||||
return instance
|
||||
|
||||
def get_num_adventures(self, obj):
|
||||
return Adventure.objects.filter(category=obj, user_id=obj.user_id).count()
|
||||
|
||||
class VisitSerializer(serializers.ModelSerializer):
|
||||
|
||||
class Meta:
|
||||
model = Visit
|
||||
fields = ['id', 'start_date', 'end_date', 'timezone', 'notes']
|
||||
read_only_fields = ['id']
|
||||
|
||||
class AdventureSerializer(CustomModelSerializer):
|
||||
images = serializers.SerializerMethodField()
|
||||
visits = VisitSerializer(many=True, read_only=False, required=False)
|
||||
attachments = AttachmentSerializer(many=True, read_only=True)
|
||||
category = CategorySerializer(read_only=False, required=False)
|
||||
is_visited = serializers.SerializerMethodField()
|
||||
user = serializers.SerializerMethodField()
|
||||
country = CountrySerializer(read_only=True)
|
||||
region = RegionSerializer(read_only=True)
|
||||
city = CitySerializer(read_only=True)
|
||||
collections = serializers.PrimaryKeyRelatedField(
|
||||
many=True,
|
||||
queryset=Collection.objects.all(),
|
||||
required=False
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Adventure
|
||||
fields = [
|
||||
'id', 'user_id', 'name', 'description', 'rating', 'activity_types', 'location',
|
||||
'is_public', 'collections', 'created_at', 'updated_at', 'images', 'link', 'longitude',
|
||||
'latitude', 'visits', 'is_visited', 'category', 'attachments', 'user', 'city', 'country', 'region'
|
||||
]
|
||||
read_only_fields = ['id', 'created_at', 'updated_at', 'user_id', 'is_visited', 'user']
|
||||
|
||||
def get_images(self, obj):
|
||||
serializer = AdventureImageSerializer(obj.images.all(), many=True, context=self.context)
|
||||
# Filter out None values from the serialized data
|
||||
return [image for image in serializer.data if image is not None]
|
||||
|
||||
def validate_collections(self, collections):
|
||||
"""Validate that collections belong to the same user"""
|
||||
if not collections:
|
||||
return collections
|
||||
|
||||
user = self.context['request'].user
|
||||
for collection in collections:
|
||||
if collection.user_id != user and not collection.shared_with.filter(id=user.id).exists():
|
||||
raise serializers.ValidationError(
|
||||
f"Collection '{collection.name}' does not belong to the current user."
|
||||
)
|
||||
return collections
|
||||
|
||||
def validate_category(self, category_data):
|
||||
if isinstance(category_data, Category):
|
||||
return category_data
|
||||
if category_data:
|
||||
user = self.context['request'].user
|
||||
name = category_data.get('name', '').lower()
|
||||
existing_category = Category.objects.filter(user_id=user, name=name).first()
|
||||
if existing_category:
|
||||
return existing_category
|
||||
category_data['name'] = name
|
||||
return category_data
|
||||
|
||||
def get_or_create_category(self, category_data):
|
||||
user = self.context['request'].user
|
||||
|
||||
if isinstance(category_data, Category):
|
||||
return category_data
|
||||
|
||||
if isinstance(category_data, dict):
|
||||
name = category_data.get('name', '').lower()
|
||||
display_name = category_data.get('display_name', name)
|
||||
icon = category_data.get('icon', '🌍')
|
||||
else:
|
||||
name = category_data.name.lower()
|
||||
display_name = category_data.display_name
|
||||
icon = category_data.icon
|
||||
|
||||
category, created = Category.objects.get_or_create(
|
||||
user_id=user,
|
||||
name=name,
|
||||
defaults={
|
||||
'display_name': display_name,
|
||||
'icon': icon
|
||||
}
|
||||
)
|
||||
return category
|
||||
|
||||
def get_user(self, obj):
|
||||
user = obj.user_id
|
||||
return CustomUserDetailsSerializer(user).data
|
||||
|
||||
def get_is_visited(self, obj):
|
||||
return obj.is_visited_status()
|
||||
|
||||
def create(self, validated_data):
|
||||
visits_data = validated_data.pop('visits', None)
|
||||
category_data = validated_data.pop('category', None)
|
||||
collections_data = validated_data.pop('collections', [])
|
||||
|
||||
print(category_data)
|
||||
adventure = Adventure.objects.create(**validated_data)
|
||||
|
||||
# Handle visits
|
||||
for visit_data in visits_data:
|
||||
Visit.objects.create(adventure=adventure, **visit_data)
|
||||
|
||||
# Handle category
|
||||
if category_data:
|
||||
category = self.get_or_create_category(category_data)
|
||||
adventure.category = category
|
||||
|
||||
# Handle collections - set after adventure is saved
|
||||
if collections_data:
|
||||
adventure.collections.set(collections_data)
|
||||
|
||||
adventure.save()
|
||||
|
||||
return adventure
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
has_visits = 'visits' in validated_data
|
||||
visits_data = validated_data.pop('visits', [])
|
||||
category_data = validated_data.pop('category', None)
|
||||
|
||||
# Update Adventure fields
|
||||
collections_data = validated_data.pop('collections', None)
|
||||
|
||||
# Update regular fields
|
||||
for attr, value in validated_data.items():
|
||||
setattr(instance, attr, value)
|
||||
instance.save()
|
||||
|
||||
# Get current visits
|
||||
# Handle category - ONLY allow the adventure owner to change categories
|
||||
user = self.context['request'].user
|
||||
if category_data and instance.user_id == user:
|
||||
# Only the owner can set categories
|
||||
category = self.get_or_create_category(category_data)
|
||||
instance.category = category
|
||||
# If not the owner, ignore category changes
|
||||
|
||||
# Handle collections - only update if collections were provided
|
||||
if collections_data is not None:
|
||||
instance.collections.set(collections_data)
|
||||
|
||||
# Handle visits
|
||||
if has_visits:
|
||||
current_visits = instance.visits.all()
|
||||
current_visit_ids = set(current_visits.values_list('id', flat=True))
|
||||
|
||||
# Update or create visits
|
||||
updated_visit_ids = set()
|
||||
for visit_data in visits_data:
|
||||
visit_id = visit_data.get('id')
|
||||
|
@ -66,28 +241,56 @@ class AdventureSerializer(serializers.ModelSerializer):
|
|||
visit.save()
|
||||
updated_visit_ids.add(visit_id)
|
||||
else:
|
||||
# If no ID is provided or ID doesn't exist, create new visit
|
||||
new_visit = Visit.objects.create(adventure=instance, **visit_data)
|
||||
updated_visit_ids.add(new_visit.id)
|
||||
|
||||
# Delete visits that are not in the updated data
|
||||
visits_to_delete = current_visit_ids - updated_visit_ids
|
||||
instance.visits.filter(id__in=visits_to_delete).delete()
|
||||
|
||||
# call save on the adventure to update the updated_at field and trigger any geocoding
|
||||
instance.save()
|
||||
|
||||
return instance
|
||||
|
||||
class TransportationSerializer(serializers.ModelSerializer):
|
||||
class TransportationSerializer(CustomModelSerializer):
|
||||
distance = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = Transportation
|
||||
fields = [
|
||||
'id', 'user_id', 'type', 'name', 'description', 'rating',
|
||||
'link', 'date', 'flight_number', 'from_location', 'to_location',
|
||||
'is_public', 'collection', 'created_at', 'updated_at', 'end_date'
|
||||
'is_public', 'collection', 'created_at', 'updated_at', 'end_date',
|
||||
'origin_latitude', 'origin_longitude', 'destination_latitude', 'destination_longitude',
|
||||
'start_timezone', 'end_timezone', 'distance' # ✅ Add distance here
|
||||
]
|
||||
read_only_fields = ['id', 'created_at', 'updated_at', 'user_id', 'distance']
|
||||
|
||||
def get_distance(self, obj):
|
||||
if (
|
||||
obj.origin_latitude and obj.origin_longitude and
|
||||
obj.destination_latitude and obj.destination_longitude
|
||||
):
|
||||
try:
|
||||
origin = (float(obj.origin_latitude), float(obj.origin_longitude))
|
||||
destination = (float(obj.destination_latitude), float(obj.destination_longitude))
|
||||
return round(geodesic(origin, destination).km, 2)
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
class LodgingSerializer(CustomModelSerializer):
|
||||
|
||||
class Meta:
|
||||
model = Lodging
|
||||
fields = [
|
||||
'id', 'user_id', 'name', 'description', 'rating', 'link', 'check_in', 'check_out',
|
||||
'reservation_number', 'price', 'latitude', 'longitude', 'location', 'is_public',
|
||||
'collection', 'created_at', 'updated_at', 'type', 'timezone'
|
||||
]
|
||||
read_only_fields = ['id', 'created_at', 'updated_at', 'user_id']
|
||||
|
||||
class NoteSerializer(serializers.ModelSerializer):
|
||||
class NoteSerializer(CustomModelSerializer):
|
||||
|
||||
class Meta:
|
||||
model = Note
|
||||
|
@ -97,7 +300,7 @@ class NoteSerializer(serializers.ModelSerializer):
|
|||
]
|
||||
read_only_fields = ['id', 'created_at', 'updated_at', 'user_id']
|
||||
|
||||
class ChecklistItemSerializer(serializers.ModelSerializer):
|
||||
class ChecklistItemSerializer(CustomModelSerializer):
|
||||
class Meta:
|
||||
model = ChecklistItem
|
||||
fields = [
|
||||
|
@ -105,8 +308,9 @@ class ChecklistItemSerializer(serializers.ModelSerializer):
|
|||
]
|
||||
read_only_fields = ['id', 'created_at', 'updated_at', 'user_id', 'checklist']
|
||||
|
||||
class ChecklistSerializer(serializers.ModelSerializer):
|
||||
class ChecklistSerializer(CustomModelSerializer):
|
||||
items = ChecklistItemSerializer(many=True, source='checklistitem_set')
|
||||
|
||||
class Meta:
|
||||
model = Checklist
|
||||
fields = [
|
||||
|
@ -117,8 +321,16 @@ class ChecklistSerializer(serializers.ModelSerializer):
|
|||
def create(self, validated_data):
|
||||
items_data = validated_data.pop('checklistitem_set')
|
||||
checklist = Checklist.objects.create(**validated_data)
|
||||
|
||||
for item_data in items_data:
|
||||
ChecklistItem.objects.create(checklist=checklist, **item_data)
|
||||
# Remove user_id from item_data to avoid constraint issues
|
||||
item_data.pop('user_id', None)
|
||||
# Set user_id from the parent checklist
|
||||
ChecklistItem.objects.create(
|
||||
checklist=checklist,
|
||||
user_id=checklist.user_id,
|
||||
**item_data
|
||||
)
|
||||
return checklist
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
|
@ -136,6 +348,9 @@ class ChecklistSerializer(serializers.ModelSerializer):
|
|||
# Update or create items
|
||||
updated_item_ids = set()
|
||||
for item_data in items_data:
|
||||
# Remove user_id from item_data to avoid constraint issues
|
||||
item_data.pop('user_id', None)
|
||||
|
||||
item_id = item_data.get('id')
|
||||
if item_id:
|
||||
if item_id in current_item_ids:
|
||||
|
@ -146,10 +361,18 @@ class ChecklistSerializer(serializers.ModelSerializer):
|
|||
updated_item_ids.add(item_id)
|
||||
else:
|
||||
# If ID is provided but doesn't exist, create new item
|
||||
ChecklistItem.objects.create(checklist=instance, **item_data)
|
||||
ChecklistItem.objects.create(
|
||||
checklist=instance,
|
||||
user_id=instance.user_id,
|
||||
**item_data
|
||||
)
|
||||
else:
|
||||
# If no ID is provided, create new item
|
||||
ChecklistItem.objects.create(checklist=instance, **item_data)
|
||||
ChecklistItem.objects.create(
|
||||
checklist=instance,
|
||||
user_id=instance.user_id,
|
||||
**item_data
|
||||
)
|
||||
|
||||
# Delete items that are not in the updated data
|
||||
items_to_delete = current_item_ids - updated_item_ids
|
||||
|
@ -165,18 +388,18 @@ class ChecklistSerializer(serializers.ModelSerializer):
|
|||
raise serializers.ValidationError(
|
||||
'Checklists associated with a public collection must be public.'
|
||||
)
|
||||
|
||||
return data
|
||||
|
||||
class CollectionSerializer(serializers.ModelSerializer):
|
||||
adventures = AdventureSerializer(many=True, read_only=True, source='adventure_set')
|
||||
class CollectionSerializer(CustomModelSerializer):
|
||||
adventures = AdventureSerializer(many=True, read_only=True)
|
||||
transportations = TransportationSerializer(many=True, read_only=True, source='transportation_set')
|
||||
notes = NoteSerializer(many=True, read_only=True, source='note_set')
|
||||
checklists = ChecklistSerializer(many=True, read_only=True, source='checklist_set')
|
||||
lodging = LodgingSerializer(many=True, read_only=True, source='lodging_set')
|
||||
|
||||
class Meta:
|
||||
model = Collection
|
||||
fields = ['id', 'description', 'user_id', 'name', 'is_public', 'adventures', 'created_at', 'start_date', 'end_date', 'transportations', 'notes', 'updated_at', 'checklists', 'is_archived', 'shared_with', 'link']
|
||||
fields = ['id', 'description', 'user_id', 'name', 'is_public', 'adventures', 'created_at', 'start_date', 'end_date', 'transportations', 'notes', 'updated_at', 'checklists', 'is_archived', 'shared_with', 'link', 'lodging']
|
||||
read_only_fields = ['id', 'created_at', 'updated_at', 'user_id']
|
||||
|
||||
def to_representation(self, instance):
|
||||
|
|
23
backend/server/adventures/signals.py
Normal file
23
backend/server/adventures/signals.py
Normal file
|
@ -0,0 +1,23 @@
|
|||
from django.db.models.signals import m2m_changed
|
||||
from django.dispatch import receiver
|
||||
from adventures.models import Adventure
|
||||
|
||||
@receiver(m2m_changed, sender=Adventure.collections.through)
|
||||
def update_adventure_publicity(sender, instance, action, **kwargs):
|
||||
"""
|
||||
Signal handler to update adventure publicity when collections are added/removed
|
||||
"""
|
||||
# Only process when collections are added or removed
|
||||
if action in ('post_add', 'post_remove', 'post_clear'):
|
||||
collections = instance.collections.all()
|
||||
|
||||
if collections.exists():
|
||||
# If any collection is public, make the adventure public
|
||||
has_public_collection = collections.filter(is_public=True).exists()
|
||||
|
||||
if has_public_collection and not instance.is_public:
|
||||
instance.is_public = True
|
||||
instance.save(update_fields=['is_public'])
|
||||
elif not has_public_collection and instance.is_public:
|
||||
instance.is_public = False
|
||||
instance.save(update_fields=['is_public'])
|
|
@ -1,6 +1,6 @@
|
|||
from django.urls import include, path
|
||||
from rest_framework.routers import DefaultRouter
|
||||
from .views import AdventureViewSet, ChecklistViewSet, CollectionViewSet, NoteViewSet, StatsViewSet, GenerateDescription, ActivityTypesView, TransportationViewSet, AdventureImageViewSet
|
||||
from adventures.views import *
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register(r'adventures', AdventureViewSet, basename='adventures')
|
||||
|
@ -12,7 +12,13 @@ router.register(r'transportations', TransportationViewSet, basename='transportat
|
|||
router.register(r'notes', NoteViewSet, basename='notes')
|
||||
router.register(r'checklists', ChecklistViewSet, basename='checklists')
|
||||
router.register(r'images', AdventureImageViewSet, basename='images')
|
||||
|
||||
router.register(r'reverse-geocode', ReverseGeocodeViewSet, basename='reverse-geocode')
|
||||
router.register(r'categories', CategoryViewSet, basename='categories')
|
||||
router.register(r'ics-calendar', IcsCalendarGeneratorViewSet, basename='ics-calendar')
|
||||
router.register(r'search', GlobalSearchView, basename='search')
|
||||
router.register(r'attachments', AttachmentViewSet, basename='attachments')
|
||||
router.register(r'lodging', LodgingViewSet, basename='lodging')
|
||||
router.register(r'recommendations', RecommendationsViewSet, basename='recommendations')
|
||||
|
||||
urlpatterns = [
|
||||
# Include the router under the 'api/' prefix
|
||||
|
|
48
backend/server/adventures/utils/file_permissions.py
Normal file
48
backend/server/adventures/utils/file_permissions.py
Normal file
|
@ -0,0 +1,48 @@
|
|||
from adventures.models import AdventureImage, Attachment
|
||||
|
||||
protected_paths = ['images/', 'attachments/']
|
||||
|
||||
def checkFilePermission(fileId, user, mediaType):
|
||||
if mediaType not in protected_paths:
|
||||
return True
|
||||
if mediaType == 'images/':
|
||||
try:
|
||||
# Construct the full relative path to match the database field
|
||||
image_path = f"images/{fileId}"
|
||||
# Fetch the AdventureImage object
|
||||
adventure = AdventureImage.objects.get(image=image_path).adventure
|
||||
if adventure.is_public:
|
||||
return True
|
||||
elif adventure.user_id == user:
|
||||
return True
|
||||
elif adventure.collections.exists():
|
||||
# Check if the user is in any collection's shared_with list
|
||||
for collection in adventure.collections.all():
|
||||
if collection.shared_with.filter(id=user.id).exists():
|
||||
return True
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
except AdventureImage.DoesNotExist:
|
||||
return False
|
||||
elif mediaType == 'attachments/':
|
||||
try:
|
||||
# Construct the full relative path to match the database field
|
||||
attachment_path = f"attachments/{fileId}"
|
||||
# Fetch the Attachment object
|
||||
attachment = Attachment.objects.get(file=attachment_path)
|
||||
adventure = attachment.adventure
|
||||
if adventure.is_public:
|
||||
return True
|
||||
elif adventure.user_id == user:
|
||||
return True
|
||||
elif adventure.collections.exists():
|
||||
# Check if the user is in any collection's shared_with list
|
||||
for collection in adventure.collections.all():
|
||||
if collection.shared_with.filter(id=user.id).exists():
|
||||
return True
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
except Attachment.DoesNotExist:
|
||||
return False
|
6
backend/server/adventures/utils/pagination.py
Normal file
6
backend/server/adventures/utils/pagination.py
Normal file
|
@ -0,0 +1,6 @@
|
|||
from rest_framework.pagination import PageNumberPagination
|
||||
|
||||
class StandardResultsSetPagination(PageNumberPagination):
|
||||
page_size = 25
|
||||
page_size_query_param = 'page_size'
|
||||
max_page_size = 1000
|
File diff suppressed because it is too large
Load diff
16
backend/server/adventures/views/__init__.py
Normal file
16
backend/server/adventures/views/__init__.py
Normal file
|
@ -0,0 +1,16 @@
|
|||
from .activity_types_view import *
|
||||
from .adventure_image_view import *
|
||||
from .adventure_view import *
|
||||
from .category_view import *
|
||||
from .checklist_view import *
|
||||
from .collection_view import *
|
||||
from .generate_description_view import *
|
||||
from .ics_calendar_view import *
|
||||
from .note_view import *
|
||||
from .reverse_geocode_view import *
|
||||
from .stats_view import *
|
||||
from .transportation_view import *
|
||||
from .global_search_view import *
|
||||
from .attachment_view import *
|
||||
from .lodging_view import *
|
||||
from .recommendations_view import *
|
32
backend/server/adventures/views/activity_types_view.py
Normal file
32
backend/server/adventures/views/activity_types_view.py
Normal file
|
@ -0,0 +1,32 @@
|
|||
from rest_framework import viewsets
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from adventures.models import Adventure
|
||||
|
||||
class ActivityTypesView(viewsets.ViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
@action(detail=False, methods=['get'])
|
||||
def types(self, request):
|
||||
"""
|
||||
Retrieve a list of distinct activity types for adventures associated with the current user.
|
||||
|
||||
Args:
|
||||
request (HttpRequest): The HTTP request object.
|
||||
|
||||
Returns:
|
||||
Response: A response containing a list of distinct activity types.
|
||||
"""
|
||||
types = Adventure.objects.filter(user_id=request.user.id).values_list('activity_types', flat=True).distinct()
|
||||
|
||||
allTypes = []
|
||||
|
||||
for i in types:
|
||||
if not i:
|
||||
continue
|
||||
for x in i:
|
||||
if x and x not in allTypes:
|
||||
allTypes.append(x)
|
||||
|
||||
return Response(allTypes)
|
215
backend/server/adventures/views/adventure_image_view.py
Normal file
215
backend/server/adventures/views/adventure_image_view.py
Normal file
|
@ -0,0 +1,215 @@
|
|||
from rest_framework import viewsets, status
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from django.db.models import Q
|
||||
from django.core.files.base import ContentFile
|
||||
from adventures.models import Adventure, AdventureImage
|
||||
from adventures.serializers import AdventureImageSerializer
|
||||
from integrations.models import ImmichIntegration
|
||||
import uuid
|
||||
import requests
|
||||
|
||||
class AdventureImageViewSet(viewsets.ModelViewSet):
|
||||
serializer_class = AdventureImageSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
@action(detail=True, methods=['post'])
|
||||
def image_delete(self, request, *args, **kwargs):
|
||||
return self.destroy(request, *args, **kwargs)
|
||||
|
||||
@action(detail=True, methods=['post'])
|
||||
def toggle_primary(self, request, *args, **kwargs):
|
||||
# Makes the image the primary image for the adventure, if there is already a primary image linked to the adventure, it is set to false and the new image is set to true. make sure that the permission is set to the owner of the adventure
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED)
|
||||
|
||||
instance = self.get_object()
|
||||
adventure = instance.adventure
|
||||
if adventure.user_id != request.user:
|
||||
return Response({"error": "User does not own this adventure"}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
# Check if the image is already the primary image
|
||||
if instance.is_primary:
|
||||
return Response({"error": "Image is already the primary image"}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
# Set the current primary image to false
|
||||
AdventureImage.objects.filter(adventure=adventure, is_primary=True).update(is_primary=False)
|
||||
|
||||
# Set the new image to true
|
||||
instance.is_primary = True
|
||||
instance.save()
|
||||
return Response({"success": "Image set as primary image"})
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED)
|
||||
adventure_id = request.data.get('adventure')
|
||||
try:
|
||||
adventure = Adventure.objects.get(id=adventure_id)
|
||||
except Adventure.DoesNotExist:
|
||||
return Response({"error": "Adventure not found"}, status=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
if adventure.user_id != request.user:
|
||||
# Check if the adventure has any collections
|
||||
if adventure.collections.exists():
|
||||
# Check if the user is in the shared_with list of any of the adventure's collections
|
||||
user_has_access = False
|
||||
for collection in adventure.collections.all():
|
||||
if collection.shared_with.filter(id=request.user.id).exists():
|
||||
user_has_access = True
|
||||
break
|
||||
|
||||
if not user_has_access:
|
||||
return Response({"error": "User does not have permission to access this adventure"}, status=status.HTTP_403_FORBIDDEN)
|
||||
else:
|
||||
return Response({"error": "User does not own this adventure"}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
# Handle Immich ID for shared users by downloading the image
|
||||
if (request.user != adventure.user_id and
|
||||
'immich_id' in request.data and
|
||||
request.data.get('immich_id')):
|
||||
|
||||
immich_id = request.data.get('immich_id')
|
||||
|
||||
# Get the shared user's Immich integration
|
||||
try:
|
||||
user_integration = ImmichIntegration.objects.get(user_id=request.user)
|
||||
except ImmichIntegration.DoesNotExist:
|
||||
return Response({
|
||||
"error": "No Immich integration found for your account. Please set up Immich integration first.",
|
||||
"code": "immich_integration_not_found"
|
||||
}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
# Download the image from the shared user's Immich server
|
||||
try:
|
||||
immich_response = requests.get(
|
||||
f'{user_integration.server_url}/assets/{immich_id}/thumbnail?size=preview',
|
||||
headers={'x-api-key': user_integration.api_key},
|
||||
timeout=10
|
||||
)
|
||||
immich_response.raise_for_status()
|
||||
|
||||
# Create a temporary file with the downloaded content
|
||||
content_type = immich_response.headers.get('Content-Type', 'image/jpeg')
|
||||
if not content_type.startswith('image/'):
|
||||
return Response({
|
||||
"error": "Invalid content type returned from Immich server.",
|
||||
"code": "invalid_content_type"
|
||||
}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
# Determine file extension from content type
|
||||
ext_map = {
|
||||
'image/jpeg': '.jpg',
|
||||
'image/png': '.png',
|
||||
'image/webp': '.webp',
|
||||
'image/gif': '.gif'
|
||||
}
|
||||
file_ext = ext_map.get(content_type, '.jpg')
|
||||
filename = f"immich_{immich_id}{file_ext}"
|
||||
|
||||
# Create a Django ContentFile from the downloaded image
|
||||
image_file = ContentFile(immich_response.content, name=filename)
|
||||
|
||||
# Modify request data to use the downloaded image instead of immich_id
|
||||
request_data = request.data.copy()
|
||||
request_data.pop('immich_id', None) # Remove immich_id
|
||||
request_data['image'] = image_file # Add the image file
|
||||
|
||||
# Create the serializer with the modified data
|
||||
serializer = self.get_serializer(data=request_data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
# Save with the downloaded image
|
||||
adventure = serializer.validated_data['adventure']
|
||||
serializer.save(user_id=adventure.user_id, image=image_file)
|
||||
|
||||
return Response(serializer.data, status=status.HTTP_201_CREATED)
|
||||
|
||||
except requests.exceptions.RequestException:
|
||||
return Response({
|
||||
"error": f"Failed to fetch image from Immich server",
|
||||
"code": "immich_fetch_failed"
|
||||
}, status=status.HTTP_502_BAD_GATEWAY)
|
||||
except Exception:
|
||||
return Response({
|
||||
"error": f"Unexpected error processing Immich image",
|
||||
"code": "immich_processing_error"
|
||||
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
||||
|
||||
return super().create(request, *args, **kwargs)
|
||||
|
||||
def update(self, request, *args, **kwargs):
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED)
|
||||
|
||||
adventure_id = request.data.get('adventure')
|
||||
try:
|
||||
adventure = Adventure.objects.get(id=adventure_id)
|
||||
except Adventure.DoesNotExist:
|
||||
return Response({"error": "Adventure not found"}, status=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
if adventure.user_id != request.user:
|
||||
return Response({"error": "User does not own this adventure"}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
return super().update(request, *args, **kwargs)
|
||||
|
||||
def perform_destroy(self, instance):
|
||||
print("perform_destroy")
|
||||
return super().perform_destroy(instance)
|
||||
|
||||
def destroy(self, request, *args, **kwargs):
|
||||
print("destroy")
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED)
|
||||
|
||||
instance = self.get_object()
|
||||
adventure = instance.adventure
|
||||
if adventure.user_id != request.user:
|
||||
return Response({"error": "User does not own this adventure"}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
return super().destroy(request, *args, **kwargs)
|
||||
|
||||
def partial_update(self, request, *args, **kwargs):
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED)
|
||||
|
||||
instance = self.get_object()
|
||||
adventure = instance.adventure
|
||||
if adventure.user_id != request.user:
|
||||
return Response({"error": "User does not own this adventure"}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
return super().partial_update(request, *args, **kwargs)
|
||||
|
||||
@action(detail=False, methods=['GET'], url_path='(?P<adventure_id>[0-9a-f-]+)')
|
||||
def adventure_images(self, request, adventure_id=None, *args, **kwargs):
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED)
|
||||
|
||||
try:
|
||||
adventure_uuid = uuid.UUID(adventure_id)
|
||||
except ValueError:
|
||||
return Response({"error": "Invalid adventure ID"}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
# Updated queryset to include images from adventures the user owns OR has shared access to
|
||||
queryset = AdventureImage.objects.filter(
|
||||
Q(adventure__id=adventure_uuid) & (
|
||||
Q(adventure__user_id=request.user) | # User owns the adventure
|
||||
Q(adventure__collections__shared_with=request.user) # User has shared access via collection
|
||||
)
|
||||
).distinct()
|
||||
|
||||
serializer = self.get_serializer(queryset, many=True, context={'request': request})
|
||||
return Response(serializer.data)
|
||||
|
||||
def get_queryset(self):
|
||||
# Updated to include images from adventures the user owns OR has shared access to
|
||||
return AdventureImage.objects.filter(
|
||||
Q(adventure__user_id=self.request.user) | # User owns the adventure
|
||||
Q(adventure__collections__shared_with=self.request.user) # User has shared access via collection
|
||||
).distinct()
|
||||
|
||||
def perform_create(self, serializer):
|
||||
# Always set the image owner to the adventure owner, not the current user
|
||||
adventure = serializer.validated_data['adventure']
|
||||
serializer.save(user_id=adventure.user_id)
|
341
backend/server/adventures/views/adventure_view.py
Normal file
341
backend/server/adventures/views/adventure_view.py
Normal file
|
@ -0,0 +1,341 @@
|
|||
from django.utils import timezone
|
||||
from django.db import transaction
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.db.models import Q, Max
|
||||
from django.db.models.functions import Lower
|
||||
from rest_framework import viewsets, status
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
import requests
|
||||
|
||||
from adventures.models import Adventure, Category, Transportation, Lodging
|
||||
from adventures.permissions import IsOwnerOrSharedWithFullAccess
|
||||
from adventures.serializers import AdventureSerializer, TransportationSerializer, LodgingSerializer
|
||||
from adventures.utils import pagination
|
||||
|
||||
|
||||
class AdventureViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
ViewSet for managing Adventure objects with support for filtering, sorting,
|
||||
and sharing functionality.
|
||||
"""
|
||||
serializer_class = AdventureSerializer
|
||||
permission_classes = [IsOwnerOrSharedWithFullAccess]
|
||||
pagination_class = pagination.StandardResultsSetPagination
|
||||
|
||||
# ==================== QUERYSET & PERMISSIONS ====================
|
||||
|
||||
def get_queryset(self):
|
||||
"""
|
||||
Returns queryset based on user authentication and action type.
|
||||
Public actions allow unauthenticated access to public adventures.
|
||||
"""
|
||||
user = self.request.user
|
||||
public_allowed_actions = {'retrieve', 'additional_info'}
|
||||
|
||||
if not user.is_authenticated:
|
||||
if self.action in public_allowed_actions:
|
||||
return Adventure.objects.retrieve_adventures(
|
||||
user, include_public=True
|
||||
).order_by('-updated_at')
|
||||
return Adventure.objects.none()
|
||||
|
||||
include_public = self.action in public_allowed_actions
|
||||
return Adventure.objects.retrieve_adventures(
|
||||
user,
|
||||
include_public=include_public,
|
||||
include_owned=True,
|
||||
include_shared=True
|
||||
).order_by('-updated_at')
|
||||
|
||||
# ==================== SORTING & FILTERING ====================
|
||||
|
||||
def apply_sorting(self, queryset):
|
||||
"""Apply sorting and collection filtering to queryset."""
|
||||
order_by = self.request.query_params.get('order_by', 'updated_at')
|
||||
order_direction = self.request.query_params.get('order_direction', 'asc')
|
||||
include_collections = self.request.query_params.get('include_collections', 'true')
|
||||
|
||||
# Validate parameters
|
||||
valid_order_by = ['name', 'type', 'date', 'rating', 'updated_at']
|
||||
if order_by not in valid_order_by:
|
||||
order_by = 'name'
|
||||
|
||||
if order_direction not in ['asc', 'desc']:
|
||||
order_direction = 'asc'
|
||||
|
||||
# Apply sorting logic
|
||||
queryset = self._apply_ordering(queryset, order_by, order_direction)
|
||||
|
||||
# Filter adventures without collections if requested
|
||||
if include_collections == 'false':
|
||||
queryset = queryset.filter(collections__isnull=True)
|
||||
|
||||
return queryset
|
||||
|
||||
def _apply_ordering(self, queryset, order_by, order_direction):
|
||||
"""Apply ordering to queryset based on field type."""
|
||||
if order_by == 'date':
|
||||
queryset = queryset.annotate(
|
||||
latest_visit=Max('visits__start_date')
|
||||
).filter(latest_visit__isnull=False)
|
||||
ordering = 'latest_visit'
|
||||
elif order_by == 'name':
|
||||
queryset = queryset.annotate(lower_name=Lower('name'))
|
||||
ordering = 'lower_name'
|
||||
elif order_by == 'rating':
|
||||
queryset = queryset.filter(rating__isnull=False)
|
||||
ordering = 'rating'
|
||||
elif order_by == 'updated_at':
|
||||
# Special handling for updated_at (reverse default order)
|
||||
ordering = '-updated_at' if order_direction == 'asc' else 'updated_at'
|
||||
return queryset.order_by(ordering)
|
||||
else:
|
||||
ordering = order_by
|
||||
|
||||
# Apply direction
|
||||
if order_direction == 'desc':
|
||||
ordering = f'-{ordering}'
|
||||
|
||||
return queryset.order_by(ordering)
|
||||
|
||||
# ==================== CRUD OPERATIONS ====================
|
||||
|
||||
@transaction.atomic
|
||||
def perform_create(self, serializer):
|
||||
"""Create adventure with collection validation and ownership logic."""
|
||||
collections = serializer.validated_data.get('collections', [])
|
||||
|
||||
# Validate permissions for all collections
|
||||
self._validate_collection_permissions(collections)
|
||||
|
||||
# Determine what user to assign as owner
|
||||
user_to_assign = self.request.user
|
||||
|
||||
if collections:
|
||||
# Use the current user as owner since ManyToMany allows multiple collection owners
|
||||
user_to_assign = self.request.user
|
||||
|
||||
serializer.save(user_id=user_to_assign)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
"""Update adventure."""
|
||||
# Just save the adventure - the signal will handle publicity updates
|
||||
serializer.save()
|
||||
|
||||
def update(self, request, *args, **kwargs):
|
||||
"""Handle adventure updates with collection permission validation."""
|
||||
instance = self.get_object()
|
||||
partial = kwargs.pop('partial', False)
|
||||
|
||||
serializer = self.get_serializer(instance, data=request.data, partial=partial)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
# Validate collection permissions if collections are being updated
|
||||
if 'collections' in serializer.validated_data:
|
||||
self._validate_collection_update_permissions(
|
||||
instance, serializer.validated_data['collections']
|
||||
)
|
||||
else:
|
||||
# Remove collections from validated_data if not provided
|
||||
serializer.validated_data.pop('collections', None)
|
||||
|
||||
self.perform_update(serializer)
|
||||
return Response(serializer.data)
|
||||
|
||||
# ==================== CUSTOM ACTIONS ====================
|
||||
|
||||
@action(detail=False, methods=['get'])
|
||||
def filtered(self, request):
|
||||
"""Filter adventures by category types and visit status."""
|
||||
types = request.query_params.get('types', '').split(',')
|
||||
|
||||
# Handle 'all' types
|
||||
if 'all' in types:
|
||||
types = Category.objects.filter(
|
||||
user_id=request.user
|
||||
).values_list('name', flat=True)
|
||||
else:
|
||||
# Validate provided types
|
||||
if not types or not all(
|
||||
Category.objects.filter(user_id=request.user, name=type_name).exists()
|
||||
for type_name in types
|
||||
):
|
||||
return Response(
|
||||
{"error": "Invalid category or no types provided"},
|
||||
status=400
|
||||
)
|
||||
|
||||
# Build base queryset
|
||||
queryset = Adventure.objects.filter(
|
||||
category__in=Category.objects.filter(name__in=types, user_id=request.user),
|
||||
user_id=request.user.id
|
||||
)
|
||||
|
||||
# Apply visit status filtering
|
||||
queryset = self._apply_visit_filtering(queryset, request)
|
||||
queryset = self.apply_sorting(queryset)
|
||||
|
||||
return self.paginate_and_respond(queryset, request)
|
||||
|
||||
@action(detail=False, methods=['get'])
|
||||
def all(self, request):
|
||||
"""Get all adventures (public and owned) with optional collection filtering."""
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=400)
|
||||
|
||||
include_collections = request.query_params.get('include_collections', 'false') == 'true'
|
||||
|
||||
# Build queryset with collection filtering
|
||||
base_filter = Q(user_id=request.user.id)
|
||||
|
||||
if include_collections:
|
||||
queryset = Adventure.objects.filter(base_filter)
|
||||
else:
|
||||
queryset = Adventure.objects.filter(base_filter, collections__isnull=True)
|
||||
|
||||
queryset = self.apply_sorting(queryset)
|
||||
serializer = self.get_serializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
@action(detail=True, methods=['get'], url_path='additional-info')
|
||||
def additional_info(self, request, pk=None):
|
||||
"""Get adventure with additional sunrise/sunset information."""
|
||||
adventure = self.get_object()
|
||||
user = request.user
|
||||
|
||||
# Validate access permissions
|
||||
if not self._has_adventure_access(adventure, user):
|
||||
return Response(
|
||||
{"error": "User does not have permission to access this adventure"},
|
||||
status=status.HTTP_403_FORBIDDEN
|
||||
)
|
||||
|
||||
# Get base adventure data
|
||||
serializer = self.get_serializer(adventure)
|
||||
response_data = serializer.data
|
||||
|
||||
# Add sunrise/sunset data
|
||||
response_data['sun_times'] = self._get_sun_times(adventure, response_data.get('visits', []))
|
||||
|
||||
return Response(response_data)
|
||||
|
||||
# ==================== HELPER METHODS ====================
|
||||
|
||||
def _validate_collection_permissions(self, collections):
|
||||
"""Validate user has permission to use all provided collections. Only the owner or shared users can use collections."""
|
||||
for collection in collections:
|
||||
if not (collection.user_id == self.request.user or
|
||||
collection.shared_with.filter(uuid=self.request.user.uuid).exists()):
|
||||
raise PermissionDenied(
|
||||
f"You do not have permission to use collection '{collection.name}'."
|
||||
)
|
||||
|
||||
def _validate_collection_update_permissions(self, instance, new_collections):
|
||||
"""Validate permissions for collection updates (add/remove)."""
|
||||
# Check permissions for new collections being added
|
||||
for collection in new_collections:
|
||||
if (collection.user_id != self.request.user and
|
||||
not collection.shared_with.filter(uuid=self.request.user.uuid).exists()):
|
||||
raise PermissionDenied(
|
||||
f"You do not have permission to use collection '{collection.name}'."
|
||||
)
|
||||
|
||||
# Check permissions for collections being removed
|
||||
current_collections = set(instance.collections.all())
|
||||
new_collections_set = set(new_collections)
|
||||
collections_to_remove = current_collections - new_collections_set
|
||||
|
||||
for collection in collections_to_remove:
|
||||
if (collection.user_id != self.request.user and
|
||||
not collection.shared_with.filter(uuid=self.request.user.uuid).exists()):
|
||||
raise PermissionDenied(
|
||||
f"You cannot remove the adventure from collection '{collection.name}' "
|
||||
f"as you don't have permission."
|
||||
)
|
||||
|
||||
def _apply_visit_filtering(self, queryset, request):
|
||||
"""Apply visit status filtering to queryset."""
|
||||
is_visited_param = request.query_params.get('is_visited')
|
||||
if is_visited_param is None:
|
||||
return queryset
|
||||
|
||||
# Convert parameter to boolean
|
||||
if is_visited_param.lower() == 'true':
|
||||
is_visited_bool = True
|
||||
elif is_visited_param.lower() == 'false':
|
||||
is_visited_bool = False
|
||||
else:
|
||||
return queryset
|
||||
|
||||
# Apply visit filtering
|
||||
now = timezone.now().date()
|
||||
if is_visited_bool:
|
||||
queryset = queryset.filter(visits__start_date__lte=now).distinct()
|
||||
else:
|
||||
queryset = queryset.exclude(visits__start_date__lte=now).distinct()
|
||||
|
||||
return queryset
|
||||
|
||||
def _has_adventure_access(self, adventure, user):
|
||||
"""Check if user has access to adventure."""
|
||||
# Allow if public
|
||||
if adventure.is_public:
|
||||
return True
|
||||
|
||||
# Check ownership
|
||||
if user.is_authenticated and adventure.user_id == user:
|
||||
return True
|
||||
|
||||
# Check shared collection access
|
||||
if user.is_authenticated:
|
||||
for collection in adventure.collections.all():
|
||||
if collection.shared_with.filter(uuid=user.uuid).exists():
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def _get_sun_times(self, adventure, visits):
|
||||
"""Get sunrise/sunset times for adventure visits."""
|
||||
sun_times = []
|
||||
|
||||
for visit in visits:
|
||||
date = visit.get('start_date')
|
||||
if not (date and adventure.longitude and adventure.latitude):
|
||||
continue
|
||||
|
||||
api_url = (
|
||||
f'https://api.sunrisesunset.io/json?'
|
||||
f'lat={adventure.latitude}&lng={adventure.longitude}&date={date}'
|
||||
)
|
||||
|
||||
try:
|
||||
response = requests.get(api_url)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
results = data.get('results', {})
|
||||
|
||||
if results.get('sunrise') and results.get('sunset'):
|
||||
sun_times.append({
|
||||
"date": date,
|
||||
"visit_id": visit.get('id'),
|
||||
"sunrise": results.get('sunrise'),
|
||||
"sunset": results.get('sunset')
|
||||
})
|
||||
except requests.RequestException:
|
||||
# Skip this visit if API call fails
|
||||
continue
|
||||
|
||||
return sun_times
|
||||
|
||||
def paginate_and_respond(self, queryset, request):
|
||||
"""Paginate queryset and return response."""
|
||||
paginator = self.pagination_class()
|
||||
page = paginator.paginate_queryset(queryset, request)
|
||||
|
||||
if page is not None:
|
||||
serializer = self.get_serializer(page, many=True)
|
||||
return paginator.get_paginated_response(serializer.data)
|
||||
|
||||
serializer = self.get_serializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
56
backend/server/adventures/views/attachment_view.py
Normal file
56
backend/server/adventures/views/attachment_view.py
Normal file
|
@ -0,0 +1,56 @@
|
|||
from rest_framework import viewsets, status
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from adventures.models import Adventure, Attachment
|
||||
from adventures.serializers import AttachmentSerializer
|
||||
|
||||
class AttachmentViewSet(viewsets.ModelViewSet):
|
||||
serializer_class = AttachmentSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def get_queryset(self):
|
||||
return Attachment.objects.filter(user_id=self.request.user)
|
||||
|
||||
@action(detail=True, methods=['post'])
|
||||
def attachment_delete(self, request, *args, **kwargs):
|
||||
return self.destroy(request, *args, **kwargs)
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED)
|
||||
adventure_id = request.data.get('adventure')
|
||||
try:
|
||||
adventure = Adventure.objects.get(id=adventure_id)
|
||||
except Adventure.DoesNotExist:
|
||||
return Response({"error": "Adventure not found"}, status=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
if adventure.user_id != request.user:
|
||||
# Check if the adventure has any collections
|
||||
if adventure.collections.exists():
|
||||
# Check if the user is in the shared_with list of any of the adventure's collections
|
||||
user_has_access = False
|
||||
for collection in adventure.collections.all():
|
||||
if collection.shared_with.filter(id=request.user.id).exists():
|
||||
user_has_access = True
|
||||
break
|
||||
|
||||
if not user_has_access:
|
||||
return Response({"error": "User does not have permission to access this adventure"}, status=status.HTTP_403_FORBIDDEN)
|
||||
else:
|
||||
return Response({"error": "User does not own this adventure"}, status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
return super().create(request, *args, **kwargs)
|
||||
|
||||
def perform_create(self, serializer):
|
||||
adventure_id = self.request.data.get('adventure')
|
||||
adventure = Adventure.objects.get(id=adventure_id)
|
||||
|
||||
# If the adventure belongs to collections, set the owner to the collection owner
|
||||
if adventure.collections.exists():
|
||||
# Get the first collection's owner (assuming all collections have the same owner)
|
||||
collection = adventure.collections.first()
|
||||
serializer.save(user_id=collection.user_id)
|
||||
else:
|
||||
# Otherwise, set the owner to the request user
|
||||
serializer.save(user_id=self.request.user)
|
42
backend/server/adventures/views/category_view.py
Normal file
42
backend/server/adventures/views/category_view.py
Normal file
|
@ -0,0 +1,42 @@
|
|||
from rest_framework import viewsets
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from adventures.models import Category, Adventure
|
||||
from adventures.serializers import CategorySerializer
|
||||
|
||||
class CategoryViewSet(viewsets.ModelViewSet):
|
||||
queryset = Category.objects.all()
|
||||
serializer_class = CategorySerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def get_queryset(self):
|
||||
return Category.objects.filter(user_id=self.request.user)
|
||||
|
||||
@action(detail=False, methods=['get'])
|
||||
def categories(self, request):
|
||||
"""
|
||||
Retrieve a list of distinct categories for adventures associated with the current user.
|
||||
"""
|
||||
categories = self.get_queryset().distinct()
|
||||
serializer = self.get_serializer(categories, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
def destroy(self, request, *args, **kwargs):
|
||||
instance = self.get_object()
|
||||
if instance.user_id != request.user:
|
||||
return Response({"error": "User does not own this category"}, status
|
||||
=400)
|
||||
|
||||
if instance.name == 'general':
|
||||
return Response({"error": "Cannot delete the general category"}, status=400)
|
||||
|
||||
# set any adventures with this category to a default category called general before deleting the category, if general does not exist create it for the user
|
||||
general_category = Category.objects.filter(user_id=request.user, name='general').first()
|
||||
|
||||
if not general_category:
|
||||
general_category = Category.objects.create(user_id=request.user, name='general', icon='🌍', display_name='General')
|
||||
|
||||
Adventure.objects.filter(category=instance).update(category=general_category)
|
||||
|
||||
return super().destroy(request, *args, **kwargs)
|
130
backend/server/adventures/views/checklist_view.py
Normal file
130
backend/server/adventures/views/checklist_view.py
Normal file
|
@ -0,0 +1,130 @@
|
|||
from rest_framework import viewsets, status
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from django.db.models import Q
|
||||
from adventures.models import Checklist
|
||||
from adventures.serializers import ChecklistSerializer
|
||||
from rest_framework.exceptions import PermissionDenied
|
||||
from adventures.permissions import IsOwnerOrSharedWithFullAccess
|
||||
|
||||
class ChecklistViewSet(viewsets.ModelViewSet):
|
||||
queryset = Checklist.objects.all()
|
||||
serializer_class = ChecklistSerializer
|
||||
permission_classes = [IsOwnerOrSharedWithFullAccess]
|
||||
filterset_fields = ['is_public', 'collection']
|
||||
|
||||
# return error message if user is not authenticated on the root endpoint
|
||||
def list(self, request, *args, **kwargs):
|
||||
# Prevent listing all adventures
|
||||
return Response({"detail": "Listing all checklists is not allowed."},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
@action(detail=False, methods=['get'])
|
||||
def all(self, request):
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=400)
|
||||
queryset = Checklist.objects.filter(
|
||||
Q(user_id=request.user.id)
|
||||
)
|
||||
serializer = self.get_serializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
def get_queryset(self):
|
||||
# if the user is not authenticated return only public transportations for retrieve action
|
||||
if not self.request.user.is_authenticated:
|
||||
if self.action == 'retrieve':
|
||||
return Checklist.objects.filter(is_public=True).distinct().order_by('-updated_at')
|
||||
return Checklist.objects.none()
|
||||
|
||||
|
||||
if self.action == 'retrieve':
|
||||
# For individual adventure retrieval, include public adventures
|
||||
return Checklist.objects.filter(
|
||||
Q(is_public=True) | Q(user_id=self.request.user.id) | Q(collection__shared_with=self.request.user)
|
||||
).distinct().order_by('-updated_at')
|
||||
else:
|
||||
# For other actions, include user's own adventures and shared adventures
|
||||
return Checklist.objects.filter(
|
||||
Q(user_id=self.request.user.id) | Q(collection__shared_with=self.request.user)
|
||||
).distinct().order_by('-updated_at')
|
||||
|
||||
def partial_update(self, request, *args, **kwargs):
|
||||
# Retrieve the current object
|
||||
instance = self.get_object()
|
||||
|
||||
# Partially update the instance with the request data
|
||||
serializer = self.get_serializer(instance, data=request.data, partial=True)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
# Retrieve the collection from the validated data
|
||||
new_collection = serializer.validated_data.get('collection')
|
||||
|
||||
user = request.user
|
||||
print(new_collection)
|
||||
|
||||
if new_collection is not None and new_collection!=instance.collection:
|
||||
# Check if the user is the owner of the new collection
|
||||
if new_collection.user_id != user or instance.user_id != user:
|
||||
raise PermissionDenied("You do not have permission to use this collection.")
|
||||
elif new_collection is None:
|
||||
# Handle the case where the user is trying to set the collection to None
|
||||
if instance.collection is not None and instance.collection.user_id != user:
|
||||
raise PermissionDenied("You cannot remove the collection as you are not the owner.")
|
||||
|
||||
# Perform the update
|
||||
self.perform_update(serializer)
|
||||
|
||||
# Return the updated instance
|
||||
return Response(serializer.data)
|
||||
|
||||
def partial_update(self, request, *args, **kwargs):
|
||||
# Retrieve the current object
|
||||
instance = self.get_object()
|
||||
|
||||
# Partially update the instance with the request data
|
||||
serializer = self.get_serializer(instance, data=request.data, partial=True)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
# Retrieve the collection from the validated data
|
||||
new_collection = serializer.validated_data.get('collection')
|
||||
|
||||
user = request.user
|
||||
print(new_collection)
|
||||
|
||||
if new_collection is not None and new_collection!=instance.collection:
|
||||
# Check if the user is the owner of the new collection
|
||||
if new_collection.user_id != user or instance.user_id != user:
|
||||
raise PermissionDenied("You do not have permission to use this collection.")
|
||||
elif new_collection is None:
|
||||
# Handle the case where the user is trying to set the collection to None
|
||||
if instance.collection is not None and instance.collection.user_id != user:
|
||||
raise PermissionDenied("You cannot remove the collection as you are not the owner.")
|
||||
|
||||
# Perform the update
|
||||
self.perform_update(serializer)
|
||||
|
||||
# Return the updated instance
|
||||
return Response(serializer.data)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
serializer.save()
|
||||
|
||||
# when creating an adventure, make sure the user is the owner of the collection or shared with the collection
|
||||
def perform_create(self, serializer):
|
||||
# Retrieve the collection from the validated data
|
||||
collection = serializer.validated_data.get('collection')
|
||||
|
||||
# Check if a collection is provided
|
||||
if collection:
|
||||
user = self.request.user
|
||||
# Check if the user is the owner or is in the shared_with list
|
||||
if collection.user_id != user and not collection.shared_with.filter(id=user.id).exists():
|
||||
# Return an error response if the user does not have permission
|
||||
raise PermissionDenied("You do not have permission to use this collection.")
|
||||
# if collection the owner of the adventure is the owner of the collection
|
||||
serializer.save(user_id=collection.user_id)
|
||||
return
|
||||
|
||||
# Save the adventure with the current user as the owner
|
||||
serializer.save(user_id=self.request.user)
|
240
backend/server/adventures/views/collection_view.py
Normal file
240
backend/server/adventures/views/collection_view.py
Normal file
|
@ -0,0 +1,240 @@
|
|||
from django.db.models import Q
|
||||
from django.db.models.functions import Lower
|
||||
from django.db import transaction
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from adventures.models import Collection, Adventure, Transportation, Note, Checklist
|
||||
from adventures.permissions import CollectionShared
|
||||
from adventures.serializers import CollectionSerializer
|
||||
from users.models import CustomUser as User
|
||||
from adventures.utils import pagination
|
||||
|
||||
class CollectionViewSet(viewsets.ModelViewSet):
|
||||
serializer_class = CollectionSerializer
|
||||
permission_classes = [CollectionShared]
|
||||
pagination_class = pagination.StandardResultsSetPagination
|
||||
|
||||
# def get_queryset(self):
|
||||
# return Collection.objects.filter(Q(user_id=self.request.user.id) & Q(is_archived=False))
|
||||
|
||||
def apply_sorting(self, queryset):
|
||||
order_by = self.request.query_params.get('order_by', 'name')
|
||||
order_direction = self.request.query_params.get('order_direction', 'asc')
|
||||
|
||||
valid_order_by = ['name', 'updated_at', 'start_date']
|
||||
if order_by not in valid_order_by:
|
||||
order_by = 'updated_at'
|
||||
|
||||
if order_direction not in ['asc', 'desc']:
|
||||
order_direction = 'asc'
|
||||
|
||||
# Apply case-insensitive sorting for the 'name' field
|
||||
if order_by == 'name':
|
||||
queryset = queryset.annotate(lower_name=Lower('name'))
|
||||
ordering = 'lower_name'
|
||||
if order_direction == 'desc':
|
||||
ordering = f'-{ordering}'
|
||||
elif order_by == 'start_date':
|
||||
ordering = 'start_date'
|
||||
if order_direction == 'asc':
|
||||
ordering = 'start_date'
|
||||
else:
|
||||
ordering = '-start_date'
|
||||
else:
|
||||
order_by == 'updated_at'
|
||||
ordering = 'updated_at'
|
||||
if order_direction == 'asc':
|
||||
ordering = '-updated_at'
|
||||
|
||||
#print(f"Ordering by: {ordering}") # For debugging
|
||||
|
||||
return queryset.order_by(ordering)
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
# make sure the user is authenticated
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=400)
|
||||
queryset = Collection.objects.filter(user_id=request.user.id, is_archived=False)
|
||||
queryset = self.apply_sorting(queryset)
|
||||
collections = self.paginate_and_respond(queryset, request)
|
||||
return collections
|
||||
|
||||
@action(detail=False, methods=['get'])
|
||||
def all(self, request):
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=400)
|
||||
|
||||
queryset = Collection.objects.filter(
|
||||
Q(user_id=request.user.id)
|
||||
)
|
||||
|
||||
queryset = self.apply_sorting(queryset)
|
||||
serializer = self.get_serializer(queryset, many=True)
|
||||
|
||||
return Response(serializer.data)
|
||||
|
||||
@action(detail=False, methods=['get'])
|
||||
def archived(self, request):
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=400)
|
||||
|
||||
queryset = Collection.objects.filter(
|
||||
Q(user_id=request.user.id) & Q(is_archived=True)
|
||||
)
|
||||
|
||||
queryset = self.apply_sorting(queryset)
|
||||
serializer = self.get_serializer(queryset, many=True)
|
||||
|
||||
return Response(serializer.data)
|
||||
|
||||
# this make the is_public field of the collection cascade to the adventures
|
||||
@transaction.atomic
|
||||
def update(self, request, *args, **kwargs):
|
||||
partial = kwargs.pop('partial', False)
|
||||
instance = self.get_object()
|
||||
serializer = self.get_serializer(instance, data=request.data, partial=partial)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
if 'collection' in serializer.validated_data:
|
||||
new_collection = serializer.validated_data['collection']
|
||||
# if the new collection is different from the old one and the user making the request is not the owner of the new collection return an error
|
||||
if new_collection != instance.collection and new_collection.user_id != request.user:
|
||||
return Response({"error": "User does not own the new collection"}, status=400)
|
||||
|
||||
# Check if the 'is_public' field is present in the update data
|
||||
if 'is_public' in serializer.validated_data:
|
||||
new_public_status = serializer.validated_data['is_public']
|
||||
|
||||
# if is_public has changed and the user is not the owner of the collection return an error
|
||||
if new_public_status != instance.is_public and instance.user_id != request.user:
|
||||
print(f"User {request.user.id} does not own the collection {instance.id} that is owned by {instance.user_id}")
|
||||
return Response({"error": "User does not own the collection"}, status=400)
|
||||
|
||||
# Get all adventures in this collection
|
||||
adventures_in_collection = Adventure.objects.filter(collections=instance)
|
||||
|
||||
if new_public_status:
|
||||
# If collection becomes public, make all adventures public
|
||||
adventures_in_collection.update(is_public=True)
|
||||
else:
|
||||
# If collection becomes private, check each adventure
|
||||
# Only set an adventure to private if ALL of its collections are private
|
||||
# Collect adventures that do NOT belong to any other public collection (excluding the current one)
|
||||
adventure_ids_to_set_private = []
|
||||
|
||||
for adventure in adventures_in_collection:
|
||||
has_public_collection = adventure.collections.filter(is_public=True).exclude(id=instance.id).exists()
|
||||
if not has_public_collection:
|
||||
adventure_ids_to_set_private.append(adventure.id)
|
||||
|
||||
# Bulk update those adventures
|
||||
Adventure.objects.filter(id__in=adventure_ids_to_set_private).update(is_public=False)
|
||||
|
||||
# Update transportations, notes, and checklists related to this collection
|
||||
# These still use direct ForeignKey relationships
|
||||
Transportation.objects.filter(collection=instance).update(is_public=new_public_status)
|
||||
Note.objects.filter(collection=instance).update(is_public=new_public_status)
|
||||
Checklist.objects.filter(collection=instance).update(is_public=new_public_status)
|
||||
|
||||
# Log the action (optional)
|
||||
action = "public" if new_public_status else "private"
|
||||
print(f"Collection {instance.id} and its related objects were set to {action}")
|
||||
|
||||
self.perform_update(serializer)
|
||||
|
||||
if getattr(instance, '_prefetched_objects_cache', None):
|
||||
# If 'prefetch_related' has been applied to a queryset, we need to
|
||||
# forcibly invalidate the prefetch cache on the instance.
|
||||
instance._prefetched_objects_cache = {}
|
||||
|
||||
return Response(serializer.data)
|
||||
|
||||
# make an action to retreive all adventures that are shared with the user
|
||||
@action(detail=False, methods=['get'])
|
||||
def shared(self, request):
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=400)
|
||||
queryset = Collection.objects.filter(
|
||||
shared_with=request.user
|
||||
)
|
||||
queryset = self.apply_sorting(queryset)
|
||||
serializer = self.get_serializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
# Adds a new user to the shared_with field of an adventure
|
||||
@action(detail=True, methods=['post'], url_path='share/(?P<uuid>[^/.]+)')
|
||||
def share(self, request, pk=None, uuid=None):
|
||||
collection = self.get_object()
|
||||
if not uuid:
|
||||
return Response({"error": "User UUID is required"}, status=400)
|
||||
try:
|
||||
user = User.objects.get(uuid=uuid, public_profile=True)
|
||||
except User.DoesNotExist:
|
||||
return Response({"error": "User not found"}, status=404)
|
||||
|
||||
if user == request.user:
|
||||
return Response({"error": "Cannot share with yourself"}, status=400)
|
||||
|
||||
if collection.shared_with.filter(id=user.id).exists():
|
||||
return Response({"error": "Adventure is already shared with this user"}, status=400)
|
||||
|
||||
collection.shared_with.add(user)
|
||||
collection.save()
|
||||
return Response({"success": f"Shared with {user.username}"})
|
||||
|
||||
@action(detail=True, methods=['post'], url_path='unshare/(?P<uuid>[^/.]+)')
|
||||
def unshare(self, request, pk=None, uuid=None):
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=400)
|
||||
collection = self.get_object()
|
||||
if not uuid:
|
||||
return Response({"error": "User UUID is required"}, status=400)
|
||||
try:
|
||||
user = User.objects.get(uuid=uuid, public_profile=True)
|
||||
except User.DoesNotExist:
|
||||
return Response({"error": "User not found"}, status=404)
|
||||
|
||||
if user == request.user:
|
||||
return Response({"error": "Cannot unshare with yourself"}, status=400)
|
||||
|
||||
if not collection.shared_with.filter(id=user.id).exists():
|
||||
return Response({"error": "Collection is not shared with this user"}, status=400)
|
||||
|
||||
collection.shared_with.remove(user)
|
||||
collection.save()
|
||||
return Response({"success": f"Unshared with {user.username}"})
|
||||
|
||||
def get_queryset(self):
|
||||
if self.action == 'destroy':
|
||||
return Collection.objects.filter(user_id=self.request.user.id)
|
||||
|
||||
if self.action in ['update', 'partial_update']:
|
||||
return Collection.objects.filter(
|
||||
Q(user_id=self.request.user.id) | Q(shared_with=self.request.user)
|
||||
).distinct()
|
||||
|
||||
if self.action == 'retrieve':
|
||||
if not self.request.user.is_authenticated:
|
||||
return Collection.objects.filter(is_public=True)
|
||||
return Collection.objects.filter(
|
||||
Q(is_public=True) | Q(user_id=self.request.user.id) | Q(shared_with=self.request.user)
|
||||
).distinct()
|
||||
|
||||
# For list action, include collections owned by the user or shared with the user, that are not archived
|
||||
return Collection.objects.filter(
|
||||
(Q(user_id=self.request.user.id) | Q(shared_with=self.request.user)) & Q(is_archived=False)
|
||||
).distinct()
|
||||
|
||||
def perform_create(self, serializer):
|
||||
# This is ok because you cannot share a collection when creating it
|
||||
serializer.save(user_id=self.request.user)
|
||||
|
||||
def paginate_and_respond(self, queryset, request):
|
||||
paginator = self.pagination_class()
|
||||
page = paginator.paginate_queryset(queryset, request)
|
||||
if page is not None:
|
||||
serializer = self.get_serializer(page, many=True)
|
||||
return paginator.get_paginated_response(serializer.data)
|
||||
serializer = self.get_serializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
44
backend/server/adventures/views/generate_description_view.py
Normal file
44
backend/server/adventures/views/generate_description_view.py
Normal file
|
@ -0,0 +1,44 @@
|
|||
from rest_framework import viewsets
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
import requests
|
||||
|
||||
class GenerateDescription(viewsets.ViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
@action(detail=False, methods=['get'],)
|
||||
def desc(self, request):
|
||||
name = self.request.query_params.get('name', '')
|
||||
# un url encode the name
|
||||
name = name.replace('%20', ' ')
|
||||
name = self.get_search_term(name)
|
||||
url = 'https://en.wikipedia.org/w/api.php?origin=*&action=query&prop=extracts&exintro&explaintext&format=json&titles=%s' % name
|
||||
response = requests.get(url)
|
||||
data = response.json()
|
||||
data = response.json()
|
||||
page_id = next(iter(data["query"]["pages"]))
|
||||
extract = data["query"]["pages"][page_id]
|
||||
if extract.get('extract') is None:
|
||||
return Response({"error": "No description found"}, status=400)
|
||||
return Response(extract)
|
||||
@action(detail=False, methods=['get'],)
|
||||
def img(self, request):
|
||||
name = self.request.query_params.get('name', '')
|
||||
# un url encode the name
|
||||
name = name.replace('%20', ' ')
|
||||
name = self.get_search_term(name)
|
||||
url = 'https://en.wikipedia.org/w/api.php?origin=*&action=query&prop=pageimages&format=json&piprop=original&titles=%s' % name
|
||||
response = requests.get(url)
|
||||
data = response.json()
|
||||
page_id = next(iter(data["query"]["pages"]))
|
||||
extract = data["query"]["pages"][page_id]
|
||||
if extract.get('original') is None:
|
||||
return Response({"error": "No image found"}, status=400)
|
||||
return Response(extract["original"])
|
||||
|
||||
def get_search_term(self, term):
|
||||
response = requests.get(f'https://en.wikipedia.org/w/api.php?action=opensearch&search={term}&limit=10&namespace=0&format=json')
|
||||
data = response.json()
|
||||
if data[1] and len(data[1]) > 0:
|
||||
return data[1][0]
|
73
backend/server/adventures/views/global_search_view.py
Normal file
73
backend/server/adventures/views/global_search_view.py
Normal file
|
@ -0,0 +1,73 @@
|
|||
from rest_framework import viewsets
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from django.db.models import Q
|
||||
from django.contrib.postgres.search import SearchVector, SearchQuery
|
||||
from adventures.models import Adventure, Collection
|
||||
from adventures.serializers import AdventureSerializer, CollectionSerializer
|
||||
from worldtravel.models import Country, Region, City, VisitedCity, VisitedRegion
|
||||
from worldtravel.serializers import CountrySerializer, RegionSerializer, CitySerializer, VisitedCitySerializer, VisitedRegionSerializer
|
||||
from users.models import CustomUser as User
|
||||
from users.serializers import CustomUserDetailsSerializer as UserSerializer
|
||||
|
||||
class GlobalSearchView(viewsets.ViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def list(self, request):
|
||||
search_term = request.query_params.get('query', '').strip()
|
||||
if not search_term:
|
||||
return Response({"error": "Search query is required"}, status=400)
|
||||
|
||||
# Initialize empty results
|
||||
results = {
|
||||
"adventures": [],
|
||||
"collections": [],
|
||||
"users": [],
|
||||
"countries": [],
|
||||
"regions": [],
|
||||
"cities": [],
|
||||
"visited_regions": [],
|
||||
"visited_cities": []
|
||||
}
|
||||
|
||||
# Adventures: Full-Text Search
|
||||
adventures = Adventure.objects.annotate(
|
||||
search=SearchVector('name', 'description', 'location')
|
||||
).filter(search=SearchQuery(search_term), user_id=request.user)
|
||||
results["adventures"] = AdventureSerializer(adventures, many=True).data
|
||||
|
||||
# Collections: Partial Match Search
|
||||
collections = Collection.objects.filter(
|
||||
Q(name__icontains=search_term) & Q(user_id=request.user)
|
||||
)
|
||||
results["collections"] = CollectionSerializer(collections, many=True).data
|
||||
|
||||
# Users: Public Profiles Only
|
||||
users = User.objects.filter(
|
||||
(Q(username__icontains=search_term) |
|
||||
Q(first_name__icontains=search_term) |
|
||||
Q(last_name__icontains=search_term)) & Q(public_profile=True)
|
||||
)
|
||||
results["users"] = UserSerializer(users, many=True).data
|
||||
|
||||
# Countries: Full-Text Search
|
||||
countries = Country.objects.annotate(
|
||||
search=SearchVector('name', 'country_code')
|
||||
).filter(search=SearchQuery(search_term))
|
||||
results["countries"] = CountrySerializer(countries, many=True).data
|
||||
|
||||
# Regions and Cities: Partial Match Search
|
||||
regions = Region.objects.filter(Q(name__icontains=search_term))
|
||||
results["regions"] = RegionSerializer(regions, many=True).data
|
||||
|
||||
cities = City.objects.filter(Q(name__icontains=search_term))
|
||||
results["cities"] = CitySerializer(cities, many=True).data
|
||||
|
||||
# Visited Regions and Cities
|
||||
visited_regions = VisitedRegion.objects.filter(user_id=request.user)
|
||||
results["visited_regions"] = VisitedRegionSerializer(visited_regions, many=True).data
|
||||
|
||||
visited_cities = VisitedCity.objects.filter(user_id=request.user)
|
||||
results["visited_cities"] = VisitedCitySerializer(visited_cities, many=True).data
|
||||
|
||||
return Response(results)
|
67
backend/server/adventures/views/ics_calendar_view.py
Normal file
67
backend/server/adventures/views/ics_calendar_view.py
Normal file
|
@ -0,0 +1,67 @@
|
|||
from django.http import HttpResponse
|
||||
from rest_framework import viewsets
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from icalendar import Calendar, Event, vText, vCalAddress
|
||||
from datetime import datetime, timedelta
|
||||
from adventures.models import Adventure
|
||||
from adventures.serializers import AdventureSerializer
|
||||
|
||||
class IcsCalendarGeneratorViewSet(viewsets.ViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
@action(detail=False, methods=['get'])
|
||||
def generate(self, request):
|
||||
adventures = Adventure.objects.filter(user_id=request.user)
|
||||
serializer = AdventureSerializer(adventures, many=True)
|
||||
user = request.user
|
||||
name = f"{user.first_name} {user.last_name}"
|
||||
print(serializer.data)
|
||||
|
||||
cal = Calendar()
|
||||
cal.add('prodid', '-//My Adventure Calendar//example.com//')
|
||||
cal.add('version', '2.0')
|
||||
|
||||
for adventure in serializer.data:
|
||||
if adventure['visits']:
|
||||
for visit in adventure['visits']:
|
||||
# Skip if start_date is missing
|
||||
if not visit.get('start_date'):
|
||||
continue
|
||||
|
||||
# Parse start_date and handle end_date
|
||||
try:
|
||||
start_date = datetime.strptime(visit['start_date'], '%Y-%m-%d').date()
|
||||
except ValueError:
|
||||
continue # Skip if the start_date is invalid
|
||||
|
||||
end_date = (
|
||||
datetime.strptime(visit['end_date'], '%Y-%m-%d').date() + timedelta(days=1)
|
||||
if visit.get('end_date') else start_date + timedelta(days=1)
|
||||
)
|
||||
|
||||
# Create event
|
||||
event = Event()
|
||||
event.add('summary', adventure['name'])
|
||||
event.add('dtstart', start_date)
|
||||
event.add('dtend', end_date)
|
||||
event.add('dtstamp', datetime.now())
|
||||
event.add('transp', 'TRANSPARENT')
|
||||
event.add('class', 'PUBLIC')
|
||||
event.add('created', datetime.now())
|
||||
event.add('last-modified', datetime.now())
|
||||
event.add('description', adventure['description'])
|
||||
if adventure.get('location'):
|
||||
event.add('location', adventure['location'])
|
||||
if adventure.get('link'):
|
||||
event.add('url', adventure['link'])
|
||||
|
||||
organizer = vCalAddress(f'MAILTO:{user.email}')
|
||||
organizer.params['cn'] = vText(name)
|
||||
event.add('organizer', organizer)
|
||||
|
||||
cal.add_component(event)
|
||||
|
||||
response = HttpResponse(cal.to_ical(), content_type='text/calendar')
|
||||
response['Content-Disposition'] = 'attachment; filename=adventures.ics'
|
||||
return response
|
84
backend/server/adventures/views/lodging_view.py
Normal file
84
backend/server/adventures/views/lodging_view.py
Normal file
|
@ -0,0 +1,84 @@
|
|||
from rest_framework import viewsets, status
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from django.db.models import Q
|
||||
from adventures.models import Lodging
|
||||
from adventures.serializers import LodgingSerializer
|
||||
from rest_framework.exceptions import PermissionDenied
|
||||
from adventures.permissions import IsOwnerOrSharedWithFullAccess
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
|
||||
class LodgingViewSet(viewsets.ModelViewSet):
|
||||
queryset = Lodging.objects.all()
|
||||
serializer_class = LodgingSerializer
|
||||
permission_classes = [IsOwnerOrSharedWithFullAccess]
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
if not request.user.is_authenticated:
|
||||
return Response(status=status.HTTP_403_FORBIDDEN)
|
||||
queryset = Lodging.objects.filter(
|
||||
Q(user_id=request.user.id)
|
||||
)
|
||||
serializer = self.get_serializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
def get_queryset(self):
|
||||
user = self.request.user
|
||||
if self.action == 'retrieve':
|
||||
# For individual adventure retrieval, include public adventures, user's own adventures and shared adventures
|
||||
return Lodging.objects.filter(
|
||||
Q(is_public=True) | Q(user_id=user.id) | Q(collection__shared_with=user.id)
|
||||
).distinct().order_by('-updated_at')
|
||||
# For other actions, include user's own adventures and shared adventures
|
||||
return Lodging.objects.filter(
|
||||
Q(user_id=user.id) | Q(collection__shared_with=user.id)
|
||||
).distinct().order_by('-updated_at')
|
||||
|
||||
def partial_update(self, request, *args, **kwargs):
|
||||
# Retrieve the current object
|
||||
instance = self.get_object()
|
||||
user = request.user
|
||||
|
||||
# Partially update the instance with the request data
|
||||
serializer = self.get_serializer(instance, data=request.data, partial=True)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
# Retrieve the collection from the validated data
|
||||
new_collection = serializer.validated_data.get('collection')
|
||||
|
||||
if new_collection is not None and new_collection != instance.collection:
|
||||
# Check if the user is the owner of the new collection
|
||||
if new_collection.user_id != user or instance.user_id != user:
|
||||
raise PermissionDenied("You do not have permission to use this collection.")
|
||||
elif new_collection is None:
|
||||
# Handle the case where the user is trying to set the collection to None
|
||||
if instance.collection is not None and instance.collection.user_id != user:
|
||||
raise PermissionDenied("You cannot remove the collection as you are not the owner.")
|
||||
|
||||
# Perform the update
|
||||
self.perform_update(serializer)
|
||||
|
||||
# Return the updated instance
|
||||
return Response(serializer.data)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
serializer.save()
|
||||
|
||||
# when creating an adventure, make sure the user is the owner of the collection or shared with the collection
|
||||
def perform_create(self, serializer):
|
||||
# Retrieve the collection from the validated data
|
||||
collection = serializer.validated_data.get('collection')
|
||||
|
||||
# Check if a collection is provided
|
||||
if collection:
|
||||
user = self.request.user
|
||||
# Check if the user is the owner or is in the shared_with list
|
||||
if collection.user_id != user and not collection.shared_with.filter(id=user.id).exists():
|
||||
# Return an error response if the user does not have permission
|
||||
raise PermissionDenied("You do not have permission to use this collection.")
|
||||
# if collection the owner of the adventure is the owner of the collection
|
||||
serializer.save(user_id=collection.user_id)
|
||||
return
|
||||
|
||||
# Save the adventure with the current user as the owner
|
||||
serializer.save(user_id=self.request.user)
|
130
backend/server/adventures/views/note_view.py
Normal file
130
backend/server/adventures/views/note_view.py
Normal file
|
@ -0,0 +1,130 @@
|
|||
from rest_framework import viewsets, status
|
||||
from rest_framework.response import Response
|
||||
from django.db.models import Q
|
||||
from adventures.models import Note
|
||||
from adventures.serializers import NoteSerializer
|
||||
from rest_framework.exceptions import PermissionDenied
|
||||
from adventures.permissions import IsOwnerOrSharedWithFullAccess
|
||||
from rest_framework.decorators import action
|
||||
|
||||
class NoteViewSet(viewsets.ModelViewSet):
|
||||
queryset = Note.objects.all()
|
||||
serializer_class = NoteSerializer
|
||||
permission_classes = [IsOwnerOrSharedWithFullAccess]
|
||||
filterset_fields = ['is_public', 'collection']
|
||||
|
||||
# return error message if user is not authenticated on the root endpoint
|
||||
def list(self, request, *args, **kwargs):
|
||||
# Prevent listing all adventures
|
||||
return Response({"detail": "Listing all notes is not allowed."},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
@action(detail=False, methods=['get'])
|
||||
def all(self, request):
|
||||
if not request.user.is_authenticated:
|
||||
return Response({"error": "User is not authenticated"}, status=400)
|
||||
queryset = Note.objects.filter(
|
||||
Q(user_id=request.user.id)
|
||||
)
|
||||
serializer = self.get_serializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
def get_queryset(self):
|
||||
# if the user is not authenticated return only public transportations for retrieve action
|
||||
if not self.request.user.is_authenticated:
|
||||
if self.action == 'retrieve':
|
||||
return Note.objects.filter(is_public=True).distinct().order_by('-updated_at')
|
||||
return Note.objects.none()
|
||||
|
||||
|
||||
if self.action == 'retrieve':
|
||||
# For individual adventure retrieval, include public adventures
|
||||
return Note.objects.filter(
|
||||
Q(is_public=True) | Q(user_id=self.request.user.id) | Q(collection__shared_with=self.request.user)
|
||||
).distinct().order_by('-updated_at')
|
||||
else:
|
||||
# For other actions, include user's own adventures and shared adventures
|
||||
return Note.objects.filter(
|
||||
Q(user_id=self.request.user.id) | Q(collection__shared_with=self.request.user)
|
||||
).distinct().order_by('-updated_at')
|
||||
|
||||
def partial_update(self, request, *args, **kwargs):
|
||||
# Retrieve the current object
|
||||
instance = self.get_object()
|
||||
|
||||
# Partially update the instance with the request data
|
||||
serializer = self.get_serializer(instance, data=request.data, partial=True)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
# Retrieve the collection from the validated data
|
||||
new_collection = serializer.validated_data.get('collection')
|
||||
|
||||
user = request.user
|
||||
print(new_collection)
|
||||
|
||||
if new_collection is not None and new_collection!=instance.collection:
|
||||
# Check if the user is the owner of the new collection
|
||||
if new_collection.user_id != user or instance.user_id != user:
|
||||
raise PermissionDenied("You do not have permission to use this collection.")
|
||||
elif new_collection is None:
|
||||
# Handle the case where the user is trying to set the collection to None
|
||||
if instance.collection is not None and instance.collection.user_id != user:
|
||||
raise PermissionDenied("You cannot remove the collection as you are not the owner.")
|
||||
|
||||
# Perform the update
|
||||
self.perform_update(serializer)
|
||||
|
||||
# Return the updated instance
|
||||
return Response(serializer.data)
|
||||
|
||||
def partial_update(self, request, *args, **kwargs):
|
||||
# Retrieve the current object
|
||||
instance = self.get_object()
|
||||
|
||||
# Partially update the instance with the request data
|
||||
serializer = self.get_serializer(instance, data=request.data, partial=True)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
# Retrieve the collection from the validated data
|
||||
new_collection = serializer.validated_data.get('collection')
|
||||
|
||||
user = request.user
|
||||
print(new_collection)
|
||||
|
||||
if new_collection is not None and new_collection!=instance.collection:
|
||||
# Check if the user is the owner of the new collection
|
||||
if new_collection.user_id != user or instance.user_id != user:
|
||||
raise PermissionDenied("You do not have permission to use this collection.")
|
||||
elif new_collection is None:
|
||||
# Handle the case where the user is trying to set the collection to None
|
||||
if instance.collection is not None and instance.collection.user_id != user:
|
||||
raise PermissionDenied("You cannot remove the collection as you are not the owner.")
|
||||
|
||||
# Perform the update
|
||||
self.perform_update(serializer)
|
||||
|
||||
# Return the updated instance
|
||||
return Response(serializer.data)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
serializer.save()
|
||||
|
||||
# when creating an adventure, make sure the user is the owner of the collection or shared with the collection
|
||||
def perform_create(self, serializer):
|
||||
# Retrieve the collection from the validated data
|
||||
collection = serializer.validated_data.get('collection')
|
||||
|
||||
# Check if a collection is provided
|
||||
if collection:
|
||||
user = self.request.user
|
||||
# Check if the user is the owner or is in the shared_with list
|
||||
if collection.user_id != user and not collection.shared_with.filter(id=user.id).exists():
|
||||
# Return an error response if the user does not have permission
|
||||
raise PermissionDenied("You do not have permission to use this collection.")
|
||||
# if collection the owner of the adventure is the owner of the collection
|
||||
serializer.save(user_id=collection.user_id)
|
||||
return
|
||||
|
||||
# Save the adventure with the current user as the owner
|
||||
serializer.save(user_id=self.request.user)
|
258
backend/server/adventures/views/recommendations_view.py
Normal file
258
backend/server/adventures/views/recommendations_view.py
Normal file
|
@ -0,0 +1,258 @@
|
|||
from rest_framework import viewsets
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from django.conf import settings
|
||||
import requests
|
||||
from geopy.distance import geodesic
|
||||
import time
|
||||
|
||||
|
||||
class RecommendationsViewSet(viewsets.ViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
BASE_URL = "https://overpass-api.de/api/interpreter"
|
||||
HEADERS = {'User-Agent': 'AdventureLog Server'}
|
||||
|
||||
def parse_google_places(self, places, origin):
|
||||
adventures = []
|
||||
|
||||
for place in places:
|
||||
location = place.get('location', {})
|
||||
types = place.get('types', [])
|
||||
|
||||
# Updated for new API response structure
|
||||
formatted_address = place.get("formattedAddress") or place.get("shortFormattedAddress")
|
||||
display_name = place.get("displayName", {})
|
||||
name = display_name.get("text") if isinstance(display_name, dict) else display_name
|
||||
|
||||
lat = location.get('latitude')
|
||||
lon = location.get('longitude')
|
||||
|
||||
if not name or not lat or not lon:
|
||||
continue
|
||||
|
||||
distance_km = geodesic(origin, (lat, lon)).km
|
||||
|
||||
adventure = {
|
||||
"id": place.get('id'),
|
||||
"type": 'place',
|
||||
"name": name,
|
||||
"description": place.get('businessStatus', None),
|
||||
"latitude": lat,
|
||||
"longitude": lon,
|
||||
"address": formatted_address,
|
||||
"tag": types[0] if types else None,
|
||||
"distance_km": round(distance_km, 2),
|
||||
}
|
||||
|
||||
adventures.append(adventure)
|
||||
|
||||
# Sort by distance ascending
|
||||
adventures.sort(key=lambda x: x["distance_km"])
|
||||
|
||||
return adventures
|
||||
|
||||
def parse_overpass_response(self, data, request):
|
||||
nodes = data.get('elements', [])
|
||||
adventures = []
|
||||
all = request.query_params.get('all', False)
|
||||
|
||||
origin = None
|
||||
try:
|
||||
origin = (
|
||||
float(request.query_params.get('lat')),
|
||||
float(request.query_params.get('lon'))
|
||||
)
|
||||
except(ValueError, TypeError):
|
||||
origin = None
|
||||
|
||||
for node in nodes:
|
||||
if node.get('type') not in ['node', 'way', 'relation']:
|
||||
continue
|
||||
|
||||
tags = node.get('tags', {})
|
||||
lat = node.get('lat')
|
||||
lon = node.get('lon')
|
||||
name = tags.get('name', tags.get('official_name', ''))
|
||||
|
||||
if not name or lat is None or lon is None:
|
||||
if not all:
|
||||
continue
|
||||
|
||||
# Flatten address
|
||||
address_parts = [tags.get(f'addr:{k}') for k in ['housenumber', 'street', 'suburb', 'city', 'state', 'postcode', 'country']]
|
||||
formatted_address = ", ".join(filter(None, address_parts)) or name
|
||||
|
||||
# Calculate distance if possible
|
||||
distance_km = None
|
||||
if origin:
|
||||
distance_km = round(geodesic(origin, (lat, lon)).km, 2)
|
||||
|
||||
# Unified format
|
||||
adventure = {
|
||||
"id": f"osm:{node.get('id')}",
|
||||
"type": "place",
|
||||
"name": name,
|
||||
"description": tags.get('description'),
|
||||
"latitude": lat,
|
||||
"longitude": lon,
|
||||
"address": formatted_address,
|
||||
"tag": next((tags.get(key) for key in ['leisure', 'tourism', 'natural', 'historic', 'amenity'] if key in tags), None),
|
||||
"distance_km": distance_km,
|
||||
"powered_by": "osm"
|
||||
}
|
||||
|
||||
adventures.append(adventure)
|
||||
|
||||
# Sort by distance if available
|
||||
if origin:
|
||||
adventures.sort(key=lambda x: x.get("distance_km") or float("inf"))
|
||||
|
||||
return adventures
|
||||
|
||||
|
||||
def query_overpass(self, lat, lon, radius, category, request):
|
||||
if category == 'tourism':
|
||||
query = f"""
|
||||
[out:json];
|
||||
(
|
||||
node(around:{radius},{lat},{lon})["tourism"];
|
||||
node(around:{radius},{lat},{lon})["leisure"];
|
||||
node(around:{radius},{lat},{lon})["historic"];
|
||||
node(around:{radius},{lat},{lon})["sport"];
|
||||
node(around:{radius},{lat},{lon})["natural"];
|
||||
node(around:{radius},{lat},{lon})["attraction"];
|
||||
node(around:{radius},{lat},{lon})["museum"];
|
||||
node(around:{radius},{lat},{lon})["zoo"];
|
||||
node(around:{radius},{lat},{lon})["aquarium"];
|
||||
);
|
||||
out;
|
||||
"""
|
||||
elif category == 'lodging':
|
||||
query = f"""
|
||||
[out:json];
|
||||
(
|
||||
node(around:{radius},{lat},{lon})["tourism"="hotel"];
|
||||
node(around:{radius},{lat},{lon})["tourism"="motel"];
|
||||
node(around:{radius},{lat},{lon})["tourism"="guest_house"];
|
||||
node(around:{radius},{lat},{lon})["tourism"="hostel"];
|
||||
node(around:{radius},{lat},{lon})["tourism"="camp_site"];
|
||||
node(around:{radius},{lat},{lon})["tourism"="caravan_site"];
|
||||
node(around:{radius},{lat},{lon})["tourism"="chalet"];
|
||||
node(around:{radius},{lat},{lon})["tourism"="alpine_hut"];
|
||||
node(around:{radius},{lat},{lon})["tourism"="apartment"];
|
||||
);
|
||||
out;
|
||||
"""
|
||||
elif category == 'food':
|
||||
query = f"""
|
||||
[out:json];
|
||||
(
|
||||
node(around:{radius},{lat},{lon})["amenity"="restaurant"];
|
||||
node(around:{radius},{lat},{lon})["amenity"="cafe"];
|
||||
node(around:{radius},{lat},{lon})["amenity"="fast_food"];
|
||||
node(around:{radius},{lat},{lon})["amenity"="pub"];
|
||||
node(around:{radius},{lat},{lon})["amenity"="bar"];
|
||||
node(around:{radius},{lat},{lon})["amenity"="food_court"];
|
||||
node(around:{radius},{lat},{lon})["amenity"="ice_cream"];
|
||||
node(around:{radius},{lat},{lon})["amenity"="bakery"];
|
||||
node(around:{radius},{lat},{lon})["amenity"="confectionery"];
|
||||
);
|
||||
out;
|
||||
"""
|
||||
else:
|
||||
return Response({"error": "Invalid category."}, status=400)
|
||||
|
||||
overpass_url = f"{self.BASE_URL}?data={query}"
|
||||
try:
|
||||
response = requests.get(overpass_url, headers=self.HEADERS)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
except Exception as e:
|
||||
print("Overpass API error:", e)
|
||||
return Response({"error": "Failed to retrieve data from Overpass API."}, status=500)
|
||||
|
||||
adventures = self.parse_overpass_response(data, request)
|
||||
return Response(adventures)
|
||||
|
||||
def query_google_nearby(self, lat, lon, radius, category, request):
|
||||
"""Query Google Places API (New) for nearby places"""
|
||||
api_key = settings.GOOGLE_MAPS_API_KEY
|
||||
|
||||
# Updated to use new Places API endpoint
|
||||
url = "https://places.googleapis.com/v1/places:searchNearby"
|
||||
|
||||
headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Goog-Api-Key': api_key,
|
||||
'X-Goog-FieldMask': 'places.displayName.text,places.formattedAddress,places.location,places.types,places.rating,places.userRatingCount,places.businessStatus,places.id'
|
||||
}
|
||||
|
||||
# Map categories to place types for the new API
|
||||
type_mapping = {
|
||||
'lodging': 'lodging',
|
||||
'food': 'restaurant',
|
||||
'tourism': 'tourist_attraction',
|
||||
}
|
||||
|
||||
payload = {
|
||||
"includedTypes": [type_mapping[category]],
|
||||
"maxResultCount": 20,
|
||||
"locationRestriction": {
|
||||
"circle": {
|
||||
"center": {
|
||||
"latitude": float(lat),
|
||||
"longitude": float(lon)
|
||||
},
|
||||
"radius": float(radius)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.post(url, json=payload, headers=headers, timeout=10)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
places = data.get('places', [])
|
||||
origin = (float(lat), float(lon))
|
||||
adventures = self.parse_google_places(places, origin)
|
||||
|
||||
return Response(adventures)
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Google Places API error: {e}")
|
||||
# Fallback to Overpass API
|
||||
return self.query_overpass(lat, lon, radius, category, request)
|
||||
except Exception as e:
|
||||
print(f"Unexpected error with Google Places API: {e}")
|
||||
# Fallback to Overpass API
|
||||
return self.query_overpass(lat, lon, radius, category, request)
|
||||
|
||||
@action(detail=False, methods=['get'])
|
||||
def query(self, request):
|
||||
lat = request.query_params.get('lat')
|
||||
lon = request.query_params.get('lon')
|
||||
radius = request.query_params.get('radius', '1000')
|
||||
category = request.query_params.get('category', 'all')
|
||||
|
||||
if not lat or not lon:
|
||||
return Response({"error": "Latitude and longitude parameters are required."}, status=400)
|
||||
|
||||
valid_categories = {
|
||||
'lodging': 'lodging',
|
||||
'food': 'restaurant',
|
||||
'tourism': 'tourist_attraction',
|
||||
}
|
||||
|
||||
if category not in valid_categories:
|
||||
return Response({"error": f"Invalid category. Valid categories: {', '.join(valid_categories)}"}, status=400)
|
||||
|
||||
api_key = getattr(settings, 'GOOGLE_MAPS_API_KEY', None)
|
||||
|
||||
# Fallback to Overpass if no API key configured
|
||||
if not api_key:
|
||||
return self.query_overpass(lat, lon, radius, category, request)
|
||||
|
||||
# Use the new Google Places API
|
||||
return self.query_google_nearby(lat, lon, radius, category, request)
|
87
backend/server/adventures/views/reverse_geocode_view.py
Normal file
87
backend/server/adventures/views/reverse_geocode_view.py
Normal file
|
@ -0,0 +1,87 @@
|
|||
from rest_framework import viewsets
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from worldtravel.models import Region, City, VisitedRegion, VisitedCity
|
||||
from adventures.models import Adventure
|
||||
from adventures.serializers import AdventureSerializer
|
||||
import requests
|
||||
from adventures.geocoding import reverse_geocode
|
||||
from adventures.geocoding import extractIsoCode
|
||||
from django.conf import settings
|
||||
from adventures.geocoding import search_google, search_osm
|
||||
|
||||
class ReverseGeocodeViewSet(viewsets.ViewSet):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
@action(detail=False, methods=['get'])
|
||||
def reverse_geocode(self, request):
|
||||
lat = request.query_params.get('lat', '')
|
||||
lon = request.query_params.get('lon', '')
|
||||
if not lat or not lon:
|
||||
return Response({"error": "Latitude and longitude are required"}, status=400)
|
||||
try:
|
||||
lat = float(lat)
|
||||
lon = float(lon)
|
||||
except ValueError:
|
||||
return Response({"error": "Invalid latitude or longitude"}, status=400)
|
||||
data = reverse_geocode(lat, lon, self.request.user)
|
||||
if 'error' in data:
|
||||
return Response({"error": "An internal error occurred while processing the request"}, status=400)
|
||||
return Response(data)
|
||||
|
||||
@action(detail=False, methods=['get'])
|
||||
def search(self, request):
|
||||
query = request.query_params.get('query', '')
|
||||
if not query:
|
||||
return Response({"error": "Query parameter is required"}, status=400)
|
||||
|
||||
try:
|
||||
if getattr(settings, 'GOOGLE_MAPS_API_KEY', None):
|
||||
results = search_google(query)
|
||||
else:
|
||||
results = search_osm(query)
|
||||
return Response(results)
|
||||
except Exception:
|
||||
return Response({"error": "An internal error occurred while processing the request"}, status=500)
|
||||
|
||||
@action(detail=False, methods=['post'])
|
||||
def mark_visited_region(self, request):
|
||||
# searches through all of the users adventures, if the serialized data is_visited, is true, runs reverse geocode on the adventures and if a region is found, marks it as visited. Use the extractIsoCode function to get the region
|
||||
new_region_count = 0
|
||||
new_regions = {}
|
||||
new_city_count = 0
|
||||
new_cities = {}
|
||||
adventures = Adventure.objects.filter(user_id=self.request.user)
|
||||
serializer = AdventureSerializer(adventures, many=True)
|
||||
for adventure, serialized_adventure in zip(adventures, serializer.data):
|
||||
if serialized_adventure['is_visited'] == True:
|
||||
lat = adventure.latitude
|
||||
lon = adventure.longitude
|
||||
if not lat or not lon:
|
||||
continue
|
||||
|
||||
# Use the existing reverse_geocode function which handles both Google and OSM
|
||||
data = reverse_geocode(lat, lon, self.request.user)
|
||||
if 'error' in data:
|
||||
continue
|
||||
|
||||
# data already contains region_id and city_id
|
||||
if 'region_id' in data and data['region_id'] is not None:
|
||||
region = Region.objects.filter(id=data['region_id']).first()
|
||||
visited_region = VisitedRegion.objects.filter(region=region, user_id=self.request.user).first()
|
||||
if not visited_region:
|
||||
visited_region = VisitedRegion(region=region, user_id=self.request.user)
|
||||
visited_region.save()
|
||||
new_region_count += 1
|
||||
new_regions[region.id] = region.name
|
||||
|
||||
if 'city_id' in data and data['city_id'] is not None:
|
||||
city = City.objects.filter(id=data['city_id']).first()
|
||||
visited_city = VisitedCity.objects.filter(city=city, user_id=self.request.user).first()
|
||||
if not visited_city:
|
||||
visited_city = VisitedCity(city=city, user_id=self.request.user)
|
||||
visited_city.save()
|
||||
new_city_count += 1
|
||||
new_cities[city.id] = city.name
|
||||
return Response({"new_regions": new_region_count, "regions": new_regions, "new_cities": new_city_count, "cities": new_cities})
|
51
backend/server/adventures/views/stats_view.py
Normal file
51
backend/server/adventures/views/stats_view.py
Normal file
|
@ -0,0 +1,51 @@
|
|||
from rest_framework import viewsets
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.decorators import action
|
||||
from django.shortcuts import get_object_or_404
|
||||
from worldtravel.models import City, Region, Country, VisitedCity, VisitedRegion
|
||||
from adventures.models import Adventure, Collection
|
||||
from users.serializers import CustomUserDetailsSerializer as PublicUserSerializer
|
||||
from django.contrib.auth import get_user_model
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
class StatsViewSet(viewsets.ViewSet):
|
||||
"""
|
||||
A simple ViewSet for listing the stats of a user.
|
||||
"""
|
||||
@action(detail=False, methods=['get'], url_path=r'counts/(?P<username>[\w.@+-]+)')
|
||||
def counts(self, request, username):
|
||||
if request.user.username == username:
|
||||
user = get_object_or_404(User, username=username)
|
||||
else:
|
||||
user = get_object_or_404(User, username=username, public_profile=True)
|
||||
# serializer = PublicUserSerializer(user)
|
||||
|
||||
# remove the email address from the response
|
||||
user.email = None
|
||||
|
||||
# get the counts for the user
|
||||
adventure_count = Adventure.objects.filter(
|
||||
user_id=user.id).count()
|
||||
trips_count = Collection.objects.filter(
|
||||
user_id=user.id).count()
|
||||
visited_city_count = VisitedCity.objects.filter(
|
||||
user_id=user.id).count()
|
||||
total_cities = City.objects.count()
|
||||
visited_region_count = VisitedRegion.objects.filter(
|
||||
user_id=user.id).count()
|
||||
total_regions = Region.objects.count()
|
||||
visited_country_count = VisitedRegion.objects.filter(
|
||||
user_id=user.id).values('region__country').distinct().count()
|
||||
total_countries = Country.objects.count()
|
||||
return Response({
|
||||
'adventure_count': adventure_count,
|
||||
'trips_count': trips_count,
|
||||
'visited_city_count': visited_city_count,
|
||||
'total_cities': total_cities,
|
||||
'visited_region_count': visited_region_count,
|
||||
'total_regions': total_regions,
|
||||
'visited_country_count': visited_country_count,
|
||||
'total_countries': total_countries
|
||||
})
|
84
backend/server/adventures/views/transportation_view.py
Normal file
84
backend/server/adventures/views/transportation_view.py
Normal file
|
@ -0,0 +1,84 @@
|
|||
from rest_framework import viewsets, status
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from django.db.models import Q
|
||||
from adventures.models import Transportation
|
||||
from adventures.serializers import TransportationSerializer
|
||||
from rest_framework.exceptions import PermissionDenied
|
||||
from adventures.permissions import IsOwnerOrSharedWithFullAccess
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
|
||||
class TransportationViewSet(viewsets.ModelViewSet):
|
||||
queryset = Transportation.objects.all()
|
||||
serializer_class = TransportationSerializer
|
||||
permission_classes = [IsOwnerOrSharedWithFullAccess]
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
if not request.user.is_authenticated:
|
||||
return Response(status=status.HTTP_403_FORBIDDEN)
|
||||
queryset = Transportation.objects.filter(
|
||||
Q(user_id=request.user.id)
|
||||
)
|
||||
serializer = self.get_serializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
def get_queryset(self):
|
||||
user = self.request.user
|
||||
if self.action == 'retrieve':
|
||||
# For individual adventure retrieval, include public adventures, user's own adventures and shared adventures
|
||||
return Transportation.objects.filter(
|
||||
Q(is_public=True) | Q(user_id=user.id) | Q(collection__shared_with=user.id)
|
||||
).distinct().order_by('-updated_at')
|
||||
# For other actions, include user's own adventures and shared adventures
|
||||
return Transportation.objects.filter(
|
||||
Q(user_id=user.id) | Q(collection__shared_with=user.id)
|
||||
).distinct().order_by('-updated_at')
|
||||
|
||||
def partial_update(self, request, *args, **kwargs):
|
||||
# Retrieve the current object
|
||||
instance = self.get_object()
|
||||
user = request.user
|
||||
|
||||
# Partially update the instance with the request data
|
||||
serializer = self.get_serializer(instance, data=request.data, partial=True)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
# Retrieve the collection from the validated data
|
||||
new_collection = serializer.validated_data.get('collection')
|
||||
|
||||
if new_collection is not None and new_collection != instance.collection:
|
||||
# Check if the user is the owner of the new collection
|
||||
if new_collection.user_id != user or instance.user_id != user:
|
||||
raise PermissionDenied("You do not have permission to use this collection.")
|
||||
elif new_collection is None:
|
||||
# Handle the case where the user is trying to set the collection to None
|
||||
if instance.collection is not None and instance.collection.user_id != user:
|
||||
raise PermissionDenied("You cannot remove the collection as you are not the owner.")
|
||||
|
||||
# Perform the update
|
||||
self.perform_update(serializer)
|
||||
|
||||
# Return the updated instance
|
||||
return Response(serializer.data)
|
||||
|
||||
def perform_update(self, serializer):
|
||||
serializer.save()
|
||||
|
||||
# when creating an adventure, make sure the user is the owner of the collection or shared with the collection
|
||||
def perform_create(self, serializer):
|
||||
# Retrieve the collection from the validated data
|
||||
collection = serializer.validated_data.get('collection')
|
||||
|
||||
# Check if a collection is provided
|
||||
if collection:
|
||||
user = self.request.user
|
||||
# Check if the user is the owner or is in the shared_with list
|
||||
if collection.user_id != user and not collection.shared_with.filter(id=user.id).exists():
|
||||
# Return an error response if the user does not have permission
|
||||
raise PermissionDenied("You do not have permission to use this collection.")
|
||||
# if collection the owner of the adventure is the owner of the collection
|
||||
serializer.save(user_id=collection.user_id)
|
||||
return
|
||||
|
||||
# Save the adventure with the current user as the owner
|
||||
serializer.save(user_id=self.request.user)
|
0
backend/server/integrations/__init__.py
Normal file
0
backend/server/integrations/__init__.py
Normal file
9
backend/server/integrations/admin.py
Normal file
9
backend/server/integrations/admin.py
Normal file
|
@ -0,0 +1,9 @@
|
|||
from django.contrib import admin
|
||||
from allauth.account.decorators import secure_admin_login
|
||||
|
||||
from .models import ImmichIntegration
|
||||
|
||||
admin.autodiscover()
|
||||
admin.site.login = secure_admin_login(admin.site.login)
|
||||
|
||||
admin.site.register(ImmichIntegration)
|
6
backend/server/integrations/apps.py
Normal file
6
backend/server/integrations/apps.py
Normal file
|
@ -0,0 +1,6 @@
|
|||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class IntegrationsConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'integrations'
|
27
backend/server/integrations/migrations/0001_initial.py
Normal file
27
backend/server/integrations/migrations/0001_initial.py
Normal file
|
@ -0,0 +1,27 @@
|
|||
# Generated by Django 5.0.8 on 2025-01-02 23:16
|
||||
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='ImmichIntegration',
|
||||
fields=[
|
||||
('server_url', models.CharField(max_length=255)),
|
||||
('api_key', models.CharField(max_length=255)),
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
]
|
|
@ -0,0 +1,18 @@
|
|||
# Generated by Django 5.2.1 on 2025-06-01 21:38
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('integrations', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='immichintegration',
|
||||
name='copy_locally',
|
||||
field=models.BooleanField(default=True, help_text='Copy image to local storage, instead of just linking to the remote URL.'),
|
||||
),
|
||||
]
|
0
backend/server/integrations/migrations/__init__.py
Normal file
0
backend/server/integrations/migrations/__init__.py
Normal file
16
backend/server/integrations/models.py
Normal file
16
backend/server/integrations/models.py
Normal file
|
@ -0,0 +1,16 @@
|
|||
from django.db import models
|
||||
from django.contrib.auth import get_user_model
|
||||
import uuid
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
class ImmichIntegration(models.Model):
|
||||
server_url = models.CharField(max_length=255)
|
||||
api_key = models.CharField(max_length=255)
|
||||
user = models.ForeignKey(
|
||||
User, on_delete=models.CASCADE)
|
||||
copy_locally = models.BooleanField(default=True, help_text="Copy image to local storage, instead of just linking to the remote URL.")
|
||||
id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
|
||||
|
||||
def __str__(self):
|
||||
return self.user.username + ' - ' + self.server_url
|
13
backend/server/integrations/serializers.py
Normal file
13
backend/server/integrations/serializers.py
Normal file
|
@ -0,0 +1,13 @@
|
|||
from .models import ImmichIntegration
|
||||
from rest_framework import serializers
|
||||
|
||||
class ImmichIntegrationSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = ImmichIntegration
|
||||
fields = '__all__'
|
||||
read_only_fields = ['id', 'user']
|
||||
|
||||
def to_representation(self, instance):
|
||||
representation = super().to_representation(instance)
|
||||
representation.pop('user', None)
|
||||
return representation
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue