Compare commits
368 Commits
cbea87f74d
...
master
Author | SHA1 | Date | |
---|---|---|---|
25459cf429 | |||
c96e5bffa1 | |||
7dbb858d69 | |||
ac30cb5e4d | |||
d189c5a8d8 | |||
69e9a108ef | |||
2c8fd4e89a | |||
349d768d22 | |||
3c3cbd9c29 | |||
0034de71b5 | |||
068fffc1fd | |||
6f7a2de41e | |||
ce9d663bc3 | |||
37dc92dc43 | |||
79b12624d8 | |||
4901557217 | |||
c51721505f | |||
515412d663 | |||
d6f0daca61 | |||
f91b8dadb8 | |||
3c2a14800e | |||
fbe8e9b270 | |||
e588f2c87a | |||
bef5aa5c61 | |||
9fe0962c4a | |||
b2466bdee1 | |||
3cd102046a | |||
7a7d57c0d7 | |||
c8abf6647a | |||
60d8c0b766 | |||
8e33b99bca | |||
1b4d7822ed | |||
1c927122c2 | |||
ce257f83b8 | |||
b4c78cd10c | |||
0fa75406ed | |||
43447a1286 | |||
6e75f69263 | |||
c4720934fc | |||
93435b9ace | |||
78d9bb5fc2 | |||
5126855b1d | |||
d39e34b256 | |||
f769c5c5b5 | |||
7a12d375c1 | |||
14335084a1 | |||
32f2e3f1ed | |||
5f58a85892 | |||
3dd6b7b6f7 | |||
02da524aaa | |||
95d12a0a2d | |||
d6fa3bb15d | |||
26dfd25763 | |||
74de589513 | |||
d28669f527 | |||
7e5d75998d | |||
11322370b1 | |||
8a062bf07a | |||
359cb59bfe | |||
f0216bf770 | |||
951713b37f | |||
4b1953c8e7 | |||
673e7a69f5 | |||
b151acd6ac | |||
2f5d2a9938 | |||
15e38a9baf | |||
abb0295858 | |||
e127a72850 | |||
8f1605e1e9 | |||
da38e224bb | |||
67a0219cf7 | |||
0126361b8d | |||
76c78e0c01 | |||
f06bc2d382 | |||
10bf4fdf77 | |||
cc47ff4583 | |||
ba6e827cf8 | |||
63c42befb4 | |||
5630988ac2 | |||
390ac7e883 | |||
973ebe6d6d | |||
5f5f2bd1a5 | |||
dd5ce8074b | |||
4a7e41d4a9 | |||
625e86a7fd | |||
94decc6bad | |||
fd31120312 | |||
6228c186d7 | |||
14f4da6c91 | |||
ed77a443b8 | |||
87b6bee1f3 | |||
e35171ab81 | |||
a3cb407d89 | |||
be1beb713c | |||
a15a0d1c11 | |||
4b89474534 | |||
ed8afe8324 | |||
ecc2bff9a0 | |||
e1f1cd5130 | |||
5ce0e33359 | |||
b5f91b17e0 | |||
350cab0ff0 | |||
c738cff381 | |||
c1567f713a | |||
12ffcb7c5b | |||
3a4948d590 | |||
269e79ca58 | |||
14c17eded8 | |||
db59826253 | |||
60fa7a5bff | |||
a16c4c0764 | |||
0e3b1b6a37 | |||
9e8480640b | |||
a48553fff9 | |||
46d4082e38 | |||
c454bd0d5c | |||
79c34c1225 | |||
d7ed6ee33b | |||
ffb05154f9 | |||
a2633e6494 | |||
e16201a3ad | |||
429ca64f9d | |||
39218d19f3 | |||
9e2f2eedf9 | |||
0904f91b01 | |||
1d92b8945e | |||
59f0288c27 | |||
b756a9f19c | |||
748f442cbc | |||
d8dabd002b | |||
b888cf5acb | |||
57b908e5a0 | |||
9d9b2ac866 | |||
39ef6f9e0a | |||
644c0e6afb | |||
2ca6c615ff | |||
e90458c049 | |||
7a6dfeb9e6 | |||
2bb979668c | |||
2558b89b63 | |||
f609ac878a | |||
86db065117 | |||
ef8759e51d | |||
62d09717bb | |||
19e1b5f7c6 | |||
1a3e43a12f | |||
8cd7dca8aa | |||
0e4c0e5017 | |||
3c7ae284ac | |||
e37238436f | |||
6de2ef00a2 | |||
0ceee18524 | |||
c31d390a0b | |||
34d166bec8 | |||
710e2dc040 | |||
ade3dbdeee | |||
3213a3969e | |||
76e7dd7a07 | |||
79a61cc732 | |||
25eb0585d5 | |||
050d3e3f89 | |||
2543e1d125 | |||
c125565896 | |||
851c8e2f70 | |||
45d5ea5a68 | |||
fb33f4abc9 | |||
03f72d548d | |||
39889fe43d | |||
8d1db481de | |||
d2ffde8469 | |||
bca0f9025c | |||
08ba9ae758 | |||
d49c960be5 | |||
e1aad5519c | |||
2c138d06ee | |||
9dd03e0734 | |||
09335ea99f | |||
e906874b2e | |||
615fe3ff6c | |||
f9a01bff70 | |||
553a87ab78 | |||
f14a9be3ec | |||
ca64e056b9 | |||
0132b91394 | |||
c185fde553 | |||
1bd2da2850 | |||
001c9a8140 | |||
d889d22d11 | |||
89b495577e | |||
9bb55f10ce | |||
4d602220d2 | |||
6f26a44838 | |||
362e691b37 | |||
1e16e5c343 | |||
6c25f14189 | |||
d1bbf751d3 | |||
d6b6f2e399 | |||
db85cebe06 | |||
f86a7527a9 | |||
f5544e73f3 | |||
aca0aa97aa | |||
8191ad8187 | |||
277f1ee05f | |||
b226409caf | |||
9a59df6b5e | |||
16391ce18f | |||
86cdf28b22 | |||
d2f24d0be2 | |||
c01714b3fc | |||
45698db199 | |||
41af202623 | |||
13a65ad518 | |||
20e399bb39 | |||
a131a5bf86 | |||
aab0724653 | |||
9207a4f164 | |||
486bb69977 | |||
a0a3ef09d0 | |||
f89ec89b67 | |||
9a1e749649 | |||
ae269dfb3b | |||
bed420c16d | |||
4fac4a45b5 | |||
9cf4068844 | |||
a9bfb5767c | |||
d3371a7240 | |||
c55d0579f5 | |||
2470c4ac53 | |||
008d531855 | |||
6e14684539 | |||
2fbf7c4808 | |||
8aa627ef43 | |||
fca4032031 | |||
0383cdf407 | |||
6bb5699ec4 | |||
3a3c929858 | |||
6638a9bf14 | |||
dbd71e8b1b | |||
e9c7921d39 | |||
830484fee1 | |||
f19de97e8e | |||
ec0a2c3ac6 | |||
2d66b8acc0 | |||
2fe32d6c98 | |||
0fd742ffd2 | |||
f07364269a | |||
0519d99bbd | |||
7ae1f8021b | |||
27994733dd | |||
8cd154f0de | |||
0c686d7f06 | |||
09bc86da02 | |||
bce500a5c2 | |||
16d1790fb1 | |||
2366c3fd42 | |||
30399be718 | |||
37aa69e6ca | |||
ee62f3bef8 | |||
a4d8a3b37f | |||
761d73100b | |||
c8d55d0b2c | |||
f49cd3a892 | |||
2f8f799926 | |||
1925f26f16 | |||
93251c05f4 | |||
5af3e280b9 | |||
fba515fc70 | |||
dda0687b1a | |||
2cf24c4724 | |||
8429d72ad1 | |||
7b8ca225a8 | |||
d4dfa810d1 | |||
96b36c1db4 | |||
f5664715f8 | |||
045744aa18 | |||
3a5a84ae56 | |||
18dedfc493 | |||
e704c59664 | |||
248f97742b | |||
7f79c1a5ad | |||
06acabcd1a | |||
75b7c20d62 | |||
6ff637212f | |||
c67a38f4bb | |||
ad3257dabf | |||
e4d2a625d9 | |||
50704892f0 | |||
b778822247 | |||
fe339e722f | |||
4fa351b923 | |||
74cfd7ed23 | |||
15d8449d2e | |||
e836a97435 | |||
02d6801a7f | |||
0015952f92 | |||
d7113b5237 | |||
5b8eff7a42 | |||
93285e3ac1 | |||
396b5c6122 | |||
247dfbb46c | |||
8e38735ad8 | |||
c198565ced | |||
608c52ace6 | |||
b58466e8f6 | |||
a4ad17b038 | |||
dc86e33b9e | |||
c79c8d3618 | |||
52c864b11f | |||
11e6218185 | |||
fc493e82c3 | |||
850efcdc8b | |||
890148d580 | |||
fe8c5d2821 | |||
c656dc184a | |||
d75131cab4 | |||
4b8bc3e09b | |||
7d36755a72 | |||
827423ae3f | |||
80a8a31726 | |||
4709760edc | |||
da557fbe60 | |||
744a2511e9 | |||
fa87a8e838 | |||
dc7e83eb61 | |||
1542507715 | |||
4fb31ef20e | |||
69716216eb | |||
f78a1447d5 | |||
1181b1e5ce | |||
82a6c6dd31 | |||
017b67d738 | |||
97e2bb586c | |||
4aae5700e0 | |||
ed9066ca7b | |||
49363c801a | |||
e74d38f479 | |||
f36592dd37 | |||
f8377e7029 | |||
36bb84e48c | |||
6e98029eb4 | |||
ef3aa99827 | |||
2116e5b390 | |||
97e1d1f87e | |||
562af023f1 | |||
fb0c7860e0 | |||
93d959e7a6 | |||
bdfd74eaf4 | |||
19be4e2a67 | |||
327941455e | |||
311700db04 | |||
2b4ffb6811 | |||
1664fa62c4 | |||
36afe6ce3f | |||
b2ed560019 | |||
8c7338a752 | |||
87603e8bc5 | |||
30e55a5c6e | |||
298e1fe617 | |||
1eb7e88362 | |||
12cbb670df | |||
920492d5a6 | |||
a61da4f65e | |||
c14d3f70a3 | |||
2f87f9bc32 | |||
b1518f030b | |||
437c2e5b4b | |||
ea460c3623 | |||
d954cb87e6 |
2
.github/workflows/nightly.yml
vendored
2
.github/workflows/nightly.yml
vendored
@ -2,7 +2,7 @@ name: release-nightly
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
branches: [master]
|
||||
|
||||
jobs:
|
||||
build-docker:
|
||||
|
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,4 +1,6 @@
|
||||
/uploads
|
||||
/dist
|
||||
/keys
|
||||
|
||||
.DS_Store
|
||||
.idea
|
8
.idea/.gitignore
generated
vendored
8
.idea/.gitignore
generated
vendored
@ -1,8 +0,0 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
9
.idea/Interactive.iml
generated
9
.idea/Interactive.iml
generated
@ -1,9 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="WEB_MODULE" version="4">
|
||||
<component name="Go" enabled="true" />
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
53
.idea/codeStyles/Project.xml
generated
53
.idea/codeStyles/Project.xml
generated
@ -1,53 +0,0 @@
|
||||
<component name="ProjectCodeStyleConfiguration">
|
||||
<code_scheme name="Project" version="173">
|
||||
<HTMLCodeStyleSettings>
|
||||
<option name="HTML_SPACE_INSIDE_EMPTY_TAG" value="true" />
|
||||
</HTMLCodeStyleSettings>
|
||||
<JSCodeStyleSettings version="0">
|
||||
<option name="FORCE_SEMICOLON_STYLE" value="true" />
|
||||
<option name="SPACE_BEFORE_FUNCTION_LEFT_PARENTH" value="false" />
|
||||
<option name="FORCE_QUOTE_STYlE" value="true" />
|
||||
<option name="ENFORCE_TRAILING_COMMA" value="Remove" />
|
||||
<option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
|
||||
<option name="SPACES_WITHIN_IMPORTS" value="true" />
|
||||
</JSCodeStyleSettings>
|
||||
<TypeScriptCodeStyleSettings version="0">
|
||||
<option name="FORCE_SEMICOLON_STYLE" value="true" />
|
||||
<option name="SPACE_BEFORE_FUNCTION_LEFT_PARENTH" value="false" />
|
||||
<option name="FORCE_QUOTE_STYlE" value="true" />
|
||||
<option name="ENFORCE_TRAILING_COMMA" value="Remove" />
|
||||
<option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
|
||||
<option name="SPACES_WITHIN_IMPORTS" value="true" />
|
||||
</TypeScriptCodeStyleSettings>
|
||||
<codeStyleSettings language="HTML">
|
||||
<option name="SOFT_MARGINS" value="120" />
|
||||
<indentOptions>
|
||||
<option name="INDENT_SIZE" value="2" />
|
||||
<option name="CONTINUATION_INDENT_SIZE" value="2" />
|
||||
<option name="TAB_SIZE" value="2" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="JavaScript">
|
||||
<option name="SOFT_MARGINS" value="120" />
|
||||
<indentOptions>
|
||||
<option name="INDENT_SIZE" value="2" />
|
||||
<option name="CONTINUATION_INDENT_SIZE" value="2" />
|
||||
<option name="TAB_SIZE" value="2" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="TypeScript">
|
||||
<option name="SOFT_MARGINS" value="120" />
|
||||
<indentOptions>
|
||||
<option name="INDENT_SIZE" value="2" />
|
||||
<option name="CONTINUATION_INDENT_SIZE" value="2" />
|
||||
<option name="TAB_SIZE" value="2" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
<codeStyleSettings language="Vue">
|
||||
<option name="SOFT_MARGINS" value="120" />
|
||||
<indentOptions>
|
||||
<option name="CONTINUATION_INDENT_SIZE" value="2" />
|
||||
</indentOptions>
|
||||
</codeStyleSettings>
|
||||
</code_scheme>
|
||||
</component>
|
5
.idea/codeStyles/codeStyleConfig.xml
generated
5
.idea/codeStyles/codeStyleConfig.xml
generated
@ -1,5 +0,0 @@
|
||||
<component name="ProjectCodeStyleConfiguration">
|
||||
<state>
|
||||
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
|
||||
</state>
|
||||
</component>
|
12
.idea/dataSources.xml
generated
12
.idea/dataSources.xml
generated
@ -1,12 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
|
||||
<data-source source="LOCAL" name="hy_interactive@localhost" uuid="2e2101b2-4037-47ee-88ed-456dc2cb4423">
|
||||
<driver-ref>postgresql</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
|
||||
<jdbc-url>jdbc:postgresql://localhost:5432/hy_interactive</jdbc-url>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
</data-source>
|
||||
</component>
|
||||
</project>
|
11
.idea/inspectionProfiles/Project_Default.xml
generated
11
.idea/inspectionProfiles/Project_Default.xml
generated
@ -1,11 +0,0 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="DuplicatedCode" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||
<Languages>
|
||||
<language minSize="54" name="TypeScript" />
|
||||
</Languages>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="SqlDialectInspection" enabled="false" level="WARNING" enabled_by_default="false" />
|
||||
</profile>
|
||||
</component>
|
8
.idea/modules.xml
generated
8
.idea/modules.xml
generated
@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/Interactive.iml" filepath="$PROJECT_DIR$/.idea/Interactive.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
7
.idea/sqldialects.xml
generated
7
.idea/sqldialects.xml
generated
@ -1,7 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="SqlDialectMappings">
|
||||
<file url="file://$PROJECT_DIR$/pkg/server/moments_api.go" dialect="PostgreSQL" />
|
||||
<file url="file://$APPLICATION_CONFIG_DIR$/consoles/db/2e2101b2-4037-47ee-88ed-456dc2cb4423/console.sql" dialect="PostgreSQL" />
|
||||
</component>
|
||||
</project>
|
6
.idea/vcs.xml
generated
6
.idea/vcs.xml
generated
@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
@ -1,15 +1,9 @@
|
||||
# Building Backend
|
||||
FROM golang:alpine as interactive-server
|
||||
|
||||
RUN apk add nodejs npm
|
||||
|
||||
WORKDIR /source
|
||||
COPY . .
|
||||
WORKDIR /source/pkg/views
|
||||
RUN npm install
|
||||
RUN npm run build
|
||||
WORKDIR /source
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -buildvcs -o /dist ./pkg/cmd/main.go
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -buildvcs -o /dist ./pkg/main.go
|
||||
|
||||
# Runtime
|
||||
FROM golang:alpine
|
||||
|
124
go.mod
124
go.mod
@ -1,75 +1,105 @@
|
||||
module code.smartsheep.studio/hydrogen/interactive
|
||||
module git.solsynth.dev/hypernet/interactive
|
||||
|
||||
go 1.21.6
|
||||
go 1.23.2
|
||||
|
||||
require (
|
||||
github.com/go-playground/validator/v10 v10.17.0
|
||||
github.com/gofiber/fiber/v2 v2.52.0
|
||||
github.com/golang-jwt/jwt/v5 v5.2.0
|
||||
github.com/google/uuid v1.5.0
|
||||
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible
|
||||
git.solsynth.dev/hypernet/insight v0.0.0-20250129172551-974266b2c1d2
|
||||
git.solsynth.dev/hypernet/nexus v0.0.0-20250329075932-d5422ab5b04c
|
||||
git.solsynth.dev/hypernet/paperclip v0.0.0-20250330164539-11d54c7c7874
|
||||
git.solsynth.dev/hypernet/passport v0.0.0-20250329100405-b327e0806279
|
||||
git.solsynth.dev/hypernet/pusher v0.0.0-20250216145944-5fb769823a88
|
||||
git.solsynth.dev/hypernet/wallet v0.0.0-20250323095812-468cd655f886
|
||||
github.com/fatih/color v1.18.0
|
||||
github.com/go-ap/activitypub v0.0.0-20250212090640-aeb6499ba581
|
||||
github.com/go-playground/validator/v10 v10.22.1
|
||||
github.com/goccy/go-json v0.10.3
|
||||
github.com/gofiber/fiber/v2 v2.52.6
|
||||
github.com/json-iterator/go v1.1.12
|
||||
github.com/rs/zerolog v1.31.0
|
||||
github.com/samber/lo v1.39.0
|
||||
github.com/spf13/viper v1.18.2
|
||||
golang.org/x/crypto v0.19.0
|
||||
golang.org/x/oauth2 v0.16.0
|
||||
gorm.io/datatypes v1.2.0
|
||||
gorm.io/driver/postgres v1.5.4
|
||||
gorm.io/gorm v1.25.6
|
||||
github.com/pemistahl/lingua-go v1.4.0
|
||||
github.com/robfig/cron/v3 v3.0.1
|
||||
github.com/rs/zerolog v1.33.0
|
||||
github.com/samber/lo v1.47.0
|
||||
github.com/spf13/viper v1.19.0
|
||||
google.golang.org/grpc v1.70.0
|
||||
google.golang.org/protobuf v1.36.4
|
||||
gorm.io/datatypes v1.2.4
|
||||
gorm.io/driver/postgres v1.5.9
|
||||
gorm.io/gorm v1.25.12
|
||||
)
|
||||
|
||||
require (
|
||||
code.smartsheep.studio/hydrogen/identity v0.0.0-20240221130517-c169ffdacda8 // indirect
|
||||
github.com/andybalholm/brotli v1.0.5 // indirect
|
||||
github.com/fsnotify/fsnotify v1.7.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
github.com/gertd/go-pluralize v0.2.1 // indirect
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078 // indirect
|
||||
github.com/andybalholm/brotli v1.1.1 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/eko/gocache/lib/v4 v4.2.0 // indirect
|
||||
github.com/eko/gocache/store/redis/v4 v4.2.2 // indirect
|
||||
github.com/fsnotify/fsnotify v1.8.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||
github.com/go-ap/errors v0.0.0-20250124135319-3da8adefd4a9 // indirect
|
||||
github.com/go-ap/jsonld v0.0.0-20221030091449-f2a191312c73 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-sql-driver/mysql v1.7.1 // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/go-sql-driver/mysql v1.8.1 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1 // indirect
|
||||
github.com/golang/mock v1.6.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect
|
||||
github.com/jackc/pgx/v5 v5.5.1 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx/v5 v5.7.1 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/klauspost/compress v1.17.0 // indirect
|
||||
github.com/leodido/go-urn v1.2.4 // indirect
|
||||
github.com/klauspost/compress v1.18.0 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/magiconair/properties v1.8.7 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.15 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/minio/minio-go/v7 v7.0.70 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.1.1 // indirect
|
||||
github.com/philhofer/fwd v1.1.2 // indirect
|
||||
github.com/rivo/uniseg v0.2.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.4.0 // indirect
|
||||
github.com/nats-io/nats.go v1.37.0 // indirect
|
||||
github.com/nats-io/nkeys v0.4.7 // indirect
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
||||
github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c // indirect
|
||||
github.com/prometheus/client_golang v1.19.0 // indirect
|
||||
github.com/prometheus/client_model v0.6.1 // indirect
|
||||
github.com/prometheus/common v0.52.3 // indirect
|
||||
github.com/prometheus/procfs v0.13.0 // indirect
|
||||
github.com/redis/go-redis/v9 v9.7.3 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/rs/xid v1.5.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.6.0 // indirect
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
|
||||
github.com/shopspring/decimal v1.4.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||
github.com/spf13/afero v1.11.0 // indirect
|
||||
github.com/spf13/cast v1.6.0 // indirect
|
||||
github.com/spf13/cast v1.7.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/tinylib/msgp v1.1.8 // indirect
|
||||
github.com/tinylib/msgp v1.2.5 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.51.0 // indirect
|
||||
github.com/valyala/tcplisten v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.59.0 // indirect
|
||||
github.com/valyala/fastjson v1.6.4 // indirect
|
||||
go.uber.org/mock v0.4.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20231219180239-dc181d75b848 // indirect
|
||||
golang.org/x/net v0.21.0 // indirect
|
||||
golang.org/x/sync v0.5.0 // indirect
|
||||
golang.org/x/sys v0.17.0 // indirect
|
||||
golang.org/x/text v0.14.0 // indirect
|
||||
google.golang.org/appengine v1.6.8 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240221002015-b0ce06bbee7c // indirect
|
||||
google.golang.org/grpc v1.61.1 // indirect
|
||||
google.golang.org/protobuf v1.32.0 // indirect
|
||||
golang.org/x/crypto v0.33.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c // indirect
|
||||
golang.org/x/net v0.35.0 // indirect
|
||||
golang.org/x/sync v0.11.0 // indirect
|
||||
golang.org/x/sys v0.30.0 // indirect
|
||||
golang.org/x/text v0.22.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250127172529-29210b9bc287 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
gorm.io/driver/mysql v1.5.2 // indirect
|
||||
gorm.io/driver/mysql v1.5.7 // indirect
|
||||
)
|
||||
|
336
go.sum
336
go.sum
@ -1,94 +1,139 @@
|
||||
code.smartsheep.studio/hydrogen/identity v0.0.0-20240220134615-3b0cbbb6c9ed h1:/3rRncEKlN1GYWjUSJF8bUkwnCkTFon2opa+tGUTwEQ=
|
||||
code.smartsheep.studio/hydrogen/identity v0.0.0-20240220134615-3b0cbbb6c9ed/go.mod h1:db+/Y/fLPSOu1JlsCoXEYPD26644S0S3Bg/1XNLtlHQ=
|
||||
code.smartsheep.studio/hydrogen/identity v0.0.0-20240221124039-3393f751a072 h1:T3pP/cWpfHoxA6VrhFPq0EcrDVnUVXtfwQSzM3jFRfo=
|
||||
code.smartsheep.studio/hydrogen/identity v0.0.0-20240221124039-3393f751a072/go.mod h1:db+/Y/fLPSOu1JlsCoXEYPD26644S0S3Bg/1XNLtlHQ=
|
||||
code.smartsheep.studio/hydrogen/identity v0.0.0-20240221130517-c169ffdacda8 h1:WBi14r+jomgixVDFa8pPecrQshhlyJKBT51VZNs+PBY=
|
||||
code.smartsheep.studio/hydrogen/identity v0.0.0-20240221130517-c169ffdacda8/go.mod h1:db+/Y/fLPSOu1JlsCoXEYPD26644S0S3Bg/1XNLtlHQ=
|
||||
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
|
||||
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
git.solsynth.dev/hypernet/insight v0.0.0-20250129172551-974266b2c1d2 h1:dPBdssDIb+SqkAYlZgv80iftkfiijpMBCKe/6o4jwuA=
|
||||
git.solsynth.dev/hypernet/insight v0.0.0-20250129172551-974266b2c1d2/go.mod h1:NKSTeRc1mgg726iaCLEBoYEcVroIrGU5w2rnGf92LWE=
|
||||
git.solsynth.dev/hypernet/nexus v0.0.0-20250329075932-d5422ab5b04c h1:XgdTgJxSAQuCbiG15hN5pY6chzcz8sX3Onm2itS+Ufs=
|
||||
git.solsynth.dev/hypernet/nexus v0.0.0-20250329075932-d5422ab5b04c/go.mod h1:5tk62VQ1DcbR0EAN2jAOqYxHiegUPEC805JlfQ/G19I=
|
||||
git.solsynth.dev/hypernet/paperclip v0.0.0-20250329141722-820d7a9f42e6 h1:n7MgY8/TRJZXO4EJKmRqmzJQmE0E0X02Vf/pNJjRfms=
|
||||
git.solsynth.dev/hypernet/paperclip v0.0.0-20250329141722-820d7a9f42e6/go.mod h1:TdFsd/W3e04GAFVOWXBP9acSYF+YpmSeSdocnvt/4IY=
|
||||
git.solsynth.dev/hypernet/paperclip v0.0.0-20250330164539-11d54c7c7874 h1:Bdgn9y/0qxX9+zgCtZ8UwdGe7nyy4Bifem3Qf6dK/kY=
|
||||
git.solsynth.dev/hypernet/paperclip v0.0.0-20250330164539-11d54c7c7874/go.mod h1:TdFsd/W3e04GAFVOWXBP9acSYF+YpmSeSdocnvt/4IY=
|
||||
git.solsynth.dev/hypernet/passport v0.0.0-20250329100405-b327e0806279 h1:7eL9za4zGsoKImiCXkpGFdXcSYhdegSRVsXfBJq7Q5I=
|
||||
git.solsynth.dev/hypernet/passport v0.0.0-20250329100405-b327e0806279/go.mod h1:lbE/HrtMsnplOGvkg1JNjJL6DiXAnYczayxqN72UAJc=
|
||||
git.solsynth.dev/hypernet/pusher v0.0.0-20250216145944-5fb769823a88 h1:2HEENe9KUrdaJeNBzx9lsuXQGyzWqCgnLTKQnr8xFr8=
|
||||
git.solsynth.dev/hypernet/pusher v0.0.0-20250216145944-5fb769823a88/go.mod h1:ildzMtLagNsLK0Rkw4Hgk2TrrwqZnjwJIUx0MNZwcDY=
|
||||
git.solsynth.dev/hypernet/wallet v0.0.0-20250323095812-468cd655f886 h1:rVssXF8jZ64ctAfzlCgIgF22NCT9VAPAVxrwlcItx3s=
|
||||
git.solsynth.dev/hypernet/wallet v0.0.0-20250323095812-468cd655f886/go.mod h1:rmomNGQ6RBSp8TpZGA8tFr5M54AL2NADJ/1n0MfrIRM=
|
||||
git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078 h1:cliQ4HHsCo6xi2oWZYKWW4bly/Ory9FuTpFPRxj/mAg=
|
||||
git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078/go.mod h1:g/V2Hjas6Z1UHUp4yIx6bATpNzJ7DYtD0FG3+xARWxs=
|
||||
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
|
||||
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/eko/gocache/lib/v4 v4.2.0 h1:MNykyi5Xw+5Wu3+PUrvtOCaKSZM1nUSVftbzmeC7Yuw=
|
||||
github.com/eko/gocache/lib/v4 v4.2.0/go.mod h1:7ViVmbU+CzDHzRpmB4SXKyyzyuJ8A3UW3/cszpcqB4M=
|
||||
github.com/eko/gocache/store/redis/v4 v4.2.2 h1:Thw31fzGuH3WzJywsdbMivOmP550D6JS7GDHhvCJPA0=
|
||||
github.com/eko/gocache/store/redis/v4 v4.2.2/go.mod h1:LaTxLKx9TG/YUEybQvPMij++D7PBTIJ4+pzvk0ykz0w=
|
||||
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
|
||||
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
|
||||
github.com/gertd/go-pluralize v0.2.1 h1:M3uASbVjMnTsPb0PNqg+E/24Vwigyo/tvyMTtAlLgiA=
|
||||
github.com/gertd/go-pluralize v0.2.1/go.mod h1:rbYaKDbsXxmRfr8uygAEKhOWsjyrrqrkHVpZvoOp8zk=
|
||||
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
|
||||
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
|
||||
github.com/go-ap/activitypub v0.0.0-20250212090640-aeb6499ba581 h1:73sFEdBsWBTBut0aDMPgt8HRuMO+ML0fd8AA/zjO8BQ=
|
||||
github.com/go-ap/activitypub v0.0.0-20250212090640-aeb6499ba581/go.mod h1:IO2PtAsxfGXN5IHrPuOslENFbq7MprYLNOyiiOELoRQ=
|
||||
github.com/go-ap/errors v0.0.0-20250124135319-3da8adefd4a9 h1:AJBGzuJVgfkKF3LoXCNQfH9yWmsVDV/oPDJE/zeXOjE=
|
||||
github.com/go-ap/errors v0.0.0-20250124135319-3da8adefd4a9/go.mod h1:Vkh+Z3f24K8nMsJKXo1FHn5ebPsXvB/WDH5JRtYqdNo=
|
||||
github.com/go-ap/jsonld v0.0.0-20221030091449-f2a191312c73 h1:GMKIYXyXPGIp+hYiWOhfqK4A023HdgisDT4YGgf99mw=
|
||||
github.com/go-ap/jsonld v0.0.0-20221030091449-f2a191312c73/go.mod h1:jyveZeGw5LaADntW+UEsMjl3IlIwk+DxlYNsbofQkGA=
|
||||
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
||||
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.17.0 h1:SmVVlfAOtlZncTxRuinDPomC2DkXJ4E5T9gDA0AIH74=
|
||||
github.com/go-playground/validator/v10 v10.17.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
|
||||
github.com/go-playground/validator/v10 v10.22.1 h1:40JcKH+bBNGFczGuoBYgX4I6m/i27HYW8P9FDk5PbgA=
|
||||
github.com/go-playground/validator/v10 v10.22.1/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
|
||||
github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=
|
||||
github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
|
||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
|
||||
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/gofiber/fiber/v2 v2.52.0 h1:S+qXi7y+/Pgvqq4DrSmREGiFwtB7Bu6+QFLuIHYw/UE=
|
||||
github.com/gofiber/fiber/v2 v2.52.0/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.0 h1:d/ix8ftRUorsN+5eMIlF4T6J8CAt9rch3My2winC1Jw=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/gofiber/fiber/v2 v2.52.6 h1:Rfp+ILPiYSvvVuIPvxrBns+HJp8qGLDnLJawAu27XVI=
|
||||
github.com/gofiber/fiber/v2 v2.52.6/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA=
|
||||
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
|
||||
github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A=
|
||||
github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
|
||||
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
|
||||
github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
|
||||
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
|
||||
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 h1:L0QtFUgDarD7Fpv9jeVMgy/+Ec0mtnmYuImjTz6dtDA=
|
||||
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.5.1 h1:5I9etrGkLrN+2XPCsi6XLlV5DITbSL/xBZdmAxFcXPI=
|
||||
github.com/jackc/pgx/v5 v5.5.1/go.mod h1:Ig06C2Vu0t5qXC60W8sqIthScaEnFvojjj9dSljmHRA=
|
||||
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
|
||||
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.7.1 h1:x7SYsPBYDkHDksogeSmZZ5xzThcTgRz++I5E+ePFUcs=
|
||||
github.com/jackc/pgx/v5 v5.7.1/go.mod h1:e7O26IywZZ+naJtWWos6i6fvWK+29etgITqrqHLfoZA=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible h1:jdpOPRN1zP63Td1hDQbZW73xKmzDvZHzVdNYxhnTMDA=
|
||||
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible/go.mod h1:1c7szIrayyPPB/987hsnvNzLushdWf4o/79s3P08L8A=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM=
|
||||
github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
|
||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
|
||||
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
||||
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
|
||||
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mattn/go-sqlite3 v1.14.15 h1:vfoHhTN1af61xCRSWzFIWzx2YskyMTwHLrExkBOjvxI=
|
||||
github.com/mattn/go-sqlite3 v1.14.15/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
|
||||
github.com/microsoft/go-mssqldb v0.17.0 h1:Fto83dMZPnYv1Zwx5vHHxpNraeEaUlQ/hhHLgZiaenE=
|
||||
github.com/microsoft/go-mssqldb v0.17.0/go.mod h1:OkoNGhGEs8EZqchVTtochlXruEhEOaO4S0d2sB5aeGQ=
|
||||
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.0.70 h1:1u9NtMgfK1U42kUxcsl5v0yj6TEOPR497OAQxpJnn2g=
|
||||
github.com/minio/minio-go/v7 v7.0.70/go.mod h1:4yBA8v80xGA30cfM3fz0DKYMXunWl/AV/6tWEs9ryzo=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
@ -96,130 +141,137 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI=
|
||||
github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
|
||||
github.com/philhofer/fwd v1.1.2 h1:bnDivRJ1EWPjUIRXV5KfORO897HTbpFAQddBdE8t7Gw=
|
||||
github.com/philhofer/fwd v1.1.2/go.mod h1:qkPdfjR2SIEbspLqpe1tO4n5yICnr2DY7mqEx2tUTP0=
|
||||
github.com/nats-io/nats.go v1.37.0 h1:07rauXbVnnJvv1gfIyghFEo6lUcYRY0WXc3x7x0vUxE=
|
||||
github.com/nats-io/nats.go v1.37.0/go.mod h1:Ubdu4Nh9exXdSz0RVWRFBbRfrbSxOYd26oF0wkWclB8=
|
||||
github.com/nats-io/nkeys v0.4.7 h1:RwNJbbIdYCoClSDNY7QVKZlyb/wfT6ugvFCiKy6vDvI=
|
||||
github.com/nats-io/nkeys v0.4.7/go.mod h1:kqXRgRDPlGy7nGaEDMuYzmiJCIAAWDK0IMBtDmGD0nc=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
|
||||
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
|
||||
github.com/pemistahl/lingua-go v1.4.0 h1:ifYhthrlW7iO4icdubwlduYnmwU37V1sbNrwhKBR4rM=
|
||||
github.com/pemistahl/lingua-go v1.4.0/go.mod h1:ECuM1Hp/3hvyh7k8aWSqNCPlTxLemFZsRjocUf3KgME=
|
||||
github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c h1:dAMKvw0MlJT1GshSTtih8C2gDs04w8dReiOGXrGLNoY=
|
||||
github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/prometheus/client_golang v1.19.0 h1:ygXvpU1AoN1MhdzckN+PyD9QJOSD4x7kmXYlnfbA6JU=
|
||||
github.com/prometheus/client_golang v1.19.0/go.mod h1:ZRM9uEAypZakd+q/x7+gmsvXdURP+DABIEIjnmDdp+k=
|
||||
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
|
||||
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
|
||||
github.com/prometheus/common v0.52.3 h1:5f8uj6ZwHSscOGNdIQg6OiZv/ybiK2CO2q2drVZAQSA=
|
||||
github.com/prometheus/common v0.52.3/go.mod h1:BrxBKv3FWBIGXw89Mg1AeBq7FSyRzXWI3l3e7W3RN5U=
|
||||
github.com/prometheus/procfs v0.13.0 h1:GqzLlQyfsPbaEHaQkO7tbDlriv/4o5Hudv6OXHGKX7o=
|
||||
github.com/prometheus/procfs v0.13.0/go.mod h1:cd4PFCR54QLnGKPaKGA6l+cfuNXtht43ZKY6tow0Y1g=
|
||||
github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM=
|
||||
github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
|
||||
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
|
||||
github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc=
|
||||
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||
github.com/rs/zerolog v1.31.0 h1:FcTR3NnLWW+NnTwwhFWiJSZr4ECLpqCm6QsEnyvbV4A=
|
||||
github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
|
||||
github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=
|
||||
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
|
||||
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
|
||||
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
|
||||
github.com/sagikazarmark/locafero v0.6.0 h1:ON7AQg37yzcRPU69mt7gwhFEBwxI6P9T4Qu3N51bwOk=
|
||||
github.com/sagikazarmark/locafero v0.6.0/go.mod h1:77OmuIc6VTraTXKXIs/uvUxKGUXjE1GbemJYHqdNjX0=
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
|
||||
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
|
||||
github.com/samber/lo v1.39.0 h1:4gTz1wUhNYLhFSKl6O+8peW0v2F4BCY034GRpU9WnuA=
|
||||
github.com/samber/lo v1.39.0/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA=
|
||||
github.com/samber/lo v1.47.0 h1:z7RynLwP5nbyRscyvcD043DWYoOcYRv3mV8lBeqOCLc=
|
||||
github.com/samber/lo v1.47.0/go.mod h1:RmDH9Ct32Qy3gduHQuKJ3gW1fMHAnE/fAzQuf6He5cU=
|
||||
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
|
||||
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
|
||||
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
|
||||
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
|
||||
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
|
||||
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
|
||||
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
|
||||
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/cast v1.7.0 h1:ntdiHjuueXFgm5nzDRdOS4yfT43P5Fnud6DH50rz/7w=
|
||||
github.com/spf13/cast v1.7.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ=
|
||||
github.com/spf13/viper v1.18.2/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMVB+yk=
|
||||
github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI=
|
||||
github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/tinylib/msgp v1.1.8 h1:FCXC1xanKO4I8plpHGH2P7koL/RzZs12l/+r7vakfm0=
|
||||
github.com/tinylib/msgp v1.1.8/go.mod h1:qkpG+2ldGg4xRFmx+jfTvZPxfGFhi64BcnL9vkCm/Tw=
|
||||
github.com/tinylib/msgp v1.2.5 h1:WeQg1whrXRFiZusidTQqzETkRpGjFjcIhW6uqWH09po=
|
||||
github.com/tinylib/msgp v1.2.5/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA=
|
||||
github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g=
|
||||
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
|
||||
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/valyala/fasthttp v1.59.0 h1:Qu0qYHfXvPk1mSLNqcFtEk6DpxgA26hy6bmydotDpRI=
|
||||
github.com/valyala/fasthttp v1.59.0/go.mod h1:GTxNb9Bc6r2a9D0TWNSPwDz78UxnTGBViY3xZNEqyYU=
|
||||
github.com/valyala/fastjson v1.6.4 h1:uAUNq9Z6ymTgGhcm0UynUAB6tlbakBrz6CQFax3BXVQ=
|
||||
github.com/valyala/fastjson v1.6.4/go.mod h1:CLCAqky6SMuOcxStkYQvblddUtoRxhYMGLrsQns1aXY=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||
go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U=
|
||||
go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg=
|
||||
go.opentelemetry.io/otel/metric v1.32.0 h1:xV2umtmNcThh2/a/aCP+h64Xx5wsj8qqnkYZktzNa0M=
|
||||
go.opentelemetry.io/otel/metric v1.32.0/go.mod h1:jH7CIbbK6SH2V2wE16W05BHCtIDzauciCRLoc/SyMv8=
|
||||
go.opentelemetry.io/otel/sdk v1.32.0 h1:RNxepc9vK59A8XsgZQouW8ue8Gkb4jpWtJm9ge5lEG4=
|
||||
go.opentelemetry.io/otel/sdk v1.32.0/go.mod h1:LqgegDBjKMmb2GC6/PrTnteJG39I8/vJCAP9LlJXEjU=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.32.0 h1:rZvFnvmvawYb0alrYkjraqJq0Z4ZUJAiyYCU9snn1CU=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.32.0/go.mod h1:PWeZlq0zt9YkYAp3gjKZ0eicRYvOh1Gd+X99x6GHpCQ=
|
||||
go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQDe03fM=
|
||||
go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8=
|
||||
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
|
||||
go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc=
|
||||
golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=
|
||||
golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo=
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/exp v0.0.0-20231219180239-dc181d75b848 h1:+iq7lrkxmFNBM7xx+Rae2W6uyPfhPeDWD+n+JgppptE=
|
||||
golang.org/x/exp v0.0.0-20231219180239-dc181d75b848/go.mod h1:iRJReGqOEeBhDZGkGbynYwcHlctCvnjTYIamk7uXpHI=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
|
||||
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
|
||||
golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c h1:7dEasQXItcW1xKJ2+gg5VOiBnqWrJc+rq0DPKyvvdbY=
|
||||
golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c/go.mod h1:NQtJDoLvd6faHhE7m4T/1IY708gDefGGjR/iUW8yQQ8=
|
||||
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
|
||||
golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo=
|
||||
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
|
||||
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/oauth2 v0.16.0 h1:aDkGMBSYxElaoP81NpoUoz2oo2R2wHdZpGToUxfyQrQ=
|
||||
golang.org/x/oauth2 v0.16.0/go.mod h1:hqZ+0LWXsiVoZpeld6jVt06P3adbS2Uu911W1SsJv2o=
|
||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
|
||||
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
|
||||
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
|
||||
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=
|
||||
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
||||
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ=
|
||||
golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM=
|
||||
google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds=
|
||||
google.golang.org/genproto v0.0.0-20231106174013-bbf56f31fb17 h1:wpZ8pe2x1Q3f2KyT5f8oP/fa9rHAKgFPr/HZdNuS+PQ=
|
||||
google.golang.org/genproto v0.0.0-20240213162025-012b6fc9bca9 h1:9+tzLLstTlPTRyJTh+ah5wIMsBW5c4tQwGTN3thOW9Y=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20231120223509-83a465c0220f h1:ultW7fxlIvee4HYrtnaRPon9HpEgFk5zYpmfMgtKB5I=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20231120223509-83a465c0220f/go.mod h1:L9KNLi232K1/xB6f7AlSX692koaRnKaWSR0stBki0Yc=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240221002015-b0ce06bbee7c h1:NUsgEN92SQQqzfA+YtqYNqYmB3DMMYLlIwUZAQFVFbo=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240221002015-b0ce06bbee7c/go.mod h1:H4O17MA/PE9BsGx3w+a+W2VOLLD1Qf7oJneAoU6WktY=
|
||||
google.golang.org/grpc v1.59.0 h1:Z5Iec2pjwb+LEOqzpB2MR12/eKFhDPhuqW91O+4bwUk=
|
||||
google.golang.org/grpc v1.59.0/go.mod h1:aUPDwccQo6OTjy7Hct4AfBPD1GptF4fyUjIkQ9YtF98=
|
||||
google.golang.org/grpc v1.61.1 h1:kLAiWrZs7YeDM6MumDe7m3y4aM6wacLzM1Y/wiLP9XY=
|
||||
google.golang.org/grpc v1.61.1/go.mod h1:VUbo7IFqmF1QtCAstipjG0GIoq49KvMe9+h1jFLBNJs=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
|
||||
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250127172529-29210b9bc287 h1:J1H9f+LEdWAfHcez/4cvaVBox7cOYT+IU6rgqj5x++8=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250127172529-29210b9bc287/go.mod h1:8BS3B93F/U1juMFq9+EDk+qOT5CO1R9IzXxG3PTqiRk=
|
||||
google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ=
|
||||
google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw=
|
||||
google.golang.org/protobuf v1.36.4 h1:6A3ZDJHn/eNqc1i+IdefRzy/9PokBTPvcqMySR7NNIM=
|
||||
google.golang.org/protobuf v1.36.4/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
@ -228,16 +280,16 @@ gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/datatypes v1.2.0 h1:5YT+eokWdIxhJgWHdrb2zYUimyk0+TaFth+7a0ybzco=
|
||||
gorm.io/datatypes v1.2.0/go.mod h1:o1dh0ZvjIjhH/bngTpypG6lVRJ5chTBxE09FH/71k04=
|
||||
gorm.io/driver/mysql v1.5.2 h1:QC2HRskSE75wBuOxe0+iCkyJZ+RqpudsQtqkp+IMuXs=
|
||||
gorm.io/driver/mysql v1.5.2/go.mod h1:pQLhh1Ut/WUAySdTHwBpBv6+JKcj+ua4ZFx1QQTBzb8=
|
||||
gorm.io/driver/postgres v1.5.4 h1:Iyrp9Meh3GmbSuyIAGyjkN+n9K+GHX9b9MqsTL4EJCo=
|
||||
gorm.io/driver/postgres v1.5.4/go.mod h1:Bgo89+h0CRcdA33Y6frlaHHVuTdOf87pmyzwW9C/BH0=
|
||||
gorm.io/datatypes v1.2.4 h1:uZmGAcK/QZ0uyfCuVg0VQY1ZmV9h1fuG0tMwKByO1z4=
|
||||
gorm.io/datatypes v1.2.4/go.mod h1:f4BsLcFAX67szSv8svwLRjklArSHAvHLeE3pXAS5DZI=
|
||||
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
|
||||
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
|
||||
gorm.io/driver/postgres v1.5.9 h1:DkegyItji119OlcaLjqN11kHoUgZ/j13E0jkJZgD6A8=
|
||||
gorm.io/driver/postgres v1.5.9/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
|
||||
gorm.io/driver/sqlite v1.4.3 h1:HBBcZSDnWi5BW3B3rwvVTc510KGkBkexlOg0QrmLUuU=
|
||||
gorm.io/driver/sqlite v1.4.3/go.mod h1:0Aq3iPO+v9ZKbcdiz8gLWRw5VOPcBOPUQJFLq5e2ecI=
|
||||
gorm.io/driver/sqlserver v1.4.1 h1:t4r4r6Jam5E6ejqP7N82qAJIJAht27EGT41HyPfXRw0=
|
||||
gorm.io/driver/sqlserver v1.4.1/go.mod h1:DJ4P+MeZbc5rvY58PnmN1Lnyvb5gw5NPzGshHDnJLig=
|
||||
gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
|
||||
gorm.io/gorm v1.25.6 h1:V92+vVda1wEISSOMtodHVRcUIOPYa2tgQtyF+DfFx+A=
|
||||
gorm.io/gorm v1.25.6/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
|
||||
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
|
||||
|
BIN
pkg/.DS_Store
vendored
BIN
pkg/.DS_Store
vendored
Binary file not shown.
@ -1,60 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/grpc"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/server"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
interactive "code.smartsheep.studio/hydrogen/interactive/pkg"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func init() {
|
||||
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout})
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Configure settings
|
||||
viper.AddConfigPath(".")
|
||||
viper.AddConfigPath("..")
|
||||
viper.SetConfigName("settings")
|
||||
viper.SetConfigType("toml")
|
||||
|
||||
// Load settings
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
log.Panic().Err(err).Msg("An error occurred when loading settings.")
|
||||
}
|
||||
|
||||
// Connect to database
|
||||
if err := database.NewSource(); err != nil {
|
||||
log.Fatal().Err(err).Msg("An error occurred when connect to database.")
|
||||
} else if err := database.RunMigration(database.C); err != nil {
|
||||
log.Fatal().Err(err).Msg("An error occurred when running database auto migration.")
|
||||
}
|
||||
|
||||
// Connect other services
|
||||
go func() {
|
||||
if err := grpc.ConnectPassport(); err != nil {
|
||||
log.Fatal().Err(err).Msg("An error occurred when connecting to identity grpc endpoint...")
|
||||
}
|
||||
}()
|
||||
|
||||
// Server
|
||||
server.NewServer()
|
||||
go server.Listen()
|
||||
|
||||
// Messages
|
||||
log.Info().Msgf("Interactive v%s is started...", interactive.AppVersion)
|
||||
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-quit
|
||||
|
||||
log.Info().Msgf("Interactive v%s is quitting...", interactive.AppVersion)
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func RunMigration(source *gorm.DB) error {
|
||||
if err := source.AutoMigrate(
|
||||
&models.Account{},
|
||||
&models.AccountMembership{},
|
||||
&models.Realm{},
|
||||
&models.RealmMember{},
|
||||
&models.Category{},
|
||||
&models.Tag{},
|
||||
&models.Moment{},
|
||||
&models.Article{},
|
||||
&models.Comment{},
|
||||
&models.Reaction{},
|
||||
&models.Attachment{},
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/samber/lo"
|
||||
"github.com/spf13/viper"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
"gorm.io/gorm/schema"
|
||||
)
|
||||
|
||||
var C *gorm.DB
|
||||
|
||||
func NewSource() error {
|
||||
var err error
|
||||
|
||||
dialector := postgres.Open(viper.GetString("database.dsn"))
|
||||
C, err = gorm.Open(dialector, &gorm.Config{NamingStrategy: schema.NamingStrategy{
|
||||
TablePrefix: viper.GetString("database.prefix"),
|
||||
}, Logger: logger.New(&log.Logger, logger.Config{
|
||||
Colorful: true,
|
||||
IgnoreRecordNotFoundError: true,
|
||||
LogLevel: lo.Ternary(viper.GetBool("debug"), logger.Info, logger.Silent),
|
||||
})})
|
||||
|
||||
return err
|
||||
}
|
@ -1,24 +0,0 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
pwpb "code.smartsheep.studio/hydrogen/identity/pkg/grpc/proto"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
var Notify pwpb.NotifyClient
|
||||
var Auth pwpb.AuthClient
|
||||
|
||||
func ConnectPassport() error {
|
||||
addr := viper.GetString("identity.grpc_endpoint")
|
||||
if conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials())); err != nil {
|
||||
return err
|
||||
} else {
|
||||
Notify = pwpb.NewNotifyClient(conn)
|
||||
Auth = pwpb.NewAuthClient(conn)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
32
pkg/internal/database/migrator.go
Normal file
32
pkg/internal/database/migrator.go
Normal file
@ -0,0 +1,32 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var AutoMaintainRange = []any{
|
||||
&models.Publisher{},
|
||||
&models.Category{},
|
||||
&models.Tag{},
|
||||
&models.Post{},
|
||||
&models.PostInsight{},
|
||||
&models.Subscription{},
|
||||
&models.Poll{},
|
||||
&models.PollAnswer{},
|
||||
&models.PostFlag{},
|
||||
&models.PostView{},
|
||||
}
|
||||
|
||||
func RunMigration(source *gorm.DB) error {
|
||||
if err := source.AutoMigrate(
|
||||
append(
|
||||
AutoMaintainRange,
|
||||
&models.Reaction{},
|
||||
)...,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
31
pkg/internal/database/source.go
Normal file
31
pkg/internal/database/source.go
Normal file
@ -0,0 +1,31 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/samber/lo"
|
||||
"github.com/spf13/viper"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
var C *gorm.DB
|
||||
|
||||
func NewGorm() error {
|
||||
dsn, err := cruda.NewCrudaConn(gap.Nx).AllocDatabase("interactive")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to alloc database from nexus: %v", err)
|
||||
}
|
||||
|
||||
C, err = gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.New(&log.Logger, logger.Config{
|
||||
Colorful: true,
|
||||
IgnoreRecordNotFoundError: true,
|
||||
LogLevel: lo.Ternary(viper.GetBool("debug.database"), logger.Info, logger.Silent),
|
||||
})})
|
||||
|
||||
return err
|
||||
}
|
62
pkg/internal/gap/server.go
Normal file
62
pkg/internal/gap/server.go
Normal file
@ -0,0 +1,62 @@
|
||||
package gap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/cachekit"
|
||||
"git.solsynth.dev/hypernet/pusher/pkg/pushkit/pushcon"
|
||||
"github.com/samber/lo"
|
||||
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/proto"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
Nx *nex.Conn
|
||||
Px *pushcon.Conn
|
||||
Ca *cachekit.Conn
|
||||
)
|
||||
|
||||
func InitializeToNexus() error {
|
||||
grpcBind := strings.SplitN(viper.GetString("grpc_bind"), ":", 2)
|
||||
httpBind := strings.SplitN(viper.GetString("bind"), ":", 2)
|
||||
|
||||
outboundIp, _ := nex.GetOutboundIP()
|
||||
|
||||
grpcOutbound := fmt.Sprintf("%s:%s", outboundIp, grpcBind[1])
|
||||
httpOutbound := fmt.Sprintf("%s:%s", outboundIp, httpBind[1])
|
||||
|
||||
var err error
|
||||
Nx, err = nex.NewNexusConn(viper.GetString("nexus_addr"), &proto.ServiceInfo{
|
||||
Id: viper.GetString("id"),
|
||||
Type: "co",
|
||||
Label: "Interactive",
|
||||
GrpcAddr: grpcOutbound,
|
||||
HttpAddr: lo.ToPtr("http://" + httpOutbound + "/api"),
|
||||
})
|
||||
if err == nil {
|
||||
go func() {
|
||||
err := Nx.RunRegistering()
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred while registering service...")
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
Px, err = pushcon.NewConn(Nx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error during initialize pushcon: %v", err)
|
||||
}
|
||||
|
||||
Ca, err = cachekit.NewConn(Nx, 3*time.Second)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error during initialize cachekit: %v", err)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
26
pkg/internal/grpc/health.go
Normal file
26
pkg/internal/grpc/health.go
Normal file
@ -0,0 +1,26 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
health "google.golang.org/grpc/health/grpc_health_v1"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (v *App) Check(ctx context.Context, request *health.HealthCheckRequest) (*health.HealthCheckResponse, error) {
|
||||
return &health.HealthCheckResponse{
|
||||
Status: health.HealthCheckResponse_SERVING,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (v *App) Watch(request *health.HealthCheckRequest, server health.Health_WatchServer) error {
|
||||
for {
|
||||
if server.Send(&health.HealthCheckResponse{
|
||||
Status: health.HealthCheckResponse_SERVING,
|
||||
}) != nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(1000 * time.Millisecond)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
38
pkg/internal/grpc/server.go
Normal file
38
pkg/internal/grpc/server.go
Normal file
@ -0,0 +1,38 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/proto"
|
||||
"github.com/spf13/viper"
|
||||
"google.golang.org/grpc"
|
||||
health "google.golang.org/grpc/health/grpc_health_v1"
|
||||
"google.golang.org/grpc/reflection"
|
||||
"net"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
proto.UnimplementedDirectoryServiceServer
|
||||
|
||||
srv *grpc.Server
|
||||
}
|
||||
|
||||
func NewGrpc() *App {
|
||||
server := &App{
|
||||
srv: grpc.NewServer(),
|
||||
}
|
||||
|
||||
health.RegisterHealthServer(server.srv, server)
|
||||
proto.RegisterDirectoryServiceServer(server.srv, server)
|
||||
|
||||
reflection.Register(server.srv)
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
func (v *App) Listen() error {
|
||||
listener, err := net.Listen("tcp", viper.GetString("grpc_bind"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return v.srv.Serve(listener)
|
||||
}
|
59
pkg/internal/grpc/services.go
Normal file
59
pkg/internal/grpc/services.go
Normal file
@ -0,0 +1,59 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/proto"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (v *App) BroadcastEvent(ctx context.Context, in *proto.EventInfo) (*proto.EventResponse, error) {
|
||||
switch in.GetEvent() {
|
||||
case "deletion":
|
||||
data := nex.DecodeMap(in.GetData())
|
||||
resType, ok := data["type"].(string)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
switch resType {
|
||||
case "account":
|
||||
var data struct {
|
||||
ID int `json:"id"`
|
||||
}
|
||||
if err := jsoniter.Unmarshal(in.GetData(), &data); err != nil {
|
||||
break
|
||||
}
|
||||
tx := database.C.Begin()
|
||||
for _, model := range database.AutoMaintainRange {
|
||||
switch model.(type) {
|
||||
default:
|
||||
tx.Delete(model, "account_id = ?", data.ID)
|
||||
}
|
||||
}
|
||||
tx.Commit()
|
||||
case "realm":
|
||||
var data struct {
|
||||
ID int `json:"id"`
|
||||
}
|
||||
if err := jsoniter.Unmarshal(in.GetData(), &data); err != nil {
|
||||
break
|
||||
}
|
||||
var posts []models.Post
|
||||
if err := database.C.Where("realm_id = ?", data.ID).
|
||||
Select("Body").Select("ID").
|
||||
Find(&posts).Error; err != nil {
|
||||
break
|
||||
}
|
||||
if err := services.DeletePostInBatch(posts); err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred when deleting post...")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &proto.EventResponse{}, nil
|
||||
}
|
6
pkg/internal/http/admin/index.go
Normal file
6
pkg/internal/http/admin/index.go
Normal file
@ -0,0 +1,6 @@
|
||||
package admin
|
||||
|
||||
import "github.com/gofiber/fiber/v2"
|
||||
|
||||
func MapControllers(app *fiber.App, baseURL string) {
|
||||
}
|
146
pkg/internal/http/api/activitypub_api.go
Normal file
146
pkg/internal/http/api/activitypub_api.go
Normal file
@ -0,0 +1,146 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"github.com/go-ap/activitypub"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
func apUserInbox(c *fiber.Ctx) error {
|
||||
name := c.Params("name")
|
||||
|
||||
var activity activitypub.Activity
|
||||
if err := c.BodyParser(&activity); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "invalid activitypub event")
|
||||
}
|
||||
|
||||
// TODO Handle all these
|
||||
switch activity.Type {
|
||||
case activitypub.LikeType:
|
||||
log.Printf("User %s received a Like on: %s", name, activity.Object.GetID())
|
||||
case activitypub.FollowType:
|
||||
log.Printf("User %s received a Follow request from: %s", name, activity.Actor.GetID())
|
||||
case activitypub.CreateType:
|
||||
log.Printf("New post received for %s: %s", name, activity.Object.GetID())
|
||||
default:
|
||||
log.Printf("Unhandled activity type received: %+v", activity)
|
||||
}
|
||||
|
||||
return c.Status(http.StatusAccepted).SendString("Activity received")
|
||||
}
|
||||
|
||||
func apUserOutbox(c *fiber.Ctx) error {
|
||||
name := c.Params("name")
|
||||
page := c.QueryInt("page", 1)
|
||||
limit := c.QueryInt("limit", 10)
|
||||
|
||||
if limit > 100 {
|
||||
limit = 100
|
||||
}
|
||||
|
||||
var publisher models.Publisher
|
||||
if err := database.C.Where("name = ?", name).First(&publisher).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
tx, err := services.UniversalPostFilter(c, database.C)
|
||||
tx.Where("publisher_id = ? AND reply_id IS NULL", publisher.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
count, err := services.CountPost(tx)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
var activities []activitypub.Item
|
||||
if posts, err := services.ListPost(tx, limit, (page-1)*limit, "published_at DESC", nil); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
} else {
|
||||
for _, post := range posts {
|
||||
var content string
|
||||
if val, ok := post.Body["content"].(string); ok {
|
||||
content = val
|
||||
} else {
|
||||
content = "Posted a post"
|
||||
}
|
||||
note := activitypub.Note{
|
||||
ID: services.GetActivityID("/posts/" + strconv.Itoa(int(post.ID))),
|
||||
Type: activitypub.NoteType,
|
||||
Attachment: nil,
|
||||
AttributedTo: services.GetActivityIRI("/users/" + publisher.Name),
|
||||
Published: lo.TernaryF(post.PublishedAt == nil, func() time.Time {
|
||||
return post.CreatedAt
|
||||
}, func() time.Time {
|
||||
return *post.PublishedAt
|
||||
}),
|
||||
Updated: lo.TernaryF(post.EditedAt == nil, func() time.Time {
|
||||
return post.UpdatedAt
|
||||
}, func() time.Time {
|
||||
return *post.EditedAt
|
||||
}),
|
||||
To: activitypub.ItemCollection{activitypub.PublicNS},
|
||||
Content: activitypub.DefaultNaturalLanguageValue(content),
|
||||
}
|
||||
activity := activitypub.Create{
|
||||
ID: services.GetActivityID("/activities/posts/" + strconv.Itoa(int(post.ID))),
|
||||
Type: activitypub.CreateType,
|
||||
Actor: services.GetActivityIRI("/users/" + publisher.Name),
|
||||
Object: note,
|
||||
}
|
||||
activities = append(activities, activity)
|
||||
}
|
||||
}
|
||||
|
||||
totalPages := int(math.Ceil(float64(count) / float64(limit)))
|
||||
|
||||
outbox := activitypub.OrderedCollectionPage{
|
||||
ID: services.GetActivityID("/users/" + publisher.Name + "/outbox"),
|
||||
Type: activitypub.OrderedCollectionType,
|
||||
TotalItems: uint(count),
|
||||
OrderedItems: activitypub.ItemCollection(activities),
|
||||
First: services.GetActivityIRI(fmt.Sprintf("/users/%s/outbox?page=%d", publisher.Name, 1)),
|
||||
Last: services.GetActivityIRI(fmt.Sprintf("/users/%s/outbox?page=%d", publisher.Name, totalPages)),
|
||||
}
|
||||
|
||||
if page > 1 {
|
||||
outbox.Prev = services.GetActivityIRI(fmt.Sprintf("/users/%s/outbox?page=%d&limit=%d", publisher.Name, page-1, limit))
|
||||
}
|
||||
if page < totalPages {
|
||||
outbox.Next = services.GetActivityIRI(fmt.Sprintf("/users/%s/outbox?page=%d&limit=%d", publisher.Name, page+1, limit))
|
||||
}
|
||||
|
||||
return c.JSON(outbox)
|
||||
}
|
||||
|
||||
func apUserActor(c *fiber.Ctx) error {
|
||||
name := c.Params("name")
|
||||
|
||||
var publisher models.Publisher
|
||||
if err := database.C.Where("name = ?", name).First(&publisher).Error; err != nil {
|
||||
return c.Status(404).JSON(fiber.Map{"error": "User not found"})
|
||||
}
|
||||
|
||||
id := services.GetActivityID("/users/" + publisher.Name)
|
||||
actor := activitypub.Actor{
|
||||
ID: id,
|
||||
Inbox: id + "/inbox",
|
||||
Outbox: id + "/outbox",
|
||||
Type: activitypub.PersonType,
|
||||
Name: activitypub.DefaultNaturalLanguageValue(publisher.Name),
|
||||
PreferredUsername: activitypub.DefaultNaturalLanguageValue(publisher.Nick),
|
||||
}
|
||||
|
||||
return c.JSON(actor)
|
||||
}
|
217
pkg/internal/http/api/articles_api.go
Normal file
217
pkg/internal/http/api/articles_api.go
Normal file
@ -0,0 +1,217 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
"git.solsynth.dev/hypernet/passport/pkg/authkit"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/http/exts"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
func createArticle(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureGrantedPerm(c, "CreatePosts", true); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Publisher uint `json:"publisher"`
|
||||
Alias *string `json:"alias"`
|
||||
Title string `json:"title" validate:"required,max=1024"`
|
||||
Description *string `json:"description"`
|
||||
Content string `json:"content" validate:"required"`
|
||||
Thumbnail *string `json:"thumbnail"`
|
||||
Attachments []string `json:"attachments"`
|
||||
Tags []models.Tag `json:"tags"`
|
||||
Categories []models.Category `json:"categories"`
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
PublishedUntil *time.Time `json:"published_until"`
|
||||
VisibleUsers []uint `json:"visible_users_list"`
|
||||
InvisibleUsers []uint `json:"invisible_users_list"`
|
||||
Visibility *int8 `json:"visibility"`
|
||||
IsDraft bool `json:"is_draft"`
|
||||
Realm *uint `json:"realm"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
publisher, err := services.GetPublisher(data.Publisher, user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
body := models.PostArticleBody{
|
||||
Thumbnail: data.Thumbnail,
|
||||
Title: data.Title,
|
||||
Description: data.Description,
|
||||
Content: data.Content,
|
||||
Attachments: data.Attachments,
|
||||
}
|
||||
|
||||
var bodyMapping map[string]any
|
||||
rawBody, _ := jsoniter.Marshal(body)
|
||||
_ = jsoniter.Unmarshal(rawBody, &bodyMapping)
|
||||
|
||||
item := models.Post{
|
||||
Alias: data.Alias,
|
||||
Type: models.PostTypeArticle,
|
||||
Body: bodyMapping,
|
||||
Language: services.DetectLanguage(data.Content),
|
||||
Tags: data.Tags,
|
||||
Categories: data.Categories,
|
||||
IsDraft: data.IsDraft,
|
||||
PublishedAt: data.PublishedAt,
|
||||
PublishedUntil: data.PublishedUntil,
|
||||
VisibleUsers: data.VisibleUsers,
|
||||
InvisibleUsers: data.InvisibleUsers,
|
||||
PublisherID: publisher.ID,
|
||||
}
|
||||
|
||||
if item.PublishedAt == nil {
|
||||
item.PublishedAt = lo.ToPtr(time.Now())
|
||||
}
|
||||
|
||||
if data.Realm != nil {
|
||||
if _, err := authkit.GetRealmMember(gap.Nx, *data.Realm, user.ID); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("you are not a member of realm #%d", *data.Realm))
|
||||
}
|
||||
item.RealmID = data.Realm
|
||||
}
|
||||
|
||||
if data.Visibility != nil {
|
||||
item.Visibility = *data.Visibility
|
||||
} else {
|
||||
item.Visibility = models.PostVisibilityAll
|
||||
}
|
||||
|
||||
item, err = services.NewPost(publisher, item)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.new",
|
||||
map[string]interface{}{"post": item},
|
||||
c,
|
||||
)
|
||||
}
|
||||
|
||||
return c.JSON(item)
|
||||
}
|
||||
|
||||
func editArticle(c *fiber.Ctx) error {
|
||||
id, _ := c.ParamsInt("postId", 0)
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Publisher uint `json:"publisher"`
|
||||
Alias *string `json:"alias"`
|
||||
Title string `json:"title" validate:"required,max=1024"`
|
||||
Description *string `json:"description"`
|
||||
Content string `json:"content" validate:"required"`
|
||||
Thumbnail *string `json:"thumbnail"`
|
||||
Attachments []string `json:"attachments"`
|
||||
Tags []models.Tag `json:"tags"`
|
||||
Categories []models.Category `json:"categories"`
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
PublishedUntil *time.Time `json:"published_until"`
|
||||
VisibleUsers []uint `json:"visible_users_list"`
|
||||
InvisibleUsers []uint `json:"invisible_users_list"`
|
||||
Visibility *int8 `json:"visibility"`
|
||||
IsDraft bool `json:"is_draft"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
publisher, err := services.GetPublisher(data.Publisher, user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
var item models.Post
|
||||
if err := database.C.Where(models.Post{
|
||||
BaseModel: cruda.BaseModel{ID: uint(id)},
|
||||
PublisherID: publisher.ID,
|
||||
Type: models.PostTypeArticle,
|
||||
}).Preload("Publisher").First(&item).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if item.LockedAt != nil {
|
||||
return fiber.NewError(fiber.StatusForbidden, "post was locked")
|
||||
}
|
||||
|
||||
if !item.IsDraft && !data.IsDraft {
|
||||
item.EditedAt = lo.ToPtr(time.Now())
|
||||
}
|
||||
|
||||
if item.IsDraft && !data.IsDraft && data.PublishedAt == nil {
|
||||
item.PublishedAt = lo.ToPtr(time.Now())
|
||||
} else {
|
||||
item.PublishedAt = data.PublishedAt
|
||||
}
|
||||
|
||||
body := models.PostArticleBody{
|
||||
Thumbnail: data.Thumbnail,
|
||||
Title: data.Title,
|
||||
Description: data.Description,
|
||||
Content: data.Content,
|
||||
Attachments: data.Attachments,
|
||||
}
|
||||
|
||||
var bodyMapping map[string]any
|
||||
rawBody, _ := jsoniter.Marshal(body)
|
||||
_ = jsoniter.Unmarshal(rawBody, &bodyMapping)
|
||||
|
||||
og := item
|
||||
item.Alias = data.Alias
|
||||
item.Body = bodyMapping
|
||||
item.Language = services.DetectLanguage(data.Content)
|
||||
item.Tags = data.Tags
|
||||
item.Categories = data.Categories
|
||||
item.IsDraft = data.IsDraft
|
||||
item.PublishedUntil = data.PublishedUntil
|
||||
item.VisibleUsers = data.VisibleUsers
|
||||
item.InvisibleUsers = data.InvisibleUsers
|
||||
|
||||
// Preload publisher data
|
||||
item.Publisher = publisher
|
||||
|
||||
if item.PublishedAt == nil {
|
||||
item.PublishedAt = data.PublishedAt
|
||||
}
|
||||
if data.Visibility != nil {
|
||||
item.Visibility = *data.Visibility
|
||||
}
|
||||
|
||||
if item, err = services.EditPost(item, og); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.edit",
|
||||
map[string]interface{}{"post": item},
|
||||
c,
|
||||
)
|
||||
}
|
||||
|
||||
return c.JSON(item)
|
||||
}
|
@ -1,24 +1,50 @@
|
||||
package server
|
||||
package api
|
||||
|
||||
import (
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/services"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/http/exts"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func listCategories(c *fiber.Ctx) error {
|
||||
categories, err := services.ListCategory()
|
||||
func getCategory(c *fiber.Ctx) error {
|
||||
alias := c.Params("category")
|
||||
|
||||
category, err := services.GetCategory(alias)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(category)
|
||||
}
|
||||
|
||||
func listCategories(c *fiber.Ctx) error {
|
||||
take := c.QueryInt("take", 10)
|
||||
offset := c.QueryInt("offset", 0)
|
||||
probe := c.Query("probe")
|
||||
|
||||
if take > 100 {
|
||||
take = 100
|
||||
}
|
||||
|
||||
var categories []models.Category
|
||||
var err error
|
||||
if len(probe) > 0 {
|
||||
categories, err = services.SearchCategories(take, offset, probe)
|
||||
} else {
|
||||
categories, err = services.ListCategory(take, offset)
|
||||
}
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(categories)
|
||||
}
|
||||
|
||||
func newCategory(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
if user.PowerLevel <= 55 {
|
||||
return fiber.NewError(fiber.StatusForbidden, "require power level 55 to create categories")
|
||||
if err := sec.EnsureGrantedPerm(c, "CreatePostCategories", true); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var data struct {
|
||||
@ -27,7 +53,7 @@ func newCategory(c *fiber.Ctx) error {
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
if err := BindAndValidate(c, &data); err != nil {
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@ -40,9 +66,8 @@ func newCategory(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
func editCategory(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
if user.PowerLevel <= 55 {
|
||||
return fiber.NewError(fiber.StatusForbidden, "require power level 55 to edit categories")
|
||||
if err := sec.EnsureGrantedPerm(c, "CreatePostCategories", true); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
id, _ := c.ParamsInt("categoryId", 0)
|
||||
@ -57,7 +82,7 @@ func editCategory(c *fiber.Ctx) error {
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
if err := BindAndValidate(c, &data); err != nil {
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@ -70,9 +95,8 @@ func editCategory(c *fiber.Ctx) error {
|
||||
}
|
||||
|
||||
func deleteCategory(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
if user.PowerLevel <= 55 {
|
||||
return fiber.NewError(fiber.StatusForbidden, "require power level 55 to delete categories")
|
||||
if err := sec.EnsureGrantedPerm(c, "CreatePostCategories", true); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
id, _ := c.ParamsInt("categoryId", 0)
|
50
pkg/internal/http/api/flags_api.go
Normal file
50
pkg/internal/http/api/flags_api.go
Normal file
@ -0,0 +1,50 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func createFlag(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureGrantedPerm(c, "FlagPost", true); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
id := c.Params("postId")
|
||||
|
||||
var item models.Post
|
||||
var err error
|
||||
|
||||
tx := services.FilterPostDraft(database.C)
|
||||
|
||||
if numericId, paramErr := strconv.Atoi(id); paramErr == nil {
|
||||
item, err = services.GetPost(tx, uint(numericId))
|
||||
} else {
|
||||
segments := strings.Split(id, ":")
|
||||
if len(segments) != 2 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "invalid post id, must be a number or a string with two segment divided by a colon")
|
||||
}
|
||||
area := segments[0]
|
||||
alias := segments[1]
|
||||
item, err = services.GetPostByAlias(tx, alias, area)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
flag, err := services.NewFlag(item, user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(flag)
|
||||
}
|
111
pkg/internal/http/api/index.go
Normal file
111
pkg/internal/http/api/index.go
Normal file
@ -0,0 +1,111 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func MapControllers(app *fiber.App, baseURL string) {
|
||||
api := app.Group(baseURL).Name("API")
|
||||
{
|
||||
api.Get("/webfinger", getWebfinger)
|
||||
activitypub := api.Group("/activitypub").Name("ActivityPub API")
|
||||
{
|
||||
activitypub.Post("/users/:name/inbox", apUserInbox)
|
||||
activitypub.Get("/users/:name/outbox", apUserOutbox)
|
||||
activitypub.Get("/users/:name", apUserActor)
|
||||
}
|
||||
|
||||
publishers := api.Group("/publishers").Name("Publisher API")
|
||||
{
|
||||
publishers.Get("/", listRelatedPublisher)
|
||||
publishers.Get("/me", listOwnedPublisher)
|
||||
publishers.Post("/personal", createPersonalPublisher)
|
||||
publishers.Post("/organization", createOrganizationPublisher)
|
||||
publishers.Get("/:name/pins", listPinnedPost)
|
||||
publishers.Get("/:name", getPublisher)
|
||||
publishers.Put("/:name", editPublisher)
|
||||
publishers.Delete("/:name", deletePublisher)
|
||||
}
|
||||
|
||||
recommendations := api.Group("/recommendations").Name("Recommendations API")
|
||||
{
|
||||
recommendations.Get("/", listRecommendation)
|
||||
recommendations.Get("/shuffle", listRecommendationShuffle)
|
||||
recommendations.Get("/feed", getRecommendationFeed)
|
||||
}
|
||||
|
||||
stories := api.Group("/stories").Name("Story API")
|
||||
{
|
||||
stories.Post("/", createStory)
|
||||
stories.Put("/:postId", editStory)
|
||||
}
|
||||
articles := api.Group("/articles").Name("Article API")
|
||||
{
|
||||
articles.Post("/", createArticle)
|
||||
articles.Put("/:postId", editArticle)
|
||||
}
|
||||
questions := api.Group("/questions").Name("Question API")
|
||||
{
|
||||
questions.Post("/", createQuestion)
|
||||
questions.Put("/:postId", editQuestion)
|
||||
questions.Put("/:postId/answer", selectQuestionAnswer)
|
||||
}
|
||||
videos := api.Group("/videos").Name("Video API")
|
||||
{
|
||||
videos.Post("/", createVideo)
|
||||
videos.Put("/:postId", editVideo)
|
||||
}
|
||||
|
||||
posts := api.Group("/posts").Name("Posts API")
|
||||
{
|
||||
posts.Get("/", listPost)
|
||||
posts.Get("/search", searchPost)
|
||||
posts.Get("/minimal", listPostMinimal)
|
||||
posts.Get("/drafts", listDraftPost)
|
||||
posts.Get("/:postId", getPost)
|
||||
posts.Get("/:postId/insight", getPostInsight)
|
||||
posts.Post("/:postId/flag", createFlag)
|
||||
posts.Post("/:postId/react", reactPost)
|
||||
posts.Post("/:postId/pin", pinPost)
|
||||
posts.Post("/:postId/uncollapse", uncollapsePost)
|
||||
posts.Delete("/:postId", deletePost)
|
||||
|
||||
posts.Get("/:postId/replies", listPostReplies)
|
||||
posts.Get("/:postId/replies/featured", listPostFeaturedReply)
|
||||
}
|
||||
|
||||
polls := api.Group("/polls").Name("Polls API")
|
||||
{
|
||||
polls.Get("/:pollId", getPoll)
|
||||
polls.Post("/", createPoll)
|
||||
polls.Put("/:pollId", updatePoll)
|
||||
polls.Delete("/:pollId", deletePoll)
|
||||
polls.Post("/:pollId/answer", answerPoll)
|
||||
polls.Get("/:pollId/answer", getMyPollAnswer)
|
||||
}
|
||||
|
||||
subscriptions := api.Group("/subscriptions").Name("Subscriptions API")
|
||||
{
|
||||
subscriptions.Get("/users/:userId", getSubscriptionOnUser)
|
||||
subscriptions.Get("/tags/:tagId", getSubscriptionOnTag)
|
||||
subscriptions.Get("/categories/:categoryId", getSubscriptionOnCategory)
|
||||
subscriptions.Post("/users/:userId", subscribeToUser)
|
||||
subscriptions.Post("/tags/:tagId", subscribeToTag)
|
||||
subscriptions.Post("/categories/:categoryId", subscribeToCategory)
|
||||
subscriptions.Delete("/users/:userId", unsubscribeFromUser)
|
||||
subscriptions.Delete("/tags/:tagId", unsubscribeFromTag)
|
||||
subscriptions.Delete("/categories/:categoryId", unsubscribeFromCategory)
|
||||
}
|
||||
|
||||
api.Get("/categories", listCategories)
|
||||
api.Get("/categories/:category", getCategory)
|
||||
api.Post("/categories", newCategory)
|
||||
api.Put("/categories/:categoryId", editCategory)
|
||||
api.Delete("/categories/:categoryId", deleteCategory)
|
||||
|
||||
api.Get("/tags", listTags)
|
||||
api.Get("/tags/:tag", getTag)
|
||||
|
||||
api.Get("/whats-new", getWhatsNew)
|
||||
}
|
||||
}
|
58
pkg/internal/http/api/insight_api.go
Normal file
58
pkg/internal/http/api/insight_api.go
Normal file
@ -0,0 +1,58 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func getPostInsight(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
id := c.Params("postId")
|
||||
|
||||
var item models.Post
|
||||
var err error
|
||||
|
||||
tx := services.FilterPostDraft(database.C)
|
||||
|
||||
if user, authenticated := c.Locals("user").(authm.Account); authenticated {
|
||||
tx = services.FilterPostWithUserContext(c, tx, &user)
|
||||
} else {
|
||||
tx = services.FilterPostWithUserContext(c, tx, nil)
|
||||
}
|
||||
|
||||
if numericId, paramErr := strconv.Atoi(id); paramErr == nil {
|
||||
item, err = services.GetPost(tx, uint(numericId))
|
||||
} else {
|
||||
segments := strings.Split(id, ":")
|
||||
if len(segments) != 2 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "invalid post id, must be a number or a string with two segment divided by a colon")
|
||||
}
|
||||
area := segments[0]
|
||||
alias := segments[1]
|
||||
item, err = services.GetPostByAlias(tx, alias, area)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
response, err := services.GeneratePostInsights(item, user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"response": response,
|
||||
})
|
||||
}
|
78
pkg/internal/http/api/poll_answers_api.go
Normal file
78
pkg/internal/http/api/poll_answers_api.go
Normal file
@ -0,0 +1,78 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/http/exts"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func getMyPollAnswer(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
pollId, _ := c.ParamsInt("pollId")
|
||||
|
||||
var answer models.PollAnswer
|
||||
if err := database.C.Where("poll_id = ? AND account_id = ?", pollId, user.ID).First(&answer).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(answer)
|
||||
}
|
||||
|
||||
func answerPoll(c *fiber.Ctx) error {
|
||||
pollId, _ := c.ParamsInt("pollId")
|
||||
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Answer string `json:"answer" validate:"required"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var poll models.Poll
|
||||
if err := database.C.Where("id = ?", pollId).First(&poll).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
if poll.ExpiredAt != nil && time.Now().Unix() >= poll.ExpiredAt.Unix() {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "poll has been ended")
|
||||
}
|
||||
|
||||
doesContains := false
|
||||
for _, option := range poll.Options {
|
||||
if option.ID == data.Answer {
|
||||
doesContains = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !doesContains {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "poll does not have a option like that")
|
||||
}
|
||||
|
||||
answer := models.PollAnswer{
|
||||
Answer: data.Answer,
|
||||
PollID: poll.ID,
|
||||
AccountID: user.ID,
|
||||
}
|
||||
|
||||
if answer, err := services.AddPollAnswer(poll, answer); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
return c.JSON(answer)
|
||||
}
|
||||
}
|
108
pkg/internal/http/api/polls_api.go
Normal file
108
pkg/internal/http/api/polls_api.go
Normal file
@ -0,0 +1,108 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/http/exts"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func getPoll(c *fiber.Ctx) error {
|
||||
pollId, _ := c.ParamsInt("pollId")
|
||||
|
||||
var poll models.Poll
|
||||
if err := database.C.Where("id = ?", pollId).First(&poll).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
poll.Metric = services.GetPollMetric(poll)
|
||||
|
||||
return c.JSON(poll)
|
||||
}
|
||||
|
||||
func createPoll(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Options []models.PollOption `json:"options" validate:"required"`
|
||||
ExpiredAt *time.Time `json:"expired_at"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
poll := models.Poll{
|
||||
ExpiredAt: data.ExpiredAt,
|
||||
Options: data.Options,
|
||||
AccountID: user.ID,
|
||||
}
|
||||
|
||||
var err error
|
||||
if poll, err = services.NewPoll(poll); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(poll)
|
||||
}
|
||||
|
||||
func updatePoll(c *fiber.Ctx) error {
|
||||
pollId, _ := c.ParamsInt("pollId")
|
||||
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Options []models.PollOption `json:"options" validate:"required"`
|
||||
ExpiredAt *time.Time `json:"expired_at"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var poll models.Poll
|
||||
if err := database.C.Where("id = ? AND account_id = ?", pollId, user.ID).First(&poll).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
poll.Options = data.Options
|
||||
poll.ExpiredAt = data.ExpiredAt
|
||||
|
||||
var err error
|
||||
if poll, err = services.UpdatePoll(poll); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(poll)
|
||||
}
|
||||
|
||||
func deletePoll(c *fiber.Ctx) error {
|
||||
pollId, _ := c.ParamsInt("pollId")
|
||||
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var poll models.Poll
|
||||
if err := database.C.Where("id = ? AND account_id = ?", pollId, user.ID).First(&poll).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if err := database.C.Delete(&poll).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(poll)
|
||||
}
|
388
pkg/internal/http/api/posts_api.go
Normal file
388
pkg/internal/http/api/posts_api.go
Normal file
@ -0,0 +1,388 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
"git.solsynth.dev/hypernet/passport/pkg/authkit"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/http/exts"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services/queries"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
func getPost(c *fiber.Ctx) error {
|
||||
id := c.Params("postId")
|
||||
|
||||
var item models.Post
|
||||
var err error
|
||||
|
||||
var userId *uint
|
||||
if user, authenticated := c.Locals("user").(authm.Account); authenticated {
|
||||
userId = &user.ID
|
||||
}
|
||||
|
||||
tx := database.C
|
||||
if tx, err = services.UniversalPostFilter(c, tx, services.UniversalPostFilterConfig{
|
||||
ShowReply: true,
|
||||
ShowDraft: true,
|
||||
ShowCollapsed: true,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if numericId, paramErr := strconv.Atoi(id); paramErr == nil {
|
||||
if c.Get("X-API-Version", "1") == "2" {
|
||||
item, err = queries.GetPost(tx, uint(numericId), userId)
|
||||
} else {
|
||||
item, err = services.GetPost(tx, uint(numericId))
|
||||
}
|
||||
} else {
|
||||
segments := strings.Split(id, ":")
|
||||
if len(segments) != 2 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "invalid post id, must be a number or a string with two segment divided by a colon")
|
||||
}
|
||||
area := segments[0]
|
||||
alias := segments[1]
|
||||
if c.Get("X-API-Version", "1") == "2" {
|
||||
item, err = queries.GetPostByAlias(tx, alias, area, userId)
|
||||
} else {
|
||||
item, err = services.GetPostByAlias(tx, alias, area)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
item.Metric = models.PostMetric{
|
||||
ReplyCount: services.CountPostReply(item.ID),
|
||||
ReactionCount: services.CountPostReactions(item.ID),
|
||||
}
|
||||
item.Metric.ReactionList, err = services.ListPostReactions(database.C.Where("post_id = ?", item.ID))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(item)
|
||||
}
|
||||
|
||||
func searchPost(c *fiber.Ctx) error {
|
||||
take := c.QueryInt("take", 10)
|
||||
offset := c.QueryInt("offset", 0)
|
||||
|
||||
tx := database.C
|
||||
|
||||
probe := c.Query("probe")
|
||||
if len(probe) == 0 && len(c.Query("tags")) == 0 && len(c.Query("categories")) == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "search term (probe, tags or categories) is required")
|
||||
}
|
||||
|
||||
tx = services.FilterPostWithFuzzySearch(tx, probe)
|
||||
|
||||
var err error
|
||||
if tx, err = services.UniversalPostFilter(c, tx, services.UniversalPostFilterConfig{
|
||||
ShowReply: true,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var userId *uint
|
||||
if user, authenticated := c.Locals("user").(authm.Account); authenticated {
|
||||
userId = &user.ID
|
||||
}
|
||||
|
||||
var count int64
|
||||
countTx := tx
|
||||
count, err = services.CountPost(countTx)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
var items []models.Post
|
||||
|
||||
if c.Get("X-API-Version", "1") == "2" {
|
||||
items, err = queries.ListPost(tx, take, offset, "published_at DESC", userId)
|
||||
} else {
|
||||
items, err = services.ListPost(tx, take, offset, "published_at DESC", userId)
|
||||
}
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
if c.QueryBool("truncate", true) {
|
||||
for _, item := range items {
|
||||
item = services.TruncatePostContent(item)
|
||||
}
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"count": count,
|
||||
"data": items,
|
||||
})
|
||||
}
|
||||
|
||||
func listPost(c *fiber.Ctx) error {
|
||||
take := c.QueryInt("take", 10)
|
||||
offset := c.QueryInt("offset", 0)
|
||||
|
||||
tx := database.C
|
||||
|
||||
var err error
|
||||
if tx, err = services.UniversalPostFilter(c, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var userId *uint
|
||||
if user, authenticated := c.Locals("user").(authm.Account); authenticated {
|
||||
userId = &user.ID
|
||||
}
|
||||
|
||||
var count int64
|
||||
countTx := tx
|
||||
count, err = services.CountPost(countTx)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
var items []models.Post
|
||||
|
||||
if c.Get("X-API-Version", "1") == "2" {
|
||||
items, err = queries.ListPost(tx, take, offset, "published_at DESC", userId)
|
||||
} else {
|
||||
items, err = services.ListPost(tx, take, offset, "published_at DESC", userId)
|
||||
}
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
if c.QueryBool("truncate", true) {
|
||||
for _, item := range items {
|
||||
item = services.TruncatePostContent(item)
|
||||
}
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"count": count,
|
||||
"data": items,
|
||||
})
|
||||
}
|
||||
|
||||
func listPostMinimal(c *fiber.Ctx) error {
|
||||
take := c.QueryInt("take", 10)
|
||||
offset := c.QueryInt("offset", 0)
|
||||
|
||||
tx := database.C
|
||||
|
||||
var err error
|
||||
if tx, err = services.UniversalPostFilter(c, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
countTx := tx
|
||||
count, err := services.CountPost(countTx)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
items, err := services.ListPostMinimal(tx, take, offset, "published_at DESC")
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
if c.QueryBool("truncate", false) {
|
||||
for _, item := range items {
|
||||
if item != nil {
|
||||
item = lo.ToPtr(services.TruncatePostContent(*item))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"count": count,
|
||||
"data": items,
|
||||
})
|
||||
}
|
||||
|
||||
func listDraftPost(c *fiber.Ctx) error {
|
||||
take := c.QueryInt("take", 10)
|
||||
offset := c.QueryInt("offset", 0)
|
||||
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var err error
|
||||
tx := services.FilterPostWithAuthorDraft(database.C, user.ID)
|
||||
|
||||
var userId *uint
|
||||
if user, authenticated := c.Locals("user").(authm.Account); authenticated {
|
||||
userId = &user.ID
|
||||
}
|
||||
|
||||
var count int64
|
||||
countTx := tx
|
||||
count, err = services.CountPost(countTx)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
var items []models.Post
|
||||
|
||||
if c.Get("X-API-Version", "1") == "2" {
|
||||
items, err = queries.ListPost(tx, take, offset, "published_at DESC", userId)
|
||||
} else {
|
||||
items, err = services.ListPost(tx, take, offset, "published_at DESC", userId)
|
||||
}
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
if c.QueryBool("truncate", true) {
|
||||
for _, item := range items {
|
||||
item = services.TruncatePostContent(item)
|
||||
}
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"count": count,
|
||||
"data": items,
|
||||
})
|
||||
}
|
||||
|
||||
func deletePost(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
id, _ := c.ParamsInt("postId", 0)
|
||||
|
||||
publisherId := c.QueryInt("publisherId", 0)
|
||||
if publisherId <= 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "missing publisher id in request")
|
||||
}
|
||||
|
||||
publisher, err := services.GetPublisher(uint(publisherId), user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
var item models.Post
|
||||
if err := database.C.Where(models.Post{
|
||||
BaseModel: cruda.BaseModel{ID: uint(id)},
|
||||
PublisherID: publisher.ID,
|
||||
}).Preload("Publisher").First(&item).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if err := services.DeletePost(item); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.delete",
|
||||
map[string]any{"post": item},
|
||||
c,
|
||||
)
|
||||
}
|
||||
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
|
||||
func reactPost(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureGrantedPerm(c, "CreateReactions", true); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Symbol string `json:"symbol"`
|
||||
Attitude models.ReactionAttitude `json:"attitude"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
reaction := models.Reaction{
|
||||
Symbol: data.Symbol,
|
||||
Attitude: data.Attitude,
|
||||
AccountID: user.ID,
|
||||
}
|
||||
|
||||
var res models.Post
|
||||
if err := database.C.Where("id = ?", c.Params("postId")).Select("id").First(&res).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to find post to react: %v", err))
|
||||
} else {
|
||||
reaction.PostID = res.ID
|
||||
}
|
||||
|
||||
if positive, reaction, err := services.ReactPost(user, reaction); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.react",
|
||||
map[string]any{"post_id": res.ID, "reaction": reaction},
|
||||
c,
|
||||
)
|
||||
|
||||
return c.Status(lo.Ternary(positive, fiber.StatusCreated, fiber.StatusNoContent)).JSON(reaction)
|
||||
}
|
||||
}
|
||||
|
||||
func pinPost(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var res models.Post
|
||||
if err := database.C.Where("id = ? AND publisher_id = ?", c.Params("postId"), user.ID).First(&res).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to find post in your posts to pin: %v", err))
|
||||
}
|
||||
|
||||
if status, err := services.PinPost(res); err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
} else if status {
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.pin",
|
||||
map[string]any{"post": res},
|
||||
c,
|
||||
)
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
} else {
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.unpin",
|
||||
map[string]any{"post": res},
|
||||
c,
|
||||
)
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func uncollapsePost(c *fiber.Ctx) error {
|
||||
id, _ := c.ParamsInt("postId", 0)
|
||||
|
||||
if err := sec.EnsureGrantedPerm(c, "UncollapsePosts", true); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := database.C.Model(&models.Post{}).Where("id = ?", id).Update("is_collapsed", false).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
228
pkg/internal/http/api/publishers_api.go
Normal file
228
pkg/internal/http/api/publishers_api.go
Normal file
@ -0,0 +1,228 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/http/exts"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
"git.solsynth.dev/hypernet/passport/pkg/authkit"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func listPinnedPost(c *fiber.Ctx) error {
|
||||
name := c.Params("name")
|
||||
|
||||
var user models.Publisher
|
||||
if err := database.C.
|
||||
Where("name = ?", name).
|
||||
First(&user).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
tx := services.FilterPostDraft(database.C)
|
||||
tx = tx.Where("publisher_id = ?", user.ID)
|
||||
tx = tx.Where("pinned_at IS NOT NULL")
|
||||
|
||||
var userId *uint
|
||||
if user, authenticated := c.Locals("user").(authm.Account); authenticated {
|
||||
userId = &user.ID
|
||||
}
|
||||
|
||||
items, err := services.ListPost(tx, 100, 0, "published_at DESC", userId)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(items)
|
||||
}
|
||||
|
||||
func getPublisher(c *fiber.Ctx) error {
|
||||
name := c.Params("name")
|
||||
|
||||
var publisher models.Publisher
|
||||
if err := database.C.Where("name = ?", name).First(&publisher).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(publisher)
|
||||
}
|
||||
|
||||
func listRelatedPublisher(c *fiber.Ctx) error {
|
||||
tx := database.C
|
||||
if len(c.Query("user")) > 0 {
|
||||
user, err := authkit.GetUserByName(gap.Nx, c.Query("user"))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("unable to find user: %v", err))
|
||||
}
|
||||
tx = tx.Where("account_id = ? AND type = ?", user.ID, models.PublisherTypePersonal)
|
||||
} else if len(c.Query("realm")) > 0 {
|
||||
realm, err := authkit.GetRealmByAlias(gap.Nx, c.Query("realm"))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("unable to find realm: %v", err))
|
||||
}
|
||||
tx = tx.Where("realm_id = ? AND type = ?", realm.ID, models.PublisherTypeOrganization)
|
||||
} else {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "missing user or realm in query string")
|
||||
}
|
||||
|
||||
var publishers []models.Publisher
|
||||
if err := tx.Find(&publishers).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(publishers)
|
||||
}
|
||||
|
||||
func listOwnedPublisher(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var publishers []models.Publisher
|
||||
if err := database.C.Where("account_id = ?", user.ID).Find(&publishers).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(publishers)
|
||||
}
|
||||
|
||||
func createPersonalPublisher(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureGrantedPerm(c, "CreatePublishers", true); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Name string `json:"name" validate:"required,min=4,max=32,alphanum"`
|
||||
Nick string `json:"nick" validate:"required,min=2,max=64"`
|
||||
Description string `json:"description"`
|
||||
Avatar string `json:"avatar"`
|
||||
Banner string `json:"banner"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if pub, err := services.CreatePersonalPublisher(
|
||||
user,
|
||||
data.Name,
|
||||
data.Nick,
|
||||
data.Description,
|
||||
data.Avatar,
|
||||
data.Banner,
|
||||
); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
return c.JSON(pub)
|
||||
}
|
||||
}
|
||||
|
||||
func createOrganizationPublisher(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureGrantedPerm(c, "CreatePublishers", true); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Realm string `json:"realm" validate:"required"`
|
||||
Name string `json:"name" validate:"required,min=4,max=32,alphanum"`
|
||||
Nick string `json:"nick" validate:"required,min=2,max=64"`
|
||||
Description string `json:"description"`
|
||||
Avatar string `json:"avatar"`
|
||||
Banner string `json:"banner"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
realm, err := authkit.GetRealmByAlias(gap.Nx, data.Realm)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to get realm: %v", err))
|
||||
}
|
||||
if !authkit.CheckRealmMemberPerm(gap.Nx, realm.ID, int(user.ID), 100) {
|
||||
return fiber.NewError(fiber.StatusForbidden, "you least need to be the admin of this realm to create a publisher")
|
||||
}
|
||||
|
||||
if pub, err := services.CreateOrganizationPublisher(
|
||||
user,
|
||||
realm,
|
||||
data.Name,
|
||||
data.Nick,
|
||||
data.Description,
|
||||
data.Avatar,
|
||||
data.Banner,
|
||||
); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
return c.JSON(pub)
|
||||
}
|
||||
}
|
||||
|
||||
func editPublisher(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
name := c.Params("name")
|
||||
publisher, err := services.GetPublisherByName(name, user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
var data struct {
|
||||
Name string `json:"name"`
|
||||
Nick string `json:"nick"`
|
||||
Description string `json:"description"`
|
||||
Avatar string `json:"avatar"`
|
||||
Banner string `json:"banner"`
|
||||
AccountID *uint `json:"account_id"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
og := publisher
|
||||
publisher.Name = data.Name
|
||||
publisher.Nick = data.Nick
|
||||
publisher.Description = data.Description
|
||||
publisher.Avatar = data.Avatar
|
||||
publisher.Banner = data.Banner
|
||||
if data.AccountID != nil {
|
||||
publisher.AccountID = data.AccountID
|
||||
}
|
||||
|
||||
if publisher, err = services.EditPublisher(user, publisher, og); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(publisher)
|
||||
}
|
||||
|
||||
func deletePublisher(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
name := c.Params("name")
|
||||
publisher, err := services.GetPublisherByName(name, user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if err := services.DeletePublisher(publisher); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
355
pkg/internal/http/api/questions_api.go
Normal file
355
pkg/internal/http/api/questions_api.go
Normal file
@ -0,0 +1,355 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/http/exts"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
"git.solsynth.dev/hypernet/passport/pkg/authkit"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
wproto "git.solsynth.dev/hypernet/wallet/pkg/proto"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
func createQuestion(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureGrantedPerm(c, "CreatePosts", true); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Publisher uint `json:"publisher"`
|
||||
Alias *string `json:"alias"`
|
||||
Title *string `json:"title"`
|
||||
Content string `json:"content" validate:"max=4096"`
|
||||
Location *string `json:"location"`
|
||||
Thumbnail *string `json:"thumbnail"`
|
||||
Attachments []string `json:"attachments"`
|
||||
Tags []models.Tag `json:"tags"`
|
||||
Categories []models.Category `json:"categories"`
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
PublishedUntil *time.Time `json:"published_until"`
|
||||
VisibleUsers []uint `json:"visible_users_list"`
|
||||
InvisibleUsers []uint `json:"invisible_users_list"`
|
||||
Visibility *int8 `json:"visibility"`
|
||||
IsDraft bool `json:"is_draft"`
|
||||
Realm *uint `json:"realm"`
|
||||
Reward float64 `json:"reward"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
} else if len(data.Content) == 0 && len(data.Attachments) == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "content or attachments are required")
|
||||
}
|
||||
|
||||
publisher, err := services.GetPublisher(data.Publisher, user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
// Take charge
|
||||
if data.Reward > 0 {
|
||||
conn, err := gap.Nx.GetClientGrpcConn("wa")
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("unable to connect Wallet: %v", err))
|
||||
}
|
||||
wc := wproto.NewPaymentServiceClient(conn)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
|
||||
defer cancel()
|
||||
if _, err := wc.MakeTransactionWithAccount(ctx, &wproto.MakeTransactionWithAccountRequest{
|
||||
Amount: data.Reward,
|
||||
Remark: "As reward for posting a question",
|
||||
PayerAccountId: lo.ToPtr(uint64(user.ID)),
|
||||
}); err != nil {
|
||||
return fiber.NewError(fiber.StatusPaymentRequired, fmt.Sprintf("failed to handle payment: %v", err))
|
||||
}
|
||||
}
|
||||
|
||||
body := models.PostQuestionBody{
|
||||
PostStoryBody: models.PostStoryBody{
|
||||
Thumbnail: data.Thumbnail,
|
||||
Title: data.Title,
|
||||
Content: data.Content,
|
||||
Location: data.Location,
|
||||
Attachments: data.Attachments,
|
||||
},
|
||||
Reward: data.Reward,
|
||||
}
|
||||
|
||||
var bodyMapping map[string]any
|
||||
rawBody, _ := jsoniter.Marshal(body)
|
||||
_ = jsoniter.Unmarshal(rawBody, &bodyMapping)
|
||||
|
||||
item := models.Post{
|
||||
Alias: data.Alias,
|
||||
Type: models.PostTypeQuestion,
|
||||
Body: bodyMapping,
|
||||
Language: services.DetectLanguage(data.Content),
|
||||
Tags: data.Tags,
|
||||
Categories: data.Categories,
|
||||
PublishedAt: data.PublishedAt,
|
||||
PublishedUntil: data.PublishedUntil,
|
||||
IsDraft: data.IsDraft,
|
||||
VisibleUsers: data.VisibleUsers,
|
||||
InvisibleUsers: data.InvisibleUsers,
|
||||
PublisherID: publisher.ID,
|
||||
}
|
||||
|
||||
if item.PublishedAt == nil {
|
||||
item.PublishedAt = lo.ToPtr(time.Now())
|
||||
}
|
||||
|
||||
if data.Realm != nil {
|
||||
if _, err := authkit.GetRealmMember(gap.Nx, *data.Realm, user.ID); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("you are not a member of realm #%d", *data.Realm))
|
||||
}
|
||||
item.RealmID = data.Realm
|
||||
}
|
||||
|
||||
if data.Visibility != nil {
|
||||
item.Visibility = *data.Visibility
|
||||
} else {
|
||||
item.Visibility = models.PostVisibilityAll
|
||||
}
|
||||
|
||||
item, err = services.NewPost(publisher, item)
|
||||
if err != nil {
|
||||
// Failed to create post, refund the charge
|
||||
if data.Reward > 0 {
|
||||
conn, err := gap.Nx.GetClientGrpcConn("wa")
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("unable to connect Wallet: %v", err))
|
||||
}
|
||||
wc := wproto.NewPaymentServiceClient(conn)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
|
||||
defer cancel()
|
||||
if _, err := wc.MakeTransactionWithAccount(ctx, &wproto.MakeTransactionWithAccountRequest{
|
||||
Amount: data.Reward,
|
||||
Remark: "As reward for posting a question - Refund",
|
||||
PayeeAccountId: lo.ToPtr(uint64(user.ID)),
|
||||
}); err != nil {
|
||||
return fiber.NewError(fiber.StatusPaymentRequired, fmt.Sprintf("failed to handle payment: %v", err))
|
||||
}
|
||||
}
|
||||
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.new",
|
||||
map[string]any{"post": item},
|
||||
c,
|
||||
)
|
||||
}
|
||||
|
||||
return c.JSON(item)
|
||||
}
|
||||
|
||||
func editQuestion(c *fiber.Ctx) error {
|
||||
id, _ := c.ParamsInt("postId", 0)
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Publisher uint `json:"publisher"`
|
||||
Alias *string `json:"alias"`
|
||||
Title *string `json:"title"`
|
||||
Content string `json:"content" validate:"max=4096"`
|
||||
Thumbnail *string `json:"thumbnail"`
|
||||
Location *string `json:"location"`
|
||||
Attachments []string `json:"attachments"`
|
||||
Tags []models.Tag `json:"tags"`
|
||||
Categories []models.Category `json:"categories"`
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
PublishedUntil *time.Time `json:"published_until"`
|
||||
VisibleUsers []uint `json:"visible_users_list"`
|
||||
InvisibleUsers []uint `json:"invisible_users_list"`
|
||||
Visibility *int8 `json:"visibility"`
|
||||
IsDraft bool `json:"is_draft"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
} else if len(data.Content) == 0 && len(data.Attachments) == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "content or attachments are required")
|
||||
}
|
||||
|
||||
publisher, err := services.GetPublisher(data.Publisher, user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
var item models.Post
|
||||
if err := database.C.Where(models.Post{
|
||||
BaseModel: cruda.BaseModel{ID: uint(id)},
|
||||
PublisherID: publisher.ID,
|
||||
Type: models.PostTypeQuestion,
|
||||
}).Preload("Publisher").First(&item).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if item.LockedAt != nil {
|
||||
return fiber.NewError(fiber.StatusForbidden, "post was locked")
|
||||
}
|
||||
|
||||
if !item.IsDraft && !data.IsDraft {
|
||||
item.EditedAt = lo.ToPtr(time.Now())
|
||||
}
|
||||
|
||||
if item.IsDraft && !data.IsDraft && data.PublishedAt == nil {
|
||||
item.PublishedAt = lo.ToPtr(time.Now())
|
||||
} else {
|
||||
item.PublishedAt = data.PublishedAt
|
||||
}
|
||||
|
||||
var body models.PostQuestionBody
|
||||
raw, _ := jsoniter.Marshal(item.Body)
|
||||
_ = jsoniter.Unmarshal(raw, &body)
|
||||
|
||||
newBody := models.PostQuestionBody{
|
||||
PostStoryBody: models.PostStoryBody{
|
||||
Thumbnail: data.Thumbnail,
|
||||
Title: data.Title,
|
||||
Content: data.Content,
|
||||
Location: data.Location,
|
||||
Attachments: data.Attachments,
|
||||
},
|
||||
Reward: body.Reward,
|
||||
Answer: body.Answer,
|
||||
}
|
||||
|
||||
var newBodyMapping map[string]any
|
||||
rawBody, _ := jsoniter.Marshal(newBody)
|
||||
_ = jsoniter.Unmarshal(rawBody, &newBodyMapping)
|
||||
|
||||
og := item
|
||||
item.Alias = data.Alias
|
||||
item.Body = newBodyMapping
|
||||
item.Language = services.DetectLanguage(data.Content)
|
||||
item.Tags = data.Tags
|
||||
item.Categories = data.Categories
|
||||
item.IsDraft = data.IsDraft
|
||||
item.PublishedUntil = data.PublishedUntil
|
||||
item.VisibleUsers = data.VisibleUsers
|
||||
item.InvisibleUsers = data.InvisibleUsers
|
||||
|
||||
// Preload publisher data
|
||||
item.Publisher = publisher
|
||||
|
||||
if item.PublishedAt == nil {
|
||||
item.PublishedAt = data.PublishedAt
|
||||
}
|
||||
if data.Visibility != nil {
|
||||
item.Visibility = *data.Visibility
|
||||
}
|
||||
|
||||
if item, err = services.EditPost(item, og); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.edit",
|
||||
map[string]any{"post": item},
|
||||
c,
|
||||
)
|
||||
}
|
||||
|
||||
return c.JSON(item)
|
||||
}
|
||||
|
||||
func selectQuestionAnswer(c *fiber.Ctx) error {
|
||||
id, _ := c.ParamsInt("postId", 0)
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Publisher uint `json:"publisher"`
|
||||
AnswerID uint `json:"answer_id" validate:"required"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
publisher, err := services.GetPublisher(data.Publisher, user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
var item models.Post
|
||||
if err := database.C.Where(models.Post{
|
||||
BaseModel: cruda.BaseModel{ID: uint(id)},
|
||||
PublisherID: publisher.ID,
|
||||
Type: models.PostTypeQuestion,
|
||||
}).Preload("Publisher").First(&item).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
var body models.PostQuestionBody
|
||||
raw, _ := jsoniter.Marshal(item.Body)
|
||||
_ = jsoniter.Unmarshal(raw, &body)
|
||||
|
||||
if item.LockedAt != nil {
|
||||
return fiber.NewError(fiber.StatusForbidden, "post was locked")
|
||||
}
|
||||
if body.Answer != nil && *body.Answer > 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "question already has an answer")
|
||||
}
|
||||
|
||||
var answer models.Post
|
||||
if err := database.C.Where("id = ? AND reply_id = ?", data.AnswerID, item.ID).Preload("Publisher").First(&answer).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("related answer was not found: %v", err))
|
||||
}
|
||||
|
||||
item.Body["answer"] = answer.ID
|
||||
|
||||
// Preload publisher data
|
||||
item.Publisher = publisher
|
||||
if item, err = services.EditPost(item, item); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
// Give the reward
|
||||
if body.Reward > 0 && answer.Publisher.AccountID != nil {
|
||||
conn, err := gap.Nx.GetClientGrpcConn("wa")
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("unable to connect Wallet: %v", err))
|
||||
}
|
||||
wc := wproto.NewPaymentServiceClient(conn)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
|
||||
defer cancel()
|
||||
if _, err := wc.MakeTransactionWithAccount(ctx, &wproto.MakeTransactionWithAccountRequest{
|
||||
Amount: body.Reward,
|
||||
Remark: fmt.Sprintf("Answer of question %d got selected reward", item.ID),
|
||||
PayeeAccountId: lo.ToPtr(uint64(*answer.Publisher.AccountID)),
|
||||
}); err != nil {
|
||||
return fiber.NewError(fiber.StatusPaymentRequired, fmt.Sprintf("failed to handle payment: %v", err))
|
||||
}
|
||||
}
|
||||
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.edit.answer",
|
||||
map[string]any{
|
||||
"post": item,
|
||||
"answer": answer,
|
||||
},
|
||||
c,
|
||||
)
|
||||
}
|
||||
|
||||
return c.JSON(item)
|
||||
}
|
120
pkg/internal/http/api/recommendation_api.go
Normal file
120
pkg/internal/http/api/recommendation_api.go
Normal file
@ -0,0 +1,120 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services/queries"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
func listRecommendation(c *fiber.Ctx) error {
|
||||
const featuredMax = 5
|
||||
|
||||
var err error
|
||||
var posts []models.Post
|
||||
posts, err = services.GetFeaturedPosts(featuredMax)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
postIdx := lo.Map(posts, func(item models.Post, index int) uint {
|
||||
return item.ID
|
||||
})
|
||||
|
||||
var userId *uint
|
||||
if user, authenticated := c.Locals("user").(authm.Account); authenticated {
|
||||
userId = &user.ID
|
||||
}
|
||||
|
||||
tx := database.C.Where("id IN ?", postIdx)
|
||||
var newPosts []models.Post
|
||||
if c.Get("X-API-Version", "1") == "2" {
|
||||
newPosts, err = queries.ListPost(tx, featuredMax, 0, "id ASC", userId)
|
||||
} else {
|
||||
newPosts, err = services.ListPost(tx, featuredMax, 0, "id ASC", userId)
|
||||
}
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
newPostMap := lo.SliceToMap(newPosts, func(item models.Post) (uint, models.Post) {
|
||||
return item.ID, item
|
||||
})
|
||||
|
||||
// Revert the position & truncate
|
||||
for idx, item := range posts {
|
||||
posts[idx] = services.TruncatePostContent(newPostMap[item.ID])
|
||||
}
|
||||
|
||||
return c.JSON(posts)
|
||||
}
|
||||
|
||||
func listRecommendationShuffle(c *fiber.Ctx) error {
|
||||
take := c.QueryInt("take", 10)
|
||||
offset := c.QueryInt("offset", 0)
|
||||
|
||||
var err error
|
||||
tx := database.C
|
||||
if tx, err = services.UniversalPostFilter(c, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var userId *uint
|
||||
if user, authenticated := c.Locals("user").(authm.Account); authenticated {
|
||||
userId = &user.ID
|
||||
}
|
||||
|
||||
var count int64
|
||||
countTx := tx
|
||||
count, err = services.CountPost(countTx)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
var items []models.Post
|
||||
if c.Get("X-API-Version", "1") == "2" {
|
||||
items, err = queries.ListPost(tx, take, offset, "RANDOM()", userId)
|
||||
} else {
|
||||
items, err = services.ListPost(tx, take, offset, "RANDOM()", userId)
|
||||
}
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
if c.QueryBool("truncate", true) {
|
||||
for _, item := range items {
|
||||
item = services.TruncatePostContent(item)
|
||||
}
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"count": count,
|
||||
"data": items,
|
||||
})
|
||||
}
|
||||
|
||||
func getRecommendationFeed(c *fiber.Ctx) error {
|
||||
limit := c.QueryInt("limit", 20)
|
||||
cursor := c.QueryInt("cursor", 0)
|
||||
|
||||
var cursorTime *time.Time
|
||||
if cursor > 0 {
|
||||
cursorTime = lo.ToPtr(time.UnixMilli(int64(cursor - 1)))
|
||||
}
|
||||
|
||||
var userId *uint
|
||||
if user, authenticated := c.Locals("user").(authm.Account); authenticated {
|
||||
userId = &user.ID
|
||||
}
|
||||
|
||||
entries, err := queries.GetFeed(c, limit, userId, cursorTime)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(entries)
|
||||
}
|
99
pkg/internal/http/api/replies_api.go
Normal file
99
pkg/internal/http/api/replies_api.go
Normal file
@ -0,0 +1,99 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func listPostReplies(c *fiber.Ctx) error {
|
||||
take := c.QueryInt("take", 10)
|
||||
offset := c.QueryInt("offset", 0)
|
||||
|
||||
tx := database.C
|
||||
var post models.Post
|
||||
if err := database.C.Where("id = ?", c.Params("postId")).First(&post).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to find post: %v", err))
|
||||
} else {
|
||||
tx = services.FilterPostReply(tx, post.ID)
|
||||
}
|
||||
|
||||
if len(c.Query("author")) > 0 {
|
||||
var author models.Publisher
|
||||
if err := database.C.Where("name = ?", c.Query("author")).First(&author).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
tx = tx.Where("publisher_id = ?", author.ID)
|
||||
}
|
||||
|
||||
if len(c.Query("category")) > 0 {
|
||||
tx = services.FilterPostWithCategory(tx, c.Query("category"))
|
||||
}
|
||||
if len(c.Query("tag")) > 0 {
|
||||
tx = services.FilterPostWithTag(tx, c.Query("tag"))
|
||||
}
|
||||
|
||||
var userId *uint
|
||||
if user, authenticated := c.Locals("user").(authm.Account); authenticated {
|
||||
userId = &user.ID
|
||||
}
|
||||
|
||||
count, err := services.CountPost(tx)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
items, err := services.ListPost(tx, take, offset, "published_at DESC", userId)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"count": count,
|
||||
"data": items,
|
||||
})
|
||||
}
|
||||
|
||||
func listPostFeaturedReply(c *fiber.Ctx) error {
|
||||
take := c.QueryInt("take", 10)
|
||||
take = max(1, min(take, 3))
|
||||
|
||||
var userId *uint
|
||||
if user, authenticated := c.Locals("user").(authm.Account); authenticated {
|
||||
userId = &user.ID
|
||||
}
|
||||
|
||||
tx := database.C
|
||||
var post models.Post
|
||||
if err := database.C.Where("id = ?", c.Params("postId")).First(&post).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to find post: %v", err))
|
||||
} else {
|
||||
tx = services.FilterPostReply(tx, post.ID)
|
||||
}
|
||||
|
||||
if len(c.Query("author")) > 0 {
|
||||
var author models.Publisher
|
||||
if err := database.C.Where("name = ?", c.Query("author")).First(&author).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
tx = tx.Where("publisher_id = ?", author.ID)
|
||||
}
|
||||
|
||||
if len(c.Query("category")) > 0 {
|
||||
tx = services.FilterPostWithCategory(tx, c.Query("category"))
|
||||
}
|
||||
if len(c.Query("tag")) > 0 {
|
||||
tx = services.FilterPostWithTag(tx, c.Query("tag"))
|
||||
}
|
||||
|
||||
items, err := services.ListPost(tx, take, 0, "(COALESCE(total_upvote, 0) - COALESCE(total_downvote, 0)) DESC, published_at DESC", userId)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(items)
|
||||
}
|
244
pkg/internal/http/api/stories_api.go
Normal file
244
pkg/internal/http/api/stories_api.go
Normal file
@ -0,0 +1,244 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
"git.solsynth.dev/hypernet/passport/pkg/authkit"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/http/exts"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
func createStory(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureGrantedPerm(c, "CreatePosts", true); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Publisher uint `json:"publisher"`
|
||||
Alias *string `json:"alias"`
|
||||
Title *string `json:"title"`
|
||||
Content string `json:"content" validate:"max=4096"`
|
||||
Location *string `json:"location"`
|
||||
Thumbnail *string `json:"thumbnail"`
|
||||
Attachments []string `json:"attachments"`
|
||||
Tags []models.Tag `json:"tags"`
|
||||
Categories []models.Category `json:"categories"`
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
PublishedUntil *time.Time `json:"published_until"`
|
||||
VisibleUsers []uint `json:"visible_users_list"`
|
||||
InvisibleUsers []uint `json:"invisible_users_list"`
|
||||
Visibility *int8 `json:"visibility"`
|
||||
IsDraft bool `json:"is_draft"`
|
||||
ReplyTo *uint `json:"reply_to"`
|
||||
RepostTo *uint `json:"repost_to"`
|
||||
Poll *uint `json:"poll"`
|
||||
Realm *uint `json:"realm"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
} else if len(data.Content) == 0 && len(data.Attachments) == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "content or attachments are required")
|
||||
}
|
||||
|
||||
publisher, err := services.GetPublisher(data.Publisher, user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
body := models.PostStoryBody{
|
||||
Thumbnail: data.Thumbnail,
|
||||
Title: data.Title,
|
||||
Content: data.Content,
|
||||
Location: data.Location,
|
||||
Attachments: data.Attachments,
|
||||
}
|
||||
|
||||
var bodyMapping map[string]any
|
||||
rawBody, _ := jsoniter.Marshal(body)
|
||||
_ = jsoniter.Unmarshal(rawBody, &bodyMapping)
|
||||
|
||||
item := models.Post{
|
||||
Alias: data.Alias,
|
||||
Type: models.PostTypeStory,
|
||||
Body: bodyMapping,
|
||||
Language: services.DetectLanguage(data.Content),
|
||||
Tags: data.Tags,
|
||||
Categories: data.Categories,
|
||||
PublishedAt: data.PublishedAt,
|
||||
PublishedUntil: data.PublishedUntil,
|
||||
IsDraft: data.IsDraft,
|
||||
VisibleUsers: data.VisibleUsers,
|
||||
InvisibleUsers: data.InvisibleUsers,
|
||||
PublisherID: publisher.ID,
|
||||
PollID: data.Poll,
|
||||
}
|
||||
|
||||
if item.PublishedAt == nil {
|
||||
item.PublishedAt = lo.ToPtr(time.Now())
|
||||
}
|
||||
|
||||
if data.Visibility != nil {
|
||||
item.Visibility = *data.Visibility
|
||||
} else {
|
||||
item.Visibility = models.PostVisibilityAll
|
||||
}
|
||||
|
||||
if data.Realm != nil {
|
||||
if _, err := authkit.GetRealmMember(gap.Nx, *data.Realm, user.ID); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("you are not a member of realm #%d", *data.Realm))
|
||||
}
|
||||
item.RealmID = data.Realm
|
||||
}
|
||||
|
||||
if data.ReplyTo != nil {
|
||||
var replyTo models.Post
|
||||
if err := database.C.Where("id = ?", data.ReplyTo).First(&replyTo).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("related post was not found: %v", err))
|
||||
} else {
|
||||
item.ReplyID = &replyTo.ID
|
||||
}
|
||||
}
|
||||
if data.RepostTo != nil {
|
||||
var repostTo models.Post
|
||||
if err := database.C.Where("id = ?", data.RepostTo).First(&repostTo).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("related post was not found: %v", err))
|
||||
} else {
|
||||
item.RepostID = &repostTo.ID
|
||||
}
|
||||
}
|
||||
|
||||
item, err = services.NewPost(publisher, item)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.edit",
|
||||
map[string]interface{}{"post": item},
|
||||
c,
|
||||
)
|
||||
}
|
||||
|
||||
return c.JSON(item)
|
||||
}
|
||||
|
||||
func editStory(c *fiber.Ctx) error {
|
||||
id, _ := c.ParamsInt("postId", 0)
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Publisher uint `json:"publisher"`
|
||||
Alias *string `json:"alias"`
|
||||
Title *string `json:"title"`
|
||||
Content string `json:"content" validate:"max=4096"`
|
||||
Thumbnail *string `json:"thumbnail"`
|
||||
Location *string `json:"location"`
|
||||
Attachments []string `json:"attachments"`
|
||||
Tags []models.Tag `json:"tags"`
|
||||
Categories []models.Category `json:"categories"`
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
PublishedUntil *time.Time `json:"published_until"`
|
||||
VisibleUsers []uint `json:"visible_users_list"`
|
||||
InvisibleUsers []uint `json:"invisible_users_list"`
|
||||
Visibility *int8 `json:"visibility"`
|
||||
IsDraft bool `json:"is_draft"`
|
||||
Poll *uint `json:"poll"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
} else if len(data.Content) == 0 && len(data.Attachments) == 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "content or attachments are required")
|
||||
}
|
||||
|
||||
publisher, err := services.GetPublisher(data.Publisher, user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
var item models.Post
|
||||
if err := database.C.Where(models.Post{
|
||||
BaseModel: cruda.BaseModel{ID: uint(id)},
|
||||
PublisherID: publisher.ID,
|
||||
Type: models.PostTypeStory,
|
||||
}).Preload("Publisher").First(&item).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if item.LockedAt != nil {
|
||||
return fiber.NewError(fiber.StatusForbidden, "post was locked")
|
||||
}
|
||||
|
||||
if !item.IsDraft && !data.IsDraft {
|
||||
item.EditedAt = lo.ToPtr(time.Now())
|
||||
}
|
||||
|
||||
if item.IsDraft && !data.IsDraft && data.PublishedAt == nil {
|
||||
item.PublishedAt = lo.ToPtr(time.Now())
|
||||
} else {
|
||||
item.PublishedAt = data.PublishedAt
|
||||
}
|
||||
|
||||
body := models.PostStoryBody{
|
||||
Thumbnail: data.Thumbnail,
|
||||
Title: data.Title,
|
||||
Content: data.Content,
|
||||
Location: data.Location,
|
||||
Attachments: data.Attachments,
|
||||
}
|
||||
|
||||
var bodyMapping map[string]any
|
||||
rawBody, _ := jsoniter.Marshal(body)
|
||||
_ = jsoniter.Unmarshal(rawBody, &bodyMapping)
|
||||
|
||||
og := item
|
||||
item.Alias = data.Alias
|
||||
item.Body = bodyMapping
|
||||
item.Language = services.DetectLanguage(data.Content)
|
||||
item.Tags = data.Tags
|
||||
item.Categories = data.Categories
|
||||
item.IsDraft = data.IsDraft
|
||||
item.PublishedUntil = data.PublishedUntil
|
||||
item.VisibleUsers = data.VisibleUsers
|
||||
item.InvisibleUsers = data.InvisibleUsers
|
||||
item.PollID = data.Poll
|
||||
|
||||
// Preload publisher data
|
||||
item.Publisher = publisher
|
||||
|
||||
if item.PublishedAt == nil {
|
||||
item.PublishedAt = data.PublishedAt
|
||||
}
|
||||
if data.Visibility != nil {
|
||||
item.Visibility = *data.Visibility
|
||||
}
|
||||
|
||||
if item, err = services.EditPost(item, og); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.edit",
|
||||
map[string]interface{}{"post": item},
|
||||
c,
|
||||
)
|
||||
}
|
||||
|
||||
return c.JSON(item)
|
||||
}
|
241
pkg/internal/http/api/subscriptions_api.go
Normal file
241
pkg/internal/http/api/subscriptions_api.go
Normal file
@ -0,0 +1,241 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
"git.solsynth.dev/hypernet/passport/pkg/authkit"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func getSubscriptionOnUser(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
otherUserId, err := c.ParamsInt("userId", 0)
|
||||
otherUser, err := services.GetAccountWithID(uint(otherUserId))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("unable to get user: %v", err))
|
||||
}
|
||||
|
||||
subscription, err := services.GetSubscriptionOnUser(user, otherUser)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to get subscription: %v", err))
|
||||
} else if subscription == nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, "subscription does not exist")
|
||||
}
|
||||
|
||||
return c.JSON(subscription)
|
||||
}
|
||||
|
||||
func getSubscriptionOnTag(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
tagId, err := c.ParamsInt("tagId", 0)
|
||||
tag, err := services.GetTagWithID(uint(tagId))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("unable to get tag: %v", err))
|
||||
}
|
||||
|
||||
subscription, err := services.GetSubscriptionOnTag(user, tag)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to get subscription: %v", err))
|
||||
} else if subscription == nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, "subscription does not exist")
|
||||
}
|
||||
|
||||
return c.JSON(subscription)
|
||||
}
|
||||
|
||||
func getSubscriptionOnCategory(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
categoryId, err := c.ParamsInt("categoryId", 0)
|
||||
category, err := services.GetCategoryWithID(uint(categoryId))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("unable to get category: %v", err))
|
||||
}
|
||||
|
||||
subscription, err := services.GetSubscriptionOnCategory(user, category)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to get subscription: %v", err))
|
||||
} else if subscription == nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, "subscription does not exist")
|
||||
}
|
||||
|
||||
return c.JSON(subscription)
|
||||
}
|
||||
|
||||
func subscribeToUser(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
otherUserId, err := c.ParamsInt("userId", 0)
|
||||
otherUser, err := services.GetAccountWithID(uint(otherUserId))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("unable to get user: %v", err))
|
||||
}
|
||||
|
||||
subscription, err := services.SubscribeToUser(user, otherUser)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to subscribe to user: %v", err))
|
||||
}
|
||||
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.subscribe.users",
|
||||
map[string]any{"user": otherUser},
|
||||
c,
|
||||
)
|
||||
|
||||
return c.JSON(subscription)
|
||||
}
|
||||
|
||||
func subscribeToTag(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
tagId, err := c.ParamsInt("tagId", 0)
|
||||
tag, err := services.GetTagWithID(uint(tagId))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("unable to get tag: %v", err))
|
||||
}
|
||||
|
||||
subscription, err := services.SubscribeToTag(user, tag)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to subscribe to tag: %v", err))
|
||||
}
|
||||
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.subscribe.tags",
|
||||
map[string]any{"tag": tag},
|
||||
c,
|
||||
)
|
||||
|
||||
return c.JSON(subscription)
|
||||
}
|
||||
|
||||
func subscribeToCategory(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
categoryId, err := c.ParamsInt("categoryId", 0)
|
||||
category, err := services.GetCategoryWithID(uint(categoryId))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("unable to get category: %v", err))
|
||||
}
|
||||
|
||||
subscription, err := services.SubscribeToCategory(user, category)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to subscribe to category: %v", err))
|
||||
}
|
||||
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.subscribe.categories",
|
||||
map[string]any{"category": category},
|
||||
c,
|
||||
)
|
||||
|
||||
return c.JSON(subscription)
|
||||
}
|
||||
|
||||
func unsubscribeFromUser(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
otherUserId, err := c.ParamsInt("userId", 0)
|
||||
otherUser, err := services.GetAccountWithID(uint(otherUserId))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("unable to get user: %v", err))
|
||||
}
|
||||
|
||||
err = services.UnsubscribeFromUser(user, otherUser)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to unsubscribe from user: %v", err))
|
||||
}
|
||||
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.unsubscribe.users",
|
||||
map[string]any{"user": otherUser},
|
||||
c,
|
||||
)
|
||||
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
|
||||
func unsubscribeFromTag(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
tagId, err := c.ParamsInt("tagId", 0)
|
||||
tag, err := services.GetTagWithID(uint(tagId))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("unable to get tag: %v", err))
|
||||
}
|
||||
|
||||
err = services.UnsubscribeFromTag(user, tag)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to unsubscribe from tag: %v", err))
|
||||
}
|
||||
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.unsubscribe.tags",
|
||||
map[string]any{"tag": tag},
|
||||
c,
|
||||
)
|
||||
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
|
||||
func unsubscribeFromCategory(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
categoryId, err := c.ParamsInt("categoryId", 0)
|
||||
category, err := services.GetCategoryWithID(uint(categoryId))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, fmt.Sprintf("unable to get category: %v", err))
|
||||
}
|
||||
|
||||
err = services.UnsubscribeFromCategory(user, category)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("unable to unsubscribe from category: %v", err))
|
||||
}
|
||||
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.unsubscribe.categories",
|
||||
map[string]any{"category": category},
|
||||
c,
|
||||
)
|
||||
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
41
pkg/internal/http/api/tags_api.go
Normal file
41
pkg/internal/http/api/tags_api.go
Normal file
@ -0,0 +1,41 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func getTag(c *fiber.Ctx) error {
|
||||
alias := c.Params("tag")
|
||||
|
||||
tag, err := services.GetTag(alias)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(tag)
|
||||
}
|
||||
|
||||
func listTags(c *fiber.Ctx) error {
|
||||
take := c.QueryInt("take", 10)
|
||||
offset := c.QueryInt("offset", 0)
|
||||
probe := c.Query("probe")
|
||||
|
||||
if take > 100 {
|
||||
take = 100
|
||||
}
|
||||
|
||||
var tags []models.Tag
|
||||
var err error
|
||||
if len(probe) > 0 {
|
||||
tags, err = services.SearchTags(take, offset, probe)
|
||||
} else {
|
||||
tags, err = services.ListTags(take, offset)
|
||||
}
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(tags)
|
||||
}
|
228
pkg/internal/http/api/videos_api.go
Normal file
228
pkg/internal/http/api/videos_api.go
Normal file
@ -0,0 +1,228 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/http/exts"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
"git.solsynth.dev/hypernet/passport/pkg/authkit"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
func createVideo(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureGrantedPerm(c, "CreatePosts", true); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Publisher uint `json:"publisher"`
|
||||
Video string `json:"video" validate:"required"`
|
||||
Alias *string `json:"alias"`
|
||||
Title string `json:"title" validate:"required"`
|
||||
Description *string `json:"description"`
|
||||
Location *string `json:"location"`
|
||||
Thumbnail *string `json:"thumbnail"`
|
||||
Subtitles map[string]string `json:"subtitles"`
|
||||
Tags []models.Tag `json:"tags"`
|
||||
Categories []models.Category `json:"categories"`
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
PublishedUntil *time.Time `json:"published_until"`
|
||||
VisibleUsers []uint `json:"visible_users_list"`
|
||||
InvisibleUsers []uint `json:"invisible_users_list"`
|
||||
Visibility *int8 `json:"visibility"`
|
||||
Renderer *string `json:"renderer"`
|
||||
IsLive bool `json:"is_live"`
|
||||
IsDraft bool `json:"is_draft"`
|
||||
Realm *uint `json:"realm"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
publisher, err := services.GetPublisher(data.Publisher, user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
body := models.PostVideoBody{
|
||||
Thumbnail: data.Thumbnail,
|
||||
Video: data.Video,
|
||||
Title: data.Title,
|
||||
Renderer: data.Renderer,
|
||||
Description: data.Description,
|
||||
Location: data.Location,
|
||||
Subtitles: data.Subtitles,
|
||||
IsLive: data.IsLive,
|
||||
}
|
||||
|
||||
var bodyMapping map[string]any
|
||||
rawBody, _ := jsoniter.Marshal(body)
|
||||
_ = jsoniter.Unmarshal(rawBody, &bodyMapping)
|
||||
|
||||
item := models.Post{
|
||||
Alias: data.Alias,
|
||||
Type: models.PostTypeVideo,
|
||||
Body: bodyMapping,
|
||||
Language: services.DetectLanguage(data.Title),
|
||||
Tags: data.Tags,
|
||||
Categories: data.Categories,
|
||||
PublishedAt: data.PublishedAt,
|
||||
PublishedUntil: data.PublishedUntil,
|
||||
IsDraft: data.IsDraft,
|
||||
VisibleUsers: data.VisibleUsers,
|
||||
InvisibleUsers: data.InvisibleUsers,
|
||||
PublisherID: publisher.ID,
|
||||
}
|
||||
|
||||
if item.PublishedAt == nil {
|
||||
item.PublishedAt = lo.ToPtr(time.Now())
|
||||
}
|
||||
|
||||
if data.Realm != nil {
|
||||
if _, err := authkit.GetRealmMember(gap.Nx, *data.Realm, user.ID); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("you are not a member of realm #%d", *data.Realm))
|
||||
}
|
||||
item.RealmID = data.Realm
|
||||
}
|
||||
|
||||
if data.Visibility != nil {
|
||||
item.Visibility = *data.Visibility
|
||||
} else {
|
||||
item.Visibility = models.PostVisibilityAll
|
||||
}
|
||||
|
||||
item, err = services.NewPost(publisher, item)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.new",
|
||||
map[string]any{"post": item},
|
||||
c,
|
||||
)
|
||||
}
|
||||
|
||||
return c.JSON(item)
|
||||
}
|
||||
|
||||
func editVideo(c *fiber.Ctx) error {
|
||||
id, _ := c.ParamsInt("postId", 0)
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
var data struct {
|
||||
Publisher uint `json:"publisher"`
|
||||
Video string `json:"video" validate:"required"`
|
||||
Alias *string `json:"alias"`
|
||||
Title string `json:"title" validate:"required"`
|
||||
Description *string `json:"description"`
|
||||
Location *string `json:"location"`
|
||||
Thumbnail *string `json:"thumbnail"`
|
||||
Subtitles map[string]string `json:"subtitles"`
|
||||
Tags []models.Tag `json:"tags"`
|
||||
Categories []models.Category `json:"categories"`
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
PublishedUntil *time.Time `json:"published_until"`
|
||||
VisibleUsers []uint `json:"visible_users_list"`
|
||||
InvisibleUsers []uint `json:"invisible_users_list"`
|
||||
Visibility *int8 `json:"visibility"`
|
||||
Renderer *string `json:"renderer"`
|
||||
IsLive bool `json:"is_live"`
|
||||
IsDraft bool `json:"is_draft"`
|
||||
}
|
||||
|
||||
if err := exts.BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
publisher, err := services.GetPublisher(data.Publisher, user.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
var item models.Post
|
||||
if err := database.C.Where(models.Post{
|
||||
BaseModel: cruda.BaseModel{ID: uint(id)},
|
||||
PublisherID: publisher.ID,
|
||||
Type: models.PostTypeVideo,
|
||||
}).Preload("Publisher").First(&item).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if item.LockedAt != nil {
|
||||
return fiber.NewError(fiber.StatusForbidden, "post was locked")
|
||||
}
|
||||
|
||||
if !item.IsDraft && !data.IsDraft {
|
||||
item.EditedAt = lo.ToPtr(time.Now())
|
||||
}
|
||||
|
||||
if item.IsDraft && !data.IsDraft && data.PublishedAt == nil {
|
||||
item.PublishedAt = lo.ToPtr(time.Now())
|
||||
} else {
|
||||
item.PublishedAt = data.PublishedAt
|
||||
}
|
||||
|
||||
body := models.PostVideoBody{
|
||||
Thumbnail: data.Thumbnail,
|
||||
Video: data.Video,
|
||||
Title: data.Title,
|
||||
Description: data.Description,
|
||||
Location: data.Location,
|
||||
Subtitles: data.Subtitles,
|
||||
Renderer: data.Renderer,
|
||||
IsLive: data.IsLive,
|
||||
}
|
||||
|
||||
var bodyMapping map[string]any
|
||||
rawBody, _ := jsoniter.Marshal(body)
|
||||
_ = jsoniter.Unmarshal(rawBody, &bodyMapping)
|
||||
|
||||
og := item
|
||||
item.Alias = data.Alias
|
||||
item.Body = bodyMapping
|
||||
item.Language = services.DetectLanguage(data.Title)
|
||||
item.Tags = data.Tags
|
||||
item.Categories = data.Categories
|
||||
item.IsDraft = data.IsDraft
|
||||
item.PublishedUntil = data.PublishedUntil
|
||||
item.VisibleUsers = data.VisibleUsers
|
||||
item.InvisibleUsers = data.InvisibleUsers
|
||||
|
||||
// Preload publisher data
|
||||
item.Publisher = publisher
|
||||
|
||||
if item.PublishedAt == nil {
|
||||
item.PublishedAt = data.PublishedAt
|
||||
}
|
||||
if data.Visibility != nil {
|
||||
item.Visibility = *data.Visibility
|
||||
}
|
||||
|
||||
if item, err = services.EditPost(item, og); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
_ = authkit.AddEventExt(
|
||||
gap.Nx,
|
||||
"posts.edit",
|
||||
map[string]any{"post": item},
|
||||
c,
|
||||
)
|
||||
}
|
||||
|
||||
return c.JSON(item)
|
||||
}
|
65
pkg/internal/http/api/webfinger_api.go
Normal file
65
pkg/internal/http/api/webfinger_api.go
Normal file
@ -0,0 +1,65 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type WebFingerResponse struct {
|
||||
Subject string `json:"subject"`
|
||||
Aliases []string `json:"aliases"`
|
||||
Links []struct {
|
||||
Rel string `json:"rel"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Href string `json:"href"`
|
||||
} `json:"links"`
|
||||
}
|
||||
|
||||
// Although this webfinger is desgined for users
|
||||
// But in this case we will provide publisher for them
|
||||
func getWebfinger(c *fiber.Ctx) error {
|
||||
resource := c.Query("resource")
|
||||
|
||||
if len(resource) < 6 || resource[:5] != "acct:" {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "Invalid resource format"})
|
||||
}
|
||||
|
||||
username := resource[5:]
|
||||
if username == "" {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "Invalid username"})
|
||||
}
|
||||
parts := strings.SplitN(username, "@", 2)
|
||||
if len(parts) != 2 {
|
||||
return c.Status(400).JSON(fiber.Map{"error": "Invalid username"})
|
||||
}
|
||||
|
||||
var publisher models.Publisher
|
||||
if err := database.C.Where("name = ?", parts[0]).First(&publisher).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
response := WebFingerResponse{
|
||||
Subject: "acct:" + username,
|
||||
Aliases: []string{
|
||||
services.GetActivityID("/users/" + publisher.Name).String(),
|
||||
},
|
||||
Links: []struct {
|
||||
Rel string `json:"rel"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Href string `json:"href"`
|
||||
}{
|
||||
{
|
||||
Rel: "self",
|
||||
Type: "application/activity+json",
|
||||
Href: services.GetActivityID("/users/" + publisher.Name).String(),
|
||||
},
|
||||
// TODO Add avatar here
|
||||
},
|
||||
}
|
||||
|
||||
return c.JSON(response)
|
||||
}
|
52
pkg/internal/http/api/what_new_api.dart.go
Normal file
52
pkg/internal/http/api/what_new_api.dart.go
Normal file
@ -0,0 +1,52 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func getWhatsNew(c *fiber.Ctx) error {
|
||||
if err := sec.EnsureAuthenticated(c); err != nil {
|
||||
return err
|
||||
}
|
||||
user := c.Locals("user").(authm.Account)
|
||||
|
||||
pivot := c.QueryInt("pivot", 0)
|
||||
if pivot < 0 {
|
||||
return fiber.NewError(fiber.StatusBadRequest, "pivot must be greater than zero")
|
||||
}
|
||||
|
||||
tx := services.FilterPostDraft(database.C)
|
||||
tx = services.FilterPostWithUserContext(c, tx, &user)
|
||||
|
||||
tx = tx.Where("id > ?", pivot)
|
||||
|
||||
var userId *uint
|
||||
if user, authenticated := c.Locals("user").(authm.Account); authenticated {
|
||||
userId = &user.ID
|
||||
}
|
||||
|
||||
countTx := tx
|
||||
count, err := services.CountPost(countTx)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
order := "published_at DESC"
|
||||
if c.QueryBool("featured", false) {
|
||||
order = "published_at DESC, (COALESCE(total_upvote, 0) - COALESCE(total_downvote, 0)) DESC"
|
||||
}
|
||||
|
||||
items, err := services.ListPost(tx, 10, 0, order, userId)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"count": count,
|
||||
"data": items,
|
||||
})
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package server
|
||||
package exts
|
||||
|
||||
import (
|
||||
"github.com/go-playground/validator/v10"
|
77
pkg/internal/http/server.go
Normal file
77
pkg/internal/http/server.go
Normal file
@ -0,0 +1,77 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
"git.solsynth.dev/hypernet/passport/pkg/authkit"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/http/admin"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/http/api"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||
"github.com/gofiber/fiber/v2/middleware/idempotency"
|
||||
"github.com/gofiber/fiber/v2/middleware/logger"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var IReader *sec.InternalTokenReader
|
||||
|
||||
type App struct {
|
||||
app *fiber.App
|
||||
}
|
||||
|
||||
func NewServer() *App {
|
||||
app := fiber.New(fiber.Config{
|
||||
DisableStartupMessage: true,
|
||||
EnableIPValidation: true,
|
||||
ServerHeader: "Hypernet.Interactive",
|
||||
AppName: "Hypernet.Interactive",
|
||||
ProxyHeader: fiber.HeaderXForwardedFor,
|
||||
JSONEncoder: jsoniter.ConfigCompatibleWithStandardLibrary.Marshal,
|
||||
JSONDecoder: jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal,
|
||||
BodyLimit: 50 * 1024 * 1024,
|
||||
ReadBufferSize: 5 * 1024 * 1024, // 5MB for large JWT
|
||||
EnablePrintRoutes: viper.GetBool("debug.print_routes"),
|
||||
})
|
||||
|
||||
app.Use(idempotency.New())
|
||||
app.Use(cors.New(cors.Config{
|
||||
AllowCredentials: true,
|
||||
AllowMethods: strings.Join([]string{
|
||||
fiber.MethodGet,
|
||||
fiber.MethodPost,
|
||||
fiber.MethodHead,
|
||||
fiber.MethodOptions,
|
||||
fiber.MethodPut,
|
||||
fiber.MethodDelete,
|
||||
fiber.MethodPatch,
|
||||
}, ","),
|
||||
AllowOriginsFunc: func(origin string) bool {
|
||||
return true
|
||||
},
|
||||
}))
|
||||
|
||||
app.Use(logger.New(logger.Config{
|
||||
Format: "${status} | ${latency} | ${method} ${path}\n",
|
||||
Output: log.Logger,
|
||||
}))
|
||||
|
||||
app.Use(sec.ContextMiddleware(IReader))
|
||||
app.Use(authkit.ParseAccountMiddleware)
|
||||
|
||||
api.MapControllers(app, "/api")
|
||||
admin.MapControllers(app, "/api/admin")
|
||||
|
||||
return &App{
|
||||
app: app,
|
||||
}
|
||||
}
|
||||
|
||||
func (v *App) Listen() {
|
||||
if err := v.app.Listen(viper.GetString("bind")); err != nil {
|
||||
log.Fatal().Err(err).Msg("An error occurred when starting http...")
|
||||
}
|
||||
}
|
21
pkg/internal/models/categories.go
Normal file
21
pkg/internal/models/categories.go
Normal file
@ -0,0 +1,21 @@
|
||||
package models
|
||||
|
||||
import "git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
|
||||
|
||||
type Tag struct {
|
||||
cruda.BaseModel
|
||||
|
||||
Alias string `json:"alias" gorm:"uniqueIndex" validate:"lowercase"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Posts []Post `json:"posts" gorm:"many2many:post_tags"`
|
||||
}
|
||||
|
||||
type Category struct {
|
||||
cruda.BaseModel
|
||||
|
||||
Alias string `json:"alias" gorm:"uniqueIndex" validate:"lowercase,alphanum"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Posts []Post `json:"posts" gorm:"many2many:post_categories"`
|
||||
}
|
10
pkg/internal/models/flags.go
Normal file
10
pkg/internal/models/flags.go
Normal file
@ -0,0 +1,10 @@
|
||||
package models
|
||||
|
||||
import "git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
|
||||
|
||||
type PostFlag struct {
|
||||
cruda.BaseModel
|
||||
|
||||
PostID uint `json:"post_id"`
|
||||
AccountID uint `json:"account_id"`
|
||||
}
|
7
pkg/internal/models/metrics.go
Normal file
7
pkg/internal/models/metrics.go
Normal file
@ -0,0 +1,7 @@
|
||||
package models
|
||||
|
||||
type PostMetric struct {
|
||||
ReplyCount int64 `json:"reply_count"`
|
||||
ReactionCount int64 `json:"reaction_count"`
|
||||
ReactionList map[string]int64 `json:"reaction_list,omitempty"`
|
||||
}
|
39
pkg/internal/models/polls.go
Normal file
39
pkg/internal/models/polls.go
Normal file
@ -0,0 +1,39 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
|
||||
"gorm.io/datatypes"
|
||||
)
|
||||
|
||||
type Poll struct {
|
||||
cruda.BaseModel
|
||||
|
||||
ExpiredAt *time.Time `json:"expired_at"`
|
||||
Options datatypes.JSONSlice[PollOption] `json:"options"`
|
||||
AccountID uint `json:"account_id"`
|
||||
|
||||
Metric PollMetric `json:"metric" gorm:"-"`
|
||||
}
|
||||
|
||||
type PollMetric struct {
|
||||
TotalAnswer int64 `json:"total_answer"`
|
||||
ByOptions map[string]int64 `json:"by_options"`
|
||||
ByOptionsPercentage map[string]float64 `json:"by_options_percentage"`
|
||||
}
|
||||
|
||||
type PollOption struct {
|
||||
ID string `json:"id"`
|
||||
Icon string `json:"icon"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
type PollAnswer struct {
|
||||
cruda.BaseModel
|
||||
|
||||
Answer string `json:"answer"`
|
||||
PollID uint `json:"poll_id"`
|
||||
AccountID uint `json:"account_id"`
|
||||
}
|
124
pkg/internal/models/posts.go
Normal file
124
pkg/internal/models/posts.go
Normal file
@ -0,0 +1,124 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
)
|
||||
|
||||
const (
|
||||
PostTypeStory = "story"
|
||||
PostTypeArticle = "article"
|
||||
PostTypeQuestion = "question"
|
||||
PostTypeVideo = "video"
|
||||
)
|
||||
|
||||
type PostVisibilityLevel = int8
|
||||
|
||||
const (
|
||||
PostVisibilityAll = PostVisibilityLevel(iota)
|
||||
PostVisibilityFriends
|
||||
PostVisibilityFiltered
|
||||
PostVisibilitySelected
|
||||
PostVisibilityNone
|
||||
)
|
||||
|
||||
type Post struct {
|
||||
cruda.BaseModel
|
||||
|
||||
Type string `json:"type"`
|
||||
Body datatypes.JSONMap `json:"body" gorm:"index:,type:gin"`
|
||||
Language string `json:"language"`
|
||||
Alias *string `json:"alias" gorm:"index"`
|
||||
AliasPrefix *string `json:"alias_prefix" gorm:"index"`
|
||||
Tags []Tag `json:"tags" gorm:"many2many:post_tags"`
|
||||
Categories []Category `json:"categories" gorm:"many2many:post_categories"`
|
||||
Reactions []Reaction `json:"reactions"`
|
||||
Replies []Post `json:"replies" gorm:"foreignKey:ReplyID"`
|
||||
Flags []PostFlag `json:"flags" gorm:"foreignKey:PostID"`
|
||||
ReplyID *uint `json:"reply_id"`
|
||||
RepostID *uint `json:"repost_id"`
|
||||
ReplyTo *Post `json:"reply_to" gorm:"foreignKey:ReplyID"`
|
||||
RepostTo *Post `json:"repost_to" gorm:"foreignKey:RepostID"`
|
||||
|
||||
VisibleUsers datatypes.JSONSlice[uint] `json:"visible_users_list"`
|
||||
InvisibleUsers datatypes.JSONSlice[uint] `json:"invisible_users_list"`
|
||||
Visibility PostVisibilityLevel `json:"visibility"`
|
||||
|
||||
EditedAt *time.Time `json:"edited_at"`
|
||||
PinnedAt *time.Time `json:"pinned_at"`
|
||||
LockedAt *time.Time `json:"locked_at"`
|
||||
|
||||
IsCollapsed bool `json:"is_collapsed"`
|
||||
IsDraft bool `json:"is_draft"`
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
PublishedUntil *time.Time `json:"published_until"`
|
||||
|
||||
TotalUpvote int `json:"total_upvote"`
|
||||
TotalDownvote int `json:"total_downvote"`
|
||||
TotalViews int64 `json:"total_views"`
|
||||
TotalAggressiveViews int64 `json:"total_aggressive_views"`
|
||||
|
||||
PollID *uint `json:"poll_id"`
|
||||
Poll *Poll `json:"poll"`
|
||||
|
||||
RealmID *uint `json:"realm_id"`
|
||||
Realm *authm.Realm `json:"realm" gorm:"-"`
|
||||
|
||||
PublisherID uint `json:"publisher_id"`
|
||||
Publisher Publisher `json:"publisher"`
|
||||
|
||||
Metric PostMetric `json:"metric" gorm:"-"`
|
||||
}
|
||||
|
||||
type PostStoryBody struct {
|
||||
Thumbnail *string `json:"thumbnail"`
|
||||
Title *string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
Location *string `json:"location"`
|
||||
Attachments []string `json:"attachments"`
|
||||
}
|
||||
|
||||
type PostArticleBody struct {
|
||||
Thumbnail *string `json:"thumbnail"`
|
||||
Title string `json:"title"`
|
||||
Description *string `json:"description"`
|
||||
Content string `json:"content"`
|
||||
Attachments []string `json:"attachments"`
|
||||
}
|
||||
|
||||
type PostQuestionBody struct {
|
||||
PostStoryBody
|
||||
Answer *uint `json:"answer"`
|
||||
Reward float64 `json:"reward"`
|
||||
}
|
||||
|
||||
type PostVideoBody struct {
|
||||
Thumbnail *string `json:"thumbnail"`
|
||||
Title string `json:"title"`
|
||||
Description *string `json:"description"`
|
||||
Location *string `json:"location"`
|
||||
Video string `json:"video"`
|
||||
Renderer *string `json:"renderer"`
|
||||
IsLive bool `json:"is_live"`
|
||||
IsLiveEnded bool `json:"is_live_ended"`
|
||||
Subtitles map[string]string `json:"subtitles"`
|
||||
}
|
||||
|
||||
type PostInsight struct {
|
||||
cruda.BaseModel
|
||||
|
||||
Response string `json:"response"`
|
||||
Post Post `json:"post"`
|
||||
PostID uint `json:"post_id"`
|
||||
}
|
||||
|
||||
type PostView struct {
|
||||
AccountID uint `json:"account_id" gorm:"primaryKey"`
|
||||
PostID uint `json:"post_id" gorm:"primaryKey"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
35
pkg/internal/models/publishers.go
Normal file
35
pkg/internal/models/publishers.go
Normal file
@ -0,0 +1,35 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
|
||||
"git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
)
|
||||
|
||||
const (
|
||||
PublisherTypePersonal = iota
|
||||
PublisherTypeOrganization
|
||||
PublisherTypeAnonymous
|
||||
)
|
||||
|
||||
type Publisher struct {
|
||||
cruda.BaseModel
|
||||
|
||||
Type int `json:"type"`
|
||||
|
||||
Name string `json:"name" gorm:"uniqueIndex"`
|
||||
Nick string `json:"nick"`
|
||||
Description string `json:"description"`
|
||||
Avatar string `json:"avatar"`
|
||||
Banner string `json:"banner"`
|
||||
|
||||
Posts []Post `json:"posts"`
|
||||
|
||||
TotalUpvote int `json:"total_upvote"`
|
||||
TotalDownvote int `json:"total_downvote"`
|
||||
|
||||
RealmID *uint `json:"realm_id"`
|
||||
AccountID *uint `json:"account_id"`
|
||||
|
||||
Account models.Account `gorm:"-" json:"account"`
|
||||
Realm models.Realm `gorm:"-" json:"realm"`
|
||||
}
|
@ -20,8 +20,6 @@ type Reaction struct {
|
||||
Symbol string `json:"symbol"`
|
||||
Attitude ReactionAttitude `json:"attitude"`
|
||||
|
||||
ArticleID *uint `json:"article_id"`
|
||||
MomentID *uint `json:"moment_id"`
|
||||
CommentID *uint `json:"comment_id"`
|
||||
AccountID uint `json:"account_id"`
|
||||
PostID uint `json:"post_id"`
|
||||
AccountID uint `json:"account_id"`
|
||||
}
|
12
pkg/internal/models/subscriptions.go
Normal file
12
pkg/internal/models/subscriptions.go
Normal file
@ -0,0 +1,12 @@
|
||||
package models
|
||||
|
||||
import "git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
|
||||
|
||||
type Subscription struct {
|
||||
cruda.BaseModel
|
||||
|
||||
FollowerID uint `json:"follower_id"`
|
||||
AccountID *uint `json:"account_id,omitempty"`
|
||||
TagID *uint `json:"tag_id,omitempty"`
|
||||
CategoryID *uint `json:"category_id,omitempty"`
|
||||
}
|
59
pkg/internal/services/accounts.go
Normal file
59
pkg/internal/services/accounts.go
Normal file
@ -0,0 +1,59 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/passport/pkg/authkit"
|
||||
"git.solsynth.dev/hypernet/pusher/pkg/pushkit"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func GetAccountWithID(id uint) (models.Publisher, error) {
|
||||
var account models.Publisher
|
||||
if err := database.C.Where("id = ?", id).First(&account).Error; err != nil {
|
||||
return account, fmt.Errorf("unable to get account by id: %v", err)
|
||||
}
|
||||
return account, nil
|
||||
}
|
||||
|
||||
func ModifyPosterVoteCount(user models.Publisher, isUpvote bool, delta int) error {
|
||||
if isUpvote {
|
||||
user.TotalUpvote += delta
|
||||
return database.C.Model(&user).Update("total_upvote", user.TotalUpvote).Error
|
||||
} else {
|
||||
user.TotalDownvote += delta
|
||||
return database.C.Model(&user).Update("total_downvote", user.TotalDownvote).Error
|
||||
}
|
||||
}
|
||||
|
||||
func NotifyPosterAccount(pub models.Publisher, post models.Post, title, body, topic string, subtitle ...string) error {
|
||||
if pub.AccountID == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(subtitle) == 0 {
|
||||
subtitle = append(subtitle, "")
|
||||
}
|
||||
|
||||
err := authkit.NotifyUser(gap.Nx, uint64(*pub.AccountID), pushkit.Notification{
|
||||
Topic: topic,
|
||||
Title: title,
|
||||
Subtitle: subtitle[0],
|
||||
Body: body,
|
||||
Priority: 4,
|
||||
Metadata: map[string]any{
|
||||
"related_post": TruncatePostContent(post),
|
||||
"avatar": pub.Avatar,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("An error occurred when notify account...")
|
||||
} else {
|
||||
log.Debug().Uint("uid", pub.ID).Msg("Notified account.")
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
16
pkg/internal/services/activitypub.go
Normal file
16
pkg/internal/services/activitypub.go
Normal file
@ -0,0 +1,16 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"github.com/go-ap/activitypub"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func GetActivityID(uri string) activitypub.ID {
|
||||
baseUrl := viper.GetString("activitypub_base_url")
|
||||
return activitypub.ID(baseUrl + uri)
|
||||
}
|
||||
|
||||
func GetActivityIRI(uri string) activitypub.IRI {
|
||||
baseUrl := viper.GetString("activitypub_base_url")
|
||||
return activitypub.IRI(baseUrl + uri)
|
||||
}
|
@ -2,16 +2,27 @@ package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/cruda"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func ListCategory() ([]models.Category, error) {
|
||||
var categories []models.Category
|
||||
func SearchCategories(take int, offset int, probe string) ([]models.Category, error) {
|
||||
probe = "%" + probe + "%"
|
||||
|
||||
err := database.C.Find(&categories).Error
|
||||
var categories []models.Category
|
||||
err := database.C.Where("alias LIKE ?", probe).Offset(offset).Limit(take).Find(&categories).Error
|
||||
|
||||
return categories, err
|
||||
}
|
||||
|
||||
func ListCategory(take int, offset int) ([]models.Category, error) {
|
||||
var categories []models.Category
|
||||
err := database.C.Offset(offset).Limit(take).Find(&categories).Error
|
||||
|
||||
return categories, err
|
||||
}
|
||||
@ -27,7 +38,7 @@ func GetCategory(alias string) (models.Category, error) {
|
||||
func GetCategoryWithID(id uint) (models.Category, error) {
|
||||
var category models.Category
|
||||
if err := database.C.Where(models.Category{
|
||||
BaseModel: models.BaseModel{ID: id},
|
||||
BaseModel: cruda.BaseModel{ID: id},
|
||||
}).First(&category).Error; err != nil {
|
||||
return category, err
|
||||
}
|
||||
@ -60,7 +71,18 @@ func DeleteCategory(category models.Category) error {
|
||||
return database.C.Delete(category).Error
|
||||
}
|
||||
|
||||
func GetTagWithID(id uint) (models.Tag, error) {
|
||||
var tag models.Tag
|
||||
if err := database.C.Where(models.Tag{
|
||||
BaseModel: cruda.BaseModel{ID: id},
|
||||
}).First(&tag).Error; err != nil {
|
||||
return tag, err
|
||||
}
|
||||
return tag, nil
|
||||
}
|
||||
|
||||
func GetTagOrCreate(alias, name string) (models.Tag, error) {
|
||||
alias = strings.ToLower(alias)
|
||||
var tag models.Tag
|
||||
if err := database.C.Where(models.Category{Alias: alias}).First(&tag).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
39
pkg/internal/services/conversations.go
Normal file
39
pkg/internal/services/conversations.go
Normal file
@ -0,0 +1,39 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func GetConversation(start uint, offset, take int, order string, participants []uint) ([]models.Post, error) {
|
||||
var posts []models.Post
|
||||
|
||||
tablePrefix := viper.GetString("database.prefix")
|
||||
table := tablePrefix + "posts"
|
||||
|
||||
result := database.C.Raw(fmt.Sprintf(
|
||||
`
|
||||
WITH RECURSIVE conversation AS (
|
||||
SELECT *
|
||||
FROM %s
|
||||
WHERE id = ?
|
||||
|
||||
UNION ALL
|
||||
|
||||
SELECT p.*
|
||||
FROM %s p
|
||||
INNER JOIN conversation c ON p.reply_id = c.id AND p.publisher_id IN (?)
|
||||
)
|
||||
SELECT * FROM conversation ORDER BY %s DESC OFFSET %d LIMIT %d`,
|
||||
table, table, order, offset, take,
|
||||
), start, participants).Scan(&posts)
|
||||
|
||||
// Check for errors
|
||||
if result.Error != nil {
|
||||
return nil, result.Error
|
||||
}
|
||||
|
||||
return posts, nil
|
||||
}
|
41
pkg/internal/services/featured.go
Normal file
41
pkg/internal/services/featured.go
Normal file
@ -0,0 +1,41 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"time"
|
||||
)
|
||||
|
||||
// GetFeaturedPosts How to determine featured posts?
|
||||
// Get the most upvoted posts in the last 7 days
|
||||
// And then how to get the upvote count of each post in the last 7 days?
|
||||
// We will get the reactions that attitude equals to 1 and created within the last 7 days
|
||||
// By the way, the upvote count will subtract the downvote count
|
||||
// Notice, this function is a raw query, it is not recommended to return the result directly
|
||||
// Instead, you should get the id and query it again via the ListPost function
|
||||
func GetFeaturedPosts(count int) ([]models.Post, error) {
|
||||
deadline := time.Now().Add(-7 * 24 * time.Hour)
|
||||
|
||||
var posts []models.Post
|
||||
if err := database.C.Raw(`
|
||||
SELECT p.*, t.social_points
|
||||
FROM posts p
|
||||
JOIN (
|
||||
SELECT
|
||||
post_id,
|
||||
SUM(CASE WHEN attitude = 1 THEN 1 ELSE 0 END) -
|
||||
SUM(CASE WHEN attitude = 2 THEN 1 ELSE 0 END) AS social_points
|
||||
FROM reactions
|
||||
WHERE created_at >= ?
|
||||
GROUP BY post_id
|
||||
ORDER BY social_points DESC
|
||||
LIMIT ?
|
||||
) t ON p.id = t.post_id
|
||||
WHERE p.visibility = ?
|
||||
ORDER BY t.social_points DESC, p.published_at DESC
|
||||
`, deadline, count, models.PostVisibilityAll).Scan(&posts).Error; err != nil {
|
||||
return posts, err
|
||||
}
|
||||
|
||||
return posts, nil
|
||||
}
|
43
pkg/internal/services/flags.go
Normal file
43
pkg/internal/services/flags.go
Normal file
@ -0,0 +1,43 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
)
|
||||
|
||||
func NewFlag(post models.Post, account uint) (models.PostFlag, error) {
|
||||
var flag models.PostFlag
|
||||
if err := database.C.Where("post_id = ? AND account_id = ?", post.ID, account).First(&flag).Error; err == nil {
|
||||
return flag, fmt.Errorf("flag already exists")
|
||||
}
|
||||
flag = models.PostFlag{
|
||||
PostID: post.ID,
|
||||
AccountID: account,
|
||||
}
|
||||
if err := database.C.Save(&flag).Error; err != nil {
|
||||
return flag, err
|
||||
}
|
||||
if err := FlagCalculateCollapseStatus(post); err != nil {
|
||||
return flag, err
|
||||
}
|
||||
return flag, nil
|
||||
}
|
||||
|
||||
func FlagCalculateCollapseStatus(post models.Post) error {
|
||||
if post.TotalViews <= 2 {
|
||||
return nil
|
||||
}
|
||||
|
||||
collapseLimit := 0.5
|
||||
|
||||
var flagCount int64
|
||||
if err := database.C.Model(&models.PostFlag{}).Where("post_id = ?", post.ID).Count(&flagCount).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if float64(flagCount)/float64(post.TotalViews) >= collapseLimit {
|
||||
return database.C.Model(&post).Update("is_collapsed", true).Error
|
||||
}
|
||||
return nil
|
||||
}
|
60
pkg/internal/services/insight.go
Normal file
60
pkg/internal/services/insight.go
Normal file
@ -0,0 +1,60 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
iproto "git.solsynth.dev/hypernet/insight/pkg/proto"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func GeneratePostInsights(post models.Post, user uint) (string, error) {
|
||||
var insight models.PostInsight
|
||||
if err := database.C.Where("post_id = ?", post.ID).First(&insight).Error; err == nil {
|
||||
return insight.Response, nil
|
||||
}
|
||||
|
||||
var compactBuilder []string
|
||||
if val, ok := post.Body["title"].(string); ok && len(val) > 0 {
|
||||
compactBuilder = append(compactBuilder, "Title: "+val)
|
||||
}
|
||||
if val, ok := post.Body["description"].(string); ok && len(val) > 0 {
|
||||
compactBuilder = append(compactBuilder, "Description: "+val)
|
||||
}
|
||||
if val, ok := post.Body["content"].(string); ok && len(val) > 0 {
|
||||
compactBuilder = append(compactBuilder, val)
|
||||
}
|
||||
|
||||
compact := strings.Join(compactBuilder, "\n")
|
||||
|
||||
conn, err := gap.Nx.GetClientGrpcConn("ai")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to connect Insight: %v", err)
|
||||
}
|
||||
ic := iproto.NewInsightServiceClient(conn)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
|
||||
defer cancel()
|
||||
resp, err := ic.GenerateInsight(ctx, &iproto.InsightRequest{
|
||||
Source: compact,
|
||||
UserId: uint64(user),
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
insight = models.PostInsight{
|
||||
Response: resp.Response,
|
||||
Post: post,
|
||||
PostID: post.ID,
|
||||
}
|
||||
if err := database.C.Create(&insight).Error; err != nil {
|
||||
log.Error().Err(err).Msg("Failed to create post insight result in database...")
|
||||
}
|
||||
|
||||
return resp.Response, nil
|
||||
}
|
27
pkg/internal/services/languages.go
Normal file
27
pkg/internal/services/languages.go
Normal file
@ -0,0 +1,27 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/pemistahl/lingua-go"
|
||||
)
|
||||
|
||||
var detector lingua.LanguageDetector
|
||||
|
||||
func CreateLanguageDetector() lingua.LanguageDetector {
|
||||
return lingua.NewLanguageDetectorBuilder().
|
||||
FromAllLanguages().
|
||||
WithLowAccuracyMode().
|
||||
Build()
|
||||
}
|
||||
|
||||
func DetectLanguage(content string) string {
|
||||
if detector == nil {
|
||||
detector = CreateLanguageDetector()
|
||||
}
|
||||
|
||||
if lang, ok := detector.DetectLanguageOf(content); ok {
|
||||
return strings.ToLower(lang.String())
|
||||
}
|
||||
return "unknown"
|
||||
}
|
77
pkg/internal/services/polls.go
Normal file
77
pkg/internal/services/polls.go
Normal file
@ -0,0 +1,77 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func NewPoll(poll models.Poll) (models.Poll, error) {
|
||||
if err := database.C.Create(&poll).Error; err != nil {
|
||||
return poll, err
|
||||
}
|
||||
return poll, nil
|
||||
}
|
||||
|
||||
func UpdatePoll(poll models.Poll) (models.Poll, error) {
|
||||
if err := database.C.Save(&poll).Error; err != nil {
|
||||
return poll, err
|
||||
}
|
||||
return poll, nil
|
||||
}
|
||||
|
||||
func AddPollAnswer(poll models.Poll, answer models.PollAnswer) (models.PollAnswer, error) {
|
||||
answer.PollID = poll.ID
|
||||
|
||||
var currentAnswer models.PollAnswer
|
||||
if err := database.C.Model(&models.PollAnswer{}).
|
||||
Where("poll_id = ? AND account_id = ?", poll.ID, answer.AccountID).
|
||||
First(¤tAnswer).Error; err == nil {
|
||||
if err := database.C.Model(¤tAnswer).
|
||||
Where("id = ?", currentAnswer.ID).
|
||||
Updates(&models.PollAnswer{Answer: answer.Answer}).Error; err != nil {
|
||||
return answer, fmt.Errorf("failed to update your answer")
|
||||
}
|
||||
|
||||
return answer, nil
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return answer, err
|
||||
}
|
||||
|
||||
if err := database.C.Create(&answer).Error; err != nil {
|
||||
return answer, err
|
||||
}
|
||||
|
||||
return answer, nil
|
||||
}
|
||||
|
||||
func GetPollMetric(poll models.Poll) models.PollMetric {
|
||||
var answers []models.PollAnswer
|
||||
if err := database.C.Where("poll_id = ?", poll.ID).Find(&answers).Error; err != nil {
|
||||
return models.PollMetric{}
|
||||
}
|
||||
|
||||
byOptions := make(map[string]int64)
|
||||
for _, answer := range answers {
|
||||
if _, ok := byOptions[answer.Answer]; !ok {
|
||||
byOptions[answer.Answer] = 0
|
||||
}
|
||||
byOptions[answer.Answer]++
|
||||
}
|
||||
|
||||
byOptionsPercentage := make(map[string]float64)
|
||||
for _, option := range poll.Options {
|
||||
if val, ok := byOptions[option.ID]; ok {
|
||||
byOptionsPercentage[option.ID] = float64(val) / float64(len(answers))
|
||||
}
|
||||
}
|
||||
|
||||
return models.PollMetric{
|
||||
TotalAnswer: int64(len(answers)),
|
||||
ByOptions: byOptions,
|
||||
ByOptionsPercentage: byOptionsPercentage,
|
||||
}
|
||||
}
|
56
pkg/internal/services/post_views.go
Normal file
56
pkg/internal/services/post_views.go
Normal file
@ -0,0 +1,56 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"github.com/samber/lo"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
var postViewQueue []models.PostView
|
||||
|
||||
func AddPostView(post models.Post, account uint) {
|
||||
postViewQueue = append(postViewQueue, models.PostView{
|
||||
AccountID: account,
|
||||
PostID: post.ID,
|
||||
})
|
||||
}
|
||||
|
||||
func AddPostViews(posts []models.Post, account uint) {
|
||||
for _, post := range posts {
|
||||
postViewQueue = append(postViewQueue, models.PostView{
|
||||
AccountID: account,
|
||||
PostID: post.ID,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func FlushPostViews() {
|
||||
if len(postViewQueue) == 0 {
|
||||
return
|
||||
}
|
||||
workingQueue := make([]models.PostView, len(postViewQueue))
|
||||
copy(workingQueue, postViewQueue)
|
||||
clear(postViewQueue)
|
||||
updateRequiredPost := make(map[uint]int)
|
||||
for _, item := range workingQueue {
|
||||
updateRequiredPost[item.PostID]++
|
||||
}
|
||||
workingQueue = lo.UniqBy(workingQueue, func(item models.PostView) string {
|
||||
return fmt.Sprintf("%d:%d", item.PostID, item.AccountID)
|
||||
})
|
||||
_ = database.C.Clauses(clause.OnConflict{DoNothing: true}).CreateInBatches(workingQueue, 1000).Error
|
||||
for k, v := range updateRequiredPost {
|
||||
var count int64
|
||||
if err := database.C.Model(&models.PostView{}).Where("post_id = ?", k).Count(&count).Error; err != nil {
|
||||
continue
|
||||
}
|
||||
database.C.Model(&models.Post{}).Where("id = ?", k).Updates(map[string]any{
|
||||
"total_views": count,
|
||||
"total_aggressive_views": gorm.Expr("total_aggressive_views + ?", v),
|
||||
})
|
||||
}
|
||||
}
|
913
pkg/internal/services/posts.go
Normal file
913
pkg/internal/services/posts.go
Normal file
@ -0,0 +1,913 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/cachekit"
|
||||
"github.com/goccy/go-json"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/proto"
|
||||
"git.solsynth.dev/hypernet/paperclip/pkg/filekit"
|
||||
pproto "git.solsynth.dev/hypernet/paperclip/pkg/proto"
|
||||
"git.solsynth.dev/hypernet/passport/pkg/authkit"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
aproto "git.solsynth.dev/hypernet/passport/pkg/proto"
|
||||
"gorm.io/datatypes"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/samber/lo"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func FilterPostWithUserContext(c *fiber.Ctx, tx *gorm.DB, user *authm.Account) *gorm.DB {
|
||||
if user == nil {
|
||||
return tx.Where("visibility = ? AND realm_id IS NULL", models.PostVisibilityAll)
|
||||
}
|
||||
|
||||
const (
|
||||
AllVisibility = models.PostVisibilityAll
|
||||
FriendsVisibility = models.PostVisibilityFriends
|
||||
SelectedVisibility = models.PostVisibilitySelected
|
||||
FilteredVisibility = models.PostVisibilityFiltered
|
||||
)
|
||||
|
||||
type userContextState struct {
|
||||
Self []uint `json:"self"`
|
||||
Allowlist []uint `json:"allow"`
|
||||
InvisibleList []uint `json:"invisible"`
|
||||
FollowList []uint `json:"follow"`
|
||||
RealmList []uint `json:"realm"`
|
||||
}
|
||||
|
||||
var self, allowlist, invisibleList, followList, realmList []uint
|
||||
|
||||
statusCacheKey := fmt.Sprintf("post-user-filter#%d", user.ID)
|
||||
state, err := cachekit.Get[userContextState](gap.Ca, statusCacheKey)
|
||||
if err == nil {
|
||||
allowlist = state.Allowlist
|
||||
invisibleList = state.InvisibleList
|
||||
followList = state.FollowList
|
||||
realmList = state.RealmList
|
||||
self = state.Self
|
||||
} else {
|
||||
// Get itself
|
||||
{
|
||||
var publishers []models.Publisher
|
||||
if err := database.C.Where("account_id = ?", user.ID).Find(&publishers).Error; err != nil {
|
||||
return tx
|
||||
}
|
||||
self = lo.Map(publishers, func(item models.Publisher, index int) uint {
|
||||
return item.ID
|
||||
})
|
||||
allowlist = append(allowlist, self...)
|
||||
}
|
||||
|
||||
// Getting the relationships
|
||||
userFriends, _ := authkit.ListRelative(gap.Nx, user.ID, int32(authm.RelationshipFriend), true)
|
||||
userGotBlocked, _ := authkit.ListRelative(gap.Nx, user.ID, int32(authm.RelationshipBlocked), true)
|
||||
userBlocked, _ := authkit.ListRelative(gap.Nx, user.ID, int32(authm.RelationshipBlocked), false)
|
||||
|
||||
// Getting the realm list
|
||||
{
|
||||
conn, err := gap.Nx.GetClientGrpcConn(nex.ServiceTypeAuth)
|
||||
if err == nil {
|
||||
ac := aproto.NewRealmServiceClient(conn)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
|
||||
defer cancel()
|
||||
resp, err := ac.ListAvailableRealm(ctx, &aproto.LookupUserRealmRequest{
|
||||
UserId: uint64(user.ID),
|
||||
IncludePublic: lo.ToPtr(true),
|
||||
})
|
||||
if err == nil {
|
||||
realmList = lo.Map(resp.GetData(), func(item *aproto.RealmInfo, index int) uint {
|
||||
return uint(item.GetId())
|
||||
})
|
||||
} else {
|
||||
log.Warn().Err(err).Uint("user", user.ID).Msg("An error occurred when getting realm list from grpc...")
|
||||
}
|
||||
} else {
|
||||
log.Warn().Err(err).Uint("user", user.ID).Msg("An error occurred when getting grpc connection to Auth...")
|
||||
}
|
||||
}
|
||||
|
||||
userFriendList := lo.Map(userFriends, func(item *proto.UserInfo, index int) uint {
|
||||
return uint(item.GetId())
|
||||
})
|
||||
userGotBlockList := lo.Map(userGotBlocked, func(item *proto.UserInfo, index int) uint {
|
||||
return uint(item.GetId())
|
||||
})
|
||||
userBlocklist := lo.Map(userBlocked, func(item *proto.UserInfo, index int) uint {
|
||||
return uint(item.GetId())
|
||||
})
|
||||
|
||||
// Query the publishers according to the user's relationship
|
||||
var publishers []models.Publisher
|
||||
database.C.Where(
|
||||
"account_id IN ? AND type = ?",
|
||||
lo.Uniq(append(append(userFriendList, userGotBlockList...), userBlocklist...)),
|
||||
models.PublisherTypePersonal,
|
||||
).Find(&publishers)
|
||||
|
||||
// Getting the follow list
|
||||
{
|
||||
var subs []models.Subscription
|
||||
if err := database.C.Where("follower_id = ? AND account_id IS NOT NULL", user.ID).Find(&subs).Error; err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred when getting subscriptions...")
|
||||
}
|
||||
followList = lo.Map(lo.Filter(subs, func(item models.Subscription, index int) bool {
|
||||
return item.AccountID != nil
|
||||
}), func(item models.Subscription, index int) uint {
|
||||
return *item.AccountID
|
||||
})
|
||||
}
|
||||
|
||||
allowlist = lo.Map(lo.Filter(publishers, func(item models.Publisher, index int) bool {
|
||||
if item.AccountID == nil {
|
||||
return false
|
||||
}
|
||||
return lo.Contains(userFriendList, *item.AccountID)
|
||||
}), func(item models.Publisher, index int) uint {
|
||||
return item.ID
|
||||
})
|
||||
invisibleList = lo.Map(lo.Filter(publishers, func(item models.Publisher, index int) bool {
|
||||
if item.AccountID == nil {
|
||||
return false
|
||||
}
|
||||
return lo.Contains(userBlocklist, *item.AccountID)
|
||||
}), func(item models.Publisher, index int) uint {
|
||||
return item.ID
|
||||
})
|
||||
|
||||
cachekit.Set(
|
||||
gap.Ca,
|
||||
statusCacheKey,
|
||||
userContextState{
|
||||
Allowlist: allowlist,
|
||||
InvisibleList: invisibleList,
|
||||
RealmList: realmList,
|
||||
FollowList: followList,
|
||||
Self: self,
|
||||
},
|
||||
5*time.Minute,
|
||||
fmt.Sprintf("user#%d", user.ID),
|
||||
)
|
||||
}
|
||||
|
||||
if len(self) == 0 && len(allowlist) == 0 {
|
||||
tx = tx.Where(
|
||||
"(visibility = ? OR"+
|
||||
"(visibility = ? AND ?) OR "+
|
||||
"(visibility = ? AND NOT ?))",
|
||||
AllVisibility,
|
||||
SelectedVisibility,
|
||||
datatypes.JSONQuery("visible_users").HasKey(strconv.Itoa(int(user.ID))),
|
||||
FilteredVisibility,
|
||||
datatypes.JSONQuery("invisible_users").HasKey(strconv.Itoa(int(user.ID))),
|
||||
)
|
||||
} else if len(self) == 0 {
|
||||
tx = tx.Where(
|
||||
"(visibility = ? OR"+
|
||||
"(visibility = ? AND publisher_id IN ?) OR "+
|
||||
"(visibility = ? AND ?) OR "+
|
||||
"(visibility = ? AND NOT ?))",
|
||||
AllVisibility,
|
||||
FriendsVisibility,
|
||||
allowlist,
|
||||
SelectedVisibility,
|
||||
datatypes.JSONQuery("visible_users").HasKey(strconv.Itoa(int(user.ID))),
|
||||
FilteredVisibility,
|
||||
datatypes.JSONQuery("invisible_users").HasKey(strconv.Itoa(int(user.ID))),
|
||||
)
|
||||
} else {
|
||||
tx = tx.Where(
|
||||
"(publisher_id IN ? OR visibility = ? OR"+
|
||||
"(visibility = ? AND publisher_id IN ?) OR "+
|
||||
"(visibility = ? AND ?) OR "+
|
||||
"(visibility = ? AND NOT ?))",
|
||||
self,
|
||||
AllVisibility,
|
||||
FriendsVisibility,
|
||||
allowlist,
|
||||
SelectedVisibility,
|
||||
datatypes.JSONQuery("visible_users").HasKey(strconv.Itoa(int(user.ID))),
|
||||
FilteredVisibility,
|
||||
datatypes.JSONQuery("invisible_users").HasKey(strconv.Itoa(int(user.ID))),
|
||||
)
|
||||
}
|
||||
|
||||
if len(invisibleList) > 0 {
|
||||
tx = tx.Where("publisher_id NOT IN ?", invisibleList)
|
||||
}
|
||||
if len(c.Query("realm")) == 0 {
|
||||
if len(realmList) > 0 {
|
||||
tx = tx.Where("realm_id IN ? OR realm_id IS NULL", realmList)
|
||||
} else {
|
||||
tx = tx.Where("realm_id IS NULL")
|
||||
}
|
||||
}
|
||||
|
||||
switch c.Query("channel") {
|
||||
case "friends":
|
||||
tx = tx.Where("publisher_id IN ?", allowlist)
|
||||
case "following":
|
||||
tx = tx.Where("publisher_id IN ?", followList)
|
||||
}
|
||||
|
||||
return tx
|
||||
}
|
||||
|
||||
func FilterPostWithRealm(tx *gorm.DB, probe string) *gorm.DB {
|
||||
if numericId, err := strconv.Atoi(probe); err == nil {
|
||||
return tx.Where("realm_id = ?", uint(numericId))
|
||||
}
|
||||
|
||||
realm, err := authkit.GetRealmByAlias(gap.Nx, probe)
|
||||
if err != nil {
|
||||
log.Warn().Msgf("Failed to find realm with alias %s: %s", probe, err)
|
||||
return tx
|
||||
}
|
||||
|
||||
return tx.Where("realm_id = ?", realm.ID)
|
||||
}
|
||||
|
||||
func FilterPostWithCategory(tx *gorm.DB, alias string) *gorm.DB {
|
||||
aliases := strings.Split(alias, ",")
|
||||
return tx.Joins("JOIN post_categories ON posts.id = post_categories.post_id").
|
||||
Joins("JOIN categories ON categories.id = post_categories.category_id").
|
||||
Where("categories.alias IN ?", aliases).
|
||||
Group("posts.id").
|
||||
Having("COUNT(DISTINCT categories.id) = ?", len(aliases))
|
||||
}
|
||||
|
||||
func FilterPostWithTag(tx *gorm.DB, alias string) *gorm.DB {
|
||||
aliases := strings.Split(alias, ",")
|
||||
return tx.Joins("JOIN post_tags ON posts.id = post_tags.post_id").
|
||||
Joins("JOIN tags ON tags.id = post_tags.tag_id").
|
||||
Where("tags.alias IN ?", aliases).
|
||||
Group("posts.id").
|
||||
Having("COUNT(DISTINCT tags.id) = ?", len(aliases))
|
||||
}
|
||||
|
||||
func FilterPostWithType(tx *gorm.DB, t string) *gorm.DB {
|
||||
return tx.Where("type = ?", t)
|
||||
}
|
||||
|
||||
func FilterPostReply(tx *gorm.DB, replyTo ...uint) *gorm.DB {
|
||||
if len(replyTo) > 0 && replyTo[0] > 0 {
|
||||
return tx.Where("reply_id = ?", replyTo[0])
|
||||
} else {
|
||||
return tx.Where("reply_id IS NULL")
|
||||
}
|
||||
}
|
||||
|
||||
func FilterPostWithPublishedAt(tx *gorm.DB, date time.Time, uid ...uint) *gorm.DB {
|
||||
var publishers []models.Publisher
|
||||
if len(uid) > 0 {
|
||||
if err := database.C.Where("account_id = ?", uid[0]).Find(&publishers).Error; err == nil {
|
||||
}
|
||||
}
|
||||
|
||||
return tx.
|
||||
Where("(published_at < ? OR published_at IS NULL)", date).
|
||||
Where("(published_until >= ? OR published_until IS NULL)", date)
|
||||
}
|
||||
|
||||
func FilterPostWithAuthorDraft(tx *gorm.DB, uid uint) *gorm.DB {
|
||||
var publishers []models.Publisher
|
||||
if err := database.C.Where("account_id = ?", uid).Find(&publishers).Error; err != nil {
|
||||
return FilterPostDraft(tx)
|
||||
}
|
||||
if len(publishers) == 0 {
|
||||
return FilterPostDraft(tx)
|
||||
}
|
||||
idSet := lo.Map(publishers, func(item models.Publisher, index int) uint {
|
||||
return item.ID
|
||||
})
|
||||
return tx.Where("publisher_id IN ? AND is_draft = ?", idSet, true)
|
||||
}
|
||||
|
||||
func FilterPostDraft(tx *gorm.DB) *gorm.DB {
|
||||
return tx.Where("is_draft = ? OR is_draft IS NULL", false)
|
||||
}
|
||||
|
||||
func FilterPostDraftWithAuthor(tx *gorm.DB, uid uint) *gorm.DB {
|
||||
var publishers []models.Publisher
|
||||
if err := database.C.Where("account_id = ?", uid).Find(&publishers).Error; err != nil {
|
||||
return FilterPostDraft(tx)
|
||||
}
|
||||
if len(publishers) == 0 {
|
||||
return FilterPostDraft(tx)
|
||||
}
|
||||
idSet := lo.Map(publishers, func(item models.Publisher, index int) uint {
|
||||
return item.ID
|
||||
})
|
||||
return tx.Where("(is_draft = ? OR is_draft IS NULL) OR publisher_id IN ?", false, idSet)
|
||||
}
|
||||
|
||||
func FilterPostWithFuzzySearch(tx *gorm.DB, probe string) *gorm.DB {
|
||||
if len(probe) == 0 {
|
||||
return tx
|
||||
}
|
||||
|
||||
probe = "%" + probe + "%"
|
||||
return tx.
|
||||
Where(
|
||||
"(? AND body->>'content' ILIKE ? OR ? AND body->>'title' ILIKE ? OR ? AND body->>'description' ILIKE ?)",
|
||||
gorm.Expr("body ? 'content'"),
|
||||
probe,
|
||||
gorm.Expr("body ? 'title'"),
|
||||
probe,
|
||||
gorm.Expr("body ? 'description'"),
|
||||
probe,
|
||||
)
|
||||
}
|
||||
|
||||
func PreloadGeneral(tx *gorm.DB) *gorm.DB {
|
||||
return tx.
|
||||
Preload("Tags").
|
||||
Preload("Categories").
|
||||
Preload("Publisher").
|
||||
Preload("Poll")
|
||||
}
|
||||
|
||||
func GetPost(tx *gorm.DB, id uint) (models.Post, error) {
|
||||
var item models.Post
|
||||
if err := PreloadGeneral(tx).
|
||||
Where("id = ?", id).
|
||||
First(&item).Error; err != nil {
|
||||
return item, err
|
||||
}
|
||||
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func GetPostByAlias(tx *gorm.DB, alias, area string) (models.Post, error) {
|
||||
var item models.Post
|
||||
if err := PreloadGeneral(tx).
|
||||
Where("alias = ?", alias).
|
||||
Where("alias_prefix = ?", area).
|
||||
First(&item).Error; err != nil {
|
||||
return item, err
|
||||
}
|
||||
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func CountPost(tx *gorm.DB) (int64, error) {
|
||||
var count int64
|
||||
if err := tx.Model(&models.Post{}).Count(&count).Error; err != nil {
|
||||
return count, err
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func CountPostReply(id uint) int64 {
|
||||
var count int64
|
||||
if err := database.C.Model(&models.Post{}).
|
||||
Where("reply_id = ?", id).
|
||||
Count(&count).Error; err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
func CountPostReactions(id uint) int64 {
|
||||
var count int64
|
||||
if err := database.C.Model(&models.Reaction{}).
|
||||
Where("post_id = ?", id).
|
||||
Count(&count).Error; err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
func ListPost(tx *gorm.DB, take int, offset int, order any, user *uint, noReact ...bool) ([]models.Post, error) {
|
||||
if take > 100 {
|
||||
take = 100
|
||||
}
|
||||
|
||||
if take >= 0 {
|
||||
tx = tx.Limit(take)
|
||||
}
|
||||
if offset >= 0 {
|
||||
tx = tx.Offset(offset)
|
||||
}
|
||||
|
||||
tx = tx.Preload("Tags").
|
||||
Preload("Categories").
|
||||
Preload("Publisher")
|
||||
|
||||
// Fetch posts
|
||||
var posts []models.Post
|
||||
if err := tx.Order(order).Find(&posts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// If no posts found, return early
|
||||
if len(posts) == 0 {
|
||||
return posts, nil
|
||||
}
|
||||
|
||||
// Collect post IDs
|
||||
idx := make([]uint, len(posts))
|
||||
itemMap := make(map[uint]*models.Post, len(posts))
|
||||
for i, item := range posts {
|
||||
idx[i] = item.ID
|
||||
itemMap[item.ID] = &posts[i]
|
||||
}
|
||||
|
||||
// Batch load reactions
|
||||
if mapping, err := BatchListPostReactions(database.C.Where("post_id IN ?", idx), "post_id"); err != nil {
|
||||
return posts, err
|
||||
} else {
|
||||
for postID, reactions := range mapping {
|
||||
if post, exists := itemMap[postID]; exists {
|
||||
post.Metric.ReactionList = reactions
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Batch load reply counts efficiently
|
||||
var replies []struct {
|
||||
PostID uint
|
||||
Count int64
|
||||
}
|
||||
if err := database.C.Model(&models.Post{}).
|
||||
Select("reply_id as post_id, COUNT(id) as count").
|
||||
Where("reply_id IN (?)", idx).
|
||||
Group("post_id").
|
||||
Find(&replies).Error; err != nil {
|
||||
return posts, err
|
||||
}
|
||||
for _, info := range replies {
|
||||
if post, exists := itemMap[info.PostID]; exists {
|
||||
post.Metric.ReplyCount = info.Count
|
||||
}
|
||||
}
|
||||
|
||||
// Add post views for the user
|
||||
if user != nil {
|
||||
AddPostViews(posts, *user)
|
||||
}
|
||||
|
||||
return posts, nil
|
||||
}
|
||||
|
||||
func ListPostMinimal(tx *gorm.DB, take int, offset int, order any) ([]*models.Post, error) {
|
||||
if take > 500 {
|
||||
take = 500
|
||||
}
|
||||
|
||||
var items []*models.Post
|
||||
if err := tx.
|
||||
Limit(take).Offset(offset).
|
||||
Order(order).
|
||||
Find(&items).Error; err != nil {
|
||||
return items, err
|
||||
}
|
||||
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func EnsurePostCategoriesAndTags(item models.Post) (models.Post, error) {
|
||||
var err error
|
||||
for idx, category := range item.Categories {
|
||||
item.Categories[idx], err = GetCategory(category.Alias)
|
||||
if err != nil {
|
||||
return item, err
|
||||
}
|
||||
}
|
||||
for idx, tag := range item.Tags {
|
||||
item.Tags[idx], err = GetTagOrCreate(tag.Alias, tag.Name)
|
||||
if err != nil {
|
||||
return item, err
|
||||
}
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func NotifyReplying(item models.Post, user models.Publisher) error {
|
||||
content, ok := item.Body["content"].(string)
|
||||
if !ok {
|
||||
content = "Posted a post"
|
||||
} else {
|
||||
content = TruncatePostContentShort(content)
|
||||
}
|
||||
|
||||
var op models.Post
|
||||
if err := database.C.
|
||||
Where("id = ?", item.ReplyID).
|
||||
Preload("Publisher").
|
||||
First(&op).Error; err == nil {
|
||||
if op.Publisher.AccountID != nil && op.Publisher.ID != user.ID {
|
||||
log.Debug().Uint("user", *op.Publisher.AccountID).Msg("Notifying the original poster their post got replied...")
|
||||
err = NotifyPosterAccount(
|
||||
op.Publisher,
|
||||
op,
|
||||
"Post got replied",
|
||||
fmt.Sprintf("%s (%s) replied you: %s", user.Nick, user.Name, content),
|
||||
"interactive.reply",
|
||||
fmt.Sprintf("%s replied your post #%d", user.Nick, *item.ReplyID),
|
||||
)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred when notifying user...")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func NotifySubscribers(item models.Post, user models.Publisher) error {
|
||||
content, ok := item.Body["content"].(string)
|
||||
if !ok {
|
||||
content = "Posted a post"
|
||||
}
|
||||
var title *string
|
||||
title, _ = item.Body["title"].(*string)
|
||||
item.Publisher = user
|
||||
if err := NotifyUserSubscription(user, item, content, title); err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred when notifying subscriptions user by user...")
|
||||
}
|
||||
for _, tag := range item.Tags {
|
||||
if err := NotifyTagSubscription(tag, user, item, content, title); err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred when notifying subscriptions user by tag...")
|
||||
}
|
||||
}
|
||||
for _, category := range item.Categories {
|
||||
if err := NotifyCategorySubscription(category, user, item, content, title); err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred when notifying subscriptions user by category...")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewPost(user models.Publisher, item models.Post) (models.Post, error) {
|
||||
if item.Alias != nil && len(*item.Alias) == 0 {
|
||||
item.Alias = nil
|
||||
}
|
||||
if item.PublishedAt != nil && item.PublishedAt.UTC().Unix() < time.Now().UTC().Unix() {
|
||||
return item, fmt.Errorf("post cannot be published before now")
|
||||
}
|
||||
|
||||
if item.Alias != nil {
|
||||
re := regexp.MustCompile(`^[a-z0-9.-]+$`)
|
||||
if !re.MatchString(*item.Alias) {
|
||||
return item, fmt.Errorf("invalid post alias, learn more about alias rule on our wiki")
|
||||
}
|
||||
}
|
||||
|
||||
if item.Realm != nil {
|
||||
item.AliasPrefix = &item.Realm.Alias
|
||||
} else {
|
||||
item.AliasPrefix = &user.Name
|
||||
}
|
||||
|
||||
log.Debug().Any("body", item.Body).Msg("Posting a post...")
|
||||
start := time.Now()
|
||||
|
||||
log.Debug().Any("tags", item.Tags).Any("categories", item.Categories).Msg("Preparing categories and tags...")
|
||||
item, err := EnsurePostCategoriesAndTags(item)
|
||||
if err != nil {
|
||||
return item, err
|
||||
}
|
||||
|
||||
log.Debug().Msg("Saving post record into database...")
|
||||
if err := database.C.Save(&item).Error; err != nil {
|
||||
return item, err
|
||||
}
|
||||
|
||||
item.Publisher = user
|
||||
err = UpdatePostAttachmentMeta(item)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred when updating post attachment meta...")
|
||||
}
|
||||
|
||||
// Notify the original poster its post has been replied
|
||||
if item.ReplyID != nil && !item.IsDraft {
|
||||
go NotifyReplying(item, user)
|
||||
}
|
||||
// Notify the subscriptions
|
||||
if item.ReplyID == nil && !item.IsDraft {
|
||||
go NotifySubscribers(item, user)
|
||||
}
|
||||
|
||||
log.Debug().Dur("elapsed", time.Since(start)).Msg("The post is posted.")
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func EditPost(item models.Post, og models.Post) (models.Post, error) {
|
||||
if _, ok := item.Body["content_truncated"]; ok {
|
||||
return item, fmt.Errorf("prevented from editing post with truncated content")
|
||||
}
|
||||
|
||||
if !item.IsDraft && item.PublishedAt == nil {
|
||||
item.PublishedAt = lo.ToPtr(time.Now())
|
||||
}
|
||||
if item.Alias != nil && len(*item.Alias) == 0 {
|
||||
item.Alias = nil
|
||||
}
|
||||
|
||||
if item.Alias != nil {
|
||||
re := regexp.MustCompile(`^[a-z0-9.-]+$`)
|
||||
if !re.MatchString(*item.Alias) {
|
||||
return item, fmt.Errorf("invalid post alias, learn more about alias rule on our wiki")
|
||||
}
|
||||
}
|
||||
|
||||
if item.Realm != nil {
|
||||
item.AliasPrefix = &item.Realm.Alias
|
||||
} else {
|
||||
item.AliasPrefix = &item.Publisher.Name
|
||||
}
|
||||
|
||||
item, err := EnsurePostCategoriesAndTags(item)
|
||||
if err != nil {
|
||||
return item, err
|
||||
}
|
||||
|
||||
_ = database.C.Model(&item).Association("Categories").Replace(item.Categories)
|
||||
_ = database.C.Model(&item).Association("Tags").Replace(item.Tags)
|
||||
|
||||
pub := item.Publisher
|
||||
err = database.C.Save(&item).Error
|
||||
|
||||
if err == nil {
|
||||
item.Publisher = pub
|
||||
err = UpdatePostAttachmentMeta(item)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred when updating post attachment meta...")
|
||||
}
|
||||
|
||||
if og.IsDraft && !item.IsDraft {
|
||||
// Notify the original poster its post has been replied
|
||||
if item.ReplyID != nil {
|
||||
go NotifyReplying(item, item.Publisher)
|
||||
}
|
||||
// Notify the subscriptions
|
||||
if item.ReplyID == nil {
|
||||
go NotifySubscribers(item, item.Publisher)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return item, err
|
||||
}
|
||||
|
||||
func UpdatePostAttachmentMeta(item models.Post, old ...models.Post) error {
|
||||
log.Debug().Any("attachments", item.Body["attachments"]).Msg("Updating post attachments meta...")
|
||||
|
||||
// Marking usage
|
||||
sameAsOld := false
|
||||
if len(old) > 0 {
|
||||
sameAsOld = reflect.DeepEqual(old[0].Body, item.Body)
|
||||
}
|
||||
|
||||
var oldBody, newBody models.PostStoryBody
|
||||
if len(old) > 0 {
|
||||
raw, _ := json.Marshal(old[0].Body)
|
||||
json.Unmarshal(raw, &oldBody)
|
||||
}
|
||||
{
|
||||
raw, _ := json.Marshal(item.Body)
|
||||
json.Unmarshal(raw, &newBody)
|
||||
}
|
||||
var minusAttachments, plusAttachments []string
|
||||
if len(old) > 0 && !sameAsOld {
|
||||
minusAttachments = append(minusAttachments, oldBody.Attachments...)
|
||||
}
|
||||
if len(old) == 0 || !sameAsOld {
|
||||
plusAttachments = append(plusAttachments, newBody.Attachments...)
|
||||
}
|
||||
if dat, ok := item.Body["thumbnail"].(string); ok {
|
||||
plusAttachments = append(plusAttachments, dat)
|
||||
}
|
||||
if dat, ok := item.Body["video"].(string); ok {
|
||||
plusAttachments = append(plusAttachments, dat)
|
||||
}
|
||||
if len(minusAttachments) > 0 {
|
||||
filekit.CountAttachmentUsage(gap.Nx, &pproto.UpdateUsageRequest{
|
||||
Rid: minusAttachments,
|
||||
Delta: -1,
|
||||
})
|
||||
}
|
||||
if len(plusAttachments) > 0 {
|
||||
filekit.CountAttachmentUsage(gap.Nx, &pproto.UpdateUsageRequest{
|
||||
Rid: plusAttachments,
|
||||
Delta: 1,
|
||||
})
|
||||
}
|
||||
|
||||
// Updating visibility
|
||||
if item.Publisher.AccountID == nil {
|
||||
log.Warn().Msg("Post publisher did not have account id, skip updating attachments meta...")
|
||||
return nil
|
||||
}
|
||||
|
||||
if val, ok := item.Body["attachments"].([]any); ok && len(val) > 0 {
|
||||
conn, err := gap.Nx.GetClientGrpcConn("uc")
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred when getting grpc connection to Paperclip...")
|
||||
return nil
|
||||
}
|
||||
|
||||
pc := pproto.NewAttachmentServiceClient(conn)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
resp, err := pc.UpdateVisibility(ctx, &pproto.UpdateVisibilityRequest{
|
||||
Rid: lo.Map(val, func(item any, _ int) string {
|
||||
return item.(string)
|
||||
}),
|
||||
UserId: lo.ToPtr(uint64(*item.Publisher.AccountID)),
|
||||
IsIndexable: item.Visibility == models.PostVisibilityAll,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Any("attachments", val).Err(err).Msg("An error occurred when updating post attachment visibility...")
|
||||
return err
|
||||
}
|
||||
|
||||
log.Debug().Any("attachments", val).Int32("count", resp.Count).Msg("Post attachment visibility updated.")
|
||||
} else {
|
||||
log.Debug().Any("attachments", val).Msg("Post attachment visibility update skipped...")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func DeletePost(item models.Post) error {
|
||||
copiedItem := item
|
||||
if err := database.C.Delete(&copiedItem).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Cleaning up related attachments
|
||||
var body models.PostStoryBody
|
||||
{
|
||||
raw, _ := json.Marshal(item.Body)
|
||||
json.Unmarshal(raw, &body)
|
||||
}
|
||||
if len(body.Attachments) > 0 {
|
||||
if item.Publisher.AccountID == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
err := filekit.CountAttachmentUsage(gap.Nx, &pproto.UpdateUsageRequest{
|
||||
Rid: lo.Uniq(body.Attachments),
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred when deleting post attachment...")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func DeletePostInBatch(items []models.Post) error {
|
||||
if err := database.C.Delete(&items).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var bodies []models.PostStoryBody
|
||||
{
|
||||
raw, _ := json.Marshal(items)
|
||||
json.Unmarshal(raw, &bodies)
|
||||
}
|
||||
|
||||
var attachments []string
|
||||
for idx := range items {
|
||||
if len(bodies[idx].Attachments) > 0 {
|
||||
attachments = append(attachments, bodies[idx].Attachments...)
|
||||
}
|
||||
}
|
||||
|
||||
err := filekit.CountAttachmentUsage(gap.Nx, &pproto.UpdateUsageRequest{
|
||||
Rid: lo.Uniq(attachments),
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred when deleting post attachment...")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ReactPost(user authm.Account, reaction models.Reaction) (bool, models.Reaction, error) {
|
||||
var op models.Post
|
||||
if err := database.C.
|
||||
Where("id = ?", reaction.PostID).
|
||||
Preload("Publisher").
|
||||
First(&op).Error; err != nil {
|
||||
return true, reaction, err
|
||||
}
|
||||
|
||||
if err := database.C.Where(reaction).First(&reaction).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
if op.Publisher.AccountID != nil && *op.Publisher.AccountID != user.ID {
|
||||
err = NotifyPosterAccount(
|
||||
op.Publisher,
|
||||
op,
|
||||
"Post got reacted",
|
||||
fmt.Sprintf("%s (%s) reacted your post a %s.", user.Nick, user.Name, reaction.Symbol),
|
||||
"interactive.feedback",
|
||||
fmt.Sprintf("%s reacted you", user.Nick),
|
||||
)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred when notifying user...")
|
||||
}
|
||||
}
|
||||
|
||||
err = database.C.Save(&reaction).Error
|
||||
if err == nil && reaction.Attitude != models.AttitudeNeutral {
|
||||
_ = ModifyPosterVoteCount(op.Publisher, reaction.Attitude == models.AttitudePositive, 1)
|
||||
|
||||
if reaction.Attitude == models.AttitudePositive {
|
||||
op.TotalUpvote++
|
||||
database.C.Model(&op).Update("total_upvote", op.TotalUpvote)
|
||||
} else {
|
||||
op.TotalDownvote++
|
||||
database.C.Model(&op).Update("total_downvote", op.TotalDownvote)
|
||||
}
|
||||
}
|
||||
|
||||
return true, reaction, err
|
||||
} else {
|
||||
return true, reaction, err
|
||||
}
|
||||
} else {
|
||||
err = database.C.Delete(&reaction).Error
|
||||
if err == nil && reaction.Attitude != models.AttitudeNeutral {
|
||||
_ = ModifyPosterVoteCount(op.Publisher, reaction.Attitude == models.AttitudePositive, -1)
|
||||
|
||||
if reaction.Attitude == models.AttitudePositive {
|
||||
op.TotalUpvote--
|
||||
database.C.Model(&op).Update("total_upvote", op.TotalUpvote)
|
||||
} else {
|
||||
op.TotalDownvote--
|
||||
database.C.Model(&op).Update("total_downvote", op.TotalDownvote)
|
||||
}
|
||||
}
|
||||
|
||||
return false, reaction, err
|
||||
}
|
||||
}
|
||||
|
||||
func PinPost(post models.Post) (bool, error) {
|
||||
if post.PinnedAt != nil {
|
||||
post.PinnedAt = nil
|
||||
} else {
|
||||
post.PinnedAt = lo.ToPtr(time.Now())
|
||||
}
|
||||
|
||||
if err := database.C.Model(&post).Update("pinned_at", post.PinnedAt).Error; err != nil {
|
||||
return post.PinnedAt != nil, err
|
||||
}
|
||||
return post.PinnedAt != nil, nil
|
||||
}
|
||||
|
||||
const TruncatePostContentThreshold = 160
|
||||
|
||||
func TruncatePostContent(post models.Post) models.Post {
|
||||
if post.Body["content"] != nil {
|
||||
if val, ok := post.Body["content"].(string); ok {
|
||||
length := TruncatePostContentThreshold
|
||||
post.Body["content_length"] = len([]rune(val))
|
||||
if len([]rune(val)) >= length {
|
||||
post.Body["content"] = string([]rune(val)[:length]) + "..."
|
||||
post.Body["content_truncated"] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if post.RepostTo != nil {
|
||||
post.RepostTo = lo.ToPtr(TruncatePostContent(*post.RepostTo))
|
||||
}
|
||||
if post.ReplyTo != nil {
|
||||
post.ReplyTo = lo.ToPtr(TruncatePostContent(*post.ReplyTo))
|
||||
}
|
||||
|
||||
return post
|
||||
}
|
||||
|
||||
const TruncatePostContentShortThreshold = 80
|
||||
|
||||
func TruncatePostContentShort(content string) string {
|
||||
length := TruncatePostContentShortThreshold
|
||||
if len([]rune(content)) >= length {
|
||||
return string([]rune(content)[:length]) + "..."
|
||||
} else {
|
||||
return content
|
||||
}
|
||||
}
|
76
pkg/internal/services/posts_getter.go
Normal file
76
pkg/internal/services/posts_getter.go
Normal file
@ -0,0 +1,76 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UniversalPostFilterConfig struct {
|
||||
ShowDraft bool
|
||||
ShowReply bool
|
||||
ShowCollapsed bool
|
||||
TimeCursor *time.Time
|
||||
}
|
||||
|
||||
func UniversalPostFilter(c *fiber.Ctx, tx *gorm.DB, cfg ...UniversalPostFilterConfig) (*gorm.DB, error) {
|
||||
var config UniversalPostFilterConfig
|
||||
if len(cfg) > 0 {
|
||||
config = cfg[0]
|
||||
} else {
|
||||
config = UniversalPostFilterConfig{}
|
||||
}
|
||||
|
||||
timeCursor := time.Now()
|
||||
if config.TimeCursor != nil {
|
||||
timeCursor = *config.TimeCursor
|
||||
}
|
||||
|
||||
if user, authenticated := c.Locals("user").(authm.Account); authenticated {
|
||||
tx = FilterPostWithUserContext(c, tx, &user)
|
||||
if c.QueryBool("noDraft", true) && !config.ShowDraft {
|
||||
tx = FilterPostDraft(tx)
|
||||
tx = FilterPostWithPublishedAt(tx, timeCursor)
|
||||
} else {
|
||||
tx = FilterPostDraftWithAuthor(database.C, user.ID)
|
||||
tx = FilterPostWithPublishedAt(tx, timeCursor, user.ID)
|
||||
}
|
||||
} else {
|
||||
tx = FilterPostWithUserContext(c, tx, nil)
|
||||
tx = FilterPostDraft(tx)
|
||||
tx = FilterPostWithPublishedAt(tx, timeCursor)
|
||||
}
|
||||
|
||||
if c.QueryBool("noReply", true) && !config.ShowReply {
|
||||
tx = FilterPostReply(tx)
|
||||
}
|
||||
|
||||
if len(c.Query("author")) > 0 {
|
||||
var author models.Publisher
|
||||
if err := database.C.Where("name = ?", c.Query("author")).First(&author).Error; err != nil {
|
||||
return tx, fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
tx = tx.Where("publisher_id = ?", author.ID)
|
||||
}
|
||||
|
||||
if len(c.Query("categories")) > 0 {
|
||||
tx = FilterPostWithCategory(tx, c.Query("categories"))
|
||||
}
|
||||
if len(c.Query("tags")) > 0 {
|
||||
tx = FilterPostWithTag(tx, c.Query("tags"))
|
||||
}
|
||||
|
||||
if len(c.Query("type")) > 0 {
|
||||
tx = FilterPostWithType(tx, c.Query("type"))
|
||||
}
|
||||
|
||||
if len(c.Query("realm")) > 0 {
|
||||
tx = FilterPostWithRealm(tx, c.Query("realm"))
|
||||
}
|
||||
|
||||
return tx, nil
|
||||
}
|
160
pkg/internal/services/publishers.go
Normal file
160
pkg/internal/services/publishers.go
Normal file
@ -0,0 +1,160 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/paperclip/pkg/filekit"
|
||||
"git.solsynth.dev/hypernet/paperclip/pkg/proto"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
)
|
||||
|
||||
func GetPublisher(id uint, userID uint) (models.Publisher, error) {
|
||||
var publisher models.Publisher
|
||||
if err := database.C.Where("id = ? AND account_id = ?", id, userID).First(&publisher).Error; err != nil {
|
||||
return publisher, fmt.Errorf("unable to get publisher: %v", err)
|
||||
}
|
||||
return publisher, nil
|
||||
}
|
||||
|
||||
func GetPublisherByName(name string, userID uint) (models.Publisher, error) {
|
||||
var publisher models.Publisher
|
||||
if err := database.C.Where("name = ? AND account_id = ?", name, userID).First(&publisher).Error; err != nil {
|
||||
return publisher, fmt.Errorf("unable to get publisher: %v", err)
|
||||
}
|
||||
return publisher, nil
|
||||
}
|
||||
|
||||
func CreatePersonalPublisher(user authm.Account, name, nick, desc, avatar, banner string) (models.Publisher, error) {
|
||||
publisher := models.Publisher{
|
||||
Type: models.PublisherTypePersonal,
|
||||
Name: name,
|
||||
Nick: nick,
|
||||
Description: desc,
|
||||
Avatar: avatar,
|
||||
Banner: banner,
|
||||
AccountID: &user.ID,
|
||||
}
|
||||
var attachments []string
|
||||
if user.Avatar != nil && len(publisher.Avatar) == 0 {
|
||||
attachments = append(attachments, *user.Avatar)
|
||||
publisher.Avatar = *user.Avatar
|
||||
}
|
||||
if user.Banner != nil && len(publisher.Banner) == 0 {
|
||||
attachments = append(attachments, *user.Banner)
|
||||
publisher.Banner = *user.Banner
|
||||
}
|
||||
|
||||
if len(attachments) > 0 {
|
||||
filekit.CountAttachmentUsage(gap.Nx, &proto.UpdateUsageRequest{
|
||||
Rid: attachments,
|
||||
Delta: 1,
|
||||
})
|
||||
}
|
||||
|
||||
if err := database.C.Create(&publisher).Error; err != nil {
|
||||
return publisher, err
|
||||
}
|
||||
return publisher, nil
|
||||
}
|
||||
|
||||
func CreateOrganizationPublisher(user authm.Account, realm authm.Realm, name, nick, desc, avatar, banner string) (models.Publisher, error) {
|
||||
publisher := models.Publisher{
|
||||
Type: models.PublisherTypeOrganization,
|
||||
Name: name,
|
||||
Nick: nick,
|
||||
Description: desc,
|
||||
Avatar: avatar,
|
||||
Banner: banner,
|
||||
RealmID: &realm.ID,
|
||||
AccountID: &user.ID,
|
||||
}
|
||||
var attachments []string
|
||||
if realm.Avatar != nil && len(publisher.Avatar) == 0 {
|
||||
attachments = append(attachments, *realm.Avatar)
|
||||
publisher.Avatar = *realm.Avatar
|
||||
}
|
||||
if realm.Banner != nil && len(publisher.Banner) == 0 {
|
||||
attachments = append(attachments, *realm.Banner)
|
||||
publisher.Banner = *realm.Banner
|
||||
}
|
||||
|
||||
if len(attachments) > 0 {
|
||||
filekit.CountAttachmentUsage(gap.Nx, &proto.UpdateUsageRequest{
|
||||
Rid: attachments,
|
||||
Delta: 1,
|
||||
})
|
||||
}
|
||||
|
||||
if err := database.C.Create(&publisher).Error; err != nil {
|
||||
return publisher, err
|
||||
}
|
||||
return publisher, nil
|
||||
}
|
||||
|
||||
func EditPublisher(user authm.Account, publisher, og models.Publisher) (models.Publisher, error) {
|
||||
if publisher.Type == models.PublisherTypePersonal {
|
||||
if *publisher.AccountID != user.ID {
|
||||
return publisher, fmt.Errorf("you cannot transfer personal publisher")
|
||||
}
|
||||
}
|
||||
|
||||
var minusAttachments, plusAttachments []string
|
||||
if publisher.Avatar != og.Avatar {
|
||||
minusAttachments = append(minusAttachments, og.Avatar)
|
||||
plusAttachments = append(plusAttachments, publisher.Avatar)
|
||||
}
|
||||
if publisher.Banner != og.Banner {
|
||||
minusAttachments = append(minusAttachments, og.Banner)
|
||||
plusAttachments = append(plusAttachments, publisher.Banner)
|
||||
}
|
||||
if len(minusAttachments) > 0 {
|
||||
filekit.CountAttachmentUsage(gap.Nx, &proto.UpdateUsageRequest{
|
||||
Rid: minusAttachments,
|
||||
Delta: -1,
|
||||
})
|
||||
}
|
||||
if len(plusAttachments) > 0 {
|
||||
filekit.CountAttachmentUsage(gap.Nx, &proto.UpdateUsageRequest{
|
||||
Rid: plusAttachments,
|
||||
Delta: 1,
|
||||
})
|
||||
}
|
||||
|
||||
err := database.C.Save(&publisher).Error
|
||||
return publisher, err
|
||||
}
|
||||
|
||||
func DeletePublisher(publisher models.Publisher) error {
|
||||
tx := database.C.Begin()
|
||||
|
||||
if err := tx.Where("publisher_id = ?", publisher.ID).Delete(&models.Post{}).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return err
|
||||
}
|
||||
if err := tx.Delete(&publisher).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return err
|
||||
}
|
||||
|
||||
err := tx.Commit().Error
|
||||
if err == nil {
|
||||
var attachments []string
|
||||
if len(publisher.Avatar) > 0 {
|
||||
attachments = append(attachments, publisher.Avatar)
|
||||
}
|
||||
if len(publisher.Banner) > 0 {
|
||||
attachments = append(attachments, publisher.Banner)
|
||||
}
|
||||
if len(attachments) > 0 {
|
||||
filekit.CountAttachmentUsage(gap.Nx, &proto.UpdateUsageRequest{
|
||||
Rid: attachments,
|
||||
Delta: -1,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
120
pkg/internal/services/queries/feed.go
Normal file
120
pkg/internal/services/queries/feed.go
Normal file
@ -0,0 +1,120 @@
|
||||
package queries
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/proto"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/samber/lo"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type FeedEntry struct {
|
||||
Type string `json:"type"`
|
||||
Data any `json:"data"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func GetFeed(c *fiber.Ctx, limit int, user *uint, cursor *time.Time) ([]FeedEntry, error) {
|
||||
// We got two types of data for now
|
||||
// Plan to let each of them take 50% of the output
|
||||
|
||||
var feed []FeedEntry
|
||||
|
||||
// Planing the feed
|
||||
limitF := float64(limit)
|
||||
interCount := int(math.Ceil(limitF * 0.7))
|
||||
readerCount := int(math.Ceil(limitF * 0.3))
|
||||
|
||||
// Internal posts
|
||||
interTx, err := services.UniversalPostFilter(c, database.C)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to prepare load interactive posts: %v", err)
|
||||
}
|
||||
if cursor != nil {
|
||||
interTx = interTx.Where("published_at < ?", *cursor)
|
||||
}
|
||||
posts, err := ListPostForFeed(interTx, interCount, user, c.Get("X-API-Version", "1"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load interactive posts: %v", err)
|
||||
}
|
||||
feed = append(feed, posts...)
|
||||
|
||||
sort.Slice(feed, func(i, j int) bool {
|
||||
return feed[i].CreatedAt.After(feed[j].CreatedAt)
|
||||
})
|
||||
|
||||
// News today - from Reader
|
||||
if news, err := ListReaderPagesForFeed(readerCount, cursor); err != nil {
|
||||
log.Error().Err(err).Msg("Failed to load news in getting feed...")
|
||||
} else {
|
||||
feed = append(feed, news...)
|
||||
}
|
||||
|
||||
return feed, nil
|
||||
}
|
||||
|
||||
// We assume the database context already handled the filtering and pagination
|
||||
// Only manage to pulling the content only
|
||||
|
||||
func ListPostForFeed(tx *gorm.DB, limit int, user *uint, api string) ([]FeedEntry, error) {
|
||||
var posts []models.Post
|
||||
var err error
|
||||
rankOrder := `(COALESCE(total_upvote, 0) - COALESCE(total_downvote, 0) +
|
||||
LOG(1 + COALESCE(total_aggressive_views, 0))) /
|
||||
POWER(EXTRACT(EPOCH FROM NOW() - published_at) / 3600 + 2, 1.5) DESC`
|
||||
if api == "2" {
|
||||
posts, err = ListPost(tx, limit, -1, rankOrder, user)
|
||||
} else {
|
||||
posts, err = services.ListPost(tx, limit, -1, rankOrder, user)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries := lo.Map(posts, func(post models.Post, _ int) FeedEntry {
|
||||
return FeedEntry{
|
||||
Type: "interactive.post",
|
||||
Data: services.TruncatePostContent(post),
|
||||
CreatedAt: post.CreatedAt,
|
||||
}
|
||||
})
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func ListReaderPagesForFeed(limit int, cursor *time.Time) ([]FeedEntry, error) {
|
||||
conn, err := gap.Nx.GetClientGrpcConn("re")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get grpc connection with reader: %v", err)
|
||||
}
|
||||
client := proto.NewFeedServiceClient(conn)
|
||||
request := &proto.GetFeedRequest{
|
||||
Limit: int64(limit),
|
||||
}
|
||||
if cursor != nil {
|
||||
request.Cursor = lo.ToPtr(uint64(cursor.UnixMilli()))
|
||||
}
|
||||
resp, err := client.GetFeed(context.Background(), request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get feed from reader: %v", err)
|
||||
}
|
||||
var createdAt time.Time
|
||||
return lo.Map(resp.Items, func(item *proto.FeedItem, _ int) FeedEntry {
|
||||
cta := time.UnixMilli(int64(item.CreatedAt))
|
||||
createdAt = lo.Ternary(createdAt.Before(cta), cta, createdAt)
|
||||
return FeedEntry{
|
||||
Type: item.Type,
|
||||
Data: nex.DecodeMap(item.Content),
|
||||
CreatedAt: cta,
|
||||
}
|
||||
}), nil
|
||||
}
|
248
pkg/internal/services/queries/posts.go
Normal file
248
pkg/internal/services/queries/posts.go
Normal file
@ -0,0 +1,248 @@
|
||||
package queries
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/goccy/go-json"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"git.solsynth.dev/hypernet/paperclip/pkg/filekit"
|
||||
fmodels "git.solsynth.dev/hypernet/paperclip/pkg/filekit/models"
|
||||
"git.solsynth.dev/hypernet/passport/pkg/authkit"
|
||||
amodels "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/samber/lo"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var singularAttachmentFields = []string{"video", "thumbnail"}
|
||||
|
||||
func CompletePostMeta(in ...models.Post) ([]models.Post, error) {
|
||||
// Collect post IDs
|
||||
idx := make([]uint, len(in))
|
||||
itemMap := make(map[uint]*models.Post, len(in))
|
||||
for i, item := range in {
|
||||
idx[i] = item.ID
|
||||
itemMap[item.ID] = &in[i]
|
||||
}
|
||||
|
||||
// Batch load reactions
|
||||
if mapping, err := services.BatchListPostReactions(database.C.Where("post_id IN ?", idx), "post_id"); err != nil {
|
||||
return in, err
|
||||
} else {
|
||||
for postID, reactions := range mapping {
|
||||
if post, exists := itemMap[postID]; exists {
|
||||
post.Metric.ReactionList = reactions
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Batch load reply counts efficiently
|
||||
var replies []struct {
|
||||
PostID uint
|
||||
Count int64
|
||||
}
|
||||
if err := database.C.Model(&models.Post{}).
|
||||
Select("reply_id as post_id, COUNT(id) as count").
|
||||
Where("reply_id IN (?)", idx).
|
||||
Group("post_id").
|
||||
Find(&replies).Error; err != nil {
|
||||
return in, err
|
||||
}
|
||||
for _, info := range replies {
|
||||
if post, exists := itemMap[info.PostID]; exists {
|
||||
post.Metric.ReplyCount = info.Count
|
||||
}
|
||||
}
|
||||
|
||||
// Batch load some metadata
|
||||
var err error
|
||||
var attachmentsRid []string
|
||||
var usersId []uint
|
||||
var realmsId []uint
|
||||
|
||||
// Scan records that can be load eagerly
|
||||
var bodies []models.PostStoryBody
|
||||
{
|
||||
raw, _ := json.Marshal(lo.Map(in, func(item models.Post, _ int) map[string]any {
|
||||
return item.Body
|
||||
}))
|
||||
json.Unmarshal(raw, &bodies)
|
||||
}
|
||||
for idx, info := range in {
|
||||
if info.Publisher.AccountID != nil {
|
||||
usersId = append(usersId, *info.Publisher.AccountID)
|
||||
}
|
||||
if info.RealmID != nil {
|
||||
realmsId = append(realmsId, *info.RealmID)
|
||||
}
|
||||
attachmentsRid = append(attachmentsRid, bodies[idx].Attachments...)
|
||||
for _, field := range singularAttachmentFields {
|
||||
if raw, ok := info.Body[field]; ok {
|
||||
if str, ok := raw.(string); ok && !strings.HasPrefix(str, "http") {
|
||||
attachmentsRid = append(attachmentsRid, str)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
log.Debug().Int("attachments", len(attachmentsRid)).Int("users", len(usersId)).Msg("Scanned metadata to load for listing post...")
|
||||
|
||||
// Batch load attachments
|
||||
attachmentsRid = lo.Uniq(attachmentsRid)
|
||||
var attachments []fmodels.Attachment
|
||||
if len(attachmentsRid) > 0 {
|
||||
attachments, err = filekit.ListAttachment(gap.Nx, attachmentsRid)
|
||||
if err != nil {
|
||||
return in, fmt.Errorf("failed to load attachments: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Batch load publisher users
|
||||
usersId = lo.Uniq(usersId)
|
||||
var users []amodels.Account
|
||||
if len(users) > 0 {
|
||||
users, err = authkit.ListUser(gap.Nx, usersId)
|
||||
if err != nil {
|
||||
return in, fmt.Errorf("failed to load users: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Batch load posts realm
|
||||
realmsId = lo.Uniq(realmsId)
|
||||
var realms []amodels.Realm
|
||||
if len(realmsId) > 0 {
|
||||
realms, err = authkit.ListRealm(gap.Nx, realmsId)
|
||||
if err != nil {
|
||||
return in, fmt.Errorf("failed to load realms: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Putting information back to data
|
||||
log.Info().Int("attachments", len(attachments)).Int("users", len(users)).Msg("Batch loaded metadata for listing post...")
|
||||
for idx, item := range in {
|
||||
var this []fmodels.Attachment
|
||||
if len(bodies[idx].Attachments) > 0 {
|
||||
this = lo.Filter(attachments, func(item fmodels.Attachment, _ int) bool {
|
||||
return lo.Contains(bodies[idx].Attachments, item.Rid)
|
||||
})
|
||||
}
|
||||
for _, field := range singularAttachmentFields {
|
||||
if raw, ok := item.Body[field]; ok {
|
||||
if str, ok := raw.(string); ok {
|
||||
result := lo.FindOrElse(this, fmodels.Attachment{}, func(item fmodels.Attachment) bool {
|
||||
return item.Rid == str
|
||||
})
|
||||
if result.ID != 0 {
|
||||
item.Body[field] = result
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
item.Body["attachments"] = this
|
||||
if item.Publisher.AccountID != nil {
|
||||
item.Publisher.Account = lo.FindOrElse(users, amodels.Account{}, func(acc amodels.Account) bool {
|
||||
return acc.ID == *item.Publisher.AccountID
|
||||
})
|
||||
}
|
||||
if item.RealmID != nil {
|
||||
item.Realm = lo.ToPtr(lo.FindOrElse(realms, amodels.Realm{}, func(realm amodels.Realm) bool {
|
||||
return realm.ID == *item.RealmID
|
||||
}))
|
||||
}
|
||||
in[idx] = item
|
||||
}
|
||||
|
||||
return in, nil
|
||||
}
|
||||
|
||||
func GetPost(tx *gorm.DB, id uint, user *uint) (models.Post, error) {
|
||||
var post models.Post
|
||||
if err := tx.Preload("Tags").
|
||||
Preload("Categories").
|
||||
Preload("Publisher").
|
||||
Preload("Poll").
|
||||
First(&post, id).Error; err != nil {
|
||||
return post, err
|
||||
}
|
||||
|
||||
out, err := CompletePostMeta(post)
|
||||
if err != nil {
|
||||
return post, err
|
||||
}
|
||||
|
||||
if user != nil {
|
||||
services.AddPostView(post, *user)
|
||||
}
|
||||
|
||||
return out[0], nil
|
||||
}
|
||||
|
||||
func GetPostByAlias(tx *gorm.DB, alias, area string, user *uint) (models.Post, error) {
|
||||
var post models.Post
|
||||
if err := tx.Preload("Tags").
|
||||
Preload("Categories").
|
||||
Preload("Publisher").
|
||||
Preload("Poll").
|
||||
Where("alias = ?", alias).
|
||||
Where("alias_prefix = ?", area).
|
||||
First(&post).Error; err != nil {
|
||||
return post, err
|
||||
}
|
||||
|
||||
out, err := CompletePostMeta(post)
|
||||
if err != nil {
|
||||
return post, err
|
||||
}
|
||||
|
||||
if user != nil {
|
||||
services.AddPostView(post, *user)
|
||||
}
|
||||
|
||||
return out[0], nil
|
||||
}
|
||||
|
||||
func ListPost(tx *gorm.DB, take int, offset int, order any, user *uint) ([]models.Post, error) {
|
||||
if take > 100 {
|
||||
take = 100
|
||||
}
|
||||
|
||||
if take >= 0 {
|
||||
tx = tx.Limit(take)
|
||||
}
|
||||
if offset >= 0 {
|
||||
tx = tx.Offset(offset)
|
||||
}
|
||||
|
||||
tx = tx.Preload("Tags").
|
||||
Preload("Categories").
|
||||
Preload("Publisher").
|
||||
Preload("Poll")
|
||||
|
||||
// Fetch posts
|
||||
var posts []models.Post
|
||||
if err := tx.Order(order).Find(&posts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// If no posts found, return early
|
||||
if len(posts) == 0 {
|
||||
return posts, nil
|
||||
}
|
||||
|
||||
// Load data eagerly
|
||||
posts, err := CompletePostMeta(posts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Add post views for the user
|
||||
if user != nil {
|
||||
services.AddPostViews(posts, *user)
|
||||
}
|
||||
|
||||
return posts, nil
|
||||
}
|
60
pkg/internal/services/reactions.go
Normal file
60
pkg/internal/services/reactions.go
Normal file
@ -0,0 +1,60 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"github.com/samber/lo"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func ListPostReactions(tx *gorm.DB) (map[string]int64, error) {
|
||||
var reactions []struct {
|
||||
Symbol string
|
||||
Count int64
|
||||
}
|
||||
|
||||
if err := tx.Model(&models.Reaction{}).
|
||||
Select("symbol, COUNT(id) as count").
|
||||
Group("symbol").
|
||||
Scan(&reactions).Error; err != nil {
|
||||
return map[string]int64{}, err
|
||||
}
|
||||
|
||||
return lo.SliceToMap(reactions, func(item struct {
|
||||
Symbol string
|
||||
Count int64
|
||||
},
|
||||
) (string, int64) {
|
||||
return item.Symbol, item.Count
|
||||
}), nil
|
||||
}
|
||||
|
||||
func BatchListPostReactions(tx *gorm.DB, indexField string) (map[uint]map[string]int64, error) {
|
||||
var reactions []struct {
|
||||
ID uint
|
||||
Symbol string
|
||||
Count int64
|
||||
}
|
||||
|
||||
reactInfo := map[uint]map[string]int64{}
|
||||
if err := tx.Model(&models.Reaction{}).
|
||||
Select(fmt.Sprintf("%s as id, symbol, COUNT(*) as count", indexField)).
|
||||
Group("id, symbol").
|
||||
Scan(&reactions).Error; err != nil {
|
||||
return reactInfo, err
|
||||
}
|
||||
|
||||
for _, info := range reactions {
|
||||
if _, ok := reactInfo[info.ID]; !ok {
|
||||
reactInfo[info.ID] = make(map[string]int64)
|
||||
}
|
||||
if _, exists := reactInfo[info.ID][info.Symbol]; exists {
|
||||
reactInfo[info.ID][info.Symbol] += info.Count
|
||||
} else {
|
||||
reactInfo[info.ID][info.Symbol] = info.Count
|
||||
}
|
||||
}
|
||||
|
||||
return reactInfo, nil
|
||||
}
|
308
pkg/internal/services/subscriptions.go
Normal file
308
pkg/internal/services/subscriptions.go
Normal file
@ -0,0 +1,308 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/proto"
|
||||
"git.solsynth.dev/hypernet/passport/pkg/authkit"
|
||||
authm "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
|
||||
"git.solsynth.dev/hypernet/pusher/pkg/pushkit"
|
||||
"github.com/samber/lo"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func GetSubscriptionOnUser(user authm.Account, target models.Publisher) (*models.Subscription, error) {
|
||||
var subscription models.Subscription
|
||||
if err := database.C.Where("follower_id = ? AND account_id = ?", user.ID, target.ID).First(&subscription).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("unable to get subscription: %v", err)
|
||||
}
|
||||
return &subscription, nil
|
||||
}
|
||||
|
||||
func GetSubscriptionOnTag(user authm.Account, target models.Tag) (*models.Subscription, error) {
|
||||
var subscription models.Subscription
|
||||
if err := database.C.Where("follower_id = ? AND tag_id = ?", user.ID, target.ID).First(&subscription).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("unable to get subscription: %v", err)
|
||||
}
|
||||
return &subscription, nil
|
||||
}
|
||||
|
||||
func GetSubscriptionOnCategory(user authm.Account, target models.Category) (*models.Subscription, error) {
|
||||
var subscription models.Subscription
|
||||
if err := database.C.Where("follower_id = ? AND category_id = ?", user.ID, target.ID).First(&subscription).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("unable to get subscription: %v", err)
|
||||
}
|
||||
return &subscription, nil
|
||||
}
|
||||
|
||||
func SubscribeToUser(user authm.Account, target models.Publisher) (models.Subscription, error) {
|
||||
var subscription models.Subscription
|
||||
if err := database.C.Where("follower_id = ? AND account_id = ?", user.ID, target.ID).First(&subscription).Error; err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return subscription, fmt.Errorf("subscription already exists")
|
||||
}
|
||||
}
|
||||
|
||||
subscription = models.Subscription{
|
||||
FollowerID: user.ID,
|
||||
AccountID: &target.ID,
|
||||
}
|
||||
|
||||
err := database.C.Save(&subscription).Error
|
||||
return subscription, err
|
||||
}
|
||||
|
||||
func SubscribeToTag(user authm.Account, target models.Tag) (models.Subscription, error) {
|
||||
var subscription models.Subscription
|
||||
if err := database.C.Where("follower_id = ? AND tag_id = ?", user.ID, target.ID).First(&subscription).Error; err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return subscription, fmt.Errorf("subscription already exists")
|
||||
}
|
||||
}
|
||||
|
||||
subscription = models.Subscription{
|
||||
FollowerID: user.ID,
|
||||
TagID: &target.ID,
|
||||
}
|
||||
|
||||
err := database.C.Save(&subscription).Error
|
||||
return subscription, err
|
||||
}
|
||||
|
||||
func SubscribeToCategory(user authm.Account, target models.Category) (models.Subscription, error) {
|
||||
var subscription models.Subscription
|
||||
if err := database.C.Where("follower_id = ? AND category_id = ?", user.ID, target.ID).First(&subscription).Error; err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return subscription, fmt.Errorf("subscription already exists")
|
||||
}
|
||||
}
|
||||
|
||||
subscription = models.Subscription{
|
||||
FollowerID: user.ID,
|
||||
CategoryID: &target.ID,
|
||||
}
|
||||
|
||||
err := database.C.Save(&subscription).Error
|
||||
return subscription, err
|
||||
}
|
||||
|
||||
func UnsubscribeFromUser(user authm.Account, target models.Publisher) error {
|
||||
var subscription models.Subscription
|
||||
if err := database.C.Where("follower_id = ? AND account_id = ?", user.ID, target.ID).First(&subscription).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("subscription does not exist")
|
||||
}
|
||||
return fmt.Errorf("unable to check subscription is exists or not: %v", err)
|
||||
}
|
||||
|
||||
err := database.C.Delete(&subscription).Error
|
||||
return err
|
||||
}
|
||||
|
||||
func UnsubscribeFromTag(user authm.Account, target models.Tag) error {
|
||||
var subscription models.Subscription
|
||||
if err := database.C.Where("follower_id = ? AND tag_id = ?", user.ID, target.ID).First(&subscription).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("subscription does not exist")
|
||||
}
|
||||
return fmt.Errorf("unable to check subscription is exists or not: %v", err)
|
||||
}
|
||||
|
||||
err := database.C.Delete(&subscription).Error
|
||||
return err
|
||||
}
|
||||
|
||||
func UnsubscribeFromCategory(user authm.Account, target models.Category) error {
|
||||
var subscription models.Subscription
|
||||
if err := database.C.Where("follower_id = ? AND category_id = ?", user.ID, target.ID).First(&subscription).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("subscription does not exist")
|
||||
}
|
||||
return fmt.Errorf("unable to check subscription is exists or not: %v", err)
|
||||
}
|
||||
|
||||
err := database.C.Delete(&subscription).Error
|
||||
return err
|
||||
}
|
||||
|
||||
func NotifyUserSubscription(poster models.Publisher, item models.Post, content string, title *string) error {
|
||||
if item.Visibility == models.PostVisibilityNone {
|
||||
return nil
|
||||
}
|
||||
|
||||
var subscriptions []models.Subscription
|
||||
if err := database.C.Where("account_id = ?", poster.ID).Find(&subscriptions).Error; err != nil {
|
||||
return fmt.Errorf("unable to get subscriptions: %v", err)
|
||||
}
|
||||
|
||||
nTitle := fmt.Sprintf("New post from %s (%s)", poster.Nick, poster.Name)
|
||||
nSubtitle := "From your subscription"
|
||||
|
||||
body := TruncatePostContentShort(content)
|
||||
if title != nil {
|
||||
body = fmt.Sprintf("%s\n%s", *title, body)
|
||||
}
|
||||
|
||||
userIDs := make([]uint64, 0, len(subscriptions))
|
||||
for _, subscription := range subscriptions {
|
||||
userIDs = append(userIDs, uint64(subscription.FollowerID))
|
||||
}
|
||||
|
||||
if item.Visibility == models.PostVisibilitySelected {
|
||||
userIDs = lo.Filter(userIDs, func(entry uint64, index int) bool {
|
||||
return lo.Contains(item.VisibleUsers, uint(entry))
|
||||
})
|
||||
} else if item.Visibility == models.PostVisibilityFiltered {
|
||||
userIDs = lo.Filter(userIDs, func(entry uint64, index int) bool {
|
||||
return !lo.Contains(item.InvisibleUsers, uint(entry))
|
||||
})
|
||||
} else if invisibleList := ListPostInvisibleUser(poster, item.Visibility); len(invisibleList) > 0 {
|
||||
userIDs = lo.Filter(userIDs, func(entry uint64, index int) bool {
|
||||
return !lo.Contains(invisibleList, uint(entry))
|
||||
})
|
||||
}
|
||||
|
||||
metadata := map[string]any{
|
||||
"related_post": TruncatePostContent(item),
|
||||
}
|
||||
|
||||
err := authkit.NotifyUserBatch(gap.Nx, userIDs, pushkit.Notification{
|
||||
Topic: "interactive.subscription",
|
||||
Title: nTitle,
|
||||
Subtitle: nSubtitle,
|
||||
Body: body,
|
||||
Metadata: metadata,
|
||||
Priority: 3,
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func NotifyTagSubscription(poster models.Tag, og models.Publisher, item models.Post, content string, title *string) error {
|
||||
if item.Visibility == models.PostVisibilityNone {
|
||||
return nil
|
||||
}
|
||||
|
||||
var subscriptions []models.Subscription
|
||||
if err := database.C.Where("tag_id = ?", poster.ID).Find(&subscriptions).Error; err != nil {
|
||||
return fmt.Errorf("unable to get subscriptions: %v", err)
|
||||
}
|
||||
|
||||
nTitle := fmt.Sprintf("New post in %s by %s (%s)", poster.Name, og.Nick, og.Name)
|
||||
nSubtitle := "From your subscription"
|
||||
|
||||
body := TruncatePostContentShort(content)
|
||||
if title != nil {
|
||||
body = fmt.Sprintf("%s\n%s", *title, body)
|
||||
}
|
||||
|
||||
userIDs := make([]uint64, 0, len(subscriptions))
|
||||
for _, subscription := range subscriptions {
|
||||
userIDs = append(userIDs, uint64(subscription.FollowerID))
|
||||
}
|
||||
|
||||
if item.Visibility == models.PostVisibilitySelected {
|
||||
userIDs = lo.Filter(userIDs, func(entry uint64, index int) bool {
|
||||
return lo.Contains(item.VisibleUsers, uint(entry))
|
||||
})
|
||||
} else if item.Visibility == models.PostVisibilityFiltered {
|
||||
userIDs = lo.Filter(userIDs, func(entry uint64, index int) bool {
|
||||
return !lo.Contains(item.InvisibleUsers, uint(entry))
|
||||
})
|
||||
} else if invisibleList := ListPostInvisibleUser(item.Publisher, item.Visibility); len(invisibleList) > 0 {
|
||||
userIDs = lo.Filter(userIDs, func(entry uint64, index int) bool {
|
||||
return !lo.Contains(invisibleList, uint(entry))
|
||||
})
|
||||
}
|
||||
|
||||
err := authkit.NotifyUserBatch(gap.Nx, userIDs, pushkit.Notification{
|
||||
Topic: "interactive.subscription",
|
||||
Title: nTitle,
|
||||
Subtitle: nSubtitle,
|
||||
Body: body,
|
||||
Priority: 3,
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func NotifyCategorySubscription(poster models.Category, og models.Publisher, item models.Post, content string, title *string) error {
|
||||
if item.Visibility == models.PostVisibilityNone {
|
||||
return nil
|
||||
}
|
||||
|
||||
var subscriptions []models.Subscription
|
||||
if err := database.C.Where("category_id = ?", poster.ID).Find(&subscriptions).Error; err != nil {
|
||||
return fmt.Errorf("unable to get subscriptions: %v", err)
|
||||
}
|
||||
|
||||
nTitle := fmt.Sprintf("New post in %s by %s (%s)", poster.Name, og.Nick, og.Name)
|
||||
nSubtitle := "From your subscription"
|
||||
|
||||
body := TruncatePostContentShort(content)
|
||||
if title != nil {
|
||||
body = fmt.Sprintf("%s\n%s", *title, body)
|
||||
}
|
||||
|
||||
userIDs := make([]uint64, 0, len(subscriptions))
|
||||
for _, subscription := range subscriptions {
|
||||
userIDs = append(userIDs, uint64(subscription.FollowerID))
|
||||
}
|
||||
|
||||
if item.Visibility == models.PostVisibilitySelected {
|
||||
userIDs = lo.Filter(userIDs, func(entry uint64, index int) bool {
|
||||
return lo.Contains(item.VisibleUsers, uint(entry))
|
||||
})
|
||||
} else if item.Visibility == models.PostVisibilityFiltered {
|
||||
userIDs = lo.Filter(userIDs, func(entry uint64, index int) bool {
|
||||
return !lo.Contains(item.InvisibleUsers, uint(entry))
|
||||
})
|
||||
} else if invisibleList := ListPostInvisibleUser(item.Publisher, item.Visibility); len(invisibleList) > 0 {
|
||||
userIDs = lo.Filter(userIDs, func(entry uint64, index int) bool {
|
||||
return !lo.Contains(invisibleList, uint(entry))
|
||||
})
|
||||
}
|
||||
|
||||
err := authkit.NotifyUserBatch(gap.Nx, userIDs, pushkit.Notification{
|
||||
Topic: "interactive.subscription",
|
||||
Title: nTitle,
|
||||
Subtitle: nSubtitle,
|
||||
Body: body,
|
||||
Priority: 3,
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ListPostInvisibleUser will return a list of users which should not be notified the post.
|
||||
// NOTICE If the visibility is PostVisibilitySelected, PostVisibilityFiltered or PostVisibilityNone, you need do extra steps to filter users
|
||||
// WARNING This function won't use cache, be careful of the queries
|
||||
func ListPostInvisibleUser(og models.Publisher, visibility models.PostVisibilityLevel) []uint {
|
||||
switch visibility {
|
||||
case models.PostVisibilityAll:
|
||||
return []uint{}
|
||||
case models.PostVisibilityFriends:
|
||||
if og.AccountID == nil {
|
||||
return []uint{}
|
||||
}
|
||||
userFriends, _ := authkit.ListRelative(gap.Nx, *og.AccountID, int32(authm.RelationshipFriend), true)
|
||||
return lo.Map(userFriends, func(item *proto.UserInfo, index int) uint {
|
||||
return uint(item.GetId())
|
||||
})
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
30
pkg/internal/services/tags.go
Normal file
30
pkg/internal/services/tags.go
Normal file
@ -0,0 +1,30 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/models"
|
||||
)
|
||||
|
||||
func ListTags(take int, offset int) ([]models.Tag, error) {
|
||||
var tags []models.Tag
|
||||
err := database.C.Offset(offset).Limit(take).Find(&tags).Error
|
||||
|
||||
return tags, err
|
||||
}
|
||||
|
||||
func SearchTags(take int, offset int, probe string) ([]models.Tag, error) {
|
||||
probe = "%" + probe + "%"
|
||||
|
||||
var tags []models.Tag
|
||||
err := database.C.Where("alias LIKE ?", probe).Offset(offset).Limit(take).Find(&tags).Error
|
||||
|
||||
return tags, err
|
||||
}
|
||||
|
||||
func GetTag(alias string) (models.Tag, error) {
|
||||
var tag models.Tag
|
||||
if err := database.C.Where(models.Tag{Alias: alias}).First(&tag).Error; err != nil {
|
||||
return tag, err
|
||||
}
|
||||
return tag, nil
|
||||
}
|
83
pkg/main.go
Normal file
83
pkg/main.go
Normal file
@ -0,0 +1,83 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
pkg "git.solsynth.dev/hypernet/interactive/pkg/internal"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/gap"
|
||||
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
|
||||
"github.com/fatih/color"
|
||||
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/database"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/grpc"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/http"
|
||||
"git.solsynth.dev/hypernet/interactive/pkg/internal/services"
|
||||
"github.com/robfig/cron/v3"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func init() {
|
||||
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout})
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Booting screen
|
||||
fmt.Println(color.YellowString(" ___ _ _ _\n|_ _|_ __ | |_ ___ _ __ __ _ ___| |_(_)_ _____\n | || '_ \\| __/ _ \\ '__/ _` |/ __| __| \\ \\ / / _ \\\n | || | | | || __/ | | (_| | (__| |_| |\\ V / __/\n|___|_| |_|\\__\\___|_| \\__,_|\\___|\\__|_| \\_/ \\___|"))
|
||||
fmt.Printf("%s v%s\n", color.New(color.FgHiYellow).Add(color.Bold).Sprintf("Hypernet.Interactive"), pkg.AppVersion)
|
||||
fmt.Printf("The social networking service in Hypernet\n")
|
||||
color.HiBlack("=====================================================\n")
|
||||
|
||||
// Configure settings
|
||||
viper.AddConfigPath(".")
|
||||
viper.AddConfigPath("..")
|
||||
viper.SetConfigName("settings")
|
||||
viper.SetConfigType("toml")
|
||||
|
||||
// Load settings
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
log.Panic().Err(err).Msg("An error occurred when loading settings.")
|
||||
}
|
||||
|
||||
// Connect to nexus
|
||||
if err := gap.InitializeToNexus(); err != nil {
|
||||
log.Fatal().Err(err).Msg("An error occurred when connecting to nexus...")
|
||||
}
|
||||
|
||||
// Load keypair
|
||||
if reader, err := sec.NewInternalTokenReader(viper.GetString("security.internal_public_key")); err != nil {
|
||||
log.Error().Err(err).Msg("An error occurred when reading internal public key for jwt. Authentication related features will be disabled.")
|
||||
} else {
|
||||
http.IReader = reader
|
||||
log.Info().Msg("Internal jwt public key loaded.")
|
||||
}
|
||||
|
||||
// Connect to database
|
||||
if err := database.NewGorm(); err != nil {
|
||||
log.Fatal().Err(err).Msg("An error occurred when connect to database.")
|
||||
} else if err := database.RunMigration(database.C); err != nil {
|
||||
log.Fatal().Err(err).Msg("An error occurred when running database auto migration.")
|
||||
}
|
||||
|
||||
// Configure timed tasks
|
||||
quartz := cron.New(cron.WithLogger(cron.VerbosePrintfLogger(&log.Logger)))
|
||||
quartz.AddFunc("@every 5m", services.FlushPostViews)
|
||||
quartz.Start()
|
||||
|
||||
// App
|
||||
go http.NewServer().Listen()
|
||||
|
||||
go grpc.NewGrpc().Listen()
|
||||
|
||||
// Messages
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-quit
|
||||
|
||||
quartz.Stop()
|
||||
}
|
@ -1,34 +0,0 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// Account profiles basically fetched from Hydrogen.Identity
|
||||
// But cache at here for better usage
|
||||
// At the same time this model can make relations between local models
|
||||
type Account struct {
|
||||
BaseModel
|
||||
|
||||
Name string `json:"name"`
|
||||
Nick string `json:"nick"`
|
||||
Avatar string `json:"avatar"`
|
||||
Description string `json:"description"`
|
||||
EmailAddress string `json:"email_address"`
|
||||
PowerLevel int `json:"power_level"`
|
||||
Moments []Moment `json:"moments" gorm:"foreignKey:AuthorID"`
|
||||
Articles []Article `json:"articles" gorm:"foreignKey:AuthorID"`
|
||||
Attachments []Attachment `json:"attachments" gorm:"foreignKey:AuthorID"`
|
||||
Reactions []Reaction `json:"reactions"`
|
||||
RealmIdentities []RealmMember `json:"identities"`
|
||||
Realms []Realm `json:"realms"`
|
||||
ExternalID uint `json:"external_id"`
|
||||
}
|
||||
|
||||
type AccountMembership struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Follower Account `json:"follower"`
|
||||
Following Account `json:"following"`
|
||||
FollowerID uint
|
||||
FollowingID uint
|
||||
}
|
@ -1,41 +0,0 @@
|
||||
package models
|
||||
|
||||
type Article struct {
|
||||
PostBase
|
||||
|
||||
Title string `json:"title"`
|
||||
Hashtags []Tag `json:"tags" gorm:"many2many:article_tags"`
|
||||
Categories []Category `json:"categories" gorm:"many2many:article_categories"`
|
||||
Reactions []Reaction `json:"reactions"`
|
||||
Attachments []Attachment `json:"attachments"`
|
||||
Description string `json:"description"`
|
||||
Content string `json:"content"`
|
||||
RealmID *uint `json:"realm_id"`
|
||||
Realm *Realm `json:"realm"`
|
||||
|
||||
Comments []Comment `json:"comments" gorm:"foreignKey:ArticleID"`
|
||||
}
|
||||
|
||||
func (p *Article) GetReplyTo() PostInterface {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Article) GetRepostTo() PostInterface {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Article) GetHashtags() []Tag {
|
||||
return p.Hashtags
|
||||
}
|
||||
|
||||
func (p *Article) GetCategories() []Category {
|
||||
return p.Categories
|
||||
}
|
||||
|
||||
func (p *Article) SetHashtags(tags []Tag) {
|
||||
p.Hashtags = tags
|
||||
}
|
||||
|
||||
func (p *Article) SetCategories(categories []Category) {
|
||||
p.Categories = categories
|
||||
}
|
@ -1,42 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type AttachmentType = uint8
|
||||
|
||||
const (
|
||||
AttachmentOthers = AttachmentType(iota)
|
||||
AttachmentPhoto
|
||||
AttachmentVideo
|
||||
AttachmentAudio
|
||||
)
|
||||
|
||||
type Attachment struct {
|
||||
BaseModel
|
||||
|
||||
FileID string `json:"file_id"`
|
||||
Filesize int64 `json:"filesize"`
|
||||
Filename string `json:"filename"`
|
||||
Mimetype string `json:"mimetype"`
|
||||
Type AttachmentType `json:"type"`
|
||||
ExternalUrl string `json:"external_url"`
|
||||
Author Account `json:"author"`
|
||||
ArticleID *uint `json:"article_id"`
|
||||
MomentID *uint `json:"moment_id"`
|
||||
CommentID *uint `json:"comment_id"`
|
||||
AuthorID uint `json:"author_id"`
|
||||
}
|
||||
|
||||
func (v Attachment) GetStoragePath() string {
|
||||
basepath := viper.GetString("content")
|
||||
return filepath.Join(basepath, v.FileID)
|
||||
}
|
||||
|
||||
func (v Attachment) GetAccessPath() string {
|
||||
return fmt.Sprintf("/api/attachments/o/%s", v.FileID)
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type JSONMap = datatypes.JSONType[map[string]any]
|
||||
|
||||
type BaseModel struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
|
||||
}
|
@ -1,23 +0,0 @@
|
||||
package models
|
||||
|
||||
type Tag struct {
|
||||
BaseModel
|
||||
|
||||
Alias string `json:"alias" gorm:"uniqueIndex" validate:"lowercase,alphanum,min=4,max=24"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Articles []Article `json:"articles" gorm:"many2many:article_tags"`
|
||||
Moments []Moment `json:"moments" gorm:"many2many:moment_tags"`
|
||||
Comments []Comment `json:"comments" gorm:"many2many:comment_tags"`
|
||||
}
|
||||
|
||||
type Category struct {
|
||||
BaseModel
|
||||
|
||||
Alias string `json:"alias" gorm:"uniqueIndex" validate:"lowercase,alphanum,min=4,max=24"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Articles []Article `json:"articles" gorm:"many2many:article_categories"`
|
||||
Moments []Moment `json:"moments" gorm:"many2many:moment_categories"`
|
||||
Comments []Comment `json:"comments" gorm:"many2many:comment_categories"`
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
package models
|
||||
|
||||
type Comment struct {
|
||||
PostBase
|
||||
|
||||
Content string `json:"content"`
|
||||
Hashtags []Tag `json:"tags" gorm:"many2many:comment_tags"`
|
||||
Categories []Category `json:"categories" gorm:"many2many:comment_categories"`
|
||||
Reactions []Reaction `json:"reactions"`
|
||||
ReplyID *uint `json:"reply_id"`
|
||||
ReplyTo *Comment `json:"reply_to" gorm:"foreignKey:ReplyID"`
|
||||
|
||||
ArticleID *uint `json:"article_id"`
|
||||
MomentID *uint `json:"moment_id"`
|
||||
Article *Article `json:"article"`
|
||||
Moment *Moment `json:"moment"`
|
||||
}
|
||||
|
||||
func (p *Comment) GetReplyTo() PostInterface {
|
||||
return p.ReplyTo
|
||||
}
|
||||
|
||||
func (p *Comment) GetHashtags() []Tag {
|
||||
return p.Hashtags
|
||||
}
|
||||
|
||||
func (p *Comment) GetCategories() []Category {
|
||||
return p.Categories
|
||||
}
|
||||
|
||||
func (p *Comment) SetHashtags(tags []Tag) {
|
||||
p.Hashtags = tags
|
||||
}
|
||||
|
||||
func (p *Comment) SetCategories(categories []Category) {
|
||||
p.Categories = categories
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
package models
|
||||
|
||||
type Feed struct {
|
||||
BaseModel
|
||||
|
||||
Alias string `json:"alias"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Content string `json:"content"`
|
||||
ModelType string `json:"model_type"`
|
||||
|
||||
CommentCount int64 `json:"comment_count"`
|
||||
ReactionCount int64 `json:"reaction_count"`
|
||||
|
||||
AuthorID uint `json:"author_id"`
|
||||
RealmID *uint `json:"realm_id"`
|
||||
|
||||
Author Account `json:"author" gorm:"embedded"`
|
||||
|
||||
Attachments []Attachment `json:"attachments" gorm:"-"`
|
||||
ReactionList map[string]int64 `json:"reaction_list" gorm:"-"`
|
||||
}
|
@ -1,41 +0,0 @@
|
||||
package models
|
||||
|
||||
type Moment struct {
|
||||
PostBase
|
||||
|
||||
Content string `json:"content"`
|
||||
Hashtags []Tag `json:"tags" gorm:"many2many:moment_tags"`
|
||||
Categories []Category `json:"categories" gorm:"many2many:moment_categories"`
|
||||
Reactions []Reaction `json:"reactions"`
|
||||
Attachments []Attachment `json:"attachments"`
|
||||
RealmID *uint `json:"realm_id"`
|
||||
RepostID *uint `json:"repost_id"`
|
||||
Realm *Realm `json:"realm"`
|
||||
RepostTo *Moment `json:"repost_to" gorm:"foreignKey:RepostID"`
|
||||
|
||||
Comments []Comment `json:"comments" gorm:"foreignKey:MomentID"`
|
||||
}
|
||||
|
||||
func (p *Moment) GetRepostTo() PostInterface {
|
||||
return p.RepostTo
|
||||
}
|
||||
|
||||
func (p *Moment) GetRealm() *Realm {
|
||||
return p.Realm
|
||||
}
|
||||
|
||||
func (p *Moment) GetHashtags() []Tag {
|
||||
return p.Hashtags
|
||||
}
|
||||
|
||||
func (p *Moment) GetCategories() []Category {
|
||||
return p.Categories
|
||||
}
|
||||
|
||||
func (p *Moment) SetHashtags(tags []Tag) {
|
||||
p.Hashtags = tags
|
||||
}
|
||||
|
||||
func (p *Moment) SetCategories(categories []Category) {
|
||||
p.Categories = categories
|
||||
}
|
@ -1,64 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type PostReactInfo struct {
|
||||
PostID uint `json:"post_id"`
|
||||
LikeCount int64 `json:"like_count"`
|
||||
DislikeCount int64 `json:"dislike_count"`
|
||||
ReplyCount int64 `json:"reply_count"`
|
||||
RepostCount int64 `json:"repost_count"`
|
||||
}
|
||||
|
||||
type PostBase struct {
|
||||
BaseModel
|
||||
|
||||
Alias string `json:"alias" gorm:"uniqueIndex"`
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
|
||||
AuthorID uint `json:"author_id"`
|
||||
Author Account `json:"author"`
|
||||
|
||||
// Dynamic Calculated Values
|
||||
ReactionList map[string]int64 `json:"reaction_list" gorm:"-"`
|
||||
}
|
||||
|
||||
func (p *PostBase) GetID() uint {
|
||||
return p.ID
|
||||
}
|
||||
|
||||
func (p *PostBase) GetReplyTo() PostInterface {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *PostBase) GetRepostTo() PostInterface {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *PostBase) GetAuthor() Account {
|
||||
return p.Author
|
||||
}
|
||||
|
||||
func (p *PostBase) GetRealm() *Realm {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *PostBase) SetReactionList(list map[string]int64) {
|
||||
p.ReactionList = list
|
||||
}
|
||||
|
||||
type PostInterface interface {
|
||||
GetID() uint
|
||||
GetHashtags() []Tag
|
||||
GetCategories() []Category
|
||||
GetReplyTo() PostInterface
|
||||
GetRepostTo() PostInterface
|
||||
GetAuthor() Account
|
||||
GetRealm() *Realm
|
||||
|
||||
SetHashtags([]Tag)
|
||||
SetCategories([]Category)
|
||||
SetReactionList(map[string]int64)
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
package models
|
||||
|
||||
type RealmType = int
|
||||
|
||||
const (
|
||||
RealmTypePublic = RealmType(iota)
|
||||
RealmTypeRestricted
|
||||
RealmTypePrivate
|
||||
)
|
||||
|
||||
type Realm struct {
|
||||
BaseModel
|
||||
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Articles []Article `json:"article"`
|
||||
Moments []Moment `json:"moments"`
|
||||
Members []RealmMember `json:"members"`
|
||||
RealmType RealmType `json:"realm_type"`
|
||||
AccountID uint `json:"account_id"`
|
||||
}
|
||||
|
||||
type RealmMember struct {
|
||||
BaseModel
|
||||
|
||||
RealmID uint `json:"realm_id"`
|
||||
AccountID uint `json:"account_id"`
|
||||
}
|
271
pkg/proto/feed.pb.go
Normal file
271
pkg/proto/feed.pb.go
Normal file
@ -0,0 +1,271 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.35.1
|
||||
// protoc v5.28.3
|
||||
// source: feed.proto
|
||||
|
||||
package proto
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type FeedItem struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"`
|
||||
CreatedAt uint64 `protobuf:"varint,2,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"`
|
||||
Content []byte `protobuf:"bytes,3,opt,name=content,proto3" json:"content,omitempty"`
|
||||
}
|
||||
|
||||
func (x *FeedItem) Reset() {
|
||||
*x = FeedItem{}
|
||||
mi := &file_feed_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *FeedItem) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*FeedItem) ProtoMessage() {}
|
||||
|
||||
func (x *FeedItem) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_feed_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use FeedItem.ProtoReflect.Descriptor instead.
|
||||
func (*FeedItem) Descriptor() ([]byte, []int) {
|
||||
return file_feed_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *FeedItem) GetType() string {
|
||||
if x != nil {
|
||||
return x.Type
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *FeedItem) GetCreatedAt() uint64 {
|
||||
if x != nil {
|
||||
return x.CreatedAt
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *FeedItem) GetContent() []byte {
|
||||
if x != nil {
|
||||
return x.Content
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type GetFeedRequest struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Limit int64 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"`
|
||||
UserId uint64 `protobuf:"varint,2,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
|
||||
Cursor *uint64 `protobuf:"varint,3,opt,name=cursor,proto3,oneof" json:"cursor,omitempty"`
|
||||
}
|
||||
|
||||
func (x *GetFeedRequest) Reset() {
|
||||
*x = GetFeedRequest{}
|
||||
mi := &file_feed_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *GetFeedRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GetFeedRequest) ProtoMessage() {}
|
||||
|
||||
func (x *GetFeedRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_feed_proto_msgTypes[1]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetFeedRequest.ProtoReflect.Descriptor instead.
|
||||
func (*GetFeedRequest) Descriptor() ([]byte, []int) {
|
||||
return file_feed_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *GetFeedRequest) GetLimit() int64 {
|
||||
if x != nil {
|
||||
return x.Limit
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *GetFeedRequest) GetUserId() uint64 {
|
||||
if x != nil {
|
||||
return x.UserId
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *GetFeedRequest) GetCursor() uint64 {
|
||||
if x != nil && x.Cursor != nil {
|
||||
return *x.Cursor
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type GetFeedResponse struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
Items []*FeedItem `protobuf:"bytes,1,rep,name=items,proto3" json:"items,omitempty"`
|
||||
}
|
||||
|
||||
func (x *GetFeedResponse) Reset() {
|
||||
*x = GetFeedResponse{}
|
||||
mi := &file_feed_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *GetFeedResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GetFeedResponse) ProtoMessage() {}
|
||||
|
||||
func (x *GetFeedResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_feed_proto_msgTypes[2]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetFeedResponse.ProtoReflect.Descriptor instead.
|
||||
func (*GetFeedResponse) Descriptor() ([]byte, []int) {
|
||||
return file_feed_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *GetFeedResponse) GetItems() []*FeedItem {
|
||||
if x != nil {
|
||||
return x.Items
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_feed_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_feed_proto_rawDesc = []byte{
|
||||
0x0a, 0x0a, 0x66, 0x65, 0x65, 0x64, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x05, 0x70, 0x72,
|
||||
0x6f, 0x74, 0x6f, 0x22, 0x57, 0x0a, 0x08, 0x46, 0x65, 0x65, 0x64, 0x49, 0x74, 0x65, 0x6d, 0x12,
|
||||
0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74,
|
||||
0x79, 0x70, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x61,
|
||||
0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64,
|
||||
0x41, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x03, 0x20,
|
||||
0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x22, 0x67, 0x0a, 0x0e,
|
||||
0x47, 0x65, 0x74, 0x46, 0x65, 0x65, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14,
|
||||
0x0a, 0x05, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x6c,
|
||||
0x69, 0x6d, 0x69, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18,
|
||||
0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x12, 0x1b, 0x0a,
|
||||
0x06, 0x63, 0x75, 0x72, 0x73, 0x6f, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x48, 0x00, 0x52,
|
||||
0x06, 0x63, 0x75, 0x72, 0x73, 0x6f, 0x72, 0x88, 0x01, 0x01, 0x42, 0x09, 0x0a, 0x07, 0x5f, 0x63,
|
||||
0x75, 0x72, 0x73, 0x6f, 0x72, 0x22, 0x38, 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x46, 0x65, 0x65, 0x64,
|
||||
0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x25, 0x0a, 0x05, 0x69, 0x74, 0x65, 0x6d,
|
||||
0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e,
|
||||
0x46, 0x65, 0x65, 0x64, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x05, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x32,
|
||||
0x47, 0x0a, 0x0b, 0x46, 0x65, 0x65, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x38,
|
||||
0x0a, 0x07, 0x47, 0x65, 0x74, 0x46, 0x65, 0x65, 0x64, 0x12, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74,
|
||||
0x6f, 0x2e, 0x47, 0x65, 0x74, 0x46, 0x65, 0x65, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74,
|
||||
0x1a, 0x16, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x47, 0x65, 0x74, 0x46, 0x65, 0x65, 0x64,
|
||||
0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x09, 0x5a, 0x07, 0x2e, 0x3b, 0x70, 0x72,
|
||||
0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_feed_proto_rawDescOnce sync.Once
|
||||
file_feed_proto_rawDescData = file_feed_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_feed_proto_rawDescGZIP() []byte {
|
||||
file_feed_proto_rawDescOnce.Do(func() {
|
||||
file_feed_proto_rawDescData = protoimpl.X.CompressGZIP(file_feed_proto_rawDescData)
|
||||
})
|
||||
return file_feed_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_feed_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
|
||||
var file_feed_proto_goTypes = []any{
|
||||
(*FeedItem)(nil), // 0: proto.FeedItem
|
||||
(*GetFeedRequest)(nil), // 1: proto.GetFeedRequest
|
||||
(*GetFeedResponse)(nil), // 2: proto.GetFeedResponse
|
||||
}
|
||||
var file_feed_proto_depIdxs = []int32{
|
||||
0, // 0: proto.GetFeedResponse.items:type_name -> proto.FeedItem
|
||||
1, // 1: proto.FeedService.GetFeed:input_type -> proto.GetFeedRequest
|
||||
2, // 2: proto.FeedService.GetFeed:output_type -> proto.GetFeedResponse
|
||||
2, // [2:3] is the sub-list for method output_type
|
||||
1, // [1:2] is the sub-list for method input_type
|
||||
1, // [1:1] is the sub-list for extension type_name
|
||||
1, // [1:1] is the sub-list for extension extendee
|
||||
0, // [0:1] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_feed_proto_init() }
|
||||
func file_feed_proto_init() {
|
||||
if File_feed_proto != nil {
|
||||
return
|
||||
}
|
||||
file_feed_proto_msgTypes[1].OneofWrappers = []any{}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_feed_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 3,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_feed_proto_goTypes,
|
||||
DependencyIndexes: file_feed_proto_depIdxs,
|
||||
MessageInfos: file_feed_proto_msgTypes,
|
||||
}.Build()
|
||||
File_feed_proto = out.File
|
||||
file_feed_proto_rawDesc = nil
|
||||
file_feed_proto_goTypes = nil
|
||||
file_feed_proto_depIdxs = nil
|
||||
}
|
25
pkg/proto/feed.proto
Normal file
25
pkg/proto/feed.proto
Normal file
@ -0,0 +1,25 @@
|
||||
syntax = "proto3";
|
||||
|
||||
option go_package = ".;proto";
|
||||
|
||||
package proto;
|
||||
|
||||
service FeedService {
|
||||
rpc GetFeed(GetFeedRequest) returns (GetFeedResponse);
|
||||
}
|
||||
|
||||
message FeedItem {
|
||||
string type = 1;
|
||||
uint64 created_at = 2;
|
||||
bytes content = 3;
|
||||
}
|
||||
|
||||
message GetFeedRequest {
|
||||
int64 limit = 1;
|
||||
uint64 user_id = 2;
|
||||
optional uint64 cursor = 3;
|
||||
}
|
||||
|
||||
message GetFeedResponse {
|
||||
repeated FeedItem items = 1;
|
||||
}
|
121
pkg/proto/feed_grpc.pb.go
Normal file
121
pkg/proto/feed_grpc.pb.go
Normal file
@ -0,0 +1,121 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v5.28.3
|
||||
// source: feed.proto
|
||||
|
||||
package proto
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.64.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
FeedService_GetFeed_FullMethodName = "/proto.FeedService/GetFeed"
|
||||
)
|
||||
|
||||
// FeedServiceClient is the client API for FeedService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type FeedServiceClient interface {
|
||||
GetFeed(ctx context.Context, in *GetFeedRequest, opts ...grpc.CallOption) (*GetFeedResponse, error)
|
||||
}
|
||||
|
||||
type feedServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewFeedServiceClient(cc grpc.ClientConnInterface) FeedServiceClient {
|
||||
return &feedServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *feedServiceClient) GetFeed(ctx context.Context, in *GetFeedRequest, opts ...grpc.CallOption) (*GetFeedResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetFeedResponse)
|
||||
err := c.cc.Invoke(ctx, FeedService_GetFeed_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// FeedServiceServer is the server API for FeedService service.
|
||||
// All implementations must embed UnimplementedFeedServiceServer
|
||||
// for forward compatibility.
|
||||
type FeedServiceServer interface {
|
||||
GetFeed(context.Context, *GetFeedRequest) (*GetFeedResponse, error)
|
||||
mustEmbedUnimplementedFeedServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedFeedServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedFeedServiceServer struct{}
|
||||
|
||||
func (UnimplementedFeedServiceServer) GetFeed(context.Context, *GetFeedRequest) (*GetFeedResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetFeed not implemented")
|
||||
}
|
||||
func (UnimplementedFeedServiceServer) mustEmbedUnimplementedFeedServiceServer() {}
|
||||
func (UnimplementedFeedServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeFeedServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to FeedServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeFeedServiceServer interface {
|
||||
mustEmbedUnimplementedFeedServiceServer()
|
||||
}
|
||||
|
||||
func RegisterFeedServiceServer(s grpc.ServiceRegistrar, srv FeedServiceServer) {
|
||||
// If the following call pancis, it indicates UnimplementedFeedServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&FeedService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _FeedService_GetFeed_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetFeedRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(FeedServiceServer).GetFeed(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: FeedService_GetFeed_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(FeedServiceServer).GetFeed(ctx, req.(*GetFeedRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// FeedService_ServiceDesc is the grpc.ServiceDesc for FeedService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var FeedService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "proto.FeedService",
|
||||
HandlerType: (*FeedServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "GetFeed",
|
||||
Handler: _FeedService_GetFeed_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "feed.proto",
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
package security
|
||||
|
||||
import "golang.org/x/crypto/bcrypt"
|
||||
|
||||
func HashPassword(raw string) string {
|
||||
data, _ := bcrypt.GenerateFromPassword([]byte(raw), 12)
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func VerifyPassword(text string, password string) bool {
|
||||
return bcrypt.CompareHashAndPassword([]byte(password), []byte(text)) == nil
|
||||
}
|
@ -1,81 +0,0 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type PayloadClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
|
||||
Type string `json:"typ"`
|
||||
}
|
||||
|
||||
const (
|
||||
JwtAccessType = "access"
|
||||
JwtRefreshType = "refresh"
|
||||
)
|
||||
|
||||
const (
|
||||
CookieAccessKey = "identity_auth_key"
|
||||
CookieRefreshKey = "identity_refresh_key"
|
||||
)
|
||||
|
||||
func EncodeJwt(id string, typ, sub string, aud []string, exp time.Time) (string, error) {
|
||||
tk := jwt.NewWithClaims(jwt.SigningMethodHS512, PayloadClaims{
|
||||
jwt.RegisteredClaims{
|
||||
Subject: sub,
|
||||
Audience: aud,
|
||||
Issuer: fmt.Sprintf("https://%s", viper.GetString("domain")),
|
||||
ExpiresAt: jwt.NewNumericDate(exp),
|
||||
NotBefore: jwt.NewNumericDate(time.Now()),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
ID: id,
|
||||
},
|
||||
typ,
|
||||
})
|
||||
|
||||
return tk.SignedString([]byte(viper.GetString("secret")))
|
||||
}
|
||||
|
||||
func DecodeJwt(str string) (PayloadClaims, error) {
|
||||
var claims PayloadClaims
|
||||
tk, err := jwt.ParseWithClaims(str, &claims, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(viper.GetString("secret")), nil
|
||||
})
|
||||
if err != nil {
|
||||
return claims, err
|
||||
}
|
||||
|
||||
if data, ok := tk.Claims.(*PayloadClaims); ok {
|
||||
return *data, nil
|
||||
} else {
|
||||
return claims, fmt.Errorf("unexpected token payload: not payload claims type")
|
||||
}
|
||||
}
|
||||
|
||||
func SetJwtCookieSet(c *fiber.Ctx, access, refresh string) {
|
||||
c.Cookie(&fiber.Cookie{
|
||||
Name: CookieAccessKey,
|
||||
Value: access,
|
||||
Domain: viper.GetString("security.cookie_domain"),
|
||||
SameSite: viper.GetString("security.cookie_samesite"),
|
||||
Expires: time.Now().Add(60 * time.Minute),
|
||||
Path: "/",
|
||||
})
|
||||
c.Cookie(&fiber.Cookie{
|
||||
Name: CookieRefreshKey,
|
||||
Value: refresh,
|
||||
Domain: viper.GetString("security.cookie_domain"),
|
||||
SameSite: viper.GetString("security.cookie_samesite"),
|
||||
Expires: time.Now().Add(24 * 30 * time.Hour),
|
||||
Path: "/",
|
||||
})
|
||||
}
|
@ -1,140 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func contextArticle() *services.PostTypeContext {
|
||||
return &services.PostTypeContext{
|
||||
Tx: database.C,
|
||||
TableName: "articles",
|
||||
ColumnName: "article",
|
||||
CanReply: false,
|
||||
CanRepost: false,
|
||||
}
|
||||
}
|
||||
|
||||
func createArticle(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
|
||||
var data struct {
|
||||
Alias string `json:"alias" form:"alias"`
|
||||
Title string `json:"title" form:"title" validate:"required"`
|
||||
Description string `json:"description" form:"description"`
|
||||
Content string `json:"content" form:"content" validate:"required"`
|
||||
Hashtags []models.Tag `json:"hashtags" form:"hashtags"`
|
||||
Categories []models.Category `json:"categories" form:"categories"`
|
||||
Attachments []models.Attachment `json:"attachments" form:"attachments"`
|
||||
PublishedAt *time.Time `json:"published_at" form:"published_at"`
|
||||
RealmID *uint `json:"realm_id" form:"realm_id"`
|
||||
}
|
||||
|
||||
if err := BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
} else if len(data.Alias) == 0 {
|
||||
data.Alias = strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
}
|
||||
|
||||
item := &models.Article{
|
||||
PostBase: models.PostBase{
|
||||
Alias: data.Alias,
|
||||
PublishedAt: data.PublishedAt,
|
||||
AuthorID: user.ID,
|
||||
},
|
||||
Hashtags: data.Hashtags,
|
||||
Categories: data.Categories,
|
||||
Attachments: data.Attachments,
|
||||
Title: data.Title,
|
||||
Description: data.Description,
|
||||
Content: data.Content,
|
||||
RealmID: data.RealmID,
|
||||
}
|
||||
|
||||
var realm *models.Realm
|
||||
if data.RealmID != nil {
|
||||
if err := database.C.Where(&models.Realm{
|
||||
BaseModel: models.BaseModel{ID: *data.RealmID},
|
||||
}).First(&realm).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if item, err := services.NewPost(item); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
return c.JSON(item)
|
||||
}
|
||||
}
|
||||
|
||||
func editArticle(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
id, _ := c.ParamsInt("articleId", 0)
|
||||
|
||||
var data struct {
|
||||
Alias string `json:"alias" form:"alias" validate:"required"`
|
||||
Title string `json:"title" form:"title" validate:"required"`
|
||||
Description string `json:"description" form:"description"`
|
||||
Content string `json:"content" form:"content" validate:"required"`
|
||||
PublishedAt *time.Time `json:"published_at" form:"published_at"`
|
||||
Hashtags []models.Tag `json:"hashtags" form:"hashtags"`
|
||||
Categories []models.Category `json:"categories" form:"categories"`
|
||||
Attachments []models.Attachment `json:"attachments" form:"attachments"`
|
||||
}
|
||||
|
||||
if err := BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var item *models.Article
|
||||
if err := database.C.Where(models.Article{
|
||||
PostBase: models.PostBase{
|
||||
BaseModel: models.BaseModel{ID: uint(id)},
|
||||
AuthorID: user.ID,
|
||||
},
|
||||
}).First(&item).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
item.Alias = data.Alias
|
||||
item.Title = data.Title
|
||||
item.Description = data.Description
|
||||
item.Content = data.Content
|
||||
item.PublishedAt = data.PublishedAt
|
||||
item.Hashtags = data.Hashtags
|
||||
item.Categories = data.Categories
|
||||
item.Attachments = data.Attachments
|
||||
|
||||
if item, err := services.EditPost(item); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
return c.JSON(item)
|
||||
}
|
||||
}
|
||||
|
||||
func deleteArticle(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
id, _ := c.ParamsInt("articleId", 0)
|
||||
|
||||
var item *models.Article
|
||||
if err := database.C.Where(models.Article{
|
||||
PostBase: models.PostBase{
|
||||
BaseModel: models.BaseModel{ID: uint(id)},
|
||||
AuthorID: user.ID,
|
||||
},
|
||||
}).First(&item).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if err := services.DeletePost(item); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
@ -1,38 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/spf13/viper"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func openAttachment(c *fiber.Ctx) error {
|
||||
id := c.Params("fileId")
|
||||
basepath := viper.GetString("content")
|
||||
|
||||
return c.SendFile(filepath.Join(basepath, id))
|
||||
}
|
||||
|
||||
func uploadAttachment(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
file, err := c.FormFile("attachment")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
attachment, err := services.NewAttachment(user, file)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
if err := c.SaveFile(file, attachment.GetStoragePath()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"info": attachment,
|
||||
"url": attachment.GetAccessPath(),
|
||||
})
|
||||
}
|
@ -1,51 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/security"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func authMiddleware(c *fiber.Ctx) error {
|
||||
var token string
|
||||
if cookie := c.Cookies(security.CookieAccessKey); len(cookie) > 0 {
|
||||
token = cookie
|
||||
}
|
||||
if header := c.Get(fiber.HeaderAuthorization); len(header) > 0 {
|
||||
tk := strings.Replace(header, "Bearer", "", 1)
|
||||
token = strings.TrimSpace(tk)
|
||||
}
|
||||
|
||||
c.Locals("token", token)
|
||||
|
||||
if err := authFunc(c); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
func authFunc(c *fiber.Ctx, overrides ...string) error {
|
||||
var token string
|
||||
if len(overrides) > 0 {
|
||||
token = overrides[0]
|
||||
} else {
|
||||
if tk, ok := c.Locals("token").(string); !ok {
|
||||
return fiber.NewError(fiber.StatusUnauthorized)
|
||||
} else {
|
||||
token = tk
|
||||
}
|
||||
}
|
||||
|
||||
rtk := c.Cookies(security.CookieRefreshKey)
|
||||
if user, atk, rtk, err := services.Authenticate(token, rtk); err == nil {
|
||||
if atk != token {
|
||||
security.SetJwtCookieSet(c, atk, rtk)
|
||||
}
|
||||
c.Locals("principal", user)
|
||||
return nil
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
@ -1,187 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func contextComment() *services.PostTypeContext {
|
||||
return &services.PostTypeContext{
|
||||
Tx: database.C,
|
||||
TableName: "comments",
|
||||
ColumnName: "comment",
|
||||
CanReply: false,
|
||||
CanRepost: true,
|
||||
}
|
||||
}
|
||||
|
||||
func listComment(c *fiber.Ctx) error {
|
||||
take := c.QueryInt("take", 0)
|
||||
offset := c.QueryInt("offset", 0)
|
||||
|
||||
alias := c.Params("postId")
|
||||
|
||||
mx := c.Locals(postContextKey).(*services.PostTypeContext).
|
||||
FilterPublishedAt(time.Now())
|
||||
|
||||
item, err := mx.GetViaAlias(alias)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
data, err := mx.ListComment(item.ID, take, offset)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
count, err := mx.CountComment(item.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"count": count,
|
||||
"data": data,
|
||||
})
|
||||
}
|
||||
|
||||
func createComment(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
|
||||
var data struct {
|
||||
Alias string `json:"alias" form:"alias"`
|
||||
Content string `json:"content" form:"content" validate:"required"`
|
||||
PublishedAt *time.Time `json:"published_at" form:"published_at"`
|
||||
Hashtags []models.Tag `json:"hashtags" form:"hashtags"`
|
||||
Categories []models.Category `json:"categories" form:"categories"`
|
||||
ReplyTo uint `json:"reply_to" form:"reply_to"`
|
||||
}
|
||||
|
||||
if err := BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
} else if len(data.Alias) == 0 {
|
||||
data.Alias = strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
}
|
||||
|
||||
item := &models.Comment{
|
||||
PostBase: models.PostBase{
|
||||
Alias: data.Alias,
|
||||
PublishedAt: data.PublishedAt,
|
||||
AuthorID: user.ID,
|
||||
},
|
||||
Hashtags: data.Hashtags,
|
||||
Categories: data.Categories,
|
||||
Content: data.Content,
|
||||
}
|
||||
|
||||
postType := c.Params("postType")
|
||||
alias := c.Params("postId")
|
||||
|
||||
var err error
|
||||
var res models.Feed
|
||||
|
||||
switch postType {
|
||||
case "moments":
|
||||
err = database.C.Model(&models.Moment{}).Where("alias = ?", alias).Select("id").First(&res).Error
|
||||
case "articles":
|
||||
err = database.C.Model(&models.Article{}).Where("alias = ?", alias).Select("id").First(&res).Error
|
||||
default:
|
||||
return fiber.NewError(fiber.StatusBadRequest, "comment must belongs to a resource")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("belongs to resource was not found: %v", err))
|
||||
} else {
|
||||
switch postType {
|
||||
case "moments":
|
||||
item.MomentID = &res.ID
|
||||
case "articles":
|
||||
item.ArticleID = &res.ID
|
||||
}
|
||||
}
|
||||
|
||||
var relatedCount int64
|
||||
if data.ReplyTo > 0 {
|
||||
if err := database.C.Where("id = ?", data.ReplyTo).
|
||||
Model(&models.Comment{}).Count(&relatedCount).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else if relatedCount <= 0 {
|
||||
return fiber.NewError(fiber.StatusNotFound, "related post was not found")
|
||||
} else {
|
||||
item.ReplyID = &data.ReplyTo
|
||||
}
|
||||
}
|
||||
|
||||
if item, err := services.NewPost(item); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
return c.JSON(item)
|
||||
}
|
||||
}
|
||||
|
||||
func editComment(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
id, _ := c.ParamsInt("commentId", 0)
|
||||
|
||||
var data struct {
|
||||
Alias string `json:"alias" form:"alias" validate:"required"`
|
||||
Content string `json:"content" form:"content" validate:"required"`
|
||||
PublishedAt *time.Time `json:"published_at" form:"published_at"`
|
||||
Hashtags []models.Tag `json:"hashtags" form:"hashtags"`
|
||||
Categories []models.Category `json:"categories" form:"categories"`
|
||||
}
|
||||
|
||||
if err := BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var item *models.Comment
|
||||
if err := database.C.Where(models.Comment{
|
||||
PostBase: models.PostBase{
|
||||
BaseModel: models.BaseModel{ID: uint(id)},
|
||||
AuthorID: user.ID,
|
||||
},
|
||||
}).First(&item).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
item.Alias = data.Alias
|
||||
item.Content = data.Content
|
||||
item.PublishedAt = data.PublishedAt
|
||||
item.Hashtags = data.Hashtags
|
||||
item.Categories = data.Categories
|
||||
|
||||
if item, err := services.EditPost(item); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
return c.JSON(item)
|
||||
}
|
||||
}
|
||||
|
||||
func deleteComment(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
id, _ := c.ParamsInt("commentId", 0)
|
||||
|
||||
var item *models.Comment
|
||||
if err := database.C.Where(models.Comment{
|
||||
PostBase: models.PostBase{
|
||||
BaseModel: models.BaseModel{ID: uint(id)},
|
||||
AuthorID: user.ID,
|
||||
},
|
||||
}).First(&item).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if err := services.DeletePost(item); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
@ -1,191 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/samber/lo"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const (
|
||||
queryArticle = "id, created_at, updated_at, alias, title, NULL as content, description, realm_id, author_id, 'article' as model_type"
|
||||
queryMoment = "id, created_at, updated_at, alias, NULL as title, content, NULL as description, realm_id, author_id, 'moment' as model_type"
|
||||
)
|
||||
|
||||
func listFeed(c *fiber.Ctx) error {
|
||||
take := c.QueryInt("take", 0)
|
||||
offset := c.QueryInt("offset", 0)
|
||||
realmId := c.QueryInt("realmId", 0)
|
||||
|
||||
if take > 20 {
|
||||
take = 20
|
||||
}
|
||||
|
||||
var whereCondition string
|
||||
|
||||
if realmId > 0 {
|
||||
whereCondition += fmt.Sprintf("feed.realm_id = %d", realmId)
|
||||
} else {
|
||||
whereCondition += "feed.realm_id IS NULL"
|
||||
}
|
||||
|
||||
var author models.Account
|
||||
if len(c.Query("authorId")) > 0 {
|
||||
if err := database.C.Where(&models.Account{Name: c.Query("authorId")}).First(&author).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
} else {
|
||||
whereCondition += fmt.Sprintf("AND feed.author_id = %d", author.ID)
|
||||
}
|
||||
}
|
||||
|
||||
var result []*models.Feed
|
||||
|
||||
userTable := viper.GetString("database.prefix") + "accounts"
|
||||
commentTable := viper.GetString("database.prefix") + "comments"
|
||||
reactionTable := viper.GetString("database.prefix") + "reactions"
|
||||
|
||||
database.C.Raw(
|
||||
fmt.Sprintf(`SELECT feed.*, author.*,
|
||||
COALESCE(comment_count, 0) AS comment_count,
|
||||
COALESCE(reaction_count, 0) AS reaction_count
|
||||
FROM (? UNION ALL ?) AS feed
|
||||
INNER JOIN %s AS author ON author_id = author.id
|
||||
LEFT JOIN (SELECT article_id, moment_id, COUNT(*) AS comment_count
|
||||
FROM %s
|
||||
GROUP BY article_id, moment_id) AS comments
|
||||
ON (feed.model_type = 'article' AND feed.id = comments.article_id) OR
|
||||
(feed.model_type = 'moment' AND feed.id = comments.moment_id)
|
||||
LEFT JOIN (SELECT article_id, moment_id, COUNT(*) AS reaction_count
|
||||
FROM %s
|
||||
GROUP BY article_id, moment_id) AS reactions
|
||||
ON (feed.model_type = 'article' AND feed.id = reactions.article_id) OR
|
||||
(feed.model_type = 'moment' AND feed.id = reactions.moment_id)
|
||||
WHERE %s ORDER BY feed.created_at desc LIMIT ? OFFSET ?`,
|
||||
userTable,
|
||||
commentTable,
|
||||
reactionTable,
|
||||
whereCondition,
|
||||
),
|
||||
database.C.Select(queryArticle).Model(&models.Article{}),
|
||||
database.C.Select(queryMoment).Model(&models.Moment{}),
|
||||
take,
|
||||
offset,
|
||||
).Scan(&result)
|
||||
|
||||
if !c.QueryBool("noReact", false) {
|
||||
var reactions []struct {
|
||||
PostID uint
|
||||
Symbol string
|
||||
Count int64
|
||||
}
|
||||
|
||||
revertReaction := func(dataset string) error {
|
||||
itemMap := lo.SliceToMap(lo.FilterMap(result, func(item *models.Feed, index int) (*models.Feed, bool) {
|
||||
return item, item.ModelType == dataset
|
||||
}), func(item *models.Feed) (uint, *models.Feed) {
|
||||
return item.ID, item
|
||||
})
|
||||
|
||||
idx := lo.Map(lo.Filter(result, func(item *models.Feed, index int) bool {
|
||||
return item.ModelType == dataset
|
||||
}), func(item *models.Feed, index int) uint {
|
||||
return item.ID
|
||||
})
|
||||
|
||||
if err := database.C.Model(&models.Reaction{}).
|
||||
Select(dataset+"_id as post_id, symbol, COUNT(id) as count").
|
||||
Where(dataset+"_id IN (?)", idx).
|
||||
Group("post_id, symbol").
|
||||
Scan(&reactions).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
list := map[uint]map[string]int64{}
|
||||
for _, info := range reactions {
|
||||
if _, ok := list[info.PostID]; !ok {
|
||||
list[info.PostID] = make(map[string]int64)
|
||||
}
|
||||
list[info.PostID][info.Symbol] = info.Count
|
||||
}
|
||||
|
||||
for k, v := range list {
|
||||
if post, ok := itemMap[k]; ok {
|
||||
post.ReactionList = v
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := revertReaction("article"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := revertReaction("moment"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if !c.QueryBool("noAttachment", false) {
|
||||
revertAttachment := func(dataset string) error {
|
||||
var attachments []struct {
|
||||
models.Attachment
|
||||
|
||||
PostID uint `json:"post_id"`
|
||||
}
|
||||
|
||||
itemMap := lo.SliceToMap(lo.FilterMap(result, func(item *models.Feed, index int) (*models.Feed, bool) {
|
||||
return item, item.ModelType == dataset
|
||||
}), func(item *models.Feed) (uint, *models.Feed) {
|
||||
return item.ID, item
|
||||
})
|
||||
|
||||
idx := lo.Map(lo.Filter(result, func(item *models.Feed, index int) bool {
|
||||
return item.ModelType == dataset
|
||||
}), func(item *models.Feed, index int) uint {
|
||||
return item.ID
|
||||
})
|
||||
|
||||
if err := database.C.
|
||||
Model(&models.Attachment{}).
|
||||
Select(dataset+"_id as post_id, *").
|
||||
Where(dataset+"_id IN (?)", idx).
|
||||
Scan(&attachments).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
list := map[uint][]models.Attachment{}
|
||||
for _, info := range attachments {
|
||||
list[info.PostID] = append(list[info.PostID], info.Attachment)
|
||||
}
|
||||
|
||||
for k, v := range list {
|
||||
if post, ok := itemMap[k]; ok {
|
||||
post.Attachments = v
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := revertAttachment("article"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := revertAttachment("moment"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
var count int64
|
||||
database.C.Raw(`SELECT COUNT(*) FROM (? UNION ALL ?) as feed`,
|
||||
database.C.Select(queryArticle).Model(&models.Article{}),
|
||||
database.C.Select(queryMoment).Model(&models.Moment{}),
|
||||
).Scan(&count)
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"count": count,
|
||||
"data": result,
|
||||
})
|
||||
}
|
@ -1,146 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func contextMoment() *services.PostTypeContext {
|
||||
return &services.PostTypeContext{
|
||||
Tx: database.C,
|
||||
TableName: "moments",
|
||||
ColumnName: "moment",
|
||||
CanReply: false,
|
||||
CanRepost: true,
|
||||
}
|
||||
}
|
||||
|
||||
func createMoment(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
|
||||
var data struct {
|
||||
Alias string `json:"alias" form:"alias"`
|
||||
Content string `json:"content" form:"content" validate:"required,max=1024"`
|
||||
Hashtags []models.Tag `json:"hashtags" form:"hashtags"`
|
||||
Categories []models.Category `json:"categories" form:"categories"`
|
||||
Attachments []models.Attachment `json:"attachments" form:"attachments"`
|
||||
PublishedAt *time.Time `json:"published_at" form:"published_at"`
|
||||
RealmID *uint `json:"realm_id" form:"realm_id"`
|
||||
RepostTo uint `json:"repost_to" form:"repost_to"`
|
||||
}
|
||||
|
||||
if err := BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
} else if len(data.Alias) == 0 {
|
||||
data.Alias = strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
}
|
||||
|
||||
item := &models.Moment{
|
||||
PostBase: models.PostBase{
|
||||
Alias: data.Alias,
|
||||
PublishedAt: data.PublishedAt,
|
||||
AuthorID: user.ID,
|
||||
},
|
||||
Hashtags: data.Hashtags,
|
||||
Categories: data.Categories,
|
||||
Attachments: data.Attachments,
|
||||
Content: data.Content,
|
||||
RealmID: data.RealmID,
|
||||
}
|
||||
|
||||
var relatedCount int64
|
||||
if data.RepostTo > 0 {
|
||||
if err := database.C.Where("id = ?", data.RepostTo).
|
||||
Model(&models.Moment{}).Count(&relatedCount).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else if relatedCount <= 0 {
|
||||
return fiber.NewError(fiber.StatusNotFound, "related post was not found")
|
||||
} else {
|
||||
item.RepostID = &data.RepostTo
|
||||
}
|
||||
}
|
||||
|
||||
var realm *models.Realm
|
||||
if data.RealmID != nil {
|
||||
if err := database.C.Where(&models.Realm{
|
||||
BaseModel: models.BaseModel{ID: *data.RealmID},
|
||||
}).First(&realm).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
item, err := services.NewPost(item)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(item)
|
||||
}
|
||||
|
||||
func editMoment(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
id, _ := c.ParamsInt("momentId", 0)
|
||||
|
||||
var data struct {
|
||||
Alias string `json:"alias" form:"alias" validate:"required"`
|
||||
Content string `json:"content" form:"content" validate:"required,max=1024"`
|
||||
PublishedAt *time.Time `json:"published_at" form:"published_at"`
|
||||
Hashtags []models.Tag `json:"hashtags" form:"hashtags"`
|
||||
Categories []models.Category `json:"categories" form:"categories"`
|
||||
Attachments []models.Attachment `json:"attachments" form:"attachments"`
|
||||
}
|
||||
|
||||
if err := BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var item *models.Moment
|
||||
if err := database.C.Where(models.Comment{
|
||||
PostBase: models.PostBase{
|
||||
BaseModel: models.BaseModel{ID: uint(id)},
|
||||
AuthorID: user.ID,
|
||||
},
|
||||
}).First(&item).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
item.Alias = data.Alias
|
||||
item.Content = data.Content
|
||||
item.PublishedAt = data.PublishedAt
|
||||
item.Hashtags = data.Hashtags
|
||||
item.Categories = data.Categories
|
||||
item.Attachments = data.Attachments
|
||||
|
||||
if item, err := services.EditPost(item); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
return c.JSON(item)
|
||||
}
|
||||
}
|
||||
|
||||
func deleteMoment(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
id, _ := c.ParamsInt("momentId", 0)
|
||||
|
||||
var item *models.Moment
|
||||
if err := database.C.Where(models.Comment{
|
||||
PostBase: models.PostBase{
|
||||
BaseModel: models.BaseModel{ID: uint(id)},
|
||||
AuthorID: user.ID,
|
||||
},
|
||||
}).First(&item).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if err := services.DeletePost(item); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
@ -1,151 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
var postContextKey = "ptx"
|
||||
|
||||
func useDynamicContext(c *fiber.Ctx) error {
|
||||
postType := c.Params("postType")
|
||||
switch postType {
|
||||
case "articles":
|
||||
c.Locals(postContextKey, contextArticle())
|
||||
case "moments":
|
||||
c.Locals(postContextKey, contextMoment())
|
||||
case "comments":
|
||||
c.Locals(postContextKey, contextComment())
|
||||
default:
|
||||
return fiber.NewError(fiber.StatusBadRequest, "invalid dataset")
|
||||
}
|
||||
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
func getPost(c *fiber.Ctx) error {
|
||||
alias := c.Params("postId")
|
||||
|
||||
mx := c.Locals(postContextKey).(*services.PostTypeContext).
|
||||
FilterPublishedAt(time.Now())
|
||||
|
||||
item, err := mx.GetViaAlias(alias)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
item.ReactionList, err = mx.CountReactions(item.ID)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(item)
|
||||
}
|
||||
|
||||
func listPost(c *fiber.Ctx) error {
|
||||
take := c.QueryInt("take", 0)
|
||||
offset := c.QueryInt("offset", 0)
|
||||
realmId := c.QueryInt("realmId", 0)
|
||||
|
||||
mx := c.Locals(postContextKey).(*services.PostTypeContext).
|
||||
FilterPublishedAt(time.Now()).
|
||||
FilterRealm(uint(realmId)).
|
||||
SortCreatedAt("desc")
|
||||
|
||||
var author models.Account
|
||||
if len(c.Query("authorId")) > 0 {
|
||||
if err := database.C.Where(&models.Account{Name: c.Query("authorId")}).First(&author).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
mx = mx.FilterAuthor(author.ID)
|
||||
}
|
||||
|
||||
if len(c.Query("category")) > 0 {
|
||||
mx = mx.FilterWithCategory(c.Query("category"))
|
||||
}
|
||||
if len(c.Query("tag")) > 0 {
|
||||
mx = mx.FilterWithTag(c.Query("tag"))
|
||||
}
|
||||
|
||||
if !c.QueryBool("reply", true) {
|
||||
mx = mx.FilterReply(true)
|
||||
}
|
||||
|
||||
count, err := mx.Count()
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
items, err := mx.List(take, offset)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"count": count,
|
||||
"data": items,
|
||||
})
|
||||
}
|
||||
|
||||
func reactPost(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
|
||||
var data struct {
|
||||
Symbol string `json:"symbol" form:"symbol" validate:"required"`
|
||||
Attitude models.ReactionAttitude `json:"attitude" form:"attitude" validate:"required"`
|
||||
}
|
||||
|
||||
if err := BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mx := c.Locals(postContextKey).(*services.PostTypeContext)
|
||||
|
||||
reaction := models.Reaction{
|
||||
Symbol: data.Symbol,
|
||||
Attitude: data.Attitude,
|
||||
AccountID: user.ID,
|
||||
}
|
||||
|
||||
postType := c.Params("postType")
|
||||
alias := c.Params("postId")
|
||||
|
||||
var err error
|
||||
var res models.Feed
|
||||
|
||||
switch postType {
|
||||
case "moments":
|
||||
err = database.C.Model(&models.Moment{}).Where("id = ?", alias).Select("id").First(&res).Error
|
||||
case "articles":
|
||||
err = database.C.Model(&models.Article{}).Where("id = ?", alias).Select("id").First(&res).Error
|
||||
case "comments":
|
||||
err = database.C.Model(&models.Comment{}).Where("id = ?", alias).Select("id").First(&res).Error
|
||||
default:
|
||||
return fiber.NewError(fiber.StatusBadRequest, "comment must belongs to a resource")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, fmt.Sprintf("belongs to resource was not found: %v", err))
|
||||
} else {
|
||||
switch postType {
|
||||
case "moments":
|
||||
reaction.MomentID = &res.ID
|
||||
case "articles":
|
||||
reaction.ArticleID = &res.ID
|
||||
case "comments":
|
||||
reaction.CommentID = &res.ID
|
||||
}
|
||||
}
|
||||
|
||||
if positive, reaction, err := mx.React(reaction); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
return c.Status(lo.Ternary(positive, fiber.StatusCreated, fiber.StatusNoContent)).JSON(reaction)
|
||||
}
|
||||
}
|
@ -1,193 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func getRealm(c *fiber.Ctx) error {
|
||||
id, _ := c.ParamsInt("realmId", 0)
|
||||
|
||||
var realm models.Realm
|
||||
if err := database.C.Where(&models.Realm{
|
||||
BaseModel: models.BaseModel{ID: uint(id)},
|
||||
}).First(&realm).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(realm)
|
||||
}
|
||||
|
||||
func listRealm(c *fiber.Ctx) error {
|
||||
realms, err := services.ListRealm()
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(realms)
|
||||
}
|
||||
|
||||
func listOwnedRealm(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
|
||||
realms, err := services.ListRealmWithUser(user)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(realms)
|
||||
}
|
||||
|
||||
func listAvailableRealm(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
|
||||
realms, err := services.ListRealmIsAvailable(user)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(realms)
|
||||
}
|
||||
|
||||
func createRealm(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
if user.PowerLevel < 10 {
|
||||
return fiber.NewError(fiber.StatusForbidden, "require power level 10 to create realms")
|
||||
}
|
||||
|
||||
var data struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Description string `json:"description"`
|
||||
RealmType int `json:"realm_type"`
|
||||
}
|
||||
|
||||
if err := BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
realm, err := services.NewRealm(user, data.Name, data.Description, data.RealmType)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(realm)
|
||||
}
|
||||
|
||||
func inviteRealm(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
realmId, _ := c.ParamsInt("realmId", 0)
|
||||
|
||||
var data struct {
|
||||
AccountName string `json:"account_name" validate:"required"`
|
||||
}
|
||||
|
||||
if err := BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var realm models.Realm
|
||||
if err := database.C.Where(&models.Realm{
|
||||
BaseModel: models.BaseModel{ID: uint(realmId)},
|
||||
AccountID: user.ID,
|
||||
}).First(&realm).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
var account models.Account
|
||||
if err := database.C.Where(&models.Account{
|
||||
Name: data.AccountName,
|
||||
}).First(&account).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if err := services.InviteRealmMember(account, realm); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
func kickRealm(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
realmId, _ := c.ParamsInt("realmId", 0)
|
||||
|
||||
var data struct {
|
||||
AccountName string `json:"account_name" validate:"required"`
|
||||
}
|
||||
|
||||
if err := BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var realm models.Realm
|
||||
if err := database.C.Where(&models.Realm{
|
||||
BaseModel: models.BaseModel{ID: uint(realmId)},
|
||||
AccountID: user.ID,
|
||||
}).First(&realm).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
var account models.Account
|
||||
if err := database.C.Where(&models.Account{
|
||||
Name: data.AccountName,
|
||||
}).First(&account).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if err := services.KickRealmMember(account, realm); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
func editRealm(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
id, _ := c.ParamsInt("realmId", 0)
|
||||
|
||||
var data struct {
|
||||
Name string `json:"name" validate:"required"`
|
||||
Description string `json:"description"`
|
||||
RealmType int `json:"realm_type"`
|
||||
}
|
||||
|
||||
if err := BindAndValidate(c, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var realm models.Realm
|
||||
if err := database.C.Where(&models.Realm{
|
||||
BaseModel: models.BaseModel{ID: uint(id)},
|
||||
AccountID: user.ID,
|
||||
}).First(&realm).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
realm, err := services.EditRealm(realm, data.Name, data.Description, data.RealmType)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(realm)
|
||||
}
|
||||
|
||||
func deleteRealm(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
id, _ := c.ParamsInt("realmId", 0)
|
||||
|
||||
var realm models.Realm
|
||||
if err := database.C.Where(&models.Realm{
|
||||
BaseModel: models.BaseModel{ID: uint(id)},
|
||||
AccountID: user.ID,
|
||||
}).First(&realm).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if err := services.DeleteRealm(realm); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
@ -1,134 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/views"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/cache"
|
||||
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||
"github.com/gofiber/fiber/v2/middleware/filesystem"
|
||||
"github.com/gofiber/fiber/v2/middleware/idempotency"
|
||||
"github.com/gofiber/fiber/v2/middleware/logger"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var A *fiber.App
|
||||
|
||||
func NewServer() {
|
||||
A = fiber.New(fiber.Config{
|
||||
DisableStartupMessage: true,
|
||||
EnableIPValidation: true,
|
||||
ServerHeader: "Hydrogen.Interactive",
|
||||
AppName: "Hydrogen.Interactive",
|
||||
ProxyHeader: fiber.HeaderXForwardedFor,
|
||||
JSONEncoder: jsoniter.ConfigCompatibleWithStandardLibrary.Marshal,
|
||||
JSONDecoder: jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal,
|
||||
BodyLimit: 50 * 1024 * 1024,
|
||||
EnablePrintRoutes: viper.GetBool("debug"),
|
||||
})
|
||||
|
||||
A.Use(idempotency.New())
|
||||
A.Use(cors.New(cors.Config{
|
||||
AllowCredentials: true,
|
||||
AllowMethods: strings.Join([]string{
|
||||
fiber.MethodGet,
|
||||
fiber.MethodPost,
|
||||
fiber.MethodHead,
|
||||
fiber.MethodOptions,
|
||||
fiber.MethodPut,
|
||||
fiber.MethodDelete,
|
||||
fiber.MethodPatch,
|
||||
}, ","),
|
||||
AllowOriginsFunc: func(origin string) bool {
|
||||
return true
|
||||
},
|
||||
}))
|
||||
|
||||
A.Use(logger.New(logger.Config{
|
||||
Format: "${status} | ${latency} | ${method} ${path}\n",
|
||||
Output: log.Logger,
|
||||
}))
|
||||
|
||||
A.Get("/.well-known", getMetadata)
|
||||
|
||||
api := A.Group("/api").Name("API")
|
||||
{
|
||||
api.Get("/users/me", authMiddleware, getUserinfo)
|
||||
api.Get("/users/:accountId", getOthersInfo)
|
||||
api.Get("/users/:accountId/follow", authMiddleware, getAccountFollowed)
|
||||
api.Post("/users/:accountId/follow", authMiddleware, doFollowAccount)
|
||||
|
||||
api.Get("/attachments/o/:fileId", cache.New(cache.Config{
|
||||
Expiration: 365 * 24 * time.Hour,
|
||||
CacheControl: true,
|
||||
}), openAttachment)
|
||||
api.Post("/attachments", authMiddleware, uploadAttachment)
|
||||
|
||||
api.Get("/feed", listFeed)
|
||||
|
||||
posts := api.Group("/p/:postType").Use(useDynamicContext).Name("Dataset Universal API")
|
||||
{
|
||||
posts.Get("/", listPost)
|
||||
posts.Get("/:postId", getPost)
|
||||
posts.Post("/:postId/react", authMiddleware, reactPost)
|
||||
posts.Get("/:postId/comments", listComment)
|
||||
posts.Post("/:postId/comments", authMiddleware, createComment)
|
||||
}
|
||||
|
||||
moments := api.Group("/p/moments").Name("Moments API")
|
||||
{
|
||||
moments.Post("/", authMiddleware, createMoment)
|
||||
moments.Put("/:momentId", authMiddleware, editMoment)
|
||||
moments.Delete("/:momentId", authMiddleware, deleteMoment)
|
||||
}
|
||||
|
||||
articles := api.Group("/p/articles").Name("Articles API")
|
||||
{
|
||||
articles.Post("/", authMiddleware, createArticle)
|
||||
articles.Put("/:articleId", authMiddleware, editArticle)
|
||||
articles.Delete("/:articleId", authMiddleware, deleteArticle)
|
||||
}
|
||||
|
||||
comments := api.Group("/p/comments").Name("Comments API")
|
||||
{
|
||||
comments.Put("/:commentId", authMiddleware, editComment)
|
||||
comments.Delete("/:commentId", authMiddleware, deleteComment)
|
||||
}
|
||||
|
||||
api.Get("/categories", listCategories)
|
||||
api.Post("/categories", authMiddleware, newCategory)
|
||||
api.Put("/categories/:categoryId", authMiddleware, editCategory)
|
||||
api.Delete("/categories/:categoryId", authMiddleware, deleteCategory)
|
||||
|
||||
api.Get("/realms", listRealm)
|
||||
api.Get("/realms/me", authMiddleware, listOwnedRealm)
|
||||
api.Get("/realms/me/available", authMiddleware, listAvailableRealm)
|
||||
api.Get("/realms/:realmId", getRealm)
|
||||
api.Post("/realms", authMiddleware, createRealm)
|
||||
api.Post("/realms/:realmId/invite", authMiddleware, inviteRealm)
|
||||
api.Post("/realms/:realmId/kick", authMiddleware, kickRealm)
|
||||
api.Put("/realms/:realmId", authMiddleware, editRealm)
|
||||
api.Delete("/realms/:realmId", authMiddleware, deleteRealm)
|
||||
}
|
||||
|
||||
A.Use("/", cache.New(cache.Config{
|
||||
Expiration: 24 * time.Hour,
|
||||
CacheControl: true,
|
||||
}), filesystem.New(filesystem.Config{
|
||||
Root: http.FS(views.FS),
|
||||
PathPrefix: "dist",
|
||||
Index: "index.html",
|
||||
NotFoundFile: "dist/index.html",
|
||||
}))
|
||||
}
|
||||
|
||||
func Listen() {
|
||||
if err := A.Listen(viper.GetString("bind")); err != nil {
|
||||
log.Fatal().Err(err).Msg("An error occurred when starting server...")
|
||||
}
|
||||
}
|
@ -1,76 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/database"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/models"
|
||||
"code.smartsheep.studio/hydrogen/interactive/pkg/services"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func getUserinfo(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
|
||||
var data models.Account
|
||||
if err := database.C.
|
||||
Where(&models.Account{BaseModel: models.BaseModel{ID: user.ID}}).
|
||||
First(&data).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(data)
|
||||
}
|
||||
|
||||
func getOthersInfo(c *fiber.Ctx) error {
|
||||
accountId := c.Params("accountId")
|
||||
|
||||
var data models.Account
|
||||
if err := database.C.
|
||||
Where(&models.Account{Name: accountId}).
|
||||
First(&data).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
return c.JSON(data)
|
||||
}
|
||||
|
||||
func getAccountFollowed(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
accountId, _ := c.ParamsInt("accountId", 0)
|
||||
|
||||
var data models.Account
|
||||
if err := database.C.
|
||||
Where(&models.Account{BaseModel: models.BaseModel{ID: uint(accountId)}}).
|
||||
First(&data).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
_, status := services.GetAccountFollowed(user, data)
|
||||
|
||||
return c.JSON(fiber.Map{
|
||||
"is_followed": status,
|
||||
})
|
||||
}
|
||||
|
||||
func doFollowAccount(c *fiber.Ctx) error {
|
||||
user := c.Locals("principal").(models.Account)
|
||||
id, _ := c.ParamsInt("accountId", 0)
|
||||
|
||||
var account models.Account
|
||||
if err := database.C.Where(&models.Account{
|
||||
BaseModel: models.BaseModel{ID: uint(id)},
|
||||
}).First(&account).Error; err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, err.Error())
|
||||
}
|
||||
|
||||
if _, ok := services.GetAccountFollowed(user, account); ok {
|
||||
if err := services.UnfollowAccount(user.ID, account.ID); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
} else {
|
||||
if err := services.FollowAccount(user.ID, account.ID); err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
return c.SendStatus(fiber.StatusCreated)
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user