Compare commits
198 commits
static-adm
...
develop
Author | SHA1 | Date | |
---|---|---|---|
c0a99df06a | |||
0cb4c35ee4 | |||
c9b3fcc1d3 | |||
11c5838947 | |||
180dc8b472 | |||
d330c57cda | |||
bd64d07082 | |||
9d2c558f64 | |||
ac25b051ae | |||
c5a44a59db | |||
58d5d9d7bf | |||
b6e8fde4dd | |||
bee10eab5e | |||
13215f5f06 | |||
430b376ded | |||
ccf1007883 | |||
6da783b84d | |||
8f322456a0 | |||
9c876cea21 | |||
9728e2f8f7 | |||
b0f7da9ce0 | |||
fc99c694e6 | |||
fbb13fde76 | |||
cbd236aeb5 | |||
71d3bbd7be | |||
98a3dab10a | |||
|
661b7fedb6 | ||
|
8b5aca9619 | ||
f101886709 | |||
09fa7227f6 | |||
d5b0720596 | |||
940792f8ba | |||
3c72b48a05 | |||
6475cf127e | |||
a8a231c5b2 | |||
2901fda29c | |||
bd14440386 | |||
|
b312edac4c | ||
3bb31117e6 | |||
2c5c531c35 | |||
a3101a435b | |||
d488cf476e | |||
ca182a0ae7 | |||
495a1a71e8 | |||
cf19d4901f | |||
07539f7825 | |||
0ab2f2ab45 | |||
95ed4931f8 | |||
7cd3954152 | |||
80a4e30be7 | |||
3ff0f46b9f | |||
4ff5293093 | |||
4f0cb61782 | |||
5fdb5d69d2 | |||
f66135ed08 | |||
dc34328f15 | |||
13e2a811ec | |||
1a4238bf98 | |||
c3069b9478 | |||
51f09531c4 | |||
962847fdc3 | |||
83aab0859a | |||
|
eb2b0d26e4 | ||
|
91870590ec | ||
|
c442877c25 | ||
|
16af0bad55 | ||
|
16ee6ed500 | ||
|
babf5df0e7 | ||
|
5767f59294 | ||
|
72ce0b7759 | ||
|
0cf9b44179 | ||
|
3cf335c4d0 | ||
|
1556e2be8e | ||
|
629077dce4 | ||
|
50256af6f6 | ||
|
c5d36d9679 | ||
|
fb4c5b97c7 | ||
|
a715cf4b3c | ||
|
693a6486da | ||
|
4e353f0335 | ||
5992e8bb16 | |||
57273754b7 | |||
59bfdf2ca4 | |||
a9e2e31e3b | |||
bf8f493ffd | |||
3b197503d2 | |||
c0b2bba55e | |||
4b765b1886 | |||
cba2c5725f | |||
2b96c3b224 | |||
b03edb4ff4 | |||
5b75fb2a2f | |||
4d6fb43cbd | |||
ad52135bf5 | |||
28d357f52c | |||
9c5feb81aa | |||
a360836ce3 | |||
840c70c4fa | |||
c65379afea | |||
16bed0562d | |||
a801dd7b07 | |||
1e86da43f5 | |||
411831458c | |||
56463b2121 | |||
2f5eb79473 | |||
f4daa90bd8 | |||
688748b531 | |||
2e5aa71176 | |||
7ca655a999 | |||
4746f98851 | |||
765c7e98d2 | |||
ddbe989461 | |||
4a3dd5f65e | |||
bfe4152385 | |||
5da9cbd8a5 | |||
a924e117fd | |||
d1c4b97613 | |||
2180d068ae | |||
a3840e7d1f | |||
b17d3dc6d8 | |||
f8f364d36d | |||
329d8fcba8 | |||
e2860e5292 | |||
df27567d99 | |||
be5440c5e8 | |||
68fe0a9633 | |||
0f65dd3ebe | |||
38d09cb0ce | |||
c9a03af7c1 | |||
0f7ae0fa21 | |||
30e13a8785 | |||
778b213945 | |||
bed7ff8e89 | |||
70cd5f91d8 | |||
aeaebb566c | |||
5751637926 | |||
24bab63cd8 | |||
1d4c212441 | |||
6e7cbf1885 | |||
225f87ad62 | |||
e64f031167 | |||
fa52093bac | |||
3126d15ffc | |||
8f97c15b07 | |||
3af0c53a86 | |||
fc7e07f424 | |||
59685e25d2 | |||
65aeaefa41 | |||
5d6cb6a459 | |||
8afc3bee7a | |||
72871d4514 | |||
72af38c0e9 | |||
ae19fd90c9 | |||
66b3248dd3 | |||
73ead8656a | |||
f32a7fd76a | |||
4078fd655c | |||
5bdef8c724 | |||
cdc918c8f1 | |||
f15eded3e1 | |||
05eda169fe | |||
3ce855cbde | |||
da67e69af5 | |||
c2d3221be3 | |||
5e92f955ac | |||
b72127b45a | |||
9a91299f96 | |||
fbd961c747 | |||
0c2b33458d | |||
842cac2a50 | |||
|
3e1f5e5372 | ||
|
3a21293970 | ||
|
0d66237205 | ||
6ef6b2a289 | |||
94e9c8f48a | |||
873aa9da1c | |||
34a48cb87f | |||
|
50403351f4 | ||
|
a953b1d927 | ||
bb29c5bed2 | |||
bc46f3da4c | |||
7e709768c3 | |||
76ded10a70 | |||
4457928e32 | |||
ee03149ba1 | |||
ea6bc8a7c5 | |||
bd74693db6 | |||
5256678901 | |||
b7e3d44756 | |||
010e8c7bb2 | |||
9671cdecdf | |||
f531484063 | |||
ec7e9da734 | |||
3c384c1b76 | |||
2437a3e9ba | |||
ad7dcf38a8 | |||
|
3947012691 | ||
|
d61b7d4b49 |
217 changed files with 35899 additions and 22861 deletions
|
@ -1,4 +1,5 @@
|
|||
platform: linux/amd64
|
||||
labels:
|
||||
platform: linux/amd64
|
||||
|
||||
depends_on:
|
||||
- test
|
||||
|
@ -34,7 +35,7 @@ variables:
|
|||
- &clean "(rm -rf release || true) && (rm -rf _build || true) && (rm -rf /root/.mix)"
|
||||
- &mix-clean "mix deps.clean --all && mix clean"
|
||||
|
||||
pipeline:
|
||||
steps:
|
||||
# Canonical amd64
|
||||
debian-bookworm:
|
||||
image: hexpm/elixir:1.15.4-erlang-26.0.2-debian-bookworm-20230612
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
platform: linux/arm64
|
||||
labels:
|
||||
platform: linux/aarch64
|
||||
|
||||
depends_on:
|
||||
- test
|
||||
|
@ -34,7 +35,7 @@ variables:
|
|||
- &clean "(rm -rf release || true) && (rm -rf _build || true) && (rm -rf /root/.mix)"
|
||||
- &mix-clean "mix deps.clean --all && mix clean"
|
||||
|
||||
pipeline:
|
||||
steps:
|
||||
# Canonical arm64
|
||||
debian-bookworm:
|
||||
image: hexpm/elixir:1.15.4-erlang-26.0.2-debian-bookworm-20230612
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
platform: linux/amd64
|
||||
labels:
|
||||
platform: linux/amd64
|
||||
|
||||
depends_on:
|
||||
- test
|
||||
|
@ -45,7 +46,7 @@ variables:
|
|||
- &clean "(rm -rf release || true) && (rm -rf _build || true) && (rm -rf /root/.mix)"
|
||||
- &mix-clean "mix deps.clean --all && mix clean"
|
||||
|
||||
pipeline:
|
||||
steps:
|
||||
docs:
|
||||
<<: *on-point-release
|
||||
secrets:
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
platform: linux/amd64
|
||||
labels:
|
||||
platform: linux/amd64
|
||||
|
||||
variables:
|
||||
- &scw-secrets
|
||||
|
@ -41,9 +42,9 @@ variables:
|
|||
- &clean "(rm -rf release || true) && (rm -rf _build || true) && (rm -rf /root/.mix)"
|
||||
- &mix-clean "mix deps.clean --all && mix clean"
|
||||
|
||||
pipeline:
|
||||
steps:
|
||||
lint:
|
||||
image: akkoma/ci-base:1.15-otp26
|
||||
image: akkoma/ci-base:1.16-otp26
|
||||
<<: *on-pr-open
|
||||
environment:
|
||||
MIX_ENV: test
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
platform: linux/amd64
|
||||
labels:
|
||||
platform: linux/amd64
|
||||
|
||||
depends_on:
|
||||
- lint
|
||||
|
@ -12,12 +13,6 @@ matrix:
|
|||
- 25
|
||||
- 26
|
||||
include:
|
||||
- ELIXIR_VERSION: 1.14
|
||||
OTP_VERSION: 25
|
||||
- ELIXIR_VERSION: 1.15
|
||||
OTP_VERSION: 25
|
||||
- ELIXIR_VERSION: 1.15
|
||||
OTP_VERSION: 26
|
||||
- ELIXIR_VERSION: 1.16
|
||||
OTP_VERSION: 26
|
||||
|
||||
|
@ -73,7 +68,7 @@ services:
|
|||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
|
||||
pipeline:
|
||||
steps:
|
||||
test:
|
||||
image: akkoma/ci-base:${ELIXIR_VERSION}-otp${OTP_VERSION}
|
||||
<<: *on-pr-open
|
||||
|
@ -92,5 +87,5 @@ pipeline:
|
|||
- mix ecto.create
|
||||
- mix ecto.migrate
|
||||
- mkdir -p test/tmp
|
||||
- mix test --preload-modules --exclude erratic --exclude federated --exclude mocked
|
||||
- mix test --preload-modules --only mocked
|
||||
- mix test --preload-modules --exclude erratic --exclude federated --exclude mocked || mix test --failed
|
||||
- mix test --preload-modules --only mocked || mix test --failed
|
||||
|
|
31
CHANGELOG.md
31
CHANGELOG.md
|
@ -4,7 +4,35 @@ All notable changes to this project will be documented in this file.
|
|||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
|
||||
|
||||
## Unreleased
|
||||
## UNRELEASED
|
||||
|
||||
## BREAKING
|
||||
- Minimum PostgreSQL version is raised to 12
|
||||
- Swagger UI moved from `/akkoma/swaggerui/` to `/pleroma/swaggerui/`
|
||||
|
||||
## Added
|
||||
- Implement [FEP-67ff](https://codeberg.org/fediverse/fep/src/branch/main/fep/67ff/fep-67ff.md) (federation documentation)
|
||||
- Meilisearch: it is now possible to use separate keys for search and admin actions
|
||||
- New standalone `prune_orphaned_activities` mix task with configurable batch limit
|
||||
- The `prune_objects` mix task now accepts a `--limit` parameter for initial object pruning
|
||||
|
||||
## Fixed
|
||||
- Meilisearch: order of results returned from our REST API now actually matches how Meilisearch ranks results
|
||||
- Emoji are now federated as anonymous objects, fixing issues with
|
||||
some strict servers e.g. rejecting e.g. remote emoji reactions
|
||||
- AP objects with additional JSON-LD profiles beyond ActivityStreams can now be fetched
|
||||
- Single-selection polls no longer expose the voter_count; MastoAPI demands it be null
|
||||
and this confused some clients leading to vote distributions >100%
|
||||
|
||||
## Changed
|
||||
- Refactored Rich Media to cache the content in the database. Fetching operations that could block status rendering have been eliminated.
|
||||
|
||||
## 2024.04.1 (Security)
|
||||
|
||||
## Fixed
|
||||
- Issue allowing non-owners to use media objects in posts
|
||||
- Issue allowing use of non-media objects as attachments and crashing timeline rendering
|
||||
- Issue allowing webfinger spoofing in certain situations
|
||||
|
||||
## 2024.04
|
||||
|
||||
|
@ -37,6 +65,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
|
|||
- Issue leading to Mastodon bot accounts being rejected
|
||||
- Scope misdetection of remote posts resulting from not recognising
|
||||
JSON-LD-compacted forms of public scope; affected e.g. federation with bovine
|
||||
- Ratelimits encountered when fetching objects are now respected; 429 responses will cause a backoff when we get one.
|
||||
|
||||
## Removed
|
||||
- ActivityPub Client-To-Server write API endpoints have been disabled;
|
||||
|
|
42
FEDERATION.md
Normal file
42
FEDERATION.md
Normal file
|
@ -0,0 +1,42 @@
|
|||
# Federation
|
||||
|
||||
## Supported federation protocols and standards
|
||||
|
||||
- [ActivityPub](https://www.w3.org/TR/activitypub/) (Server-to-Server)
|
||||
- [WebFinger](https://webfinger.net/)
|
||||
- [Http Signatures](https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures)
|
||||
- [NodeInfo](https://nodeinfo.diaspora.software/)
|
||||
|
||||
## Supported FEPs
|
||||
|
||||
- [FEP-67ff: FEDERATION](https://codeberg.org/fediverse/fep/src/branch/main/fep/67ff/fep-67ff.md)
|
||||
- [FEP-f1d5: NodeInfo in Fediverse Software](https://codeberg.org/fediverse/fep/src/branch/main/fep/f1d5/fep-f1d5.md)
|
||||
- [FEP-fffd: Proxy Objects](https://codeberg.org/fediverse/fep/src/branch/main/fep/fffd/fep-fffd.md)
|
||||
|
||||
## ActivityPub
|
||||
|
||||
Akkoma mostly follows the server-to-server parts of the ActivityPub standard,
|
||||
but implements quirks for Mastodon compatibility as well as Mastodon-specific
|
||||
and custom extensions.
|
||||
|
||||
See our documentation and Mastodon’s federation information
|
||||
linked further below for details on these quirks and extensions.
|
||||
|
||||
Akkoma does not perform JSON-LD processing.
|
||||
|
||||
### Required extensions
|
||||
|
||||
#### HTTP Signatures
|
||||
All AP S2S POST requests to Akkoma instances MUST be signed.
|
||||
Depending on instance configuration the same may be true for GET requests.
|
||||
|
||||
## Nodeinfo
|
||||
|
||||
Akkoma provides many additional entries in its nodeinfo response,
|
||||
see the documentation linked below for details.
|
||||
|
||||
## Additional documentation
|
||||
|
||||
- [Akkoma’s ActivityPub extensions](https://docs.akkoma.dev/develop/development/ap_extensions/)
|
||||
- [Akkoma’s nodeinfo extensions](https://docs.akkoma.dev/develop/development/nodeinfo_extensions/)
|
||||
- [Mastodon’s federation requirements](https://github.com/mastodon/mastodon/blob/main/FEDERATION.md)
|
|
@ -63,7 +63,6 @@
|
|||
uploader: Pleroma.Uploaders.Local,
|
||||
filters: [],
|
||||
link_name: false,
|
||||
proxy_remote: false,
|
||||
filename_display_max_length: 30,
|
||||
base_url: nil,
|
||||
allowed_mime_types: ["image", "audio", "video"]
|
||||
|
@ -189,8 +188,10 @@
|
|||
receive_timeout: :timer.seconds(15),
|
||||
proxy_url: nil,
|
||||
user_agent: :default,
|
||||
pool_size: 50,
|
||||
adapter: []
|
||||
pool_size: 10,
|
||||
adapter: [],
|
||||
# see: https://hexdocs.pm/finch/Finch.html#start_link/1
|
||||
pool_max_idle_time: :timer.seconds(30)
|
||||
|
||||
config :pleroma, :instance,
|
||||
name: "Akkoma",
|
||||
|
@ -437,8 +438,12 @@
|
|||
Pleroma.Web.RichMedia.Parsers.TwitterCard,
|
||||
Pleroma.Web.RichMedia.Parsers.OEmbed
|
||||
],
|
||||
failure_backoff: :timer.minutes(20),
|
||||
ttl_setters: [Pleroma.Web.RichMedia.Parser.TTL.AwsSignedUrl]
|
||||
failure_backoff: 60_000,
|
||||
ttl_setters: [
|
||||
Pleroma.Web.RichMedia.Parser.TTL.AwsSignedUrl,
|
||||
Pleroma.Web.RichMedia.Parser.TTL.Opengraph
|
||||
],
|
||||
max_body: 5_000_000
|
||||
|
||||
config :pleroma, :media_proxy,
|
||||
enabled: false,
|
||||
|
@ -576,7 +581,9 @@
|
|||
mute_expire: 5,
|
||||
search_indexing: 10,
|
||||
nodeinfo_fetcher: 1,
|
||||
database_prune: 1
|
||||
database_prune: 1,
|
||||
rich_media_backfill: 2,
|
||||
rich_media_expiration: 2
|
||||
],
|
||||
plugins: [
|
||||
Oban.Plugins.Pruner,
|
||||
|
@ -592,7 +599,8 @@
|
|||
retries: [
|
||||
federator_incoming: 5,
|
||||
federator_outgoing: 5,
|
||||
search_indexing: 2
|
||||
search_indexing: 2,
|
||||
rich_media_backfill: 3
|
||||
],
|
||||
timeout: [
|
||||
activity_expiration: :timer.seconds(5),
|
||||
|
@ -614,7 +622,8 @@
|
|||
mute_expire: :timer.seconds(5),
|
||||
search_indexing: :timer.seconds(5),
|
||||
nodeinfo_fetcher: :timer.seconds(10),
|
||||
database_prune: :timer.minutes(10)
|
||||
database_prune: :timer.minutes(10),
|
||||
rich_media_backfill: :timer.seconds(30)
|
||||
]
|
||||
|
||||
config :pleroma, Pleroma.Formatter,
|
||||
|
@ -813,8 +822,10 @@
|
|||
config :pleroma, configurable_from_database: false
|
||||
|
||||
config :pleroma, Pleroma.Repo,
|
||||
parameters: [gin_fuzzy_search_limit: "500"],
|
||||
prepare: :unnamed
|
||||
parameters: [
|
||||
gin_fuzzy_search_limit: "500",
|
||||
plan_cache_mode: "force_custom_plan"
|
||||
]
|
||||
|
||||
config :pleroma, :majic_pool, size: 2
|
||||
|
||||
|
|
|
@ -118,14 +118,6 @@
|
|||
"font"
|
||||
]
|
||||
},
|
||||
%{
|
||||
key: :proxy_remote,
|
||||
type: :boolean,
|
||||
description: """
|
||||
Proxy requests to the remote uploader.\n
|
||||
Useful if media upload endpoint is not internet accessible.
|
||||
"""
|
||||
},
|
||||
%{
|
||||
key: :filename_display_max_length,
|
||||
type: :integer,
|
||||
|
@ -2717,8 +2709,8 @@
|
|||
%{
|
||||
key: :pool_size,
|
||||
type: :integer,
|
||||
description: "Number of concurrent outbound HTTP requests to allow. Default 50.",
|
||||
suggestions: [50]
|
||||
description: "Number of concurrent outbound HTTP requests to allow PER HOST. Default 10.",
|
||||
suggestions: [10]
|
||||
},
|
||||
%{
|
||||
key: :adapter,
|
||||
|
@ -2741,6 +2733,13 @@
|
|||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
%{
|
||||
key: :pool_max_idle_time,
|
||||
type: :integer,
|
||||
description:
|
||||
"Number of seconds to retain an HTTP pool; pool will remain if actively in use. Default 30 seconds (in ms).",
|
||||
suggestions: [30_000]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
|
|
@ -51,7 +51,8 @@
|
|||
hostname: System.get_env("DB_HOST") || "localhost",
|
||||
pool: Ecto.Adapters.SQL.Sandbox,
|
||||
pool_size: 50,
|
||||
queue_target: 5000
|
||||
queue_target: 5000,
|
||||
log: false
|
||||
|
||||
config :pleroma, :dangerzone, override_repo_pool_size: true
|
||||
|
||||
|
@ -63,7 +64,8 @@
|
|||
config :pleroma, :rich_media,
|
||||
enabled: false,
|
||||
ignore_hosts: [],
|
||||
ignore_tld: ["local", "localdomain", "lan"]
|
||||
ignore_tld: ["local", "localdomain", "lan"],
|
||||
max_body: 2_000_000
|
||||
|
||||
config :pleroma, :instance,
|
||||
multi_factor_authentication: [
|
||||
|
@ -141,6 +143,8 @@
|
|||
config :pleroma, :instances_favicons, enabled: false
|
||||
config :pleroma, :instances_nodeinfo, enabled: false
|
||||
|
||||
config :pleroma, Pleroma.Web.RichMedia.Backfill, provider: Pleroma.Web.RichMedia.Backfill
|
||||
|
||||
if File.exists?("./config/test.secret.exs") do
|
||||
import_config "test.secret.exs"
|
||||
else
|
||||
|
|
10
diagnostic-tools/binary-leak-checker.sh
Executable file
10
diagnostic-tools/binary-leak-checker.sh
Executable file
|
@ -0,0 +1,10 @@
|
|||
if [ "$#" -ne 2 ]; then
|
||||
echo "Usage: binary-leak-checker.sh <nodename> <erlang cookie>"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "The command you want to run is:
|
||||
:recon.bin_leak(10)
|
||||
"
|
||||
|
||||
iex --sname debug --remsh $1 --erl "-setcookie $2"
|
|
@ -11,4 +11,4 @@ echo "-- Running migrations..."
|
|||
mix ecto.migrate
|
||||
|
||||
echo "-- Starting!"
|
||||
mix phx.server
|
||||
elixir --erl "+sbwt none +sbwtdcpu none +sbwtdio none" -S mix phx.server
|
||||
|
|
|
@ -50,9 +50,39 @@ This will prune remote posts older than 90 days (configurable with [`config :ple
|
|||
|
||||
- `--keep-threads` - Don't prune posts when they are part of a thread where at least one post has seen local interaction (e.g. one of the posts is a local post, or is favourited by a local user, or has been repeated by a local user...). It also wont delete posts when at least one of the posts in that thread is kept (e.g. because one of the posts has seen recent activity).
|
||||
- `--keep-non-public` - Keep non-public posts like DM's and followers-only, even if they are remote.
|
||||
- `--limit` - limits how many remote posts get pruned. This limit does **not** apply to any of the follow up jobs. If wanting to keep the database load in check it is thus advisable to run the standalone `prune_orphaned_activities` task with a limit afterwards instead of passing `--prune-orphaned-activities` to this task.
|
||||
- `--prune-orphaned-activities` - Also prune orphaned activities afterwards. Activities are things like Like, Create, Announce, Flag (aka reports)... They can significantly help reduce the database size.
|
||||
- `--vacuum` - Run `VACUUM FULL` after the objects are pruned. This should not be used on a regular basis, but is useful if your instance has been running for a long time before pruning.
|
||||
|
||||
## Prune orphaned activities from the database
|
||||
|
||||
This will prune activities which are no longer referenced by anything.
|
||||
Such activities might be the result of running `prune_objects` without `--prune-orphaned-activities`.
|
||||
The same notes and warnings apply as for `prune_objects`.
|
||||
|
||||
The task will print out how many rows were freed in total in its last
|
||||
line of output in the form `Deleted 345 rows`.
|
||||
When running the job in limited batches this can be used to determine
|
||||
when all orphaned activities have been deleted.
|
||||
|
||||
=== "OTP"
|
||||
|
||||
```sh
|
||||
./bin/pleroma_ctl database prune_orphaned_activities [option ...]
|
||||
```
|
||||
|
||||
=== "From Source"
|
||||
|
||||
```sh
|
||||
mix pleroma.database prune_orphaned_activities [option ...]
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
- `--limit n` - Only delete up to `n` activities in each query making up this job, i.e. if this job runs two queries at most `2n` activities will be deleted. Running this task repeatedly in limited batches can help maintain the instance’s responsiveness while still freeing up some space.
|
||||
- `--no-singles` - Do not delete activites referencing single objects
|
||||
- `--no-arrays` - Do not delete activites referencing an array of objects
|
||||
|
||||
## Create a conversation for all existing DMs
|
||||
|
||||
Can be safely re-run
|
||||
|
|
|
@ -4,12 +4,12 @@
|
|||
|
||||
1. Stop the Akkoma service.
|
||||
2. Go to the working directory of Akkoma (default is `/opt/akkoma`)
|
||||
3. Run[¹] `sudo -Hu postgres pg_dump -d akkoma --format=custom -f </path/to/backup_location/akkoma.pgdump>` (make sure the postgres user has write access to the destination file)
|
||||
4. Copy `akkoma.pgdump`, `config/prod.secret.exs`[²], `config/setup_db.psql` (if still available) and the `uploads` folder to your backup destination. If you have other modifications, copy those changes too.
|
||||
3. Run `sudo -Hu postgres pg_dump -d akkoma --format=custom -f </path/to/backup_location/akkoma.pgdump>`[¹] (make sure the postgres user has write access to the destination file)
|
||||
4. Copy `akkoma.pgdump`, `config/config.exs`[²], `uploads` folder, and [static directory](../configuration/static_dir.md) to your backup destination. If you have other modifications, copy those changes too.
|
||||
5. Restart the Akkoma service.
|
||||
|
||||
[¹]: We assume the database name is "akkoma". If not, you can find the correct name in your config files.
|
||||
[²]: If you've installed using OTP, you need `config/config.exs` instead of `config/prod.secret.exs`.
|
||||
[¹]: We assume the database name is "akkoma". If not, you can find the correct name in your configuration files.
|
||||
[²]: If you have a from source installation, you need `config/prod.secret.exs` instead of `config/config.exs`. The `config/config.exs` file also exists, but in case of from source installations, it only contains the default values and it is tracked by Git, so you don't need to back it up.
|
||||
|
||||
## Restore/Move
|
||||
|
||||
|
@ -17,19 +17,16 @@
|
|||
2. Stop the Akkoma service.
|
||||
3. Go to the working directory of Akkoma (default is `/opt/akkoma`)
|
||||
4. Copy the above mentioned files back to their original position.
|
||||
5. Drop the existing database and user if restoring in-place[¹]. `sudo -Hu postgres psql -c 'DROP DATABASE akkoma;';` `sudo -Hu postgres psql -c 'DROP USER akkoma;'`
|
||||
6. Restore the database schema and akkoma role using either of the following options
|
||||
* You can use the original `setup_db.psql` if you have it[²]: `sudo -Hu postgres psql -f config/setup_db.psql`.
|
||||
* Or recreate the database and user yourself (replace the password with the one you find in the config file) `sudo -Hu postgres psql -c "CREATE USER akkoma WITH ENCRYPTED PASSWORD '<database-password-wich-you-can-find-in-your-config-file>'; CREATE DATABASE akkoma OWNER akkoma;"`.
|
||||
5. Drop the existing database and user[¹]. `sudo -Hu postgres psql -c 'DROP DATABASE akkoma;';` `sudo -Hu postgres psql -c 'DROP USER akkoma;'`
|
||||
6. Restore the database schema and akkoma role[¹] (replace the password with the one you find in the configuration file), `sudo -Hu postgres psql -c "CREATE USER akkoma WITH ENCRYPTED PASSWORD '<database-password-wich-you-can-find-in-your-configuration-file>';"` `sudo -Hu postgres psql -c "CREATE DATABASE akkoma OWNER akkoma;"`.
|
||||
7. Now restore the Akkoma instance's data into the empty database schema[¹]: `sudo -Hu postgres pg_restore -d akkoma -v -1 </path/to/backup_location/akkoma.pgdump>`
|
||||
8. If you installed a newer Akkoma version, you should run `MIX_ENV=prod mix ecto.migrate`[³]. This task performs database migrations, if there were any.
|
||||
8. If you installed a newer Akkoma version, you should run the database migrations `./bin/pleroma_ctl migrate`[²].
|
||||
9. Restart the Akkoma service.
|
||||
10. Run `sudo -Hu postgres vacuumdb --all --analyze-in-stages`. This will quickly generate the statistics so that postgres can properly plan queries.
|
||||
11. If setting up on a new server configure Nginx by using the `installation/akkoma.nginx` config sample or reference the Akkoma installation guide for your OS which contains the Nginx configuration instructions.
|
||||
11. If setting up on a new server, configure Nginx by using the `installation/nginx/akkoma.nginx` configuration sample or reference the Akkoma installation guide which contains the Nginx configuration instructions.
|
||||
|
||||
[¹]: We assume the database name and user are both "akkoma". If not, you can find the correct name in your config files.
|
||||
[²]: You can recreate the `config/setup_db.psql` by running the `mix pleroma.instance gen` task again. You can ignore most of the questions, but make the database user, name, and password the same as found in your backed up config file. This will also create a new `config/generated_config.exs` file which you may delete as it is not needed.
|
||||
[³]: Prefix with `MIX_ENV=prod` to run it using the production config file.
|
||||
[¹]: We assume the database name and user are both "akkoma". If not, you can find the correct name in your configuration files.
|
||||
[²]: If you have a from source installation, the command is `MIX_ENV=prod mix ecto.migrate`. Note that we prefix with `MIX_ENV=prod` to use the `config/prod.secret.exs` configuration file.
|
||||
|
||||
## Remove
|
||||
|
||||
|
|
|
@ -63,6 +63,8 @@ To add configuration to your config file, you can copy it from the base config.
|
|||
* `local_bubble`: Array of domains representing instances closely related to yours. Used to populate the `bubble` timeline. e.g `["example.com"]`, (default: `[]`)
|
||||
* `languages`: List of Language Codes used by the instance. This is used to try and set a default language from the frontend. It will try and find the first match between the languages set here and the user's browser languages. It will default to the first language in this setting if there is no match.. (default `["en"]`)
|
||||
* `export_prometheus_metrics`: Enable prometheus metrics, served at `/api/v1/akkoma/metrics`, requiring the `admin:metrics` oauth scope.
|
||||
* `privileged_staff`: Set to `true` to give moderators access to a few higher responsibility actions.
|
||||
* `federated_timeline_available`: Set to `false` to remove access to the federated timeline for all users.
|
||||
|
||||
## :database
|
||||
* `improved_hashtag_timeline`: Setting to force toggle / force disable improved hashtags timeline. `:enabled` forces hashtags to be fetched from `hashtags` table for hashtags timeline. `:disabled` forces object-embedded hashtags to be used (slower). Keep it `:auto` for automatic behaviour (it is auto-set to `:enabled` [unless overridden] when HashtagsTableMigrator completes).
|
||||
|
@ -336,7 +338,7 @@ config :pleroma, :frontends,
|
|||
|
||||
* `:primary` - The frontend that will be served at `/`
|
||||
* `:admin` - The frontend that will be served at `/pleroma/admin`
|
||||
* `:swagger` - Config for developers to act as an API reference to be served at `/akkoma/swaggerui/` (trailing slash _needed_). Disabled by default.
|
||||
* `:swagger` - Config for developers to act as an API reference to be served at `/pleroma/swaggerui/` (trailing slash _needed_). Disabled by default.
|
||||
* `:mastodon` - The mastodon-fe configuration. This shouldn't need to be changed. This is served at `/web` when installed.
|
||||
|
||||
### :static\_fe
|
||||
|
@ -603,7 +605,6 @@ the source code is here: [kocaptcha](https://github.com/koto-bank/kocaptcha). Th
|
|||
* `link_name`: When enabled Akkoma will add a `name` parameter to the url of the upload, for example `https://instance.tld/media/corndog.png?name=corndog.png`. This is needed to provide the correct filename in Content-Disposition headers
|
||||
* `base_url`: The base URL to access a user-uploaded file; MUST be configured explicitly.
|
||||
Using a (sub)domain distinct from the instance endpoint is **strongly** recommended. A good value might be `https://media.myakkoma.instance/media/`.
|
||||
* `proxy_remote`: If you're using a remote uploader, Akkoma will proxy media requests instead of redirecting to it.
|
||||
* `proxy_opts`: Proxy options, see `Pleroma.ReverseProxy` documentation.
|
||||
* `filename_display_max_length`: Set max length of a filename to display. 0 = no limit. Default: 30.
|
||||
|
||||
|
|
|
@ -60,4 +60,4 @@ config :pleroma, :frontends,
|
|||
|
||||
Then run the [pleroma.frontend cli task](../../administration/CLI_tasks/frontend) with the name of `swagger-ui` to install the distribution files.
|
||||
|
||||
You will now be able to view documentation at `/akkoma/swaggerui`
|
||||
You will now be able to view documentation at `/pleroma/swaggerui`
|
||||
|
|
|
@ -6,37 +6,17 @@ With the `mediaproxy` function you can use nginx to cache this content, so users
|
|||
|
||||
## Activate it
|
||||
|
||||
* Edit your nginx config and add the following location to your main server block:
|
||||
```
|
||||
location /proxy {
|
||||
return 404;
|
||||
}
|
||||
```
|
||||
|
||||
* Set up a subdomain for the proxy with its nginx config on the same machine
|
||||
*(the latter is not strictly required, but for simplicity we’ll assume so)*
|
||||
* In this subdomain’s server block add
|
||||
```
|
||||
location /proxy {
|
||||
proxy_cache akkoma_media_cache;
|
||||
proxy_cache_lock on;
|
||||
proxy_pass http://localhost:4000;
|
||||
}
|
||||
```
|
||||
Also add the following on top of the configuration, outside of the `server` block:
|
||||
```
|
||||
proxy_cache_path /tmp/akkoma-media-cache levels=1:2 keys_zone=akkoma_media_cache:10m max_size=10g inactive=720m use_temp_path=off;
|
||||
```
|
||||
If you came here from one of the installation guides, take a look at the example configuration `/installation/nginx/akkoma.nginx`, where this part is already included.
|
||||
|
||||
* Edit the nginx config for the upload/MediaProxy subdomain to point to the subdomain that has been set up
|
||||
* Append the following to your `prod.secret.exs` or `dev.secret.exs` (depends on which mode your instance is running):
|
||||
```
|
||||
```elixir
|
||||
# Replace media.example.td with the subdomain you set up earlier
|
||||
config :pleroma, :media_proxy,
|
||||
enabled: true,
|
||||
proxy_opts: [
|
||||
redirect_on_failure: true
|
||||
],
|
||||
base_url: "https://cache.akkoma.social"
|
||||
base_url: "https://media.example.tld"
|
||||
```
|
||||
You **really** should use a subdomain to serve proxied files; while we will fix bugs resulting from this, serving arbitrary remote content on your main domain namespace is a significant attack surface.
|
||||
|
||||
|
|
|
@ -130,59 +130,26 @@ config :pleroma, :http_security,
|
|||
enabled: false
|
||||
```
|
||||
|
||||
Use this as the Nginx config:
|
||||
```
|
||||
proxy_cache_path /tmp/akkoma-media-cache levels=1:2 keys_zone=akkoma_media_cache:10m max_size=10g inactive=720m use_temp_path=off;
|
||||
# The above already exists in a clearnet instance's config.
|
||||
# If not, add it.
|
||||
|
||||
server {
|
||||
listen 127.0.0.1:14447;
|
||||
server_name youri2paddress;
|
||||
|
||||
# Comment to enable logs
|
||||
access_log /dev/null;
|
||||
error_log /dev/null;
|
||||
|
||||
gzip_vary on;
|
||||
gzip_proxied any;
|
||||
gzip_comp_level 6;
|
||||
gzip_buffers 16 8k;
|
||||
gzip_http_version 1.1;
|
||||
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/activity+json application/atom+xml;
|
||||
|
||||
client_max_body_size 16m;
|
||||
|
||||
location / {
|
||||
|
||||
In the Nginx config, add the following into the `location /` block:
|
||||
```nginx
|
||||
add_header X-XSS-Protection "0";
|
||||
add_header X-Permitted-Cross-Domain-Policies none;
|
||||
add_header X-Frame-Options DENY;
|
||||
add_header X-Content-Type-Options nosniff;
|
||||
add_header Referrer-Policy same-origin;
|
||||
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $http_host;
|
||||
|
||||
proxy_pass http://localhost:4000;
|
||||
|
||||
client_max_body_size 16m;
|
||||
}
|
||||
|
||||
location /proxy {
|
||||
proxy_cache akkoma_media_cache;
|
||||
proxy_cache_lock on;
|
||||
proxy_ignore_client_abort on;
|
||||
proxy_pass http://localhost:4000;
|
||||
}
|
||||
}
|
||||
```
|
||||
reload Nginx:
|
||||
|
||||
Change the `listen` directive to the following:
|
||||
```nginx
|
||||
listen 127.0.0.1:14447;
|
||||
```
|
||||
systemctl stop i2pd.service --no-block
|
||||
systemctl start i2pd.service
|
||||
|
||||
Set `server_name` to your i2p address.
|
||||
|
||||
Reload Nginx:
|
||||
```
|
||||
systemctl restart i2pd.service --no-block
|
||||
systemctl reload nginx.service
|
||||
```
|
||||
*Notice:* The stop command initiates a graceful shutdown process, i2pd stops after finishing to route transit tunnels (maximum 10 minutes).
|
||||
|
||||
|
|
|
@ -74,56 +74,23 @@ config :pleroma, :http_security,
|
|||
enabled: false
|
||||
```
|
||||
|
||||
Use this as the Nginx config:
|
||||
```
|
||||
proxy_cache_path /tmp/akkoma-media-cache levels=1:2 keys_zone=akkoma_media_cache:10m max_size=10g inactive=720m use_temp_path=off;
|
||||
# The above already exists in a clearnet instance's config.
|
||||
# If not, add it.
|
||||
|
||||
server {
|
||||
listen 127.0.0.1:8099;
|
||||
server_name youronionaddress;
|
||||
|
||||
# Comment to enable logs
|
||||
access_log /dev/null;
|
||||
error_log /dev/null;
|
||||
|
||||
gzip_vary on;
|
||||
gzip_proxied any;
|
||||
gzip_comp_level 6;
|
||||
gzip_buffers 16 8k;
|
||||
gzip_http_version 1.1;
|
||||
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/activity+json application/atom+xml;
|
||||
|
||||
client_max_body_size 16m;
|
||||
|
||||
location / {
|
||||
|
||||
In the Nginx config, add the following into the `location /` block:
|
||||
```nginx
|
||||
add_header X-XSS-Protection "0";
|
||||
add_header X-Permitted-Cross-Domain-Policies none;
|
||||
add_header X-Frame-Options DENY;
|
||||
add_header X-Content-Type-Options nosniff;
|
||||
add_header Referrer-Policy same-origin;
|
||||
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $http_host;
|
||||
|
||||
proxy_pass http://localhost:4000;
|
||||
|
||||
client_max_body_size 16m;
|
||||
}
|
||||
|
||||
location /proxy {
|
||||
proxy_cache akkoma_media_cache;
|
||||
proxy_cache_lock on;
|
||||
proxy_ignore_client_abort on;
|
||||
proxy_pass http://localhost:4000;
|
||||
}
|
||||
}
|
||||
```
|
||||
reload Nginx:
|
||||
|
||||
Change the `listen` directive to the following:
|
||||
```nginx
|
||||
listen 127.0.0.1:8099;
|
||||
```
|
||||
|
||||
Set the `server_name` to your onion address.
|
||||
|
||||
Reload Nginx:
|
||||
```
|
||||
systemctl reload nginx
|
||||
```
|
||||
|
|
|
@ -4,47 +4,10 @@ Akkoma performance is largely dependent on performance of the underlying databas
|
|||
|
||||
## PGTune
|
||||
|
||||
[PgTune](https://pgtune.leopard.in.ua) can be used to get recommended settings. Be sure to set "Number of Connections" to 20, otherwise it might produce settings hurtful to database performance. It is also recommended to not use "Network Storage" option.
|
||||
[PgTune](https://pgtune.leopard.in.ua) can be used to get recommended settings. Make sure to set the DB type to "Online transaction processing system" for optimal performance. Also set the number of connections to between 25 and 30. This will allow each connection to have access to more resources while still leaving some room for running maintenance tasks while the instance is still running.
|
||||
|
||||
If your server runs other services, you may want to take that into account. E.g. if you have 4G ram, but 1G of it is already used for other services, it may be better to tell PGTune you only have 3G. In the end, PGTune only provides recomended settings, you can always try to finetune further.
|
||||
It is also recommended to not use "Network Storage" option.
|
||||
|
||||
### Example configurations
|
||||
If your server runs other services, you may want to take that into account. E.g. if you have 4G ram, but 1G of it is already used for other services, it may be better to tell PGTune you only have 3G.
|
||||
|
||||
Here are some configuration suggestions for PostgreSQL 10+.
|
||||
|
||||
#### 1GB RAM, 1 CPU
|
||||
```
|
||||
shared_buffers = 256MB
|
||||
effective_cache_size = 768MB
|
||||
maintenance_work_mem = 64MB
|
||||
work_mem = 13107kB
|
||||
```
|
||||
|
||||
#### 2GB RAM, 2 CPU
|
||||
```
|
||||
shared_buffers = 512MB
|
||||
effective_cache_size = 1536MB
|
||||
maintenance_work_mem = 128MB
|
||||
work_mem = 26214kB
|
||||
max_worker_processes = 2
|
||||
max_parallel_workers_per_gather = 1
|
||||
max_parallel_workers = 2
|
||||
```
|
||||
|
||||
## Disable generic query plans
|
||||
|
||||
When PostgreSQL receives a query, it decides on a strategy for searching the requested data, this is called a query plan. The query planner has two modes: generic and custom. Generic makes a plan for all queries of the same shape, ignoring the parameters, which is then cached and reused. Custom, on the contrary, generates a unique query plan based on query parameters.
|
||||
|
||||
By default PostgreSQL has an algorithm to decide which mode is more efficient for particular query, however this algorithm has been observed to be wrong on some of the queries Akkoma sends, leading to serious performance loss. Therefore, it is recommended to disable generic mode.
|
||||
|
||||
|
||||
Akkoma already avoids generic query plans by default, however the method it uses is not the most efficient because it needs to be compatible with all supported PostgreSQL versions. For PostgreSQL 12 and higher additional performance can be gained by adding the following to Akkoma configuration:
|
||||
```elixir
|
||||
config :pleroma, Pleroma.Repo,
|
||||
prepare: :named,
|
||||
parameters: [
|
||||
plan_cache_mode: "force_custom_plan"
|
||||
]
|
||||
```
|
||||
|
||||
A more detailed explaination of the issue can be found at <https://blog.soykaf.com/post/postgresql-elixir-troubles/>.
|
||||
In the end, PGTune only provides recomended settings, you can always try to finetune further.
|
||||
|
|
|
@ -33,6 +33,7 @@ indexes faster when it can process many posts in a single batch.
|
|||
> config :pleroma, Pleroma.Search.Meilisearch,
|
||||
> url: "http://127.0.0.1:7700/",
|
||||
> private_key: "private key",
|
||||
> search_key: "search key",
|
||||
> initial_indexing_chunk_size: 100_000
|
||||
|
||||
Information about setting up meilisearch can be found in the
|
||||
|
@ -45,7 +46,7 @@ is hardly usable on a somewhat big instance.
|
|||
### Private key authentication (optional)
|
||||
|
||||
To set the private key, use the `MEILI_MASTER_KEY` environment variable when starting. After setting the _master key_,
|
||||
you have to get the _private key_, which is actually used for authentication.
|
||||
you have to get the _private key_ and possibly _search key_, which are actually used for authentication.
|
||||
|
||||
=== "OTP"
|
||||
```sh
|
||||
|
@ -57,7 +58,11 @@ you have to get the _private key_, which is actually used for authentication.
|
|||
mix pleroma.search.meilisearch show-keys <your master key here>
|
||||
```
|
||||
|
||||
You will see a "Default Admin API Key", this is the key you actually put into your configuration file.
|
||||
You will see a "Default Admin API Key", this is the key you actually put into
|
||||
your configuration file as `private_key`. You should also see a
|
||||
"Default Search API key", put this into your config as `search_key`.
|
||||
If your version of Meilisearch only showed the former,
|
||||
just leave `search_key` completely unset in Akkoma's config.
|
||||
|
||||
### Initial indexing
|
||||
|
||||
|
|
|
@ -6,7 +6,7 @@ as soon as the post is received by your instance.
|
|||
|
||||
## Nginx
|
||||
|
||||
The following are excerpts from the [suggested nginx config](../../../installation/nginx/akkoma.nginx) that demonstrates the necessary config for the media proxy to work.
|
||||
The following are excerpts from the [suggested nginx config](https://akkoma.dev/AkkomaGang/akkoma/src/branch/develop/installation/nginx/akkoma.nginx) that demonstrates the necessary config for the media proxy to work.
|
||||
|
||||
A `proxy_cache_path` must be defined, for example:
|
||||
|
||||
|
|
|
@ -1033,7 +1033,6 @@ Most of the settings will be applied in `runtime`, this means that you don't nee
|
|||
- `:pools`
|
||||
- partially settings inside these keys:
|
||||
- `:seconds_valid` in `Pleroma.Captcha`
|
||||
- `:proxy_remote` in `Pleroma.Upload`
|
||||
- `:upload_limit` in `:instance`
|
||||
|
||||
- Params:
|
||||
|
@ -1094,7 +1093,6 @@ List of settings which support only full update by subkey:
|
|||
{"tuple": [":uploader", "Pleroma.Uploaders.Local"]},
|
||||
{"tuple": [":filters", ["Pleroma.Upload.Filter.Dedupe"]]},
|
||||
{"tuple": [":link_name", true]},
|
||||
{"tuple": [":proxy_remote", false]},
|
||||
{"tuple": [":proxy_opts", [
|
||||
{"tuple": [":redirect_on_failure", false]},
|
||||
{"tuple": [":max_body_length", 1048576]},
|
||||
|
|
|
@ -4,7 +4,6 @@
|
|||
The following endpoints are additionally present into our actors.
|
||||
|
||||
- `oauthRegistrationEndpoint` (`http://litepub.social/ns#oauthRegistrationEndpoint`)
|
||||
- `uploadMedia` (`https://www.w3.org/ns/activitystreams#uploadMedia`)
|
||||
|
||||
### oauthRegistrationEndpoint
|
||||
|
||||
|
@ -12,6 +11,279 @@ Points to MastodonAPI `/api/v1/apps` for now.
|
|||
|
||||
See <https://docs.joinmastodon.org/methods/apps/>
|
||||
|
||||
## Emoji reactions
|
||||
|
||||
Emoji reactions are implemented as a new activity type `EmojiReact`.
|
||||
A single user is allowed to react multiple times with different emoji to the
|
||||
same post. However, they may only react at most once with the same emoji.
|
||||
Repeated reaction from the same user with the same emoji are to be ignored.
|
||||
Emoji reactions are also distinct from `Like` activities and a user may both
|
||||
`Like` and react to a post.
|
||||
|
||||
!!! note
|
||||
Misskey also supports emoji reactions, but the implementations differs.
|
||||
It equates likes and reactions and only allows a single reaction per post.
|
||||
|
||||
The emoji is placed in the `content` field of the activity
|
||||
and the `object` property points to the note reacting to.
|
||||
|
||||
Emoji can either be any Unicode emoji sequence or a custom emoji.
|
||||
The latter must place their shortcode, including enclosing colons,
|
||||
into `content` and put the emoji object inside the `tag` property.
|
||||
The `tag` property MAY be omitted for Unicode emoji.
|
||||
|
||||
An example reaction with a Unicode emoji:
|
||||
```json
|
||||
{
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/activitystreams",
|
||||
"https://example.org/schemas/litepub-0.1.jsonld",
|
||||
{
|
||||
"@language": "und"
|
||||
}
|
||||
],
|
||||
"type": "EmojiReact",
|
||||
"id": "https://example.org/activities/23143872a0346141",
|
||||
"actor": "https://example.org/users/akko",
|
||||
"nickname": "akko",
|
||||
"to": ["https://remote.example/users/diana", "https://example.org/users/akko/followers"],
|
||||
"cc": ["https://www.w3.org/ns/activitystreams#Public"],
|
||||
"content": "🧡",
|
||||
"object": "https://remote.example/objects/9f0e93499d8314a9"
|
||||
}
|
||||
```
|
||||
|
||||
An example reaction with a custom emoji:
|
||||
```json
|
||||
{
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/activitystreams",
|
||||
"https://example.org/schemas/litepub-0.1.jsonld",
|
||||
{
|
||||
"@language": "und"
|
||||
}
|
||||
],
|
||||
"type": "EmojiReact",
|
||||
"id": "https://example.org/activities/d75586dec0541650",
|
||||
"actor": "https://example.org/users/akko",
|
||||
"nickname": "akko",
|
||||
"to": ["https://remote.example/users/diana", "https://example.org/users/akko/followers"],
|
||||
"cc": ["https://www.w3.org/ns/activitystreams#Public"],
|
||||
"content": ":mouse:",
|
||||
"object": "https://remote.example/objects/9f0e93499d8314a9",
|
||||
"tag": [{
|
||||
"type": "Emoji",
|
||||
"id": null,
|
||||
"name": "mouse",
|
||||
"icon": {
|
||||
"type": "Image",
|
||||
"url": "https://example.org/emoji/mouse/mouse.png"
|
||||
}
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
!!! note
|
||||
Although an emoji reaction can only contain a single emoji,
|
||||
for compatibility with older versions of Pleroma and Akkoma,
|
||||
it is recommended to wrap the emoji object in a single-element array.
|
||||
|
||||
When reacting with a remote custom emoji do not include the remote domain in `content`’s shortcode
|
||||
*(unlike in our REST API which needs the domain)*:
|
||||
```json
|
||||
{
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/activitystreams",
|
||||
"https://example.org/schemas/litepub-0.1.jsonld",
|
||||
{
|
||||
"@language": "und"
|
||||
}
|
||||
],
|
||||
"type": "EmojiReact",
|
||||
"id": "https://example.org/activities/7993dcae98d8d5ec",
|
||||
"actor": "https://example.org/users/akko",
|
||||
"nickname": "akko",
|
||||
"to": ["https://remote.example/users/diana", "https://example.org/users/akko/followers"],
|
||||
"cc": ["https://www.w3.org/ns/activitystreams#Public"],
|
||||
"content": ":hug:",
|
||||
"object": "https://remote.example/objects/9f0e93499d8314a9",
|
||||
"tag": [{
|
||||
"type": "Emoji",
|
||||
"id": "https://other.example/emojis/hug",
|
||||
"name": "hug",
|
||||
"icon": {
|
||||
"type": "Image",
|
||||
"url": "https://other.example/files/b71cea432b3fad67.webp"
|
||||
}
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
Emoji reactions can be retracted using a standard `Undo` activity:
|
||||
```json
|
||||
{
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/activitystreams",
|
||||
"http://example.org/schemas/litepub-0.1.jsonld",
|
||||
{
|
||||
"@language": "und"
|
||||
}
|
||||
],
|
||||
"type": "Undo",
|
||||
"id": "http://example.org/activities/4685792e-efb6-4309-b508-ae4f355dd695",
|
||||
"actor": "https://example.org/users/akko",
|
||||
"to": ["https://remote.example/users/diana", "https://example.org/users/akko/followers"],
|
||||
"cc": ["https://www.w3.org/ns/activitystreams#Public"],
|
||||
"object": "https://example.org/activities/23143872a0346141"
|
||||
}
|
||||
```
|
||||
|
||||
## User profile backgrounds
|
||||
|
||||
Akkoma federates user profile backgrounds the same way as Sharkey.
|
||||
|
||||
An actors ActivityPub representation contains an additional
|
||||
`backgroundUrl` property containing an `Image` object. This property
|
||||
belongs to the `"sharkey": "https://joinsharkey.org/ns#"` namespace.
|
||||
|
||||
## Quote Posts
|
||||
|
||||
Akkoma allows referencing a single other note as a quote,
|
||||
which will be prominently displayed in the interface.
|
||||
|
||||
The quoted post is referenced by its ActivityPub id in the `quoteUri` property.
|
||||
|
||||
!!! note
|
||||
Old Misskey only understood and modern Misskey still prefers
|
||||
the `_misskey_quote` property for this. Similar some other older
|
||||
software used `quoteUrl` or `quoteURL`.
|
||||
All current implementations with quote support understand `quoteUri`.
|
||||
|
||||
Example:
|
||||
```json
|
||||
{
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/activitystreams",
|
||||
"https://example.org/schemas/litepub-0.1.jsonld",
|
||||
{
|
||||
"@language": "und"
|
||||
}
|
||||
],
|
||||
"type": "Note",
|
||||
"id": "https://example.org/activities/85717e587f95d5c0",
|
||||
"actor": "https://example.org/users/akko",
|
||||
"to": ["https://remote.example/users/diana", "https://example.org/users/akko/followers"],
|
||||
"cc": ["https://www.w3.org/ns/activitystreams#Public"],
|
||||
"context": "https://example.org/contexts/1",
|
||||
"content": "Look at that!",
|
||||
"quoteUri": "http://remote.example/status/85717e587f95d5c0",
|
||||
"contentMap": {
|
||||
"en": "Look at that!"
|
||||
},
|
||||
"source": {
|
||||
"content": "Look at that!",
|
||||
"mediaType": "text/plain"
|
||||
},
|
||||
"published": "2024-04-06T23:40:28Z",
|
||||
"updated": "2024-04-06T23:40:28Z",
|
||||
"attachemnt": [],
|
||||
"tag": []
|
||||
}
|
||||
```
|
||||
|
||||
## Threads
|
||||
|
||||
Akkoma assigns all posts of the same thread the same `context`. This is a
|
||||
standard ActivityPub property but its meaning is left vague. Akkoma will
|
||||
always treat posts with identical `context` as part of the same thread.
|
||||
|
||||
`context` must not be assumed to hold any meaning or be dereferencable.
|
||||
|
||||
Incoming posts without `context` will be assigned a new context.
|
||||
|
||||
!!! note
|
||||
Mastodon uses the non-standard `conversation` property for the same purpose
|
||||
*(named after an older OStatus property)*. For incoming posts without
|
||||
`context` but with `converstions` Akkoma will use the value from
|
||||
`conversations` to fill in `context`.
|
||||
For outgoing posts Akkoma will duplicate the context into `conversation`.
|
||||
|
||||
## Post Source
|
||||
|
||||
Unlike Mastodon, Akkoma supports drafting posts in multiple source formats
|
||||
besides plaintext, like Markdown or MFM. The original input is preserved
|
||||
in the standard ActivityPub `source` property *(not supported by Mastodon)*.
|
||||
Still, `content` will always be present and contain the prerendered HTML form.
|
||||
|
||||
Supported `mediaType` include:
|
||||
- `text/plain`
|
||||
- `text/markdown`
|
||||
- `text/bbcode`
|
||||
- `text/x.misskeymarkdown`
|
||||
|
||||
## Post Language
|
||||
|
||||
!!! note
|
||||
This is also supported in and compatible with Mastodon, but since
|
||||
joinmastodon.org doesn’t document it yet it is included here.
|
||||
[GoToSocial](https://docs.gotosocial.org/en/latest/federation/federating_with_gotosocial/#content-contentmap-and-language)
|
||||
has a more refined version of this which can correctly deal with multiple language entries.
|
||||
|
||||
A post can indicate its language by including a `contentMap` object
|
||||
which contains a sub key named after the language’s ISO 639-1 code
|
||||
and it’s content identical to the post’s `content` field.
|
||||
|
||||
Currently Akkoma, just like Mastodon, only properly supports a single language entry,
|
||||
in case of multiple entries a random language will be picked.
|
||||
Furthermore, Akkoma currently only reads the `content` field
|
||||
and never the value from `contentMap`.
|
||||
|
||||
## Local post scope
|
||||
|
||||
Post using this scope will never federate to other servers
|
||||
but for the sake of completeness it is listed here.
|
||||
|
||||
In addition to the usual scopes *(public, unlisted, followers-only, direct)*
|
||||
Akkoma supports an “unlisted” post scope. Such posts will not federate to
|
||||
other instances and only be shown to logged-in users on the same instance.
|
||||
It is included into the local timeline.
|
||||
This may be useful to discuss or announce instance-specific policies and topics.
|
||||
|
||||
A post is addressed to the local scope by including `<base url of instance>/#Public`
|
||||
in its `to` field. E.g. if the instance is on `https://example.org` it would use
|
||||
`https://example.org/#Public`.
|
||||
|
||||
An implementation creating a new post MUST NOT address both the local and
|
||||
general public scope `as:Public` at the same time. A post addressing the local
|
||||
scope MUST NOT be sent to other instances or be possible to fetch by other
|
||||
instances regardless of potential other listed addressees.
|
||||
|
||||
When receiving a remote post addressing both the public scope and what appears
|
||||
to be a local-scope identifier, the post SHOULD be treated without assigning any
|
||||
special meaning to the potential local-scope identifier.
|
||||
|
||||
!!! note
|
||||
Misskey-derivatives have a similar concept of non-federated posts,
|
||||
however those are also shown publicly on the local web interface
|
||||
and are thus visible to non-members.
|
||||
|
||||
## List post scope
|
||||
|
||||
Messages originally addressed to a custom list will contain
|
||||
a `listMessage` field with an unresolvable pseudo ActivityPub id.
|
||||
|
||||
# Deprecated and Removed Extensions
|
||||
|
||||
The following extensions were used in the past but have been dropped.
|
||||
Documentation is retained here as a reference and since old objects might
|
||||
still contains related fields.
|
||||
|
||||
## Actor endpoints
|
||||
|
||||
The following endpoints used to be present:
|
||||
|
||||
- `uploadMedia` (`https://www.w3.org/ns/activitystreams#uploadMedia`)
|
||||
|
||||
### uploadMedia
|
||||
|
||||
Inspired by <https://www.w3.org/wiki/SocialCG/ActivityPub/MediaUpload>, it is part of the ActivityStreams namespace because it used to be part of the ActivityPub specification and got removed from it.
|
||||
|
@ -20,9 +292,8 @@ Content-Type: multipart/form-data
|
|||
|
||||
Parameters:
|
||||
- (required) `file`: The file being uploaded
|
||||
- (optionnal) `description`: A plain-text description of the media, for accessibility purposes.
|
||||
- (optional) `description`: A plain-text description of the media, for accessibility purposes.
|
||||
|
||||
Response: HTTP 201 Created with the object into the body, no `Location` header provided as it doesn't have an `id`
|
||||
|
||||
The object given in the reponse should then be inserted into an Object's `attachment` field.
|
||||
|
||||
The object given in the response should then be inserted into an Object's `attachment` field.
|
||||
|
|
141
docs/docs/development/nodeinfo_extensions.md
Normal file
141
docs/docs/development/nodeinfo_extensions.md
Normal file
|
@ -0,0 +1,141 @@
|
|||
# Nodeinfo Extensions
|
||||
|
||||
Akkoma currently implements version 2.0 and 2.1 of nodeinfo spec,
|
||||
but provides the following additional fields.
|
||||
|
||||
## metadata
|
||||
|
||||
The spec leaves the content of `metadata` up to implementations
|
||||
and indeed Akkoma adds many fields here apart from the commonly
|
||||
found `nodeName` and `nodeDescription` fields.
|
||||
|
||||
### accountActivationRequired
|
||||
Whether or not users need to confirm their email before completing registration.
|
||||
*(boolean)*
|
||||
|
||||
!!! note
|
||||
Not to be confused with account approval, where each registration needs to
|
||||
be manually approved by an admin. Account approval has no nodeinfo entry.
|
||||
|
||||
### features
|
||||
|
||||
Array of strings denoting supported server features. E.g. a server supporting
|
||||
quote posts should include a `"quote_posting"` entry here.
|
||||
|
||||
A non-exhaustive list of possible features:
|
||||
- `polls`
|
||||
- `quote_posting`
|
||||
- `editing`
|
||||
- `bubble_timeline`
|
||||
- `pleroma_emoji_reactions` *(Unicode emoji)*
|
||||
- `custom_emoji_reactions`
|
||||
- `akkoma_api`
|
||||
- `akkoma:machine_translation`
|
||||
- `mastodon_api`
|
||||
- `pleroma_api`
|
||||
|
||||
### federatedTimelineAvailable
|
||||
Whether or not the “federated timeline”, i.e. a timeline containing posts from
|
||||
the entire known network, is made available.
|
||||
*(boolean)*
|
||||
|
||||
### federation
|
||||
This section is optional and can contain various custom keys describing federation policies.
|
||||
The following are required to be presented:
|
||||
- `enabled` *(boolean)* whether the server federates at all
|
||||
|
||||
A non-exhaustive list of optional keys:
|
||||
- `exclusions` *(boolean)* whether some federation policies are withheld
|
||||
- `mrf_simple` *(object)* describes how the Simple MRF policy is configured
|
||||
|
||||
### fieldsLimits
|
||||
A JSON object documenting restriction for user account info fields.
|
||||
All properties are integers.
|
||||
|
||||
- `maxFields` maximum number of account info fields local users can create
|
||||
- `maxRemoteFields` maximum number of account info fields remote users can have
|
||||
before the user gets rejected or fields truncated
|
||||
- `nameLength` maximum length of a field’s name
|
||||
- `valueLength` maximum length of a field’s value
|
||||
|
||||
### invitesEnabled
|
||||
Whether or not signing up via invite codes is possible.
|
||||
*(boolean)*
|
||||
|
||||
### localBubbleInstances
|
||||
Array of domains (as strings) of other instances chosen
|
||||
by the admin which are shown in the bubble timeline.
|
||||
|
||||
### mailerEnabled
|
||||
Whether or not the instance can send out emails.
|
||||
*(boolean)*
|
||||
|
||||
### nodeDescription
|
||||
Human-friendly description of this instance
|
||||
*(string)*
|
||||
|
||||
### nodeName
|
||||
Human-friendly name of this instance
|
||||
*(string)*
|
||||
|
||||
### pollLimits
|
||||
JSON object containing limits for polls created by local users.
|
||||
All values are integers.
|
||||
- `max_options` maximum number of poll options
|
||||
- `max_option_chars` maximum characters per poll option
|
||||
- `min_expiration` minimum time in seconds a poll must be open for
|
||||
- `max_expiration` maximum time a poll is allowed to be open for
|
||||
|
||||
### postFormats
|
||||
Array of strings containing media types for supported post source formats.
|
||||
A non-exhaustive list of possible values:
|
||||
- `text/plain`
|
||||
- `text/markdown`
|
||||
- `text/bbcode`
|
||||
- `text/x.misskeymarkdown`
|
||||
|
||||
### private
|
||||
Whether or not unauthenticated API access is permitted.
|
||||
*(boolean)*
|
||||
|
||||
### privilegedStaff
|
||||
Whether or not moderators are trusted to perform some
|
||||
additional tasks like e.g. issuing password reset emails.
|
||||
|
||||
### publicTimelineVisibility
|
||||
JSON object containing boolean-valued keys reporting
|
||||
if a given timeline can be viewed without login.
|
||||
- `local`
|
||||
- `federated`
|
||||
- `bubble`
|
||||
|
||||
### restrictedNicknames
|
||||
Array of strings listing nicknames forbidden to be used during signup.
|
||||
|
||||
### skipThreadContainment
|
||||
Whether broken threads are filtered out
|
||||
*(boolean)*
|
||||
|
||||
### staffAccounts
|
||||
Array containing ActivityPub IDs of local accounts
|
||||
with some form of elevated privilege on the instance.
|
||||
|
||||
### suggestions
|
||||
JSON object containing info on whether the interaction-based
|
||||
Mastodon `/api/v1/suggestions` feature is enabled and optionally
|
||||
additional implementation-defined fields with more details
|
||||
on e.g. how suggested users are selected.
|
||||
|
||||
!!! note
|
||||
This has no relation to the newer /api/v2/suggestions API
|
||||
which also (or exclusively) contains staff-curated entries.
|
||||
|
||||
- `enabled` *(boolean)* whether or not user recommendations are enabled
|
||||
|
||||
### uploadLimits
|
||||
JSON object documenting various upload-related size limits.
|
||||
All values are integers and in bytes.
|
||||
- `avatar` maximum size of uploaded user avatars
|
||||
- `banner` maximum size of uploaded user profile banners
|
||||
- `background` maximum size of uploaded user profile backgrounds
|
||||
- `general` maximum size for all other kinds of uploads
|
|
@ -6,7 +6,9 @@ probably install frontends.
|
|||
These are no longer bundled with the distribution and need an extra
|
||||
command to install.
|
||||
|
||||
For most installations, the following will suffice:
|
||||
You **must** run frontend management tasks as the akkoma user,
|
||||
the same way you downloaded the build or cloned the git repo before.
|
||||
But otherwise, for most installations, the following will suffice:
|
||||
|
||||
=== "OTP"
|
||||
```sh
|
||||
|
@ -28,4 +30,3 @@ For most installations, the following will suffice:
|
|||
```
|
||||
|
||||
For more customised installations, refer to [Frontend Management](../../configuration/frontend_management)
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## Required dependencies
|
||||
|
||||
* PostgreSQL 9.6+
|
||||
* PostgreSQL 12+
|
||||
* Elixir 1.14+ (currently tested up to 1.16)
|
||||
* Erlang OTP 25+ (currently tested up to OTP26)
|
||||
* git
|
||||
|
|
|
@ -19,6 +19,9 @@ Environment="MIX_ENV=prod"
|
|||
; Don't listen epmd on 0.0.0.0
|
||||
Environment="ERL_EPMD_ADDRESS=127.0.0.1"
|
||||
|
||||
; Don't busy wait
|
||||
Environment="ERL_AFLAGS=+sbwt none +sbwtdcpu none +sbwtdio none"
|
||||
|
||||
; Make sure that all paths fit your installation.
|
||||
; Path to the home directory of the user running the Akkoma service.
|
||||
Environment="HOME=/var/lib/akkoma"
|
||||
|
|
|
@ -60,7 +60,7 @@ ServerTokens Prod
|
|||
Include /etc/letsencrypt/options-ssl-apache.conf
|
||||
|
||||
# Uncomment the following to enable MediaProxy caching on disk
|
||||
#CacheRoot /tmp/akkoma-media-cache/
|
||||
#CacheRoot /var/tmp/akkoma-media-cache/
|
||||
#CacheDirLevels 1
|
||||
#CacheDirLength 2
|
||||
#CacheEnable disk /proxy
|
||||
|
|
|
@ -16,7 +16,7 @@
|
|||
SCRIPTNAME=${0##*/}
|
||||
|
||||
# mod_disk_cache directory
|
||||
CACHE_DIRECTORY="/tmp/akkoma-media-cache"
|
||||
CACHE_DIRECTORY="/var/tmp/akkoma-media-cache"
|
||||
|
||||
## Removes an item via the htcacheclean utility
|
||||
## $1 - the filename, can be a pattern .
|
||||
|
|
|
@ -12,26 +12,22 @@ example.tld {
|
|||
output file /var/log/caddy/akkoma.log
|
||||
}
|
||||
|
||||
encode gzip
|
||||
|
||||
# this is explicitly IPv4 since Pleroma.Web.Endpoint binds on IPv4 only
|
||||
# and `localhost.` resolves to [::0] on some systems: see issue #930
|
||||
reverse_proxy 127.0.0.1:4000
|
||||
|
||||
# Uncomment if using a separate media subdomain
|
||||
#@mediaproxy path /media/* /proxy/*
|
||||
#handle @mediaproxy {
|
||||
# redir https://media.example.tld{uri} permanent
|
||||
#}
|
||||
@mediaproxy path /media/* /proxy/*
|
||||
handle @mediaproxy {
|
||||
redir https://media.example.tld{uri} permanent
|
||||
}
|
||||
}
|
||||
|
||||
# Uncomment if using a separate media subdomain
|
||||
#media.example.tld {
|
||||
# @mediaproxy path /media/* /proxy/*
|
||||
# reverse_proxy @mediaproxy 127.0.0.1:4000 {
|
||||
# transport http {
|
||||
# response_header_timeout 10s
|
||||
# read_timeout 15s
|
||||
# }
|
||||
# }
|
||||
#}
|
||||
media.example.tld {
|
||||
@mediaproxy path /media/* /proxy/*
|
||||
reverse_proxy @mediaproxy 127.0.0.1:4000 {
|
||||
transport http {
|
||||
response_header_timeout 10s
|
||||
read_timeout 15s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,23 +1,43 @@
|
|||
#!/sbin/openrc-run
|
||||
supervisor=supervise-daemon
|
||||
command_user=akkoma:akkoma
|
||||
command_background=1
|
||||
# Ask process to terminate within 30 seconds, otherwise kill it
|
||||
retry="SIGTERM/30/SIGKILL/5"
|
||||
pidfile="/var/run/akkoma.pid"
|
||||
directory=/opt/akkoma
|
||||
healthcheck_delay=60
|
||||
healthcheck_timer=30
|
||||
no_new_privs="yes"
|
||||
pidfile="/var/run/akkoma.pid"
|
||||
|
||||
: ${akkoma_port:-4000}
|
||||
# Ask process first to terminate itself within 60s, otherwise kill it
|
||||
retry="SIGTERM/60/SIGKILL/5"
|
||||
|
||||
# Needs OpenRC >= 0.42
|
||||
#respawn_max=0
|
||||
#respawn_delay=5
|
||||
# if you really want to use start-stop-daemon instead,
|
||||
# also put the following in the config:
|
||||
# command_background=1
|
||||
|
||||
# Adjust defaults as needed in /etc/conf.d/akkoma;
|
||||
# no need to directly edit the service file
|
||||
command_user="${command_user:-akkoma:akkoma}"
|
||||
directory="${directory:-/var/lib/akkoma/akkoma}"
|
||||
akkoma_port="${akkoma_port:-4000}"
|
||||
# whether to allow connecting a remote exlixir shell to the running Akkoma instance
|
||||
akkoma_console=${akkoma_console:-NO}
|
||||
|
||||
output_log="${output_log:-/var/log/akkoma}"
|
||||
error_log="${error_log:-/var/log/akkoma}"
|
||||
|
||||
# 0 means unlimited restarts
|
||||
respawn_max="${respawn_max:-0}"
|
||||
respawn_delay="${respawn_delay:-5}"
|
||||
# define respawn period to only count crashes within a
|
||||
# sliding time window towards respawn_max, e.g.:
|
||||
# respawn_period=2850
|
||||
|
||||
healthcheck_delay="${healthcheck_delay:-60}"
|
||||
healthcheck_timer="${healthcheck_timer:-30}"
|
||||
|
||||
MIX_ENV=prod
|
||||
ERL_EPMD_ADDRESS="${ERL_EPMD_ADDRESS:-127.0.0.1}"
|
||||
ERL_AFLAGS="${ERL_AFLAGS:-+sbwt none +sbwtdcpu none +sbwtdio none}"
|
||||
supervise_daemon_args="${supervise_daemon_args} --env MIX_ENV=${MIX_ENV}"
|
||||
supervise_daemon_args="${supervise_daemon_args} --env ERL_EPMD_ADDRESS=${ERL_EPMD_ADDRESS}"
|
||||
supervise_daemon_args="${supervise_daemon_args} --env ERL_AFLAGS='${ERL_AFLAGS}'"
|
||||
|
||||
# put akkoma_console=YES in /etc/conf.d/akkoma if you want to be able to
|
||||
# connect to akkoma via an elixir console
|
||||
if yesno "${akkoma_console}"; then
|
||||
command=elixir
|
||||
command_args="--name akkoma@127.0.0.1 --erl '-kernel inet_dist_listen_min 9001 inet_dist_listen_max 9001 inet_dist_use_interface {127,0,0,1}' -S mix phx.server"
|
||||
|
@ -31,13 +51,24 @@ else
|
|||
command_args="phx.server"
|
||||
fi
|
||||
|
||||
export MIX_ENV=prod
|
||||
export ERL_EPMD_ADDRESS=127.0.0.1
|
||||
|
||||
depend() {
|
||||
need nginx postgresql
|
||||
}
|
||||
|
||||
start_pre() {
|
||||
# Ensure logfile ownership and perms are alright
|
||||
checkpath --file --owner "$command_user" "$output_log" "$error_log" \
|
||||
|| eerror "Logfile(s) not owned by $command_user, or not a file!"
|
||||
checkpath --writable "$output_log" "$error_log" \
|
||||
|| eerror "Logfile(s) not writable!"
|
||||
|
||||
# If a recompile is needed perform it with lowest prio
|
||||
# (delaying the actual start) to avoid hogging too much
|
||||
# CPU from other services
|
||||
cd "$directory"
|
||||
doas -u "${command_user%%:*}" env MIX_ENV="$MIX_ENV" nice -n 19 "$command" compile
|
||||
}
|
||||
|
||||
healthcheck() {
|
||||
# put akkoma_health=YES in /etc/conf.d/akkoma if you want healthchecking
|
||||
# and make sure you have curl installed
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
# See the documentation at docs.akkoma.dev for your particular distro/OS for
|
||||
# installation instructions.
|
||||
|
||||
proxy_cache_path /tmp/akkoma-media-cache levels=1:2 keys_zone=akkoma_media_cache:10m max_size=1g
|
||||
proxy_cache_path /var/tmp/akkoma-media-cache levels=1:2 keys_zone=akkoma_media_cache:10m max_size=1g
|
||||
inactive=720m use_temp_path=off;
|
||||
|
||||
# this is explicitly IPv4 since Pleroma.Web.Endpoint binds on IPv4 only
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
SCRIPTNAME=${0##*/}
|
||||
|
||||
# NGINX cache directory
|
||||
CACHE_DIRECTORY="/tmp/akkoma-media-cache"
|
||||
CACHE_DIRECTORY="/var/tmp/akkoma-media-cache"
|
||||
|
||||
## Return the files where the items are cached.
|
||||
## $1 - the filename, can be a pattern .
|
||||
|
|
|
@ -16,7 +16,7 @@ defmodule Mix.Pleroma do
|
|||
:fast_html,
|
||||
:oban
|
||||
]
|
||||
@cachex_children ["object", "user", "scrubber", "web_resp"]
|
||||
@cachex_children ["object", "user", "scrubber", "web_resp", "http_backoff"]
|
||||
@doc "Common functions to be reused in mix tasks"
|
||||
def start_pleroma do
|
||||
Pleroma.Config.Holder.save_default()
|
||||
|
@ -112,18 +112,26 @@ def shell_prompt(prompt, defval \\ nil, defname \\ nil) do
|
|||
end
|
||||
end
|
||||
|
||||
def shell_info(message) do
|
||||
def shell_info(message) when is_binary(message) or is_list(message) do
|
||||
if mix_shell?(),
|
||||
do: Mix.shell().info(message),
|
||||
else: IO.puts(message)
|
||||
end
|
||||
|
||||
def shell_error(message) do
|
||||
def shell_info(message) do
|
||||
shell_info("#{inspect(message)}")
|
||||
end
|
||||
|
||||
def shell_error(message) when is_binary(message) or is_list(message) do
|
||||
if mix_shell?(),
|
||||
do: Mix.shell().error(message),
|
||||
else: IO.puts(:stderr, message)
|
||||
end
|
||||
|
||||
def shell_error(message) do
|
||||
shell_error("#{inspect(message)}")
|
||||
end
|
||||
|
||||
@doc "Performs a safe check whether `Mix.shell/0` is available (does not raise if Mix is not loaded)"
|
||||
def mix_shell?, do: :erlang.function_exported(Mix, :shell, 0)
|
||||
|
||||
|
|
|
@ -8,7 +8,6 @@ defmodule Mix.Tasks.Pleroma.Activity do
|
|||
alias Pleroma.User
|
||||
alias Pleroma.Web.CommonAPI
|
||||
alias Pleroma.Pagination
|
||||
require Logger
|
||||
import Mix.Pleroma
|
||||
import Ecto.Query
|
||||
|
||||
|
@ -17,7 +16,7 @@ def run(["get", id | _rest]) do
|
|||
|
||||
id
|
||||
|> Activity.get_by_id()
|
||||
|> IO.inspect()
|
||||
|> shell_info()
|
||||
end
|
||||
|
||||
def run(["delete_by_keyword", user, keyword | _rest]) do
|
||||
|
@ -35,7 +34,7 @@ def run(["delete_by_keyword", user, keyword | _rest]) do
|
|||
)
|
||||
|> Enum.map(fn x -> CommonAPI.delete(x.id, u) end)
|
||||
|> Enum.count()
|
||||
|> IO.puts()
|
||||
|> shell_info()
|
||||
end
|
||||
|
||||
defp query_with(q, search_query) do
|
||||
|
|
|
@ -20,6 +20,102 @@ defmodule Mix.Tasks.Pleroma.Database do
|
|||
@shortdoc "A collection of database related tasks"
|
||||
@moduledoc File.read!("docs/docs/administration/CLI_tasks/database.md")
|
||||
|
||||
defp maybe_limit(query, limit_cnt) do
|
||||
if is_number(limit_cnt) and limit_cnt > 0 do
|
||||
limit(query, [], ^limit_cnt)
|
||||
else
|
||||
query
|
||||
end
|
||||
end
|
||||
|
||||
defp limit_statement(limit) when is_number(limit) do
|
||||
if limit > 0 do
|
||||
"LIMIT #{limit}"
|
||||
else
|
||||
""
|
||||
end
|
||||
end
|
||||
|
||||
defp prune_orphaned_activities_singles(limit) do
|
||||
%{:num_rows => del_single} =
|
||||
"""
|
||||
delete from public.activities
|
||||
where id in (
|
||||
select a.id from public.activities a
|
||||
left join public.objects o on a.data ->> 'object' = o.data ->> 'id'
|
||||
left join public.activities a2 on a.data ->> 'object' = a2.data ->> 'id'
|
||||
left join public.users u on a.data ->> 'object' = u.ap_id
|
||||
where not a.local
|
||||
and jsonb_typeof(a."data" -> 'object') = 'string'
|
||||
and o.id is null
|
||||
and a2.id is null
|
||||
and u.id is null
|
||||
#{limit_statement(limit)}
|
||||
)
|
||||
"""
|
||||
|> Repo.query!([], timeout: :infinity)
|
||||
|
||||
Logger.info("Prune activity singles: deleted #{del_single} rows...")
|
||||
del_single
|
||||
end
|
||||
|
||||
defp prune_orphaned_activities_array(limit) do
|
||||
%{:num_rows => del_array} =
|
||||
"""
|
||||
delete from public.activities
|
||||
where id in (
|
||||
select a.id from public.activities a
|
||||
join json_array_elements_text((a."data" -> 'object')::json) as j
|
||||
on a.data->>'type' = 'Flag'
|
||||
left join public.objects o on j.value = o.data ->> 'id'
|
||||
left join public.activities a2 on j.value = a2.data ->> 'id'
|
||||
left join public.users u on j.value = u.ap_id
|
||||
group by a.id
|
||||
having max(o.data ->> 'id') is null
|
||||
and max(a2.data ->> 'id') is null
|
||||
and max(u.ap_id) is null
|
||||
#{limit_statement(limit)}
|
||||
)
|
||||
"""
|
||||
|> Repo.query!([], timeout: :infinity)
|
||||
|
||||
Logger.info("Prune activity arrays: deleted #{del_array} rows...")
|
||||
del_array
|
||||
end
|
||||
|
||||
def prune_orphaned_activities(limit \\ 0, opts \\ []) when is_number(limit) do
|
||||
# Activities can either refer to a single object id, and array of object ids
|
||||
# or contain an inlined object (at least after going through our normalisation)
|
||||
#
|
||||
# Flag is the only type we support with an array (and always has arrays).
|
||||
# Update the only one with inlined objects.
|
||||
#
|
||||
# We already regularly purge old Delete, Undo, Update and Remove and if
|
||||
# rejected Follow requests anyway; no need to explicitly deal with those here.
|
||||
#
|
||||
# Since there’s an index on types and there are typically only few Flag
|
||||
# activites, it’s _much_ faster to utilise the index. To avoid accidentally
|
||||
# deleting useful activities should more types be added, keep typeof for singles.
|
||||
|
||||
# Prune activities who link to an array of objects
|
||||
del_array =
|
||||
if Keyword.get(opts, :arrays, true) do
|
||||
prune_orphaned_activities_array(limit)
|
||||
else
|
||||
0
|
||||
end
|
||||
|
||||
# Prune activities who link to a single object
|
||||
del_single =
|
||||
if Keyword.get(opts, :singles, true) do
|
||||
prune_orphaned_activities_singles(limit)
|
||||
else
|
||||
0
|
||||
end
|
||||
|
||||
del_single + del_array
|
||||
end
|
||||
|
||||
def run(["remove_embedded_objects" | args]) do
|
||||
{options, [], []} =
|
||||
OptionParser.parse(
|
||||
|
@ -62,6 +158,37 @@ def run(["update_users_following_followers_counts"]) do
|
|||
)
|
||||
end
|
||||
|
||||
def run(["prune_orphaned_activities" | args]) do
|
||||
{options, [], []} =
|
||||
OptionParser.parse(
|
||||
args,
|
||||
strict: [
|
||||
limit: :integer,
|
||||
singles: :boolean,
|
||||
arrays: :boolean
|
||||
]
|
||||
)
|
||||
|
||||
start_pleroma()
|
||||
|
||||
{limit, options} = Keyword.pop(options, :limit, 0)
|
||||
|
||||
log_message = "Pruning orphaned activities"
|
||||
|
||||
log_message =
|
||||
if limit > 0 do
|
||||
log_message <> ", limiting deletion to #{limit} rows"
|
||||
else
|
||||
log_message
|
||||
end
|
||||
|
||||
Logger.info(log_message)
|
||||
|
||||
deleted = prune_orphaned_activities(limit, options)
|
||||
|
||||
Logger.info("Deleted #{deleted} rows")
|
||||
end
|
||||
|
||||
def run(["prune_objects" | args]) do
|
||||
{options, [], []} =
|
||||
OptionParser.parse(
|
||||
|
@ -70,7 +197,8 @@ def run(["prune_objects" | args]) do
|
|||
vacuum: :boolean,
|
||||
keep_threads: :boolean,
|
||||
keep_non_public: :boolean,
|
||||
prune_orphaned_activities: :boolean
|
||||
prune_orphaned_activities: :boolean,
|
||||
limit: :integer
|
||||
]
|
||||
)
|
||||
|
||||
|
@ -79,6 +207,8 @@ def run(["prune_objects" | args]) do
|
|||
deadline = Pleroma.Config.get([:instance, :remote_post_retention_days])
|
||||
time_deadline = NaiveDateTime.utc_now() |> NaiveDateTime.add(-(deadline * 86_400))
|
||||
|
||||
limit_cnt = Keyword.get(options, :limit, 0)
|
||||
|
||||
log_message = "Pruning objects older than #{deadline} days"
|
||||
|
||||
log_message =
|
||||
|
@ -110,129 +240,124 @@ def run(["prune_objects" | args]) do
|
|||
log_message
|
||||
end
|
||||
|
||||
log_message =
|
||||
if limit_cnt > 0 do
|
||||
log_message <> ", limiting to #{limit_cnt} rows"
|
||||
else
|
||||
log_message
|
||||
end
|
||||
|
||||
Logger.info(log_message)
|
||||
|
||||
if Keyword.get(options, :keep_threads) do
|
||||
# We want to delete objects from threads where
|
||||
# 1. the newest post is still old
|
||||
# 2. none of the activities is local
|
||||
# 3. none of the activities is bookmarked
|
||||
# 4. optionally none of the posts is non-public
|
||||
deletable_context =
|
||||
if Keyword.get(options, :keep_non_public) do
|
||||
Pleroma.Activity
|
||||
|> join(:left, [a], b in Pleroma.Bookmark, on: a.id == b.activity_id)
|
||||
|> group_by([a], fragment("? ->> 'context'::text", a.data))
|
||||
|> having(
|
||||
[a],
|
||||
not fragment(
|
||||
# Posts (checked on Create Activity) is non-public
|
||||
"bool_or((not(?->'to' \\? ? OR ?->'cc' \\? ?)) and ? ->> 'type' = 'Create')",
|
||||
a.data,
|
||||
^Pleroma.Constants.as_public(),
|
||||
a.data,
|
||||
^Pleroma.Constants.as_public(),
|
||||
a.data
|
||||
{del_obj, _} =
|
||||
if Keyword.get(options, :keep_threads) do
|
||||
# We want to delete objects from threads where
|
||||
# 1. the newest post is still old
|
||||
# 2. none of the activities is local
|
||||
# 3. none of the activities is bookmarked
|
||||
# 4. optionally none of the posts is non-public
|
||||
deletable_context =
|
||||
if Keyword.get(options, :keep_non_public) do
|
||||
Pleroma.Activity
|
||||
|> join(:left, [a], b in Pleroma.Bookmark, on: a.id == b.activity_id)
|
||||
|> group_by([a], fragment("? ->> 'context'::text", a.data))
|
||||
|> having(
|
||||
[a],
|
||||
not fragment(
|
||||
# Posts (checked on Create Activity) is non-public
|
||||
"bool_or((not(?->'to' \\? ? OR ?->'cc' \\? ?)) and ? ->> 'type' = 'Create')",
|
||||
a.data,
|
||||
^Pleroma.Constants.as_public(),
|
||||
a.data,
|
||||
^Pleroma.Constants.as_public(),
|
||||
a.data
|
||||
)
|
||||
)
|
||||
)
|
||||
else
|
||||
Pleroma.Activity
|
||||
|> join(:left, [a], b in Pleroma.Bookmark, on: a.id == b.activity_id)
|
||||
|> group_by([a], fragment("? ->> 'context'::text", a.data))
|
||||
end
|
||||
|> having([a], max(a.updated_at) < ^time_deadline)
|
||||
|> having([a], not fragment("bool_or(?)", a.local))
|
||||
|> having([_, b], fragment("max(?::text) is null", b.id))
|
||||
|> select([a], fragment("? ->> 'context'::text", a.data))
|
||||
else
|
||||
Pleroma.Activity
|
||||
|> join(:left, [a], b in Pleroma.Bookmark, on: a.id == b.activity_id)
|
||||
|> group_by([a], fragment("? ->> 'context'::text", a.data))
|
||||
end
|
||||
|> having([a], max(a.updated_at) < ^time_deadline)
|
||||
|> having([a], not fragment("bool_or(?)", a.local))
|
||||
|> having([_, b], fragment("max(?::text) is null", b.id))
|
||||
|> maybe_limit(limit_cnt)
|
||||
|> select([a], fragment("? ->> 'context'::text", a.data))
|
||||
|
||||
Pleroma.Object
|
||||
|> where([o], fragment("? ->> 'context'::text", o.data) in subquery(deletable_context))
|
||||
else
|
||||
if Keyword.get(options, :keep_non_public) do
|
||||
Pleroma.Object
|
||||
|> where(
|
||||
[o],
|
||||
fragment(
|
||||
"?->'to' \\? ? OR ?->'cc' \\? ?",
|
||||
o.data,
|
||||
^Pleroma.Constants.as_public(),
|
||||
o.data,
|
||||
^Pleroma.Constants.as_public()
|
||||
)
|
||||
)
|
||||
|> where([o], fragment("? ->> 'context'::text", o.data) in subquery(deletable_context))
|
||||
else
|
||||
deletable =
|
||||
if Keyword.get(options, :keep_non_public) do
|
||||
Pleroma.Object
|
||||
|> where(
|
||||
[o],
|
||||
fragment(
|
||||
"?->'to' \\? ? OR ?->'cc' \\? ?",
|
||||
o.data,
|
||||
^Pleroma.Constants.as_public(),
|
||||
o.data,
|
||||
^Pleroma.Constants.as_public()
|
||||
)
|
||||
)
|
||||
else
|
||||
Pleroma.Object
|
||||
end
|
||||
|> where([o], o.updated_at < ^time_deadline)
|
||||
|> where(
|
||||
[o],
|
||||
fragment("split_part(?->>'actor', '/', 3) != ?", o.data, ^Pleroma.Web.Endpoint.host())
|
||||
)
|
||||
|> maybe_limit(limit_cnt)
|
||||
|> select([o], o.id)
|
||||
|
||||
Pleroma.Object
|
||||
|> where([o], o.id in subquery(deletable))
|
||||
end
|
||||
|> where([o], o.updated_at < ^time_deadline)
|
||||
|> where(
|
||||
[o],
|
||||
fragment("split_part(?->>'actor', '/', 3) != ?", o.data, ^Pleroma.Web.Endpoint.host())
|
||||
)
|
||||
end
|
||||
|> Repo.delete_all(timeout: :infinity)
|
||||
|> Repo.delete_all(timeout: :infinity)
|
||||
|
||||
Logger.info("Deleted #{del_obj} objects...")
|
||||
|
||||
if !Keyword.get(options, :keep_threads) do
|
||||
# Without the --keep-threads option, it's possible that bookmarked
|
||||
# objects have been deleted. We remove the corresponding bookmarks.
|
||||
"""
|
||||
delete from public.bookmarks
|
||||
where id in (
|
||||
select b.id from public.bookmarks b
|
||||
left join public.activities a on b.activity_id = a.id
|
||||
left join public.objects o on a."data" ->> 'object' = o.data ->> 'id'
|
||||
where o.id is null
|
||||
)
|
||||
"""
|
||||
|> Repo.query([], timeout: :infinity)
|
||||
%{:num_rows => del_bookmarks} =
|
||||
"""
|
||||
delete from public.bookmarks
|
||||
where id in (
|
||||
select b.id from public.bookmarks b
|
||||
left join public.activities a on b.activity_id = a.id
|
||||
left join public.objects o on a."data" ->> 'object' = o.data ->> 'id'
|
||||
where o.id is null
|
||||
)
|
||||
"""
|
||||
|> Repo.query!([], timeout: :infinity)
|
||||
|
||||
Logger.info("Deleted #{del_bookmarks} orphaned bookmarks...")
|
||||
end
|
||||
|
||||
if Keyword.get(options, :prune_orphaned_activities) do
|
||||
# Prune activities who link to a single object
|
||||
"""
|
||||
delete from public.activities
|
||||
where id in (
|
||||
select a.id from public.activities a
|
||||
left join public.objects o on a.data ->> 'object' = o.data ->> 'id'
|
||||
left join public.activities a2 on a.data ->> 'object' = a2.data ->> 'id'
|
||||
left join public.users u on a.data ->> 'object' = u.ap_id
|
||||
where not a.local
|
||||
and jsonb_typeof(a."data" -> 'object') = 'string'
|
||||
and o.id is null
|
||||
and a2.id is null
|
||||
and u.id is null
|
||||
)
|
||||
"""
|
||||
|> Repo.query([], timeout: :infinity)
|
||||
|
||||
# Prune activities who link to an array of objects
|
||||
"""
|
||||
delete from public.activities
|
||||
where id in (
|
||||
select a.id from public.activities a
|
||||
join json_array_elements_text((a."data" -> 'object')::json) as j on jsonb_typeof(a."data" -> 'object') = 'array'
|
||||
left join public.objects o on j.value = o.data ->> 'id'
|
||||
left join public.activities a2 on j.value = a2.data ->> 'id'
|
||||
left join public.users u on j.value = u.ap_id
|
||||
group by a.id
|
||||
having max(o.data ->> 'id') is null
|
||||
and max(a2.data ->> 'id') is null
|
||||
and max(u.ap_id) is null
|
||||
)
|
||||
"""
|
||||
|> Repo.query([], timeout: :infinity)
|
||||
del_activities = prune_orphaned_activities()
|
||||
Logger.info("Deleted #{del_activities} orphaned activities...")
|
||||
end
|
||||
|
||||
"""
|
||||
DELETE FROM hashtags AS ht
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM hashtags_objects hto
|
||||
WHERE ht.id = hto.hashtag_id)
|
||||
"""
|
||||
|> Repo.query()
|
||||
%{:num_rows => del_hashtags} =
|
||||
"""
|
||||
DELETE FROM hashtags AS ht
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM hashtags_objects hto
|
||||
WHERE ht.id = hto.hashtag_id)
|
||||
"""
|
||||
|> Repo.query!()
|
||||
|
||||
Logger.info("Deleted #{del_hashtags} no longer used hashtags...")
|
||||
|
||||
if Keyword.get(options, :vacuum) do
|
||||
Logger.info("Starting vacuum...")
|
||||
Maintenance.vacuum("full")
|
||||
end
|
||||
|
||||
Logger.info("All done!")
|
||||
end
|
||||
|
||||
def run(["prune_task"]) do
|
||||
|
|
|
@ -3,7 +3,6 @@ defmodule Mix.Tasks.Pleroma.Diagnostics do
|
|||
alias Pleroma.Repo
|
||||
alias Pleroma.User
|
||||
|
||||
require Logger
|
||||
require Pleroma.Constants
|
||||
|
||||
import Mix.Pleroma
|
||||
|
@ -14,13 +13,20 @@ def run(["http", url]) do
|
|||
start_pleroma()
|
||||
|
||||
Pleroma.HTTP.get(url)
|
||||
|> shell_info()
|
||||
end
|
||||
|
||||
def run(["fetch_object", url]) do
|
||||
start_pleroma()
|
||||
|
||||
Pleroma.Object.Fetcher.fetch_object_from_id(url)
|
||||
|> IO.inspect()
|
||||
end
|
||||
|
||||
def run(["home_timeline", nickname]) do
|
||||
start_pleroma()
|
||||
user = Repo.get_by!(User, nickname: nickname)
|
||||
Logger.info("Home timeline query #{user.nickname}")
|
||||
shell_info("Home timeline query #{user.nickname}")
|
||||
|
||||
followed_hashtags =
|
||||
user
|
||||
|
@ -49,14 +55,14 @@ def run(["home_timeline", nickname]) do
|
|||
|> limit(20)
|
||||
|
||||
Ecto.Adapters.SQL.explain(Repo, :all, query, analyze: true, timeout: :infinity)
|
||||
|> IO.puts()
|
||||
|> shell_info()
|
||||
end
|
||||
|
||||
def run(["user_timeline", nickname, reading_nickname]) do
|
||||
start_pleroma()
|
||||
user = Repo.get_by!(User, nickname: nickname)
|
||||
reading_user = Repo.get_by!(User, nickname: reading_nickname)
|
||||
Logger.info("User timeline query #{user.nickname}")
|
||||
shell_info("User timeline query #{user.nickname}")
|
||||
|
||||
params =
|
||||
%{limit: 20}
|
||||
|
@ -80,7 +86,7 @@ def run(["user_timeline", nickname, reading_nickname]) do
|
|||
|> limit(20)
|
||||
|
||||
Ecto.Adapters.SQL.explain(Repo, :all, query, analyze: true, timeout: :infinity)
|
||||
|> IO.puts()
|
||||
|> shell_info()
|
||||
end
|
||||
|
||||
def run(["notifications", nickname]) do
|
||||
|
@ -96,7 +102,7 @@ def run(["notifications", nickname]) do
|
|||
|> limit(20)
|
||||
|
||||
Ecto.Adapters.SQL.explain(Repo, :all, query, analyze: true, timeout: :infinity)
|
||||
|> IO.puts()
|
||||
|> shell_info()
|
||||
end
|
||||
|
||||
def run(["known_network", nickname]) do
|
||||
|
@ -122,6 +128,6 @@ def run(["known_network", nickname]) do
|
|||
|> limit(20)
|
||||
|
||||
Ecto.Adapters.SQL.explain(Repo, :all, query, analyze: true, timeout: :infinity)
|
||||
|> IO.puts()
|
||||
|> shell_info()
|
||||
end
|
||||
end
|
||||
|
|
|
@ -27,11 +27,11 @@ def run(["ls-packs" | args]) do
|
|||
]
|
||||
|
||||
for {param, value} <- to_print do
|
||||
IO.puts(IO.ANSI.format([:bright, param, :normal, ": ", value]))
|
||||
shell_info(IO.ANSI.format([:bright, param, :normal, ": ", value]))
|
||||
end
|
||||
|
||||
# A newline
|
||||
IO.puts("")
|
||||
shell_info("")
|
||||
end)
|
||||
end
|
||||
|
||||
|
@ -49,7 +49,7 @@ def run(["get-packs" | args]) do
|
|||
pack = manifest[pack_name]
|
||||
src = pack["src"]
|
||||
|
||||
IO.puts(
|
||||
shell_info(
|
||||
IO.ANSI.format([
|
||||
"Downloading ",
|
||||
:bright,
|
||||
|
@ -67,9 +67,9 @@ def run(["get-packs" | args]) do
|
|||
sha_status_text = ["SHA256 of ", :bright, pack_name, :normal, " source file is ", :bright]
|
||||
|
||||
if archive_sha == String.upcase(pack["src_sha256"]) do
|
||||
IO.puts(IO.ANSI.format(sha_status_text ++ [:green, "OK"]))
|
||||
shell_info(IO.ANSI.format(sha_status_text ++ [:green, "OK"]))
|
||||
else
|
||||
IO.puts(IO.ANSI.format(sha_status_text ++ [:red, "BAD"]))
|
||||
shell_info(IO.ANSI.format(sha_status_text ++ [:red, "BAD"]))
|
||||
|
||||
raise "Bad SHA256 for #{pack_name}"
|
||||
end
|
||||
|
@ -80,7 +80,7 @@ def run(["get-packs" | args]) do
|
|||
|> Path.dirname()
|
||||
|> Path.join(pack["files"])
|
||||
|
||||
IO.puts(
|
||||
shell_info(
|
||||
IO.ANSI.format([
|
||||
"Fetching the file list for ",
|
||||
:bright,
|
||||
|
@ -94,7 +94,7 @@ def run(["get-packs" | args]) do
|
|||
|
||||
files = fetch_and_decode!(files_loc)
|
||||
|
||||
IO.puts(IO.ANSI.format(["Unpacking ", :bright, pack_name]))
|
||||
shell_info(IO.ANSI.format(["Unpacking ", :bright, pack_name]))
|
||||
|
||||
pack_path =
|
||||
Path.join([
|
||||
|
@ -111,11 +111,11 @@ def run(["get-packs" | args]) do
|
|||
|
||||
{:ok, _} =
|
||||
:zip.unzip(binary_archive,
|
||||
cwd: pack_path,
|
||||
cwd: to_charlist(pack_path),
|
||||
file_list: files_to_unzip
|
||||
)
|
||||
|
||||
IO.puts(IO.ANSI.format(["Writing pack.json for ", :bright, pack_name]))
|
||||
shell_info(IO.ANSI.format(["Writing pack.json for ", :bright, pack_name]))
|
||||
|
||||
pack_json = %{
|
||||
pack: %{
|
||||
|
@ -132,7 +132,7 @@ def run(["get-packs" | args]) do
|
|||
File.write!(Path.join(pack_path, "pack.json"), Jason.encode!(pack_json, pretty: true))
|
||||
Pleroma.Emoji.reload()
|
||||
else
|
||||
IO.puts(IO.ANSI.format([:bright, :red, "No pack named \"#{pack_name}\" found"]))
|
||||
shell_info(IO.ANSI.format([:bright, :red, "No pack named \"#{pack_name}\" found"]))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -180,14 +180,14 @@ def run(["gen-pack" | args]) do
|
|||
custom_exts
|
||||
end
|
||||
|
||||
IO.puts("Using #{Enum.join(exts, " ")} extensions")
|
||||
shell_info("Using #{Enum.join(exts, " ")} extensions")
|
||||
|
||||
IO.puts("Downloading the pack and generating SHA256")
|
||||
shell_info("Downloading the pack and generating SHA256")
|
||||
|
||||
{:ok, %{body: binary_archive}} = Pleroma.HTTP.get(src)
|
||||
archive_sha = :crypto.hash(:sha256, binary_archive) |> Base.encode16()
|
||||
|
||||
IO.puts("SHA256 is #{archive_sha}")
|
||||
shell_info("SHA256 is #{archive_sha}")
|
||||
|
||||
pack_json = %{
|
||||
name => %{
|
||||
|
@ -208,7 +208,7 @@ def run(["gen-pack" | args]) do
|
|||
|
||||
File.write!(files_name, Jason.encode!(emoji_map, pretty: true))
|
||||
|
||||
IO.puts("""
|
||||
shell_info("""
|
||||
|
||||
#{files_name} has been created and contains the list of all found emojis in the pack.
|
||||
Please review the files in the pack and remove those not needed.
|
||||
|
@ -230,11 +230,11 @@ def run(["gen-pack" | args]) do
|
|||
)
|
||||
)
|
||||
|
||||
IO.puts("#{pack_file} has been updated with the #{name} pack")
|
||||
shell_info("#{pack_file} has been updated with the #{name} pack")
|
||||
else
|
||||
File.write!(pack_file, Jason.encode!(pack_json, pretty: true))
|
||||
|
||||
IO.puts("#{pack_file} has been created with the #{name} pack")
|
||||
shell_info("#{pack_file} has been created with the #{name} pack")
|
||||
end
|
||||
|
||||
Pleroma.Emoji.reload()
|
||||
|
@ -243,7 +243,7 @@ def run(["gen-pack" | args]) do
|
|||
def run(["reload"]) do
|
||||
start_pleroma()
|
||||
Pleroma.Emoji.reload()
|
||||
IO.puts("Emoji packs have been reloaded.")
|
||||
shell_info("Emoji packs have been reloaded.")
|
||||
end
|
||||
|
||||
defp fetch_and_decode!(from) do
|
||||
|
|
|
@ -11,7 +11,6 @@ defmodule Mix.Tasks.Pleroma.RefreshCounterCache do
|
|||
alias Pleroma.CounterCache
|
||||
alias Pleroma.Repo
|
||||
|
||||
require Logger
|
||||
import Ecto.Query
|
||||
|
||||
def run([]) do
|
||||
|
|
|
@ -48,7 +48,7 @@ def run(["index"]) do
|
|||
]
|
||||
)
|
||||
|
||||
IO.puts("Created indices. Starting to insert posts.")
|
||||
shell_info("Created indices. Starting to insert posts.")
|
||||
|
||||
chunk_size = Pleroma.Config.get([Pleroma.Search.Meilisearch, :initial_indexing_chunk_size])
|
||||
|
||||
|
@ -65,7 +65,7 @@ def run(["index"]) do
|
|||
)
|
||||
|
||||
count = query |> Pleroma.Repo.aggregate(:count, :data)
|
||||
IO.puts("Entries to index: #{count}")
|
||||
shell_info("Entries to index: #{count}")
|
||||
|
||||
Pleroma.Repo.stream(
|
||||
query,
|
||||
|
@ -92,10 +92,10 @@ def run(["index"]) do
|
|||
|
||||
with {:ok, res} <- result do
|
||||
if not Map.has_key?(res, "indexUid") do
|
||||
IO.puts("\nFailed to index: #{inspect(result)}")
|
||||
shell_info("\nFailed to index: #{inspect(result)}")
|
||||
end
|
||||
else
|
||||
e -> IO.puts("\nFailed to index due to network error: #{inspect(e)}")
|
||||
e -> shell_error("\nFailed to index due to network error: #{inspect(e)}")
|
||||
end
|
||||
end)
|
||||
|> Stream.run()
|
||||
|
@ -126,11 +126,15 @@ def run(["show-keys", master_key]) do
|
|||
decoded = Jason.decode!(result.body)
|
||||
|
||||
if decoded["results"] do
|
||||
Enum.each(decoded["results"], fn %{"description" => desc, "key" => key} ->
|
||||
IO.puts("#{desc}: #{key}")
|
||||
Enum.each(decoded["results"], fn
|
||||
%{"name" => name, "key" => key} ->
|
||||
shell_info("#{name}: #{key}")
|
||||
|
||||
%{"description" => desc, "key" => key} ->
|
||||
shell_info("#{desc}: #{key}")
|
||||
end)
|
||||
else
|
||||
IO.puts("Error fetching the keys, check the master key is correct: #{inspect(decoded)}")
|
||||
shell_error("Error fetching the keys, check the master key is correct: #{inspect(decoded)}")
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -138,7 +142,7 @@ def run(["stats"]) do
|
|||
start_pleroma()
|
||||
|
||||
{:ok, result} = meili_get("/indexes/objects/stats")
|
||||
IO.puts("Number of entries: #{result["numberOfDocuments"]}")
|
||||
IO.puts("Indexing? #{result["isIndexing"]}")
|
||||
shell_info("Number of entries: #{result["numberOfDocuments"]}")
|
||||
shell_info("Indexing? #{result["isIndexing"]}")
|
||||
end
|
||||
end
|
||||
|
|
|
@ -38,7 +38,7 @@ def run(["spoof-uploaded"]) do
|
|||
Logger.put_process_level(self(), :notice)
|
||||
start_pleroma()
|
||||
|
||||
IO.puts("""
|
||||
shell_info("""
|
||||
+------------------------+
|
||||
| SPOOF SEARCH UPLOADS |
|
||||
+------------------------+
|
||||
|
@ -55,7 +55,7 @@ def run(["spoof-inserted"]) do
|
|||
Logger.put_process_level(self(), :notice)
|
||||
start_pleroma()
|
||||
|
||||
IO.puts("""
|
||||
shell_info("""
|
||||
+----------------------+
|
||||
| SPOOF SEARCH NOTES |
|
||||
+----------------------+
|
||||
|
@ -77,7 +77,7 @@ defp do_spoof_uploaded() do
|
|||
uploads_search_spoofs_local_dir(Config.get!([Pleroma.Uploaders.Local, :uploads]))
|
||||
|
||||
_ ->
|
||||
IO.puts("""
|
||||
shell_info("""
|
||||
NOTE:
|
||||
Not using local uploader; thus not affected by this exploit.
|
||||
It's impossible to check for files, but in case local uploader was used before
|
||||
|
@ -98,13 +98,13 @@ defp do_spoof_uploaded() do
|
|||
|
||||
orphaned_attachs = upload_search_orphaned_attachments(not_orphaned_urls)
|
||||
|
||||
IO.puts("\nSearch concluded; here are the results:")
|
||||
shell_info("\nSearch concluded; here are the results:")
|
||||
pretty_print_list_with_title(emoji, "Emoji")
|
||||
pretty_print_list_with_title(files, "Uploaded Files")
|
||||
pretty_print_list_with_title(post_attachs, "(Not Deleted) Post Attachments")
|
||||
pretty_print_list_with_title(orphaned_attachs, "Orphaned Uploads")
|
||||
|
||||
IO.puts("""
|
||||
shell_info("""
|
||||
In total found
|
||||
#{length(emoji)} emoji
|
||||
#{length(files)} uploads
|
||||
|
@ -116,7 +116,7 @@ defp do_spoof_uploaded() do
|
|||
defp uploads_search_spoofs_local_dir(dir) do
|
||||
local_dir = String.replace_suffix(dir, "/", "")
|
||||
|
||||
IO.puts("Searching for suspicious files in #{local_dir}...")
|
||||
shell_info("Searching for suspicious files in #{local_dir}...")
|
||||
|
||||
glob_ext = "{" <> Enum.join(@activity_exts, ",") <> "}"
|
||||
|
||||
|
@ -128,7 +128,7 @@ defp uploads_search_spoofs_local_dir(dir) do
|
|||
end
|
||||
|
||||
defp uploads_search_spoofs_notes() do
|
||||
IO.puts("Now querying DB for posts with spoofing attachments. This might take a while...")
|
||||
shell_info("Now querying DB for posts with spoofing attachments. This might take a while...")
|
||||
|
||||
patterns = [local_id_pattern() | activity_ext_url_patterns()]
|
||||
|
||||
|
@ -153,7 +153,7 @@ defp uploads_search_spoofs_notes() do
|
|||
end
|
||||
|
||||
defp upload_search_orphaned_attachments(not_orphaned_urls) do
|
||||
IO.puts("""
|
||||
shell_info("""
|
||||
Now querying DB for orphaned spoofing attachment (i.e. their post was deleted,
|
||||
but if :cleanup_attachments was not enabled traces remain in the database)
|
||||
This might take a bit...
|
||||
|
@ -184,7 +184,7 @@ defp upload_search_orphaned_attachments(not_orphaned_urls) do
|
|||
# | S P O O F - I N S E R T E D |
|
||||
# +-----------------------------+
|
||||
defp do_spoof_inserted() do
|
||||
IO.puts("""
|
||||
shell_info("""
|
||||
Searching for local posts whose Create activity has no ActivityPub id...
|
||||
This is a pretty good indicator, but only for spoofs of local actors
|
||||
and only if the spoofing happened after around late 2021.
|
||||
|
@ -194,9 +194,9 @@ defp do_spoof_inserted() do
|
|||
search_local_notes_without_create_id()
|
||||
|> Enum.sort()
|
||||
|
||||
IO.puts("Done.\n")
|
||||
shell_info("Done.\n")
|
||||
|
||||
IO.puts("""
|
||||
shell_info("""
|
||||
Now trying to weed out other poorly hidden spoofs.
|
||||
This can't detect all and may have some false positives.
|
||||
""")
|
||||
|
@ -207,9 +207,9 @@ defp do_spoof_inserted() do
|
|||
search_sus_notes_by_id_patterns()
|
||||
|> Enum.filter(fn r -> !(r in likely_spoofed_posts_set) end)
|
||||
|
||||
IO.puts("Done.\n")
|
||||
shell_info("Done.\n")
|
||||
|
||||
IO.puts("""
|
||||
shell_info("""
|
||||
Finally, searching for spoofed, local user accounts.
|
||||
(It's impossible to detect spoofed remote users)
|
||||
""")
|
||||
|
@ -220,7 +220,7 @@ defp do_spoof_inserted() do
|
|||
pretty_print_list_with_title(idless_create, "Likely Spoofed Posts")
|
||||
pretty_print_list_with_title(spoofed_users, "Spoofed local user accounts")
|
||||
|
||||
IO.puts("""
|
||||
shell_info("""
|
||||
In total found:
|
||||
#{length(spoofed_users)} bogus users
|
||||
#{length(idless_create)} likely spoofed posts
|
||||
|
@ -289,27 +289,27 @@ defp search_bogus_local_users() do
|
|||
defp pretty_print_list_with_title(list, title) do
|
||||
title_len = String.length(title)
|
||||
title_underline = String.duplicate("=", title_len)
|
||||
IO.puts(title)
|
||||
IO.puts(title_underline)
|
||||
shell_info(title)
|
||||
shell_info(title_underline)
|
||||
pretty_print_list(list)
|
||||
end
|
||||
|
||||
defp pretty_print_list([]), do: IO.puts("")
|
||||
defp pretty_print_list([]), do: shell_info("")
|
||||
|
||||
defp pretty_print_list([{a, o} | rest])
|
||||
when (is_binary(a) or is_number(a)) and is_binary(o) do
|
||||
IO.puts(" {#{a}, #{o}}")
|
||||
shell_info(" {#{a}, #{o}}")
|
||||
pretty_print_list(rest)
|
||||
end
|
||||
|
||||
defp pretty_print_list([{u, a, o} | rest])
|
||||
when is_binary(a) and is_binary(u) and is_binary(o) do
|
||||
IO.puts(" {#{u}, #{a}, #{o}}")
|
||||
shell_info(" {#{u}, #{a}, #{o}}")
|
||||
pretty_print_list(rest)
|
||||
end
|
||||
|
||||
defp pretty_print_list([e | rest]) when is_binary(e) do
|
||||
IO.puts(" #{e}")
|
||||
shell_info(" #{e}")
|
||||
pretty_print_list(rest)
|
||||
end
|
||||
|
||||
|
|
|
@ -114,7 +114,7 @@ def run(["reset_password", nickname]) do
|
|||
{:ok, token} <- Pleroma.PasswordResetToken.create_token(user) do
|
||||
shell_info("Generated password reset token for #{user.nickname}")
|
||||
|
||||
IO.puts("URL: #{~p[/api/v1/pleroma/password_reset/#{token.token}]}")
|
||||
shell_info("URL: #{~p[/api/v1/pleroma/password_reset/#{token.token}]}")
|
||||
else
|
||||
_ ->
|
||||
shell_error("No local user #{nickname}")
|
||||
|
@ -301,7 +301,7 @@ def run(["invite" | rest]) do
|
|||
shell_info("Generated user invite token " <> String.replace(invite.invite_type, "_", " "))
|
||||
|
||||
url = url(~p[/registration/#{invite.token}])
|
||||
IO.puts(url)
|
||||
shell_info(url)
|
||||
else
|
||||
error ->
|
||||
shell_error("Could not create invite token: #{inspect(error)}")
|
||||
|
@ -373,7 +373,7 @@ def run(["show", nickname]) do
|
|||
nickname
|
||||
|> User.get_cached_by_nickname()
|
||||
|
||||
shell_info("#{inspect(user)}")
|
||||
shell_info(user)
|
||||
end
|
||||
|
||||
def run(["send_confirmation", nickname]) do
|
||||
|
@ -457,7 +457,7 @@ def run(["blocking", nickname]) do
|
|||
|
||||
with %User{local: true} = user <- User.get_cached_by_nickname(nickname) do
|
||||
blocks = User.following_ap_ids(user)
|
||||
IO.puts("#{inspect(blocks)}")
|
||||
shell_info(blocks)
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -516,12 +516,12 @@ def run(["fix_follow_state", local_user, remote_user]) do
|
|||
{:follow_data, Pleroma.Web.ActivityPub.Utils.fetch_latest_follow(local, remote)} do
|
||||
calculated_state = User.following?(local, remote)
|
||||
|
||||
IO.puts(
|
||||
shell_info(
|
||||
"Request state is #{request_state}, vs calculated state of following=#{calculated_state}"
|
||||
)
|
||||
|
||||
if calculated_state == false && request_state == "accept" do
|
||||
IO.puts("Discrepancy found, fixing")
|
||||
shell_info("Discrepancy found, fixing")
|
||||
Pleroma.Web.CommonAPI.reject_follow_request(local, remote)
|
||||
shell_info("Relationship fixed")
|
||||
else
|
||||
|
@ -551,14 +551,14 @@ defp refetch_public_keys(query) do
|
|||
|> Stream.each(fn users ->
|
||||
users
|
||||
|> Enum.each(fn user ->
|
||||
IO.puts("Re-Resolving: #{user.ap_id}")
|
||||
shell_info("Re-Resolving: #{user.ap_id}")
|
||||
|
||||
with {:ok, user} <- Pleroma.User.fetch_by_ap_id(user.ap_id),
|
||||
changeset <- Pleroma.User.update_changeset(user),
|
||||
{:ok, _user} <- Pleroma.User.update_and_set_cache(changeset) do
|
||||
:ok
|
||||
else
|
||||
error -> IO.puts("Could not resolve: #{user.ap_id}, #{inspect(error)}")
|
||||
error -> shell_info("Could not resolve: #{user.ap_id}, #{inspect(error)}")
|
||||
end
|
||||
end)
|
||||
end)
|
||||
|
|
|
@ -258,6 +258,27 @@ def get_create_by_object_ap_id(ap_id) when is_binary(ap_id) do
|
|||
|
||||
def get_create_by_object_ap_id(_), do: nil
|
||||
|
||||
@doc """
|
||||
Accepts a list of `ap__id`.
|
||||
Returns a query yielding Create activities for the given objects,
|
||||
in the same order as they were specified in the input list.
|
||||
"""
|
||||
@spec get_presorted_create_by_object_ap_id([String.t()]) :: Ecto.Queryable.t()
|
||||
def get_presorted_create_by_object_ap_id(ap_ids) do
|
||||
from(
|
||||
a in Activity,
|
||||
join:
|
||||
ids in fragment(
|
||||
"SELECT * FROM UNNEST(?::text[]) WITH ORDINALITY AS ids(ap_id, ord)",
|
||||
^ap_ids
|
||||
),
|
||||
on:
|
||||
ids.ap_id == fragment("?->>'object'", a.data) and
|
||||
fragment("?->>'type'", a.data) == "Create",
|
||||
order_by: [asc: ids.ord]
|
||||
)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Accepts `ap_id` or list of `ap_id`.
|
||||
Returns a query.
|
||||
|
|
|
@ -28,7 +28,7 @@ defp get_cache_keys_for(activity_id) do
|
|||
end
|
||||
end
|
||||
|
||||
defp add_cache_key_for(activity_id, additional_key) do
|
||||
def add_cache_key_for(activity_id, additional_key) do
|
||||
current = get_cache_keys_for(activity_id)
|
||||
|
||||
unless additional_key in current do
|
||||
|
|
|
@ -95,34 +95,17 @@ def start(_type, _args) do
|
|||
|
||||
opts = [strategy: :one_for_one, name: Pleroma.Supervisor, max_restarts: max_restarts]
|
||||
|
||||
with {:ok, data} <- Supervisor.start_link(children, opts) do
|
||||
set_postgres_server_version()
|
||||
{:ok, data}
|
||||
else
|
||||
case Supervisor.start_link(children, opts) do
|
||||
{:ok, data} ->
|
||||
{:ok, data}
|
||||
|
||||
e ->
|
||||
Logger.error("Failed to start!")
|
||||
Logger.error("#{inspect(e)}")
|
||||
Logger.critical("Failed to start!")
|
||||
Logger.critical("#{inspect(e)}")
|
||||
e
|
||||
end
|
||||
end
|
||||
|
||||
defp set_postgres_server_version do
|
||||
version =
|
||||
with %{rows: [[version]]} <- Ecto.Adapters.SQL.query!(Pleroma.Repo, "show server_version"),
|
||||
{num, _} <- Float.parse(version) do
|
||||
num
|
||||
else
|
||||
e ->
|
||||
Logger.warning(
|
||||
"Could not get the postgres version: #{inspect(e)}.\nSetting the default value of 9.6"
|
||||
)
|
||||
|
||||
9.6
|
||||
end
|
||||
|
||||
:persistent_term.put({Pleroma.Repo, :postgres_version}, version)
|
||||
end
|
||||
|
||||
def load_custom_modules do
|
||||
dir = Config.get([:modules, :runtime_dir])
|
||||
|
||||
|
@ -179,7 +162,9 @@ defp cachex_children do
|
|||
build_cachex("translations", default_ttl: :timer.hours(24 * 30), limit: 2500),
|
||||
build_cachex("instances", default_ttl: :timer.hours(24), ttl_interval: 1000, limit: 2500),
|
||||
build_cachex("request_signatures", default_ttl: :timer.hours(24 * 30), limit: 3000),
|
||||
build_cachex("rel_me", default_ttl: :timer.hours(24 * 30), limit: 300)
|
||||
build_cachex("rel_me", default_ttl: :timer.hours(24 * 30), limit: 300),
|
||||
build_cachex("host_meta", default_ttl: :timer.minutes(120), limit: 5000),
|
||||
build_cachex("http_backoff", default_ttl: :timer.hours(24 * 30), limit: 10000)
|
||||
]
|
||||
end
|
||||
|
||||
|
@ -279,7 +264,9 @@ def limiters_setup do
|
|||
defp http_children do
|
||||
proxy_url = Config.get([:http, :proxy_url])
|
||||
proxy = Pleroma.HTTP.AdapterHelper.format_proxy(proxy_url)
|
||||
pool_size = Config.get([:http, :pool_size])
|
||||
pool_size = Config.get([:http, :pool_size], 10)
|
||||
pool_timeout = Config.get([:http, :pool_timeout], 60_000)
|
||||
connection_timeout = Config.get([:http, :conn_max_idle_time], 10_000)
|
||||
|
||||
:public_key.cacerts_load()
|
||||
|
||||
|
@ -289,6 +276,8 @@ defp http_children do
|
|||
|> Pleroma.HTTP.AdapterHelper.add_pool_size(pool_size)
|
||||
|> Pleroma.HTTP.AdapterHelper.maybe_add_proxy_pool(proxy)
|
||||
|> Pleroma.HTTP.AdapterHelper.ensure_ipv6()
|
||||
|> Pleroma.HTTP.AdapterHelper.add_default_conn_max_idle_time(connection_timeout)
|
||||
|> Pleroma.HTTP.AdapterHelper.add_default_pool_max_idle_time(pool_timeout)
|
||||
|> Keyword.put(:name, MyFinch)
|
||||
|
||||
[{Finch, config}]
|
||||
|
|
|
@ -24,7 +24,6 @@ defp reboot_time_keys,
|
|||
defp reboot_time_subkeys,
|
||||
do: [
|
||||
{:pleroma, Pleroma.Captcha, [:seconds_valid]},
|
||||
{:pleroma, Pleroma.Upload, [:proxy_remote]},
|
||||
{:pleroma, :instance, [:upload_limit]},
|
||||
{:pleroma, :http, [:pool_size]},
|
||||
{:pleroma, :http, [:proxy_url]}
|
||||
|
|
|
@ -64,4 +64,7 @@ defmodule Pleroma.Constants do
|
|||
"Service"
|
||||
]
|
||||
)
|
||||
|
||||
# Internally used as top-level types for media attachments and user images
|
||||
const(attachment_types, do: ["Document", "Image"])
|
||||
end
|
||||
|
|
|
@ -125,7 +125,7 @@ def add_file(%Pack{} = pack, _, _, %Plug.Upload{content_type: "application/zip"}
|
|||
{:ok, _emoji_files} =
|
||||
:zip.unzip(
|
||||
to_charlist(file.path),
|
||||
[{:file_list, Enum.map(emojies, & &1[:path])}, {:cwd, tmp_dir}]
|
||||
[{:file_list, Enum.map(emojies, & &1[:path])}, {:cwd, to_charlist(tmp_dir)}]
|
||||
)
|
||||
|
||||
{_, updated_pack} =
|
||||
|
|
|
@ -79,6 +79,10 @@ def unzip(zip, dest) do
|
|||
|
||||
new_file_path = Path.join(dest, path)
|
||||
|
||||
new_file_path
|
||||
|> Path.dirname()
|
||||
|> File.rm()
|
||||
|
||||
new_file_path
|
||||
|> Path.dirname()
|
||||
|> File.mkdir_p!()
|
||||
|
|
|
@ -6,8 +6,6 @@ defmodule Pleroma.HTML do
|
|||
# Scrubbers are compiled on boot so they can be configured in OTP releases
|
||||
# @on_load :compile_scrubbers
|
||||
|
||||
@cachex Pleroma.Config.get([:cachex, :provider], Cachex)
|
||||
|
||||
def compile_scrubbers do
|
||||
dir = Path.join(:code.priv_dir(:pleroma), "scrubbers")
|
||||
|
||||
|
@ -67,22 +65,9 @@ def ensure_scrubbed_html(
|
|||
end
|
||||
end
|
||||
|
||||
def extract_first_external_url_from_object(%{data: %{"content" => content}} = object)
|
||||
@spec extract_first_external_url_from_object(Pleroma.Object.t()) :: String.t() | nil
|
||||
def extract_first_external_url_from_object(%{data: %{"content" => content}})
|
||||
when is_binary(content) do
|
||||
unless object.data["fake"] do
|
||||
key = "URL|#{object.id}"
|
||||
|
||||
@cachex.fetch!(:scrubber_cache, key, fn _key ->
|
||||
{:commit, {:ok, extract_first_external_url(content)}}
|
||||
end)
|
||||
else
|
||||
{:ok, extract_first_external_url(content)}
|
||||
end
|
||||
end
|
||||
|
||||
def extract_first_external_url_from_object(_), do: {:error, :no_content}
|
||||
|
||||
def extract_first_external_url(content) do
|
||||
content
|
||||
|> Floki.parse_fragment!()
|
||||
|> Floki.find("a:not(.mention,.hashtag,.attachment,[rel~=\"tag\"])")
|
||||
|
@ -90,4 +75,6 @@ def extract_first_external_url(content) do
|
|||
|> Floki.attribute("href")
|
||||
|> Enum.at(0)
|
||||
end
|
||||
|
||||
def extract_first_external_url_from_object(_), do: nil
|
||||
end
|
||||
|
|
|
@ -74,7 +74,12 @@ def request(method, url, body, headers, options) when is_binary(url) do
|
|||
request = build_request(method, headers, options, url, body, params)
|
||||
client = Tesla.client([Tesla.Middleware.FollowRedirects, Tesla.Middleware.Telemetry])
|
||||
|
||||
Logger.debug("Outbound: #{method} #{url}")
|
||||
request(client, request)
|
||||
rescue
|
||||
e ->
|
||||
Logger.error("Failed to fetch #{url}: #{inspect(e)}")
|
||||
{:error, :fetch_error}
|
||||
end
|
||||
|
||||
@spec request(Client.t(), keyword()) :: {:ok, Env.t()} | {:error, any()}
|
||||
|
|
|
@ -116,6 +116,20 @@ defp maybe_add_transport_opts(opts) do
|
|||
put_in(opts, [:pools, :default, :conn_opts, :transport_opts, :inet6], true)
|
||||
end
|
||||
|
||||
def add_default_pool_max_idle_time(opts, pool_timeout) do
|
||||
opts
|
||||
|> maybe_add_pools()
|
||||
|> maybe_add_default_pool()
|
||||
|> put_in([:pools, :default, :pool_max_idle_time], pool_timeout)
|
||||
end
|
||||
|
||||
def add_default_conn_max_idle_time(opts, connection_timeout) do
|
||||
opts
|
||||
|> maybe_add_pools()
|
||||
|> maybe_add_default_pool()
|
||||
|> put_in([:pools, :default, :conn_max_idle_time], connection_timeout)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Merge default connection & adapter options with received ones.
|
||||
"""
|
||||
|
|
121
lib/pleroma/http/backoff.ex
Normal file
121
lib/pleroma/http/backoff.ex
Normal file
|
@ -0,0 +1,121 @@
|
|||
defmodule Pleroma.HTTP.Backoff do
|
||||
alias Pleroma.HTTP
|
||||
require Logger
|
||||
|
||||
@cachex Pleroma.Config.get([:cachex, :provider], Cachex)
|
||||
@backoff_cache :http_backoff_cache
|
||||
|
||||
# attempt to parse a timestamp from a header
|
||||
# returns nil if it can't parse the timestamp
|
||||
@spec timestamp_or_nil(binary) :: DateTime.t() | nil
|
||||
defp timestamp_or_nil(header) do
|
||||
case DateTime.from_iso8601(header) do
|
||||
{:ok, stamp, _} ->
|
||||
stamp
|
||||
|
||||
_ ->
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
# attempt to parse the x-ratelimit-reset header from the headers
|
||||
@spec x_ratelimit_reset(headers :: list) :: DateTime.t() | nil
|
||||
defp x_ratelimit_reset(headers) do
|
||||
with {_header, value} <- List.keyfind(headers, "x-ratelimit-reset", 0),
|
||||
true <- is_binary(value) do
|
||||
timestamp_or_nil(value)
|
||||
else
|
||||
_ ->
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
# attempt to parse the Retry-After header from the headers
|
||||
# this can be either a timestamp _or_ a number of seconds to wait!
|
||||
# we'll return a datetime if we can parse it, or nil if we can't
|
||||
@spec retry_after(headers :: list) :: DateTime.t() | nil
|
||||
defp retry_after(headers) do
|
||||
with {_header, value} <- List.keyfind(headers, "retry-after", 0),
|
||||
true <- is_binary(value) do
|
||||
# first, see if it's an integer
|
||||
case Integer.parse(value) do
|
||||
{seconds, ""} ->
|
||||
Logger.debug("Parsed Retry-After header: #{seconds} seconds")
|
||||
DateTime.utc_now() |> Timex.shift(seconds: seconds)
|
||||
|
||||
_ ->
|
||||
# if it's not an integer, try to parse it as a timestamp
|
||||
timestamp_or_nil(value)
|
||||
end
|
||||
else
|
||||
_ ->
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
# given a set of headers, will attempt to find the next backoff timestamp
|
||||
# if it can't find one, it will default to 5 minutes from now
|
||||
@spec next_backoff_timestamp(%{headers: list}) :: DateTime.t()
|
||||
defp next_backoff_timestamp(%{headers: headers}) when is_list(headers) do
|
||||
default_5_minute_backoff =
|
||||
DateTime.utc_now()
|
||||
|> Timex.shift(seconds: 5 * 60)
|
||||
|
||||
backoff =
|
||||
[&x_ratelimit_reset/1, &retry_after/1]
|
||||
|> Enum.map(& &1.(headers))
|
||||
|> Enum.find(&(&1 != nil))
|
||||
|
||||
if is_nil(backoff) do
|
||||
Logger.debug("No backoff headers found, defaulting to 5 minutes from now")
|
||||
default_5_minute_backoff
|
||||
else
|
||||
Logger.debug("Found backoff header, will back off until: #{backoff}")
|
||||
backoff
|
||||
end
|
||||
end
|
||||
|
||||
defp next_backoff_timestamp(_), do: DateTime.utc_now() |> Timex.shift(seconds: 5 * 60)
|
||||
|
||||
# utility function to check the HTTP response for potential backoff headers
|
||||
# will check if we get a 429 or 503 response, and if we do, will back off for a bit
|
||||
@spec check_backoff({:ok | :error, HTTP.Env.t()}, binary()) ::
|
||||
{:ok | :error, HTTP.Env.t()} | {:error, :ratelimit}
|
||||
defp check_backoff({:ok, env}, host) do
|
||||
case env.status do
|
||||
status when status in [429, 503] ->
|
||||
Logger.error("Rate limited on #{host}! Backing off...")
|
||||
timestamp = next_backoff_timestamp(env)
|
||||
ttl = Timex.diff(timestamp, DateTime.utc_now(), :seconds)
|
||||
# we will cache the host for 5 minutes
|
||||
@cachex.put(@backoff_cache, host, true, ttl: ttl)
|
||||
{:error, :ratelimit}
|
||||
|
||||
_ ->
|
||||
{:ok, env}
|
||||
end
|
||||
end
|
||||
|
||||
defp check_backoff(env, _), do: env
|
||||
|
||||
@doc """
|
||||
this acts as a single throughput for all GET requests
|
||||
we will check if the host is in the cache, and if it is, we will automatically fail the request
|
||||
this ensures that we don't hammer the server with requests, and instead wait for the backoff to expire
|
||||
this is a very simple implementation, and can be improved upon!
|
||||
"""
|
||||
@spec get(binary, list, list) :: {:ok | :error, HTTP.Env.t()} | {:error, :ratelimit}
|
||||
def get(url, headers \\ [], options \\ []) do
|
||||
%{host: host} = URI.parse(url)
|
||||
|
||||
case @cachex.get(@backoff_cache, host) do
|
||||
{:ok, nil} ->
|
||||
url
|
||||
|> HTTP.get(headers, options)
|
||||
|> check_backoff(host)
|
||||
|
||||
_ ->
|
||||
{:error, :ratelimit}
|
||||
end
|
||||
end
|
||||
end
|
|
@ -1,46 +0,0 @@
|
|||
# Pleroma: A lightweight social networking server
|
||||
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
defmodule Pleroma.Keys do
|
||||
# Native generation of RSA keys is only available since OTP 20+ and in default build conditions
|
||||
# We try at compile time to generate natively an RSA key otherwise we fallback on the old way.
|
||||
try do
|
||||
_ = :public_key.generate_key({:rsa, 2048, 65_537})
|
||||
|
||||
def generate_rsa_pem do
|
||||
key = :public_key.generate_key({:rsa, 2048, 65_537})
|
||||
entry = :public_key.pem_entry_encode(:RSAPrivateKey, key)
|
||||
pem = :public_key.pem_encode([entry]) |> String.trim_trailing()
|
||||
{:ok, pem}
|
||||
end
|
||||
rescue
|
||||
_ ->
|
||||
def generate_rsa_pem do
|
||||
port = Port.open({:spawn, "openssl genrsa"}, [:binary])
|
||||
|
||||
{:ok, pem} =
|
||||
receive do
|
||||
{^port, {:data, pem}} -> {:ok, pem}
|
||||
end
|
||||
|
||||
Port.close(port)
|
||||
|
||||
if Regex.match?(~r/RSA PRIVATE KEY/, pem) do
|
||||
{:ok, pem}
|
||||
else
|
||||
:error
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def keys_from_pem(pem) do
|
||||
with [private_key_code] <- :public_key.pem_decode(pem),
|
||||
private_key <- :public_key.pem_entry_decode(private_key_code),
|
||||
{:RSAPrivateKey, _, modulus, exponent, _, _, _, _, _, _, _} <- private_key do
|
||||
{:ok, private_key, {:RSAPublicKey, modulus, exponent}}
|
||||
else
|
||||
error -> {:error, error}
|
||||
end
|
||||
end
|
||||
end
|
|
@ -12,8 +12,6 @@ defmodule Pleroma.Object.Containment do
|
|||
spoofing, therefore removal of object containment functions is NOT recommended.
|
||||
"""
|
||||
|
||||
alias Pleroma.Web.ActivityPub.Transmogrifier
|
||||
|
||||
def get_actor(%{"actor" => actor}) when is_binary(actor) do
|
||||
actor
|
||||
end
|
||||
|
@ -50,16 +48,39 @@ def get_object(_) do
|
|||
defp compare_uris(%URI{host: host} = _id_uri, %URI{host: host} = _other_uri), do: :ok
|
||||
defp compare_uris(_id_uri, _other_uri), do: :error
|
||||
|
||||
defp compare_uris_exact(uri, uri), do: :ok
|
||||
defp uri_strip_slash(%URI{path: path} = uri) when is_binary(path),
|
||||
do: %{uri | path: String.replace_suffix(path, "/", "")}
|
||||
|
||||
defp compare_uris_exact(%URI{} = id, %URI{} = other),
|
||||
do: compare_uris_exact(URI.to_string(id), URI.to_string(other))
|
||||
defp uri_strip_slash(uri), do: uri
|
||||
|
||||
defp compare_uris_exact(id_uri, other_uri)
|
||||
when is_binary(id_uri) and is_binary(other_uri) do
|
||||
norm_id = String.replace_suffix(id_uri, "/", "")
|
||||
norm_other = String.replace_suffix(other_uri, "/", "")
|
||||
if norm_id == norm_other, do: :ok, else: :error
|
||||
# domain names are case-insensitive per spec (other parts of URIs aren’t necessarily)
|
||||
defp uri_normalise_host(%URI{host: host} = uri) when is_binary(host),
|
||||
do: %{uri | host: String.downcase(host, :ascii)}
|
||||
|
||||
defp uri_normalise_host(uri), do: uri
|
||||
|
||||
defp compare_uri_identities(uri, uri), do: :ok
|
||||
|
||||
defp compare_uri_identities(id_uri, other_uri) when is_binary(id_uri) and is_binary(other_uri),
|
||||
do: compare_uri_identities(URI.parse(id_uri), URI.parse(other_uri))
|
||||
|
||||
defp compare_uri_identities(%URI{} = id, %URI{} = other) do
|
||||
normid =
|
||||
%{id | fragment: nil}
|
||||
|> uri_strip_slash()
|
||||
|> uri_normalise_host()
|
||||
|
||||
normother =
|
||||
%{other | fragment: nil}
|
||||
|> uri_strip_slash()
|
||||
|> uri_normalise_host()
|
||||
|
||||
# Conversion back to binary avoids issues from non-normalised deprecated authority field
|
||||
if URI.to_string(normid) == URI.to_string(normother) do
|
||||
:ok
|
||||
else
|
||||
:error
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
|
@ -93,21 +114,13 @@ def contain_origin(id, %{"attributedTo" => actor} = params),
|
|||
def contain_origin(_id, _data), do: :ok
|
||||
|
||||
@doc """
|
||||
Check whether the fetch URL (after redirects) exactly (sans tralining slash) matches either
|
||||
the canonical ActivityPub id or the objects url field (for display URLs from *key and Mastodon)
|
||||
Check whether the fetch URL (after redirects) is the
|
||||
same location the canonical ActivityPub id points to.
|
||||
|
||||
Since this is meant to be used for fetches, anonymous or transient objects are not accepted here.
|
||||
"""
|
||||
def contain_id_to_fetch(url, %{"id" => id} = data) when is_binary(id) do
|
||||
with {:id, :error} <- {:id, compare_uris_exact(id, url)},
|
||||
# "url" can be a "Link" object and this is checked before full normalisation
|
||||
display_url <- Transmogrifier.fix_url(data)["url"],
|
||||
true <- display_url != nil do
|
||||
compare_uris_exact(display_url, url)
|
||||
else
|
||||
{:id, :ok} -> :ok
|
||||
_ -> :error
|
||||
end
|
||||
def contain_id_to_fetch(url, %{"id" => id}) when is_binary(id) do
|
||||
compare_uri_identities(url, id)
|
||||
end
|
||||
|
||||
def contain_id_to_fetch(_url, _data), do: :error
|
||||
|
|
|
@ -116,7 +116,7 @@ defp reinject_object(%Object{} = object, new_data) do
|
|||
@doc "Assumes object already is in our database and refetches from remote to update (e.g. for polls)"
|
||||
def refetch_object(%Object{data: %{"id" => id}} = object) do
|
||||
with {:local, false} <- {:local, Object.local?(object)},
|
||||
{:ok, new_data} <- fetch_and_contain_remote_object_from_id(id),
|
||||
{:ok, new_data} <- fetch_and_contain_remote_object_from_id(id, true),
|
||||
{:id, true} <- {:id, new_data["id"] == id},
|
||||
{:ok, object} <- reinject_object(object, new_data) do
|
||||
{:ok, object}
|
||||
|
@ -253,14 +253,17 @@ defp maybe_date_fetch(headers, date) do
|
|||
end
|
||||
end
|
||||
|
||||
@doc "Fetches arbitrary remote object and performs basic safety and authenticity checks"
|
||||
def fetch_and_contain_remote_object_from_id(id)
|
||||
@doc """
|
||||
Fetches arbitrary remote object and performs basic safety and authenticity checks.
|
||||
When the fetch URL is known to already be a canonical AP id, checks are stricter.
|
||||
"""
|
||||
def fetch_and_contain_remote_object_from_id(id, is_ap_id \\ false)
|
||||
|
||||
def fetch_and_contain_remote_object_from_id(%{"id" => id}),
|
||||
do: fetch_and_contain_remote_object_from_id(id)
|
||||
def fetch_and_contain_remote_object_from_id(%{"id" => id}, is_ap_id),
|
||||
do: fetch_and_contain_remote_object_from_id(id, is_ap_id)
|
||||
|
||||
def fetch_and_contain_remote_object_from_id(id) when is_binary(id) do
|
||||
Logger.debug("Fetching object #{id} via AP")
|
||||
def fetch_and_contain_remote_object_from_id(id, is_ap_id) when is_binary(id) do
|
||||
Logger.debug("Fetching object #{id} via AP [ap_id=#{is_ap_id}]")
|
||||
|
||||
with {:valid_uri_scheme, true} <- {:valid_uri_scheme, String.starts_with?(id, "http")},
|
||||
%URI{} = uri <- URI.parse(id),
|
||||
|
@ -270,18 +273,31 @@ def fetch_and_contain_remote_object_from_id(id) when is_binary(id) do
|
|||
{:mrf_accept_check, Pleroma.Web.ActivityPub.MRF.SimplePolicy.check_accept(uri)},
|
||||
{:local_fetch, :ok} <- {:local_fetch, Containment.contain_local_fetch(id)},
|
||||
{:ok, final_id, body} <- get_object(id),
|
||||
# a canonical ID shouldn't be a redirect
|
||||
true <- !is_ap_id || final_id == id,
|
||||
{:ok, data} <- safe_json_decode(body),
|
||||
{_, :ok} <- {:strict_id, Containment.contain_id_to_fetch(final_id, data)},
|
||||
{_, :ok} <- {:containment, Containment.contain_origin(final_id, data)} do
|
||||
{_, :ok} <- {:containment, Containment.contain_origin(final_id, data)},
|
||||
{_, _, :ok} <- {:strict_id, data["id"], Containment.contain_id_to_fetch(final_id, data)} do
|
||||
unless Instances.reachable?(final_id) do
|
||||
Instances.set_reachable(final_id)
|
||||
end
|
||||
|
||||
{:ok, data}
|
||||
else
|
||||
{:strict_id, _} = e ->
|
||||
log_fetch_error(id, e)
|
||||
{:error, :id_mismatch}
|
||||
# E.g. Mastodon and *key serve the AP object directly under their display URLs without
|
||||
# redirecting to their canonical location first, thus ids will expectedly differ.
|
||||
# Similarly keys, either use a fragment ID and are a subobjects or a distinct ID
|
||||
# but for compatibility are still a subobject presenting their owning actors ID at the toplevel.
|
||||
# Refetching _once_ from the listed id, should yield a strict match afterwards.
|
||||
{:strict_id, ap_id, _} = e ->
|
||||
case is_ap_id do
|
||||
false ->
|
||||
fetch_and_contain_remote_object_from_id(ap_id, true)
|
||||
|
||||
true ->
|
||||
log_fetch_error(id, e)
|
||||
{:error, :id_mismatch}
|
||||
end
|
||||
|
||||
{:mrf_reject_check, _} = e ->
|
||||
log_fetch_error(id, e)
|
||||
|
@ -301,7 +317,7 @@ def fetch_and_contain_remote_object_from_id(id) when is_binary(id) do
|
|||
|
||||
{:containment, reason} ->
|
||||
log_fetch_error(id, reason)
|
||||
{:error, reason}
|
||||
{:error, {:containment, reason}}
|
||||
|
||||
{:error, e} ->
|
||||
{:error, e}
|
||||
|
@ -311,25 +327,13 @@ def fetch_and_contain_remote_object_from_id(id) when is_binary(id) do
|
|||
end
|
||||
end
|
||||
|
||||
def fetch_and_contain_remote_object_from_id(_id),
|
||||
def fetch_and_contain_remote_object_from_id(_id, _is_ap_id),
|
||||
do: {:error, :invalid_id}
|
||||
|
||||
defp check_crossdomain_redirect(final_host, original_url)
|
||||
|
||||
# HOPEFULLY TEMPORARY
|
||||
# Basically none of our Tesla mocks in tests set the (supposed to
|
||||
# exist for Tesla proper) url parameter for their responses
|
||||
# causing almost every fetch in test to fail otherwise
|
||||
if @mix_env == :test do
|
||||
defp check_crossdomain_redirect(nil, _) do
|
||||
{:cross_domain_redirect, false}
|
||||
end
|
||||
end
|
||||
|
||||
defp check_crossdomain_redirect(final_host, original_url) do
|
||||
{:cross_domain_redirect, final_host != URI.parse(original_url).host}
|
||||
end
|
||||
|
||||
if @mix_env == :test do
|
||||
defp get_final_id(nil, initial_url), do: initial_url
|
||||
defp get_final_id("", initial_url), do: initial_url
|
||||
|
@ -354,11 +358,7 @@ def get_object(id) do
|
|||
|
||||
with {:ok, %{body: body, status: code, headers: headers, url: final_url}}
|
||||
when code in 200..299 <-
|
||||
HTTP.get(id, headers),
|
||||
remote_host <-
|
||||
URI.parse(final_url).host,
|
||||
{:cross_domain_redirect, false} <-
|
||||
check_crossdomain_redirect(remote_host, id),
|
||||
HTTP.Backoff.get(id, headers),
|
||||
{:has_content_type, {_, content_type}} <-
|
||||
{:has_content_type, List.keyfind(headers, "content-type", 0)},
|
||||
{:parse_content_type, {:ok, "application", subtype, type_params}} <-
|
||||
|
@ -369,8 +369,12 @@ def get_object(id) do
|
|||
{"activity+json", _} ->
|
||||
{:ok, final_id, body}
|
||||
|
||||
{"ld+json", %{"profile" => "https://www.w3.org/ns/activitystreams"}} ->
|
||||
{:ok, final_id, body}
|
||||
{"ld+json", %{"profile" => profiles}} ->
|
||||
if "https://www.w3.org/ns/activitystreams" in String.split(profiles) do
|
||||
{:ok, final_id, body}
|
||||
else
|
||||
{:error, {:content_type, content_type}}
|
||||
end
|
||||
|
||||
_ ->
|
||||
{:error, {:content_type, content_type}}
|
||||
|
|
|
@ -28,7 +28,7 @@ defmodule Pleroma.ScheduledActivity do
|
|||
timestamps()
|
||||
end
|
||||
|
||||
def changeset(%ScheduledActivity{} = scheduled_activity, attrs) do
|
||||
defp changeset(%ScheduledActivity{} = scheduled_activity, attrs) do
|
||||
scheduled_activity
|
||||
|> cast(attrs, [:scheduled_at, :params])
|
||||
|> validate_required([:scheduled_at, :params])
|
||||
|
@ -40,26 +40,36 @@ defp with_media_attachments(
|
|||
%{changes: %{params: %{"media_ids" => media_ids} = params}} = changeset
|
||||
)
|
||||
when is_list(media_ids) do
|
||||
media_attachments = Utils.attachments_from_ids(%{media_ids: media_ids})
|
||||
user = User.get_by_id(changeset.data.user_id)
|
||||
|
||||
params =
|
||||
params
|
||||
|> Map.put("media_attachments", media_attachments)
|
||||
|> Map.put("media_ids", media_ids)
|
||||
case Utils.attachments_from_ids(user, %{media_ids: media_ids}) do
|
||||
media_attachments when is_list(media_attachments) ->
|
||||
params =
|
||||
params
|
||||
|> Map.put("media_attachments", media_attachments)
|
||||
|> Map.put("media_ids", media_ids)
|
||||
|
||||
put_change(changeset, :params, params)
|
||||
put_change(changeset, :params, params)
|
||||
|
||||
{:error, _} = e ->
|
||||
e
|
||||
|
||||
e ->
|
||||
{:error, e}
|
||||
end
|
||||
end
|
||||
|
||||
defp with_media_attachments(changeset), do: changeset
|
||||
|
||||
def update_changeset(%ScheduledActivity{} = scheduled_activity, attrs) do
|
||||
defp update_changeset(%ScheduledActivity{} = scheduled_activity, attrs) do
|
||||
# note: should this ever allow swapping media attachments, make sure ownership is checked
|
||||
scheduled_activity
|
||||
|> cast(attrs, [:scheduled_at])
|
||||
|> validate_required([:scheduled_at])
|
||||
|> validate_scheduled_at()
|
||||
end
|
||||
|
||||
def validate_scheduled_at(changeset) do
|
||||
defp validate_scheduled_at(changeset) do
|
||||
validate_change(changeset, :scheduled_at, fn _, scheduled_at ->
|
||||
cond do
|
||||
not far_enough?(scheduled_at) ->
|
||||
|
@ -77,7 +87,7 @@ def validate_scheduled_at(changeset) do
|
|||
end)
|
||||
end
|
||||
|
||||
def exceeds_daily_user_limit?(user_id, scheduled_at) do
|
||||
defp exceeds_daily_user_limit?(user_id, scheduled_at) do
|
||||
ScheduledActivity
|
||||
|> where(user_id: ^user_id)
|
||||
|> where([sa], type(sa.scheduled_at, :date) == type(^scheduled_at, :date))
|
||||
|
@ -86,7 +96,7 @@ def exceeds_daily_user_limit?(user_id, scheduled_at) do
|
|||
|> Kernel.>=(Config.get([ScheduledActivity, :daily_user_limit]))
|
||||
end
|
||||
|
||||
def exceeds_total_user_limit?(user_id) do
|
||||
defp exceeds_total_user_limit?(user_id) do
|
||||
ScheduledActivity
|
||||
|> where(user_id: ^user_id)
|
||||
|> select([sa], count(sa.id))
|
||||
|
@ -108,20 +118,29 @@ def far_enough?(scheduled_at) do
|
|||
diff > @min_offset
|
||||
end
|
||||
|
||||
def new(%User{} = user, attrs) do
|
||||
defp new(%User{} = user, attrs) do
|
||||
changeset(%ScheduledActivity{user_id: user.id}, attrs)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates ScheduledActivity and add to queue to perform at scheduled_at date
|
||||
"""
|
||||
@spec create(User.t(), map()) :: {:ok, ScheduledActivity.t()} | {:error, Ecto.Changeset.t()}
|
||||
@spec create(User.t(), map()) :: {:ok, ScheduledActivity.t()} | {:error, any()}
|
||||
def create(%User{} = user, attrs) do
|
||||
Multi.new()
|
||||
|> Multi.insert(:scheduled_activity, new(user, attrs))
|
||||
|> maybe_add_jobs(Config.get([ScheduledActivity, :enabled]))
|
||||
|> Repo.transaction()
|
||||
|> transaction_response
|
||||
case new(user, attrs) do
|
||||
%Ecto.Changeset{} = sched_data ->
|
||||
Multi.new()
|
||||
|> Multi.insert(:scheduled_activity, sched_data)
|
||||
|> maybe_add_jobs(Config.get([ScheduledActivity, :enabled]))
|
||||
|> Repo.transaction()
|
||||
|> transaction_response
|
||||
|
||||
{:error, _} = e ->
|
||||
e
|
||||
|
||||
e ->
|
||||
{:error, e}
|
||||
end
|
||||
end
|
||||
|
||||
defp maybe_add_jobs(multi, true) do
|
||||
|
@ -187,17 +206,7 @@ def for_user_query(%User{} = user) do
|
|||
|> where(user_id: ^user.id)
|
||||
end
|
||||
|
||||
def due_activities(offset \\ 0) do
|
||||
naive_datetime =
|
||||
NaiveDateTime.utc_now()
|
||||
|> NaiveDateTime.add(offset, :millisecond)
|
||||
|
||||
ScheduledActivity
|
||||
|> where([sa], sa.scheduled_at < ^naive_datetime)
|
||||
|> Repo.all()
|
||||
end
|
||||
|
||||
def job_query(scheduled_activity_id) do
|
||||
defp job_query(scheduled_activity_id) do
|
||||
from(j in Oban.Job,
|
||||
where: j.queue == "scheduled_activities",
|
||||
where: fragment("args ->> 'activity_id' = ?::text", ^to_string(scheduled_activity_id))
|
||||
|
|
|
@ -21,19 +21,12 @@ def search(user, search_query, options \\ []) do
|
|||
offset = Keyword.get(options, :offset, 0)
|
||||
author = Keyword.get(options, :author)
|
||||
|
||||
search_function =
|
||||
if :persistent_term.get({Pleroma.Repo, :postgres_version}) >= 11 do
|
||||
:websearch
|
||||
else
|
||||
:plain
|
||||
end
|
||||
|
||||
try do
|
||||
Activity
|
||||
|> Activity.with_preloaded_object()
|
||||
|> Activity.restrict_deactivated_users()
|
||||
|> restrict_public()
|
||||
|> query_with(index_type, search_query, search_function)
|
||||
|> query_with(index_type, search_query)
|
||||
|> maybe_restrict_local(user)
|
||||
|> maybe_restrict_author(author)
|
||||
|> maybe_restrict_blocked(user)
|
||||
|
@ -72,25 +65,7 @@ def restrict_public(q) do
|
|||
)
|
||||
end
|
||||
|
||||
defp query_with(q, :gin, search_query, :plain) do
|
||||
%{rows: [[tsc]]} =
|
||||
Ecto.Adapters.SQL.query!(
|
||||
Pleroma.Repo,
|
||||
"select current_setting('default_text_search_config')::regconfig::oid;"
|
||||
)
|
||||
|
||||
from([a, o] in q,
|
||||
where:
|
||||
fragment(
|
||||
"to_tsvector(?::oid::regconfig, ?->>'content') @@ plainto_tsquery(?)",
|
||||
^tsc,
|
||||
o.data,
|
||||
^search_query
|
||||
)
|
||||
)
|
||||
end
|
||||
|
||||
defp query_with(q, :gin, search_query, :websearch) do
|
||||
defp query_with(q, :gin, search_query) do
|
||||
%{rows: [[tsc]]} =
|
||||
Ecto.Adapters.SQL.query!(
|
||||
Pleroma.Repo,
|
||||
|
@ -108,19 +83,7 @@ defp query_with(q, :gin, search_query, :websearch) do
|
|||
)
|
||||
end
|
||||
|
||||
defp query_with(q, :rum, search_query, :plain) do
|
||||
from([a, o] in q,
|
||||
where:
|
||||
fragment(
|
||||
"? @@ plainto_tsquery(?)",
|
||||
o.fts_content,
|
||||
^search_query
|
||||
),
|
||||
order_by: [fragment("? <=> now()::date", o.inserted_at)]
|
||||
)
|
||||
end
|
||||
|
||||
defp query_with(q, :rum, search_query, :websearch) do
|
||||
defp query_with(q, :rum, search_query) do
|
||||
from([a, o] in q,
|
||||
where:
|
||||
fragment(
|
||||
|
|
|
@ -5,15 +5,27 @@ defmodule Pleroma.Search.Meilisearch do
|
|||
alias Pleroma.Activity
|
||||
|
||||
import Pleroma.Search.DatabaseSearch
|
||||
import Ecto.Query
|
||||
|
||||
@behaviour Pleroma.Search.SearchBackend
|
||||
|
||||
defp meili_headers do
|
||||
private_key = Pleroma.Config.get([Pleroma.Search.Meilisearch, :private_key])
|
||||
defp meili_headers(key) do
|
||||
key_header =
|
||||
if is_nil(key), do: [], else: [{"Authorization", "Bearer #{key}"}]
|
||||
|
||||
[{"Content-Type", "application/json"}] ++
|
||||
if is_nil(private_key), do: [], else: [{"Authorization", "Bearer #{private_key}"}]
|
||||
[{"Content-Type", "application/json"} | key_header]
|
||||
end
|
||||
|
||||
defp meili_headers_admin do
|
||||
private_key = Pleroma.Config.get([Pleroma.Search.Meilisearch, :private_key])
|
||||
meili_headers(private_key)
|
||||
end
|
||||
|
||||
defp meili_headers_search do
|
||||
search_key =
|
||||
Pleroma.Config.get([Pleroma.Search.Meilisearch, :search_key]) ||
|
||||
Pleroma.Config.get([Pleroma.Search.Meilisearch, :private_key])
|
||||
|
||||
meili_headers(search_key)
|
||||
end
|
||||
|
||||
def meili_get(path) do
|
||||
|
@ -22,7 +34,7 @@ def meili_get(path) do
|
|||
result =
|
||||
Pleroma.HTTP.get(
|
||||
Path.join(endpoint, path),
|
||||
meili_headers()
|
||||
meili_headers_admin()
|
||||
)
|
||||
|
||||
with {:ok, res} <- result do
|
||||
|
@ -30,14 +42,14 @@ def meili_get(path) do
|
|||
end
|
||||
end
|
||||
|
||||
def meili_post(path, params) do
|
||||
defp meili_search(params) do
|
||||
endpoint = Pleroma.Config.get([Pleroma.Search.Meilisearch, :url])
|
||||
|
||||
result =
|
||||
Pleroma.HTTP.post(
|
||||
Path.join(endpoint, path),
|
||||
Path.join(endpoint, "/indexes/objects/search"),
|
||||
Jason.encode!(params),
|
||||
meili_headers()
|
||||
meili_headers_search()
|
||||
)
|
||||
|
||||
with {:ok, res} <- result do
|
||||
|
@ -53,7 +65,7 @@ def meili_put(path, params) do
|
|||
:put,
|
||||
Path.join(endpoint, path),
|
||||
Jason.encode!(params),
|
||||
meili_headers(),
|
||||
meili_headers_admin(),
|
||||
[]
|
||||
)
|
||||
|
||||
|
@ -70,7 +82,7 @@ def meili_delete!(path) do
|
|||
:delete,
|
||||
Path.join(endpoint, path),
|
||||
"",
|
||||
meili_headers(),
|
||||
meili_headers_admin(),
|
||||
[]
|
||||
)
|
||||
end
|
||||
|
@ -81,25 +93,20 @@ def search(user, query, options \\ []) do
|
|||
author = Keyword.get(options, :author)
|
||||
|
||||
res =
|
||||
meili_post(
|
||||
"/indexes/objects/search",
|
||||
%{q: query, offset: offset, limit: limit}
|
||||
)
|
||||
meili_search(%{q: query, offset: offset, limit: limit})
|
||||
|
||||
with {:ok, result} <- res do
|
||||
hits = result["hits"] |> Enum.map(& &1["ap"])
|
||||
|
||||
try do
|
||||
hits
|
||||
|> Activity.create_by_object_ap_id()
|
||||
|> Activity.with_preloaded_object()
|
||||
|> Activity.get_presorted_create_by_object_ap_id()
|
||||
|> Activity.with_preloaded_object()
|
||||
|> Activity.restrict_deactivated_users()
|
||||
|> maybe_restrict_local(user)
|
||||
|> maybe_restrict_author(author)
|
||||
|> maybe_restrict_blocked(user)
|
||||
|> maybe_fetch(user, query)
|
||||
|> order_by([object: obj], desc: obj.data["published"])
|
||||
|> Pleroma.Repo.all()
|
||||
rescue
|
||||
_ -> maybe_fetch([], user, query)
|
||||
|
|
|
@ -5,47 +5,25 @@
|
|||
defmodule Pleroma.Signature do
|
||||
@behaviour HTTPSignatures.Adapter
|
||||
|
||||
alias Pleroma.EctoType.ActivityPub.ObjectValidators
|
||||
alias Pleroma.Keys
|
||||
alias Pleroma.User
|
||||
alias Pleroma.Web.ActivityPub.ActivityPub
|
||||
|
||||
@known_suffixes ["/publickey", "/main-key"]
|
||||
alias Pleroma.User.SigningKey
|
||||
require Logger
|
||||
|
||||
def key_id_to_actor_id(key_id) do
|
||||
uri =
|
||||
key_id
|
||||
|> URI.parse()
|
||||
|> Map.put(:fragment, nil)
|
||||
|> Map.put(:query, nil)
|
||||
|> remove_suffix(@known_suffixes)
|
||||
case SigningKey.key_id_to_ap_id(key_id) do
|
||||
nil ->
|
||||
# hm, we SHOULD have gotten this in the pipeline before we hit here!
|
||||
Logger.error("Could not figure out who owns the key #{key_id}")
|
||||
{:error, :key_owner_not_found}
|
||||
|
||||
maybe_ap_id = URI.to_string(uri)
|
||||
|
||||
case ObjectValidators.ObjectID.cast(maybe_ap_id) do
|
||||
{:ok, ap_id} ->
|
||||
{:ok, ap_id}
|
||||
|
||||
_ ->
|
||||
case Pleroma.Web.WebFinger.finger(maybe_ap_id) do
|
||||
{:ok, %{"ap_id" => ap_id}} -> {:ok, ap_id}
|
||||
_ -> {:error, maybe_ap_id}
|
||||
end
|
||||
key ->
|
||||
{:ok, key}
|
||||
end
|
||||
end
|
||||
|
||||
defp remove_suffix(uri, [test | rest]) do
|
||||
if not is_nil(uri.path) and String.ends_with?(uri.path, test) do
|
||||
Map.put(uri, :path, String.replace(uri.path, test, ""))
|
||||
else
|
||||
remove_suffix(uri, rest)
|
||||
end
|
||||
end
|
||||
|
||||
defp remove_suffix(uri, []), do: uri
|
||||
|
||||
def fetch_public_key(conn) do
|
||||
with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn),
|
||||
{:ok, %SigningKey{}} <- SigningKey.get_or_fetch_by_key_id(kid),
|
||||
{:ok, actor_id} <- key_id_to_actor_id(kid),
|
||||
{:ok, public_key} <- User.get_public_key_for_ap_id(actor_id) do
|
||||
{:ok, public_key}
|
||||
|
@ -57,8 +35,8 @@ def fetch_public_key(conn) do
|
|||
|
||||
def refetch_public_key(conn) do
|
||||
with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn),
|
||||
{:ok, %SigningKey{}} <- SigningKey.get_or_fetch_by_key_id(kid),
|
||||
{:ok, actor_id} <- key_id_to_actor_id(kid),
|
||||
{:ok, _user} <- ActivityPub.make_user_from_ap_id(actor_id),
|
||||
{:ok, public_key} <- User.get_public_key_for_ap_id(actor_id) do
|
||||
{:ok, public_key}
|
||||
else
|
||||
|
@ -67,9 +45,9 @@ def refetch_public_key(conn) do
|
|||
end
|
||||
end
|
||||
|
||||
def sign(%User{keys: keys} = user, headers) do
|
||||
with {:ok, private_key, _} <- Keys.keys_from_pem(keys) do
|
||||
HTTPSignatures.sign(private_key, user.ap_id <> "#main-key", headers)
|
||||
def sign(%User{} = user, headers) do
|
||||
with {:ok, private_key} <- SigningKey.private_key(user) do
|
||||
HTTPSignatures.sign(private_key, SigningKey.local_key_id(user.ap_id), headers)
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
@ -13,7 +13,6 @@ defmodule Pleroma.Upload do
|
|||
* `:uploader`: override uploader
|
||||
* `:filters`: override filters
|
||||
* `:size_limit`: override size limit
|
||||
* `:activity_type`: override activity type
|
||||
|
||||
The `%Pleroma.Upload{}` struct: all documented fields are meant to be overwritten in filters:
|
||||
|
||||
|
@ -48,7 +47,6 @@ defmodule Pleroma.Upload do
|
|||
@type option ::
|
||||
{:type, :avatar | :banner | :background}
|
||||
| {:description, String.t()}
|
||||
| {:activity_type, String.t()}
|
||||
| {:size_limit, nil | non_neg_integer()}
|
||||
| {:uploader, module()}
|
||||
| {:filters, [module()]}
|
||||
|
@ -143,7 +141,7 @@ defp get_opts(opts) do
|
|||
end
|
||||
|
||||
%{
|
||||
activity_type: Keyword.get(opts, :activity_type, activity_type),
|
||||
activity_type: activity_type,
|
||||
size_limit: Keyword.get(opts, :size_limit, size_limit),
|
||||
uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
|
||||
filters:
|
||||
|
|
|
@ -33,8 +33,7 @@ defp read_when_empty(current_description, _, _) when is_binary(current_descripti
|
|||
defp read_when_empty(_, file, tag) do
|
||||
try do
|
||||
{tag_content, 0} =
|
||||
System.cmd("exiftool", ["-b", "-s3", tag, file],
|
||||
stderr_to_stdout: true,
|
||||
System.cmd("exiftool", ["-b", "-s3", "-ignoreMinorErrors", "-q", "-q", tag, file],
|
||||
parallelism: true
|
||||
)
|
||||
|
||||
|
|
|
@ -18,6 +18,7 @@ defmodule Pleroma.Upload.Filter.Exiftool.StripMetadata do
|
|||
|
||||
# Formats not compatible with exiftool at this time
|
||||
def filter(%Pleroma.Upload{content_type: "image/webp"}), do: {:ok, :noop}
|
||||
def filter(%Pleroma.Upload{content_type: "image/bmp"}), do: {:ok, :noop}
|
||||
def filter(%Pleroma.Upload{content_type: "image/svg+xml"}), do: {:ok, :noop}
|
||||
|
||||
def filter(%Pleroma.Upload{tempfile: file, content_type: "image" <> _}) do
|
||||
|
|
|
@ -25,7 +25,6 @@ defmodule Pleroma.User do
|
|||
alias Pleroma.Hashtag
|
||||
alias Pleroma.User.HashtagFollow
|
||||
alias Pleroma.HTML
|
||||
alias Pleroma.Keys
|
||||
alias Pleroma.MFA
|
||||
alias Pleroma.Notification
|
||||
alias Pleroma.Object
|
||||
|
@ -43,6 +42,7 @@ defmodule Pleroma.User do
|
|||
alias Pleroma.Web.OAuth
|
||||
alias Pleroma.Web.RelMe
|
||||
alias Pleroma.Workers.BackgroundWorker
|
||||
alias Pleroma.User.SigningKey
|
||||
|
||||
use Pleroma.Web, :verified_routes
|
||||
|
||||
|
@ -101,7 +101,6 @@ defmodule Pleroma.User do
|
|||
field(:password, :string, virtual: true)
|
||||
field(:password_confirmation, :string, virtual: true)
|
||||
field(:keys, :string)
|
||||
field(:public_key, :string)
|
||||
field(:ap_id, :string)
|
||||
field(:avatar, :map, default: %{})
|
||||
field(:local, :boolean, default: true)
|
||||
|
@ -222,6 +221,10 @@ defmodule Pleroma.User do
|
|||
on_replace: :delete
|
||||
)
|
||||
|
||||
# FOR THE FUTURE: We might want to make this a one-to-many relationship
|
||||
# it's entirely possible right now, but we don't have a use case for it
|
||||
has_one(:signing_key, SigningKey, foreign_key: :user_id)
|
||||
|
||||
timestamps()
|
||||
end
|
||||
|
||||
|
@ -457,6 +460,7 @@ def remote_user_changeset(struct \\ %User{local: false}, params) do
|
|||
|> fix_follower_address()
|
||||
|
||||
struct
|
||||
|> Repo.preload(:signing_key)
|
||||
|> cast(
|
||||
params,
|
||||
[
|
||||
|
@ -466,7 +470,6 @@ def remote_user_changeset(struct \\ %User{local: false}, params) do
|
|||
:inbox,
|
||||
:shared_inbox,
|
||||
:nickname,
|
||||
:public_key,
|
||||
:avatar,
|
||||
:ap_enabled,
|
||||
:banner,
|
||||
|
@ -495,6 +498,7 @@ def remote_user_changeset(struct \\ %User{local: false}, params) do
|
|||
|> validate_required([:ap_id])
|
||||
|> validate_required([:name], trim: false)
|
||||
|> unique_constraint(:nickname)
|
||||
|> cast_assoc(:signing_key, with: &SigningKey.remote_changeset/2, required: false)
|
||||
|> validate_format(:nickname, @email_regex)
|
||||
|> validate_length(:bio, max: bio_limit)
|
||||
|> validate_length(:name, max: name_limit)
|
||||
|
@ -526,7 +530,6 @@ def update_changeset(struct, params \\ %{}) do
|
|||
:name,
|
||||
:emoji,
|
||||
:avatar,
|
||||
:public_key,
|
||||
:inbox,
|
||||
:shared_inbox,
|
||||
:is_locked,
|
||||
|
@ -570,6 +573,7 @@ def update_changeset(struct, params \\ %{}) do
|
|||
:pleroma_settings_store,
|
||||
&{:ok, Map.merge(struct.pleroma_settings_store, &1)}
|
||||
)
|
||||
|> cast_assoc(:signing_key, with: &SigningKey.remote_changeset/2, requred: false)
|
||||
|> validate_fields(false, struct)
|
||||
end
|
||||
|
||||
|
@ -828,8 +832,10 @@ def put_following_and_follower_and_featured_address(changeset) do
|
|||
end
|
||||
|
||||
defp put_private_key(changeset) do
|
||||
{:ok, pem} = Keys.generate_rsa_pem()
|
||||
put_change(changeset, :keys, pem)
|
||||
ap_id = get_field(changeset, :ap_id)
|
||||
|
||||
changeset
|
||||
|> put_assoc(:signing_key, SigningKey.generate_local_keys(ap_id))
|
||||
end
|
||||
|
||||
defp autofollow_users(user) do
|
||||
|
@ -1146,7 +1152,8 @@ def update_and_set_cache(%{data: %Pleroma.User{} = user} = changeset) do
|
|||
was_superuser_before_update = User.superuser?(user)
|
||||
|
||||
with {:ok, user} <- Repo.update(changeset, stale_error_field: :id) do
|
||||
set_cache(user)
|
||||
user
|
||||
|> set_cache()
|
||||
end
|
||||
|> maybe_remove_report_notifications(was_superuser_before_update)
|
||||
end
|
||||
|
@ -1624,8 +1631,12 @@ def blocks_user?(%User{} = user, %User{} = target) do
|
|||
|
||||
def blocks_user?(_, _), do: false
|
||||
|
||||
def blocks_domain?(%User{} = user, %User{} = target) do
|
||||
%{host: host} = URI.parse(target.ap_id)
|
||||
def blocks_domain?(%User{} = user, %User{ap_id: ap_id}) do
|
||||
blocks_domain?(user, ap_id)
|
||||
end
|
||||
|
||||
def blocks_domain?(%User{} = user, url) when is_binary(url) do
|
||||
%{host: host} = URI.parse(url)
|
||||
Enum.member?(user.domain_blocks, host)
|
||||
# TODO: functionality should probably be changed such that subdomains block as well,
|
||||
# but as it stands, this just hecks up the relationships endpoint
|
||||
|
@ -2047,24 +2058,16 @@ defp create_service_actor(uri, nickname) do
|
|||
|> set_cache()
|
||||
end
|
||||
|
||||
def public_key(%{public_key: public_key_pem}) when is_binary(public_key_pem) do
|
||||
key =
|
||||
public_key_pem
|
||||
|> :public_key.pem_decode()
|
||||
|> hd()
|
||||
|> :public_key.pem_entry_decode()
|
||||
|
||||
{:ok, key}
|
||||
end
|
||||
|
||||
def public_key(_), do: {:error, "key not found"}
|
||||
defdelegate public_key(user), to: SigningKey
|
||||
|
||||
def get_public_key_for_ap_id(ap_id) do
|
||||
with {:ok, %User{} = user} <- get_or_fetch_by_ap_id(ap_id),
|
||||
{:ok, public_key} <- public_key(user) do
|
||||
{:ok, public_key} <- SigningKey.public_key(user) do
|
||||
{:ok, public_key}
|
||||
else
|
||||
_ -> :error
|
||||
e ->
|
||||
Logger.error("Could not get public key for #{ap_id}.\n#{inspect(e)}")
|
||||
{:error, e}
|
||||
end
|
||||
end
|
||||
|
||||
|
|
262
lib/pleroma/user/signing_key.ex
Normal file
262
lib/pleroma/user/signing_key.ex
Normal file
|
@ -0,0 +1,262 @@
|
|||
defmodule Pleroma.User.SigningKey do
|
||||
use Ecto.Schema
|
||||
import Ecto.Query
|
||||
import Ecto.Changeset
|
||||
require Pleroma.Constants
|
||||
alias Pleroma.User
|
||||
alias Pleroma.Repo
|
||||
|
||||
require Logger
|
||||
|
||||
@primary_key false
|
||||
schema "signing_keys" do
|
||||
belongs_to(:user, Pleroma.User, type: FlakeId.Ecto.CompatType)
|
||||
field :public_key, :string
|
||||
field :private_key, :string
|
||||
# This is an arbitrary field given by the remote instance
|
||||
field :key_id, :string, primary_key: true
|
||||
timestamps()
|
||||
end
|
||||
|
||||
def load_key(%User{} = user) do
|
||||
user
|
||||
|> Repo.preload(:signing_key)
|
||||
end
|
||||
|
||||
def key_id_of_local_user(%User{local: true} = user) do
|
||||
case Repo.preload(user, :signing_key) do
|
||||
%User{signing_key: %__MODULE__{key_id: key_id}} -> key_id
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
@spec remote_changeset(__MODULE__, map) :: Changeset.t()
|
||||
def remote_changeset(%__MODULE__{} = signing_key, attrs) do
|
||||
signing_key
|
||||
|> cast(attrs, [:public_key, :key_id])
|
||||
|> validate_required([:public_key, :key_id])
|
||||
end
|
||||
|
||||
@spec key_id_to_user_id(String.t()) :: String.t() | nil
|
||||
@doc """
|
||||
Given a key ID, return the user ID associated with that key.
|
||||
Returns nil if the key ID is not found.
|
||||
"""
|
||||
def key_id_to_user_id(key_id) do
|
||||
from(sk in __MODULE__, where: sk.key_id == ^key_id)
|
||||
|> select([sk], sk.user_id)
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
@spec key_id_to_ap_id(String.t()) :: String.t() | nil
|
||||
@doc """
|
||||
Given a key ID, return the AP ID associated with that key.
|
||||
Returns nil if the key ID is not found.
|
||||
"""
|
||||
def key_id_to_ap_id(key_id) do
|
||||
Logger.debug("Looking up key ID: #{key_id}")
|
||||
|
||||
result =
|
||||
from(sk in __MODULE__, where: sk.key_id == ^key_id)
|
||||
|> join(:inner, [sk], u in User, on: sk.user_id == u.id)
|
||||
|> select([sk, u], %{user: u})
|
||||
|> Repo.one()
|
||||
|
||||
case result do
|
||||
%{user: %User{ap_id: ap_id}} -> ap_id
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
@spec generate_rsa_pem() :: {:ok, binary()}
|
||||
@doc """
|
||||
Generate a new RSA private key and return it as a PEM-encoded string.
|
||||
"""
|
||||
def generate_rsa_pem do
|
||||
key = :public_key.generate_key({:rsa, 2048, 65_537})
|
||||
entry = :public_key.pem_entry_encode(:RSAPrivateKey, key)
|
||||
pem = :public_key.pem_encode([entry]) |> String.trim_trailing()
|
||||
{:ok, pem}
|
||||
end
|
||||
|
||||
@spec generate_local_keys(String.t()) :: {:ok, Changeset.t()} | {:error, String.t()}
|
||||
@doc """
|
||||
Generate a new RSA key pair and create a changeset for it
|
||||
"""
|
||||
def generate_local_keys(ap_id) do
|
||||
{:ok, private_pem} = generate_rsa_pem()
|
||||
{:ok, local_pem} = private_pem_to_public_pem(private_pem)
|
||||
|
||||
%__MODULE__{}
|
||||
|> change()
|
||||
|> put_change(:public_key, local_pem)
|
||||
|> put_change(:private_key, private_pem)
|
||||
|> put_change(:key_id, local_key_id(ap_id))
|
||||
end
|
||||
|
||||
@spec local_key_id(String.t()) :: String.t()
|
||||
@doc """
|
||||
Given an AP ID, return the key ID for the local user.
|
||||
"""
|
||||
def local_key_id(ap_id) do
|
||||
ap_id <> "#main-key"
|
||||
end
|
||||
|
||||
@spec private_pem_to_public_pem(binary) :: {:ok, binary()} | {:error, String.t()}
|
||||
@doc """
|
||||
Given a private key in PEM format, return the corresponding public key in PEM format.
|
||||
"""
|
||||
def private_pem_to_public_pem(private_pem) do
|
||||
[private_key_code] = :public_key.pem_decode(private_pem)
|
||||
private_key = :public_key.pem_entry_decode(private_key_code)
|
||||
{:RSAPrivateKey, _, modulus, exponent, _, _, _, _, _, _, _} = private_key
|
||||
public_key = {:RSAPublicKey, modulus, exponent}
|
||||
public_key = :public_key.pem_entry_encode(:SubjectPublicKeyInfo, public_key)
|
||||
{:ok, :public_key.pem_encode([public_key])}
|
||||
end
|
||||
|
||||
@spec public_key(User.t()) :: {:ok, binary()} | {:error, String.t()}
|
||||
@doc """
|
||||
Given a user, return the public key for that user in binary format.
|
||||
"""
|
||||
def public_key(%User{} = user) do
|
||||
case Repo.preload(user, :signing_key) do
|
||||
%User{signing_key: %__MODULE__{public_key: public_key_pem}} ->
|
||||
key =
|
||||
public_key_pem
|
||||
|> :public_key.pem_decode()
|
||||
|> hd()
|
||||
|> :public_key.pem_entry_decode()
|
||||
|
||||
{:ok, key}
|
||||
|
||||
_ ->
|
||||
{:error, "key not found"}
|
||||
end
|
||||
end
|
||||
|
||||
def public_key(_), do: {:error, "key not found"}
|
||||
|
||||
def public_key_pem(%User{} = user) do
|
||||
case Repo.preload(user, :signing_key) do
|
||||
%User{signing_key: %__MODULE__{public_key: public_key_pem}} -> {:ok, public_key_pem}
|
||||
_ -> {:error, "key not found"}
|
||||
end
|
||||
end
|
||||
|
||||
def public_key_pem(_e) do
|
||||
{:error, "key not found"}
|
||||
end
|
||||
|
||||
@spec private_key(User.t()) :: {:ok, binary()} | {:error, String.t()}
|
||||
@doc """
|
||||
Given a user, return the private key for that user in binary format.
|
||||
"""
|
||||
def private_key(%User{} = user) do
|
||||
case Repo.preload(user, :signing_key) do
|
||||
%{signing_key: %__MODULE__{private_key: private_key_pem}} ->
|
||||
key =
|
||||
private_key_pem
|
||||
|> :public_key.pem_decode()
|
||||
|> hd()
|
||||
|> :public_key.pem_entry_decode()
|
||||
|
||||
{:ok, key}
|
||||
|
||||
_ ->
|
||||
{:error, "key not found"}
|
||||
end
|
||||
end
|
||||
|
||||
@spec get_or_fetch_by_key_id(String.t()) :: {:ok, __MODULE__} | {:error, String.t()}
|
||||
@doc """
|
||||
Given a key ID, return the signing key associated with that key.
|
||||
Will either return the key if it exists locally, or fetch it from the remote instance.
|
||||
"""
|
||||
def get_or_fetch_by_key_id(key_id) do
|
||||
case key_id_to_user_id(key_id) do
|
||||
nil ->
|
||||
fetch_remote_key(key_id)
|
||||
|
||||
user_id ->
|
||||
{:ok, Repo.get_by(__MODULE__, user_id: user_id)}
|
||||
end
|
||||
end
|
||||
|
||||
@spec fetch_remote_key(String.t()) :: {:ok, __MODULE__} | {:error, String.t()}
|
||||
@doc """
|
||||
Fetch a remote key by key ID.
|
||||
Will send a request to the remote instance to get the key ID.
|
||||
This request should, at the very least, return a user ID and a public key object.
|
||||
Though bear in mind that some implementations (looking at you, pleroma) may require a signature for this request.
|
||||
This has the potential to create an infinite loop if the remote instance requires a signature to fetch the key...
|
||||
So if we're rejected, we should probably just give up.
|
||||
"""
|
||||
def fetch_remote_key(key_id) do
|
||||
Logger.debug("Fetching remote key: #{key_id}")
|
||||
resp = Pleroma.Object.Fetcher.fetch_and_contain_remote_object_from_id(key_id)
|
||||
|
||||
case resp do
|
||||
{:ok, _body} ->
|
||||
case handle_signature_response(resp) do
|
||||
{:ok, ap_id, public_key_pem} ->
|
||||
Logger.debug("Fetched remote key: #{ap_id}")
|
||||
# fetch the user
|
||||
{:ok, user} = User.get_or_fetch_by_ap_id(ap_id)
|
||||
# store the key
|
||||
key = %__MODULE__{
|
||||
user_id: user.id,
|
||||
public_key: public_key_pem,
|
||||
key_id: key_id
|
||||
}
|
||||
|
||||
Repo.insert(key, on_conflict: :replace_all, conflict_target: :key_id)
|
||||
|
||||
e ->
|
||||
Logger.debug("Failed to fetch remote key: #{inspect(e)}")
|
||||
{:error, "Could not fetch key"}
|
||||
end
|
||||
|
||||
_ ->
|
||||
Logger.debug("Failed to fetch remote key: #{inspect(resp)}")
|
||||
{:error, "Could not fetch key"}
|
||||
end
|
||||
end
|
||||
|
||||
# Take the response from the remote instance and extract the key details
|
||||
# will check if the key ID matches the owner of the key, if not, error
|
||||
defp extract_key_details(%{"id" => ap_id, "publicKey" => public_key}) do
|
||||
if ap_id !== public_key["owner"] do
|
||||
{:error, "Key ID does not match owner"}
|
||||
else
|
||||
%{"publicKeyPem" => public_key_pem} = public_key
|
||||
{:ok, ap_id, public_key_pem}
|
||||
end
|
||||
end
|
||||
|
||||
defp handle_signature_response({:ok, body}) do
|
||||
case body do
|
||||
%{
|
||||
"type" => "CryptographicKey",
|
||||
"publicKeyPem" => public_key_pem,
|
||||
"owner" => ap_id
|
||||
} ->
|
||||
{:ok, ap_id, public_key_pem}
|
||||
|
||||
# for when we get a subset of the user object
|
||||
%{
|
||||
"id" => _user_id,
|
||||
"publicKey" => _public_key,
|
||||
"type" => actor_type
|
||||
}
|
||||
when actor_type in Pleroma.Constants.actor_types() ->
|
||||
extract_key_details(body)
|
||||
|
||||
%{"error" => error} ->
|
||||
{:error, error}
|
||||
end
|
||||
end
|
||||
|
||||
defp handle_signature_response({:error, e}), do: {:error, e}
|
||||
defp handle_signature_response(other), do: {:error, "Could not fetch key: #{inspect(other)}"}
|
||||
end
|
|
@ -155,9 +155,7 @@ def insert(map, local \\ true, fake \\ false, bypass_actor_check \\ false) when
|
|||
# Splice in the child object if we have one.
|
||||
activity = Maps.put_if_present(activity, :object, object)
|
||||
|
||||
ConcurrentLimiter.limit(Pleroma.Web.RichMedia.Helpers, fn ->
|
||||
Task.start(fn -> Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity) end)
|
||||
end)
|
||||
Pleroma.Web.RichMedia.Card.get_by_activity(activity)
|
||||
|
||||
# Add local posts to search index
|
||||
if local, do: Pleroma.Search.add_to_index(activity)
|
||||
|
@ -185,7 +183,7 @@ def insert(map, local \\ true, fake \\ false, bypass_actor_check \\ false) when
|
|||
id: "pleroma:fakeid"
|
||||
}
|
||||
|
||||
Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity)
|
||||
Pleroma.Web.RichMedia.Card.get_by_activity(activity)
|
||||
{:ok, activity}
|
||||
|
||||
{:remote_limit_pass, _} ->
|
||||
|
@ -1545,11 +1543,30 @@ defp normalize_also_known_as(aka) when is_list(aka), do: aka
|
|||
defp normalize_also_known_as(aka) when is_binary(aka), do: [aka]
|
||||
defp normalize_also_known_as(nil), do: []
|
||||
|
||||
defp normalize_attachment(%{} = attachment), do: [attachment]
|
||||
defp normalize_attachment(attachment) when is_list(attachment), do: attachment
|
||||
defp normalize_attachment(_), do: []
|
||||
|
||||
defp maybe_make_public_key_object(data) do
|
||||
if is_map(data["publicKey"]) && is_binary(data["publicKey"]["publicKeyPem"]) do
|
||||
%{
|
||||
public_key: data["publicKey"]["publicKeyPem"],
|
||||
key_id: data["publicKey"]["id"]
|
||||
}
|
||||
else
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
defp object_to_user_data(data, additional) do
|
||||
fields =
|
||||
data
|
||||
|> Map.get("attachment", [])
|
||||
|> Enum.filter(fn %{"type" => t} -> t == "PropertyValue" end)
|
||||
|> normalize_attachment()
|
||||
|> Enum.filter(fn
|
||||
%{"type" => t} -> t == "PropertyValue"
|
||||
_ -> false
|
||||
end)
|
||||
|> Enum.map(fn fields -> Map.take(fields, ["name", "value"]) end)
|
||||
|
||||
emojis =
|
||||
|
@ -1572,9 +1589,16 @@ defp object_to_user_data(data, additional) do
|
|||
featured_address = data["featured"]
|
||||
{:ok, pinned_objects} = fetch_and_prepare_featured_from_ap_id(featured_address)
|
||||
|
||||
public_key =
|
||||
if is_map(data["publicKey"]) && is_binary(data["publicKey"]["publicKeyPem"]) do
|
||||
data["publicKey"]["publicKeyPem"]
|
||||
# first, check that the owner is correct
|
||||
signing_key =
|
||||
if data["id"] !== data["publicKey"]["owner"] do
|
||||
Logger.error(
|
||||
"Owner of the public key is not the same as the actor - not saving the public key."
|
||||
)
|
||||
|
||||
nil
|
||||
else
|
||||
maybe_make_public_key_object(data)
|
||||
end
|
||||
|
||||
shared_inbox =
|
||||
|
@ -1618,7 +1642,7 @@ defp object_to_user_data(data, additional) do
|
|||
bio: data["summary"] || "",
|
||||
actor_type: actor_type,
|
||||
also_known_as: also_known_as,
|
||||
public_key: public_key,
|
||||
signing_key: signing_key,
|
||||
inbox: data["inbox"],
|
||||
shared_inbox: shared_inbox,
|
||||
pinned_objects: pinned_objects,
|
||||
|
@ -1816,19 +1840,20 @@ def fetch_and_prepare_featured_from_ap_id(ap_id) do
|
|||
end
|
||||
end
|
||||
|
||||
def pinned_fetch_task(nil), do: nil
|
||||
|
||||
def pinned_fetch_task(%{pinned_objects: pins}) do
|
||||
if Enum.all?(pins, fn {ap_id, _} ->
|
||||
Object.get_cached_by_ap_id(ap_id) ||
|
||||
match?({:ok, _object}, Fetcher.fetch_object_from_id(ap_id))
|
||||
end) do
|
||||
:ok
|
||||
else
|
||||
:error
|
||||
end
|
||||
def enqueue_pin_fetches(%{pinned_objects: pins}) do
|
||||
# enqueue a task to fetch all pinned objects
|
||||
Enum.each(pins, fn {ap_id, _} ->
|
||||
if is_nil(Object.get_cached_by_ap_id(ap_id)) do
|
||||
Pleroma.Workers.RemoteFetcherWorker.enqueue("fetch_remote", %{
|
||||
"id" => ap_id,
|
||||
"depth" => 1
|
||||
})
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
def enqueue_pin_fetches(_), do: nil
|
||||
|
||||
def make_user_from_ap_id(ap_id, additional \\ []) do
|
||||
user = User.get_cached_by_ap_id(ap_id)
|
||||
|
||||
|
@ -1836,8 +1861,6 @@ def make_user_from_ap_id(ap_id, additional \\ []) do
|
|||
Transmogrifier.upgrade_user_from_ap_id(ap_id)
|
||||
else
|
||||
with {:ok, data} <- fetch_and_prepare_user_from_ap_id(ap_id, additional) do
|
||||
{:ok, _pid} = Task.start(fn -> pinned_fetch_task(data) end)
|
||||
|
||||
user =
|
||||
if data.ap_id != ap_id do
|
||||
User.get_cached_by_ap_id(data.ap_id)
|
||||
|
@ -1849,6 +1872,7 @@ def make_user_from_ap_id(ap_id, additional \\ []) do
|
|||
user
|
||||
|> User.remote_user_changeset(data)
|
||||
|> User.update_and_set_cache()
|
||||
|> tap(fn _ -> enqueue_pin_fetches(data) end)
|
||||
else
|
||||
maybe_handle_clashing_nickname(data)
|
||||
|
||||
|
@ -1856,6 +1880,7 @@ def make_user_from_ap_id(ap_id, additional \\ []) do
|
|||
|> User.remote_user_changeset()
|
||||
|> Repo.insert()
|
||||
|> User.set_cache()
|
||||
|> tap(fn _ -> enqueue_pin_fetches(data) end)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -60,7 +60,26 @@ defp relay_active?(conn, _) do
|
|||
end
|
||||
end
|
||||
|
||||
def user(conn, %{"nickname" => nickname}) do
|
||||
@doc """
|
||||
Render the user's AP data
|
||||
WARNING: we cannot actually check if the request has a fragment! so let's play defensively
|
||||
- IF we have a valid signature, serve full user
|
||||
- IF we do not, and authorized_fetch_mode is enabled, serve the key only
|
||||
- OTHERWISE, serve the full actor (since we don't need to worry about the signature)
|
||||
"""
|
||||
def user(%{assigns: %{valid_signature: true}} = conn, params) do
|
||||
render_full_user(conn, params)
|
||||
end
|
||||
|
||||
def user(conn, params) do
|
||||
if Pleroma.Config.get([:activitypub, :authorized_fetch_mode], false) do
|
||||
render_key_only_user(conn, params)
|
||||
else
|
||||
render_full_user(conn, params)
|
||||
end
|
||||
end
|
||||
|
||||
defp render_full_user(conn, %{"nickname" => nickname}) do
|
||||
with %User{local: true} = user <- User.get_cached_by_nickname(nickname) do
|
||||
conn
|
||||
|> put_resp_content_type("application/activity+json")
|
||||
|
@ -72,6 +91,18 @@ def user(conn, %{"nickname" => nickname}) do
|
|||
end
|
||||
end
|
||||
|
||||
def render_key_only_user(conn, %{"nickname" => nickname}) do
|
||||
with %User{local: true} = user <- User.get_cached_by_nickname(nickname) do
|
||||
conn
|
||||
|> put_resp_content_type("application/activity+json")
|
||||
|> put_view(UserView)
|
||||
|> render("keys.json", %{user: user})
|
||||
else
|
||||
nil -> {:error, :not_found}
|
||||
%{local: false} -> {:error, :not_found}
|
||||
end
|
||||
end
|
||||
|
||||
def object(%{assigns: assigns} = conn, _) do
|
||||
with ap_id <- Endpoint.url() <> conn.request_path,
|
||||
%Object{} = object <- Object.get_cached_by_ap_id(ap_id),
|
||||
|
|
|
@ -233,7 +233,7 @@ def config_descriptions(policies) do
|
|||
if function_exported?(policy, :config_description, 0) do
|
||||
description =
|
||||
@default_description
|
||||
|> Map.merge(policy.config_description)
|
||||
|> Map.merge(policy.config_description())
|
||||
|> Map.put(:group, :pleroma)
|
||||
|> Map.put(:tab, :mrf)
|
||||
|> Map.put(:type, :group)
|
||||
|
|
|
@ -101,10 +101,19 @@ defp get_extension_if_safe(response) do
|
|||
end
|
||||
end
|
||||
|
||||
defp get_int_header(headers, header_name, default \\ nil) do
|
||||
with rawval when rawval != :undefined <- :proplists.get_value(header_name, headers),
|
||||
{int, ""} <- Integer.parse(rawval) do
|
||||
int
|
||||
else
|
||||
_ -> default
|
||||
end
|
||||
end
|
||||
|
||||
defp is_remote_size_within_limit?(url) do
|
||||
with {:ok, %{status: status, headers: headers} = _response} when status in 200..299 <-
|
||||
Pleroma.HTTP.request(:head, url, nil, [], []) do
|
||||
content_length = :proplists.get_value("content-length", headers, nil)
|
||||
content_length = get_int_header(headers, "content-length")
|
||||
size_limit = Config.get([:mrf_steal_emoji, :size_limit], @size_limit)
|
||||
|
||||
accept_unknown =
|
||||
|
@ -172,7 +181,7 @@ def filter(message), do: {:ok, message}
|
|||
description: <<_::272, _::_*256>>,
|
||||
key: :hosts | :rejected_shortcodes | :size_limit,
|
||||
suggestions: [any(), ...],
|
||||
type: {:list, :string} | {:list, :string} | :integer
|
||||
type: {:list, :string} | {:list, :string} | :integer | :boolean
|
||||
},
|
||||
...
|
||||
],
|
||||
|
@ -209,6 +218,12 @@ def config_description do
|
|||
type: :integer,
|
||||
description: "File size limit (in bytes), checked before an emoji is saved to the disk",
|
||||
suggestions: ["100000"]
|
||||
},
|
||||
%{
|
||||
key: :download_unknown_size,
|
||||
type: :boolean,
|
||||
description: "Whether to download emoji if size can't be determined ahead of time",
|
||||
suggestions: [false, true]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
@ -14,7 +14,6 @@ defmodule Pleroma.Web.ActivityPub.ObjectValidators.UserValidator do
|
|||
@behaviour Pleroma.Web.ActivityPub.ObjectValidator.Validating
|
||||
|
||||
alias Pleroma.Object.Containment
|
||||
alias Pleroma.Signature
|
||||
|
||||
require Pleroma.Constants
|
||||
|
||||
|
@ -23,8 +22,7 @@ def validate(object, meta)
|
|||
|
||||
def validate(%{"type" => type, "id" => _id} = data, meta)
|
||||
when type in Pleroma.Constants.actor_types() do
|
||||
with :ok <- validate_pubkey(data),
|
||||
:ok <- validate_inbox(data),
|
||||
with :ok <- validate_inbox(data),
|
||||
:ok <- contain_collection_origin(data) do
|
||||
{:ok, data, meta}
|
||||
else
|
||||
|
@ -35,33 +33,6 @@ def validate(%{"type" => type, "id" => _id} = data, meta)
|
|||
|
||||
def validate(_, _), do: {:error, "Not a user object"}
|
||||
|
||||
defp mabye_validate_owner(nil, _actor), do: :ok
|
||||
defp mabye_validate_owner(actor, actor), do: :ok
|
||||
defp mabye_validate_owner(_owner, _actor), do: :error
|
||||
|
||||
defp validate_pubkey(
|
||||
%{"id" => id, "publicKey" => %{"id" => pk_id, "publicKeyPem" => _key}} = data
|
||||
)
|
||||
when id != nil do
|
||||
with {_, {:ok, kactor}} <- {:key, Signature.key_id_to_actor_id(pk_id)},
|
||||
true <- id == kactor,
|
||||
:ok <- mabye_validate_owner(Map.get(data, "owner"), id) do
|
||||
:ok
|
||||
else
|
||||
{:key, _} ->
|
||||
{:error, "Unable to determine actor id from key id"}
|
||||
|
||||
false ->
|
||||
{:error, "Key id does not relate to user id"}
|
||||
|
||||
_ ->
|
||||
{:error, "Actor does not own its public key"}
|
||||
end
|
||||
end
|
||||
|
||||
# pubkey is optional atm
|
||||
defp validate_pubkey(_data), do: :ok
|
||||
|
||||
defp validate_inbox(%{"id" => id, "inbox" => inbox}) do
|
||||
case Containment.same_origin(id, inbox) do
|
||||
:ok -> :ok
|
||||
|
|
|
@ -225,9 +225,7 @@ def handle(%{data: %{"type" => "Create"}} = activity, meta) do
|
|||
end
|
||||
end
|
||||
|
||||
ConcurrentLimiter.limit(Pleroma.Web.RichMedia.Helpers, fn ->
|
||||
Task.start(fn -> Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity) end)
|
||||
end)
|
||||
Pleroma.Web.RichMedia.Card.get_by_activity(activity)
|
||||
|
||||
Pleroma.Search.add_to_index(Map.put(activity, :object, object))
|
||||
|
||||
|
|
|
@ -951,7 +951,7 @@ defp build_emoji_tag({name, url}) do
|
|||
"name" => ":" <> name <> ":",
|
||||
"type" => "Emoji",
|
||||
"updated" => "1970-01-01T00:00:00Z",
|
||||
"id" => url
|
||||
"id" => nil
|
||||
}
|
||||
end
|
||||
|
||||
|
@ -1034,7 +1034,7 @@ def upgrade_user_from_ap_id(ap_id) do
|
|||
with %User{local: false} = user <- User.get_cached_by_ap_id(ap_id),
|
||||
{:ok, data} <- ActivityPub.fetch_and_prepare_user_from_ap_id(ap_id),
|
||||
{:ok, user} <- update_user(user, data) do
|
||||
{:ok, _pid} = Task.start(fn -> ActivityPub.pinned_fetch_task(user) end)
|
||||
ActivityPub.enqueue_pin_fetches(user)
|
||||
TransmogrifierWorker.enqueue("user_upgrade", %{"user_id" => user.id})
|
||||
{:ok, user}
|
||||
else
|
||||
|
|
|
@ -5,7 +5,6 @@
|
|||
defmodule Pleroma.Web.ActivityPub.UserView do
|
||||
use Pleroma.Web, :view
|
||||
|
||||
alias Pleroma.Keys
|
||||
alias Pleroma.Object
|
||||
alias Pleroma.Repo
|
||||
alias Pleroma.User
|
||||
|
@ -33,9 +32,7 @@ def render("endpoints.json", %{user: %User{local: true} = _user}) do
|
|||
def render("endpoints.json", _), do: %{}
|
||||
|
||||
def render("service.json", %{user: user}) do
|
||||
{:ok, _, public_key} = Keys.keys_from_pem(user.keys)
|
||||
public_key = :public_key.pem_entry_encode(:SubjectPublicKeyInfo, public_key)
|
||||
public_key = :public_key.pem_encode([public_key])
|
||||
{:ok, public_key} = User.SigningKey.public_key_pem(user)
|
||||
|
||||
endpoints = render("endpoints.json", %{user: user})
|
||||
|
||||
|
@ -52,7 +49,7 @@ def render("service.json", %{user: user}) do
|
|||
"url" => user.ap_id,
|
||||
"manuallyApprovesFollowers" => false,
|
||||
"publicKey" => %{
|
||||
"id" => "#{user.ap_id}#main-key",
|
||||
"id" => User.SigningKey.local_key_id(user.ap_id),
|
||||
"owner" => user.ap_id,
|
||||
"publicKeyPem" => public_key
|
||||
},
|
||||
|
@ -70,9 +67,12 @@ def render("user.json", %{user: %User{nickname: "internal." <> _} = user}),
|
|||
do: render("service.json", %{user: user}) |> Map.put("preferredUsername", user.nickname)
|
||||
|
||||
def render("user.json", %{user: user}) do
|
||||
{:ok, _, public_key} = Keys.keys_from_pem(user.keys)
|
||||
public_key = :public_key.pem_entry_encode(:SubjectPublicKeyInfo, public_key)
|
||||
public_key = :public_key.pem_encode([public_key])
|
||||
public_key =
|
||||
case User.SigningKey.public_key_pem(user) do
|
||||
{:ok, public_key} -> public_key
|
||||
_ -> nil
|
||||
end
|
||||
|
||||
user = User.sanitize_html(user)
|
||||
|
||||
endpoints = render("endpoints.json", %{user: user})
|
||||
|
@ -97,7 +97,7 @@ def render("user.json", %{user: user}) do
|
|||
"url" => user.ap_id,
|
||||
"manuallyApprovesFollowers" => user.is_locked,
|
||||
"publicKey" => %{
|
||||
"id" => "#{user.ap_id}#main-key",
|
||||
"id" => User.SigningKey.local_key_id(user.ap_id),
|
||||
"owner" => user.ap_id,
|
||||
"publicKeyPem" => public_key
|
||||
},
|
||||
|
@ -116,6 +116,20 @@ def render("user.json", %{user: user}) do
|
|||
|> Map.merge(Utils.make_json_ld_header())
|
||||
end
|
||||
|
||||
def render("keys.json", %{user: user}) do
|
||||
{:ok, public_key} = User.SigningKey.public_key_pem(user)
|
||||
|
||||
%{
|
||||
"id" => user.ap_id,
|
||||
"publicKey" => %{
|
||||
"id" => User.SigningKey.key_id_of_local_user(user),
|
||||
"owner" => user.ap_id,
|
||||
"publicKeyPem" => public_key
|
||||
}
|
||||
}
|
||||
|> Map.merge(Utils.make_json_ld_header())
|
||||
end
|
||||
|
||||
def render("following.json", %{user: user, page: page} = opts) do
|
||||
showing_items = (opts[:for] && opts[:for] == user) || !user.hide_follows
|
||||
showing_count = showing_items || !user.hide_follows_count
|
||||
|
|
|
@ -32,7 +32,9 @@ defmodule Pleroma.Web.ApiSpec.Schemas.Poll do
|
|||
},
|
||||
voters_count: %Schema{
|
||||
type: :integer,
|
||||
description: "How many unique accounts have voted. Number."
|
||||
nullable: true,
|
||||
description:
|
||||
"How many unique accounts have voted for a multi-selection poll. Number, or null if single-selection poll."
|
||||
},
|
||||
voted: %Schema{
|
||||
type: :boolean,
|
||||
|
|
|
@ -41,7 +41,7 @@ defmodule Pleroma.Web.CommonAPI.ActivityDraft do
|
|||
preview?: false,
|
||||
changes: %{}
|
||||
|
||||
def new(user, params) do
|
||||
defp new(user, params) do
|
||||
%__MODULE__{user: user}
|
||||
|> put_params(params)
|
||||
end
|
||||
|
@ -92,9 +92,14 @@ defp full_payload(%{status: status, summary: summary} = draft) do
|
|||
end
|
||||
end
|
||||
|
||||
defp attachments(%{params: params} = draft) do
|
||||
attachments = Utils.attachments_from_ids(params)
|
||||
%__MODULE__{draft | attachments: attachments}
|
||||
defp attachments(%{params: params, user: user} = draft) do
|
||||
case Utils.attachments_from_ids(user, params) do
|
||||
attachments when is_list(attachments) ->
|
||||
%__MODULE__{draft | attachments: attachments}
|
||||
|
||||
{:error, reason} ->
|
||||
add_error(draft, reason)
|
||||
end
|
||||
end
|
||||
|
||||
defp in_reply_to(%{params: %{in_reply_to_status_id: ""}} = draft), do: draft
|
||||
|
|
|
@ -22,43 +22,31 @@ defmodule Pleroma.Web.CommonAPI.Utils do
|
|||
require Logger
|
||||
require Pleroma.Constants
|
||||
|
||||
def attachments_from_ids(%{media_ids: ids, descriptions: desc}) do
|
||||
attachments_from_ids_descs(ids, desc)
|
||||
def attachments_from_ids(user, %{media_ids: ids}) do
|
||||
attachments_from_ids(user, ids, [])
|
||||
end
|
||||
|
||||
def attachments_from_ids(%{media_ids: ids}) do
|
||||
attachments_from_ids_no_descs(ids)
|
||||
def attachments_from_ids(_, _), do: []
|
||||
|
||||
defp attachments_from_ids(_user, [], acc), do: Enum.reverse(acc)
|
||||
|
||||
defp attachments_from_ids(user, [media_id | ids], acc) do
|
||||
with {_, %Object{} = object} <- {:get, get_attachment(media_id)},
|
||||
:ok <- Object.authorize_access(object, user) do
|
||||
attachments_from_ids(user, ids, [object.data | acc])
|
||||
else
|
||||
{:get, _} -> attachments_from_ids(user, ids, acc)
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
def attachments_from_ids(_), do: []
|
||||
|
||||
def attachments_from_ids_no_descs([]), do: []
|
||||
|
||||
def attachments_from_ids_no_descs(ids) do
|
||||
Enum.map(ids, fn media_id ->
|
||||
case get_attachment(media_id) do
|
||||
%Object{data: data} -> data
|
||||
_ -> nil
|
||||
end
|
||||
end)
|
||||
|> Enum.reject(&is_nil/1)
|
||||
end
|
||||
|
||||
def attachments_from_ids_descs([], _), do: []
|
||||
|
||||
def attachments_from_ids_descs(ids, descs_str) do
|
||||
{_, descs} = Jason.decode(descs_str)
|
||||
|
||||
Enum.map(ids, fn media_id ->
|
||||
with %Object{data: data} <- get_attachment(media_id) do
|
||||
Map.put(data, "name", descs[media_id])
|
||||
end
|
||||
end)
|
||||
|> Enum.reject(&is_nil/1)
|
||||
end
|
||||
|
||||
defp get_attachment(media_id) do
|
||||
Repo.get(Object, media_id)
|
||||
def get_attachment(media_id) do
|
||||
with %Object{} = object <- Repo.get(Object, media_id),
|
||||
true <- object.data["type"] in Pleroma.Constants.attachment_types() do
|
||||
object
|
||||
else
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
@spec get_to_and_cc(ActivityDraft.t()) :: {list(String.t()), list(String.t())}
|
||||
|
|
|
@ -66,10 +66,10 @@ defmodule Pleroma.Web.Endpoint do
|
|||
}
|
||||
)
|
||||
|
||||
plug(Plug.Static.IndexHtml, at: "/akkoma/swaggerui")
|
||||
plug(Plug.Static.IndexHtml, at: "/pleroma/swaggerui/")
|
||||
|
||||
plug(Pleroma.Web.Plugs.FrontendStatic,
|
||||
at: "/akkoma/swaggerui",
|
||||
at: "/pleroma/swaggerui",
|
||||
frontend_type: :swagger,
|
||||
gzip: true,
|
||||
if: &Pleroma.Web.Swagger.ui_enabled?/0,
|
||||
|
|
|
@ -8,6 +8,7 @@ defmodule Pleroma.Web.MastodonAPI.MediaController do
|
|||
alias Pleroma.Object
|
||||
alias Pleroma.User
|
||||
alias Pleroma.Web.ActivityPub.ActivityPub
|
||||
alias Pleroma.Web.CommonAPI.Utils
|
||||
alias Pleroma.Web.Plugs.OAuthScopesPlug
|
||||
|
||||
action_fallback(Pleroma.Web.MastodonAPI.FallbackController)
|
||||
|
@ -55,12 +56,15 @@ def create2(_conn, _data), do: {:error, :bad_request}
|
|||
|
||||
@doc "PUT /api/v1/media/:id"
|
||||
def update(%{assigns: %{user: user}, body_params: %{description: description}} = conn, %{id: id}) do
|
||||
with %Object{} = object <- Object.get_by_id(id),
|
||||
with {_, %Object{} = object} <- {:get, Utils.get_attachment(id)},
|
||||
:ok <- Object.authorize_access(object, user),
|
||||
{:ok, %Object{data: data}} <- Object.update_data(object, %{"name" => description}) do
|
||||
attachment_data = Map.put(data, "id", object.id)
|
||||
|
||||
render(conn, "attachment.json", %{attachment: attachment_data})
|
||||
else
|
||||
{:get, _} -> {:error, :not_found}
|
||||
e -> e
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -68,11 +72,14 @@ def update(conn, data), do: show(conn, data)
|
|||
|
||||
@doc "GET /api/v1/media/:id"
|
||||
def show(%{assigns: %{user: user}} = conn, %{id: id}) do
|
||||
with %Object{data: data, id: object_id} = object <- Object.get_by_id(id),
|
||||
with {_, %Object{data: data, id: object_id} = object} <- {:get, Utils.get_attachment(id)},
|
||||
:ok <- Object.authorize_access(object, user) do
|
||||
attachment_data = Map.put(data, "id", object_id)
|
||||
|
||||
render(conn, "attachment.json", %{attachment: attachment_data})
|
||||
else
|
||||
{:get, _} -> {:error, :not_found}
|
||||
e -> e
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
@ -87,7 +87,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusController do
|
|||
%{scopes: ["write:bookmarks"]} when action in [:bookmark, :unbookmark]
|
||||
)
|
||||
|
||||
@rate_limited_status_actions ~w(reblog unreblog favourite unfavourite create delete)a
|
||||
@rate_limited_status_actions ~w(reblog unreblog favourite unfavourite create delete update)a
|
||||
|
||||
plug(
|
||||
RateLimiter,
|
||||
|
|
|
@ -19,7 +19,7 @@ def render("show.json", %{object: object, multiple: multiple, options: options}
|
|||
expired: expired,
|
||||
multiple: multiple,
|
||||
votes_count: votes_count,
|
||||
voters_count: voters_count(object),
|
||||
voters_count: voters_count(multiple, object),
|
||||
options: options,
|
||||
emojis: Pleroma.Web.MastodonAPI.StatusView.build_emojis(object.data["emoji"])
|
||||
}
|
||||
|
@ -68,11 +68,19 @@ defp options_and_votes_count(options) do
|
|||
end)
|
||||
end
|
||||
|
||||
defp voters_count(%{data: %{"voters" => voters}}) when is_list(voters) do
|
||||
defp voters_count(false, _poll_data) do
|
||||
# Mastodon always sets voter count to "null" unless multiple options were selectable
|
||||
# Some clients may rely on this to detect multiple selection polls and it can mess
|
||||
# up percentages for some clients if we never got a correct remote voter count and
|
||||
# only count local voters here; see https://akkoma.dev/AkkomaGang/akkoma/issues/190
|
||||
nil
|
||||
end
|
||||
|
||||
defp voters_count(_multiple, %{data: %{"voters" => voters}}) when is_list(voters) do
|
||||
length(voters)
|
||||
end
|
||||
|
||||
defp voters_count(_), do: 0
|
||||
defp voters_count(_, _), do: 0
|
||||
|
||||
defp voted_and_own_votes(%{object: object} = params, options) do
|
||||
if params[:for] do
|
||||
|
|
|
@ -22,17 +22,13 @@ defmodule Pleroma.Web.MastodonAPI.StatusView do
|
|||
alias Pleroma.Web.MediaProxy
|
||||
alias Pleroma.Web.PleromaAPI.EmojiReactionController
|
||||
require Logger
|
||||
alias Pleroma.Web.RichMedia.Card
|
||||
|
||||
import Pleroma.Web.ActivityPub.Visibility, only: [get_visibility: 1, visible_for_user?: 2]
|
||||
|
||||
# This is a naive way to do this, just spawning a process per activity
|
||||
# to fetch the preview. However it should be fine considering
|
||||
# pagination is restricted to 40 activities at a time
|
||||
defp fetch_rich_media_for_activities(activities) do
|
||||
Enum.each(activities, fn activity ->
|
||||
spawn(fn ->
|
||||
Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity)
|
||||
end)
|
||||
Card.get_by_activity(activity)
|
||||
end)
|
||||
end
|
||||
|
||||
|
@ -93,9 +89,7 @@ def render("index.json", opts) do
|
|||
# To do: check AdminAPIControllerTest on the reasons behind nil activities in the list
|
||||
activities = Enum.filter(opts.activities, & &1)
|
||||
|
||||
# Start fetching rich media before doing anything else, so that later calls to get the cards
|
||||
# only block for timeout in the worst case, as opposed to
|
||||
# length(activities_with_links) * timeout
|
||||
# Start prefetching rich media before doing anything else
|
||||
fetch_rich_media_for_activities(activities)
|
||||
replied_to_activities = get_replied_to_activities(activities)
|
||||
|
||||
|
@ -309,6 +303,12 @@ def render("show.json", %{activity: %{id: id, data: %{"object" => _object}} = ac
|
|||
"mastoapi:content:#{chrono_order}"
|
||||
)
|
||||
|
||||
card =
|
||||
case Card.get_by_activity(activity) do
|
||||
%Card{} = result -> render("card.json", result)
|
||||
_ -> nil
|
||||
end
|
||||
|
||||
content_plaintext =
|
||||
content
|
||||
|> Activity.HTML.get_cached_stripped_html_for_activity(
|
||||
|
@ -318,8 +318,6 @@ def render("show.json", %{activity: %{id: id, data: %{"object" => _object}} = ac
|
|||
|
||||
summary = object.data["summary"] || ""
|
||||
|
||||
card = render("card.json", Pleroma.Web.RichMedia.Helpers.fetch_data_for_activity(activity))
|
||||
|
||||
url =
|
||||
if user.local do
|
||||
url(~p[/notice/#{activity}])
|
||||
|
@ -528,37 +526,30 @@ def render("source.json", %{activity: %{data: %{"object" => _object}} = activity
|
|||
}
|
||||
end
|
||||
|
||||
def render("card.json", %{rich_media: rich_media, page_url: page_url}) do
|
||||
page_url_data = URI.parse(page_url)
|
||||
|
||||
page_url_data =
|
||||
if is_binary(rich_media["url"]) do
|
||||
URI.merge(page_url_data, URI.parse(rich_media["url"]))
|
||||
else
|
||||
page_url_data
|
||||
end
|
||||
def render("card.json", %Card{fields: rich_media}) do
|
||||
page_url_data = URI.parse(rich_media["url"])
|
||||
|
||||
page_url = page_url_data |> to_string
|
||||
|
||||
image_url_data =
|
||||
if is_binary(rich_media["image"]) do
|
||||
URI.parse(rich_media["image"])
|
||||
else
|
||||
nil
|
||||
end
|
||||
|
||||
image_url = build_image_url(image_url_data, page_url_data)
|
||||
image_url = proxied_url(rich_media["image"], page_url_data)
|
||||
audio_url = proxied_url(rich_media["audio"], page_url_data)
|
||||
video_url = proxied_url(rich_media["video"], page_url_data)
|
||||
|
||||
%{
|
||||
type: "link",
|
||||
provider_name: page_url_data.host,
|
||||
provider_url: page_url_data.scheme <> "://" <> page_url_data.host,
|
||||
url: page_url,
|
||||
image: image_url |> MediaProxy.url(),
|
||||
image: image_url,
|
||||
image_description: rich_media["image:alt"] || "",
|
||||
title: rich_media["title"] || "",
|
||||
description: rich_media["description"] || "",
|
||||
pleroma: %{
|
||||
opengraph: rich_media
|
||||
opengraph:
|
||||
rich_media
|
||||
|> Maps.put_if_present("image", image_url)
|
||||
|> Maps.put_if_present("audio", audio_url)
|
||||
|> Maps.put_if_present("video", video_url)
|
||||
}
|
||||
}
|
||||
end
|
||||
|
@ -636,6 +627,14 @@ def render("context.json", %{activity: activity, activities: activities, user: u
|
|||
}
|
||||
end
|
||||
|
||||
defp proxied_url(url, page_url_data) do
|
||||
if is_binary(url) do
|
||||
build_image_url(URI.parse(url), page_url_data) |> MediaProxy.url()
|
||||
else
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
def get_reply_to(activity, %{replied_to_activities: replied_to_activities}) do
|
||||
object = Object.normalize(activity, fetch: false)
|
||||
|
||||
|
@ -740,19 +739,7 @@ defp build_application(%{"type" => _type, "name" => name, "url" => url}),
|
|||
|
||||
defp build_application(_), do: nil
|
||||
|
||||
# Workaround for Elixir issue #10771
|
||||
# Avoid applying URI.merge unless necessary
|
||||
# TODO: revert to always attempting URI.merge(image_url_data, page_url_data)
|
||||
# when Elixir 1.12 is the minimum supported version
|
||||
@spec build_image_url(struct() | nil, struct()) :: String.t() | nil
|
||||
defp build_image_url(
|
||||
%URI{scheme: image_scheme, host: image_host} = image_url_data,
|
||||
%URI{} = _page_url_data
|
||||
)
|
||||
when not is_nil(image_scheme) and not is_nil(image_host) do
|
||||
image_url_data |> to_string
|
||||
end
|
||||
|
||||
defp build_image_url(%URI{} = image_url_data, %URI{} = page_url_data) do
|
||||
URI.merge(page_url_data, image_url_data) |> to_string
|
||||
end
|
||||
|
|
|
@ -18,6 +18,8 @@ defmodule Pleroma.Web.MastodonAPI.WebsocketHandler do
|
|||
@timeout :timer.seconds(60)
|
||||
# Hibernate every X messages
|
||||
@hibernate_every 100
|
||||
# Tune garabge collect for long-lived websocket process
|
||||
@fullsweep_after 20
|
||||
|
||||
def init(%{qs: qs} = req, state) do
|
||||
with params <- Enum.into(:cow_qs.parse_qs(qs), %{}),
|
||||
|
@ -59,6 +61,10 @@ def websocket_init(state) do
|
|||
"#{__MODULE__} accepted websocket connection for user #{(state.user || %{id: "anonymous"}).id}, topic #{state.topic}"
|
||||
)
|
||||
|
||||
# process is long-lived and can sometimes accumulate stale data in such a way it's
|
||||
# not freed by young garbage cycles, thus make full collection sweeps more frequent
|
||||
:erlang.process_flag(:fullsweep_after, @fullsweep_after)
|
||||
|
||||
Streamer.add_socket(state.topic, state.oauth_token)
|
||||
{:ok, %{state | timer: timer()}}
|
||||
end
|
||||
|
|
|
@ -52,6 +52,14 @@ defp filter_allowed_user_by_ap_id(ap_ids, excluded_ap_ids) do
|
|||
end)
|
||||
end
|
||||
|
||||
defp filter_allowed_users_by_domain(ap_ids, %User{} = for_user) do
|
||||
Enum.reject(ap_ids, fn ap_id ->
|
||||
User.blocks_domain?(for_user, ap_id)
|
||||
end)
|
||||
end
|
||||
|
||||
defp filter_allowed_users_by_domain(ap_ids, nil), do: ap_ids
|
||||
|
||||
def filter_allowed_users(reactions, user, with_muted) do
|
||||
exclude_ap_ids =
|
||||
if is_nil(user) do
|
||||
|
@ -62,7 +70,10 @@ def filter_allowed_users(reactions, user, with_muted) do
|
|||
end
|
||||
|
||||
filter_emoji = fn emoji, users, url ->
|
||||
case filter_allowed_user_by_ap_id(users, exclude_ap_ids) do
|
||||
users
|
||||
|> filter_allowed_user_by_ap_id(exclude_ap_ids)
|
||||
|> filter_allowed_users_by_domain(user)
|
||||
|> case do
|
||||
[] -> nil
|
||||
users -> {emoji, users, url}
|
||||
end
|
||||
|
|
32
lib/pleroma/web/plugs/ensure_user_public_key_plug.ex
Normal file
32
lib/pleroma/web/plugs/ensure_user_public_key_plug.ex
Normal file
|
@ -0,0 +1,32 @@
|
|||
defmodule Pleroma.Web.Plugs.EnsureUserPublicKeyPlug do
|
||||
@moduledoc """
|
||||
This plug will attempt to pull in a user's public key if we do not have it.
|
||||
We _should_ be able to request the URL from the key URL...
|
||||
"""
|
||||
|
||||
alias Pleroma.User
|
||||
|
||||
def init(options), do: options
|
||||
|
||||
def call(conn, _opts) do
|
||||
key_id = key_id_from_conn(conn)
|
||||
|
||||
unless is_nil(key_id) do
|
||||
User.SigningKey.get_or_fetch_by_key_id(key_id)
|
||||
# now we SHOULD have the user that owns the key locally. maybe.
|
||||
# if we don't, we'll error out when we try to validate.
|
||||
end
|
||||
|
||||
conn
|
||||
end
|
||||
|
||||
defp key_id_from_conn(conn) do
|
||||
case HTTPSignatures.signature_for_conn(conn) do
|
||||
%{"keyId" => key_id} when is_binary(key_id) ->
|
||||
key_id
|
||||
|
||||
_ ->
|
||||
nil
|
||||
end
|
||||
end
|
||||
end
|
|
@ -44,6 +44,26 @@ def route_aliases(%{path_info: ["objects", id], query_string: query_string}) do
|
|||
|
||||
def route_aliases(_), do: []
|
||||
|
||||
def maybe_put_created_psudoheader(conn) do
|
||||
case HTTPSignatures.signature_for_conn(conn) do
|
||||
%{"created" => created} ->
|
||||
put_req_header(conn, "(created)", created)
|
||||
|
||||
_ ->
|
||||
conn
|
||||
end
|
||||
end
|
||||
|
||||
def maybe_put_expires_psudoheader(conn) do
|
||||
case HTTPSignatures.signature_for_conn(conn) do
|
||||
%{"expires" => expires} ->
|
||||
put_req_header(conn, "(expires)", expires)
|
||||
|
||||
_ ->
|
||||
conn
|
||||
end
|
||||
end
|
||||
|
||||
defp assign_valid_signature_on_route_aliases(conn, []), do: conn
|
||||
|
||||
defp assign_valid_signature_on_route_aliases(%{assigns: %{valid_signature: true}} = conn, _),
|
||||
|
@ -55,6 +75,8 @@ defp assign_valid_signature_on_route_aliases(conn, [path | rest]) do
|
|||
conn =
|
||||
conn
|
||||
|> put_req_header("(request-target)", request_target)
|
||||
|> maybe_put_created_psudoheader()
|
||||
|> maybe_put_expires_psudoheader()
|
||||
|> case do
|
||||
%{assigns: %{digest: digest}} = conn -> put_req_header(conn, "digest", digest)
|
||||
conn -> conn
|
||||
|
@ -117,12 +139,17 @@ defp maybe_require_signature(
|
|||
defp maybe_require_signature(conn), do: conn
|
||||
|
||||
defp signature_host(conn) do
|
||||
with %{"keyId" => kid} <- HTTPSignatures.signature_for_conn(conn),
|
||||
{:ok, actor_id} <- Signature.key_id_to_actor_id(kid) do
|
||||
with {:key_id, %{"keyId" => kid}} <- {:key_id, HTTPSignatures.signature_for_conn(conn)},
|
||||
{:actor_id, {:ok, actor_id}} <- {:actor_id, Signature.key_id_to_actor_id(kid)} do
|
||||
actor_id
|
||||
else
|
||||
e ->
|
||||
{:error, e}
|
||||
{:key_id, e} ->
|
||||
Logger.error("Failed to extract key_id from signature: #{inspect(e)}")
|
||||
nil
|
||||
|
||||
{:actor_id, e} ->
|
||||
Logger.error("Failed to extract actor_id from signature: #{inspect(e)}")
|
||||
nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -4,7 +4,6 @@
|
|||
|
||||
defmodule Pleroma.Web.Plugs.MappedSignatureToIdentityPlug do
|
||||
alias Pleroma.Helpers.AuthHelper
|
||||
alias Pleroma.Signature
|
||||
alias Pleroma.User
|
||||
alias Pleroma.Web.ActivityPub.Utils
|
||||
|
||||
|
@ -33,7 +32,7 @@ def call(%{assigns: %{valid_signature: true}, params: %{"actor" => actor}} = con
|
|||
|> assign(:valid_signature, false)
|
||||
|
||||
# remove me once testsuite uses mapped capabilities instead of what we do now
|
||||
{:user, nil} ->
|
||||
{:user, _} ->
|
||||
Logger.debug("Failed to map identity from signature (lookup failure)")
|
||||
Logger.debug("key_id=#{inspect(key_id_from_conn(conn))}, actor=#{actor}")
|
||||
|
||||
|
@ -68,7 +67,8 @@ def call(%{assigns: %{valid_signature: true}} = conn, _opts) do
|
|||
Logger.debug("Failed to map identity from signature (lookup failure)")
|
||||
Logger.debug("key_id=#{inspect(key_id_from_conn(conn))}")
|
||||
|
||||
only_permit_user_routes(conn)
|
||||
conn
|
||||
|> assign(:valid_signature, false)
|
||||
|
||||
_ ->
|
||||
Logger.debug("Failed to map identity from signature (no payload actor mismatch)")
|
||||
|
@ -82,33 +82,34 @@ def call(%{assigns: %{valid_signature: true}} = conn, _opts) do
|
|||
# no signature at all
|
||||
def call(conn, _opts), do: conn
|
||||
|
||||
defp only_permit_user_routes(%{path_info: ["users", _]} = conn) do
|
||||
conn
|
||||
|> assign(:limited_ap, true)
|
||||
end
|
||||
|
||||
defp only_permit_user_routes(conn) do
|
||||
conn
|
||||
|> assign(:valid_signature, false)
|
||||
end
|
||||
|
||||
defp key_id_from_conn(conn) do
|
||||
with %{"keyId" => key_id} <- HTTPSignatures.signature_for_conn(conn),
|
||||
{:ok, ap_id} <- Signature.key_id_to_actor_id(key_id) do
|
||||
ap_id
|
||||
else
|
||||
case HTTPSignatures.signature_for_conn(conn) do
|
||||
%{"keyId" => key_id} when is_binary(key_id) ->
|
||||
key_id
|
||||
|
||||
_ ->
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
defp user_from_key_id(conn) do
|
||||
with key_actor_id when is_binary(key_actor_id) <- key_id_from_conn(conn),
|
||||
{:ok, %User{} = user} <- User.get_or_fetch_by_ap_id(key_actor_id) do
|
||||
with {:key_id, key_id} when is_binary(key_id) <- {:key_id, key_id_from_conn(conn)},
|
||||
{:mapped_ap_id, ap_id} when is_binary(ap_id) <-
|
||||
{:mapped_ap_id, User.SigningKey.key_id_to_ap_id(key_id)},
|
||||
{:user_fetch, {:ok, %User{} = user}} <- {:user_fetch, User.get_or_fetch_by_ap_id(ap_id)} do
|
||||
user
|
||||
else
|
||||
_ ->
|
||||
nil
|
||||
{:key_id, nil} ->
|
||||
Logger.debug("Failed to map identity from signature (no key ID)")
|
||||
{:key_id, nil}
|
||||
|
||||
{:mapped_ap_id, nil} ->
|
||||
Logger.debug("Failed to map identity from signature (could not map key ID to AP ID)")
|
||||
{:mapped_ap_id, nil}
|
||||
|
||||
{:user_fetch, {:error, _}} ->
|
||||
Logger.debug("Failed to map identity from signature (lookup failure)")
|
||||
{:user_fetch, nil}
|
||||
end
|
||||
end
|
||||
|
||||
|
|
98
lib/pleroma/web/rich_media/backfill.ex
Normal file
98
lib/pleroma/web/rich_media/backfill.ex
Normal file
|
@ -0,0 +1,98 @@
|
|||
# Pleroma: A lightweight social networking server
|
||||
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
defmodule Pleroma.Web.RichMedia.Backfill do
|
||||
use Pleroma.Workers.WorkerHelper,
|
||||
queue: "rich_media_backfill",
|
||||
unique: [period: 300, states: Oban.Job.states(), keys: [:op, :url_hash]]
|
||||
|
||||
alias Pleroma.Web.RichMedia.Card
|
||||
alias Pleroma.Web.RichMedia.Parser
|
||||
alias Pleroma.Web.RichMedia.Parser.TTL
|
||||
alias Pleroma.Workers.RichMediaExpirationWorker
|
||||
|
||||
require Logger
|
||||
|
||||
@cachex Pleroma.Config.get([:cachex, :provider], Cachex)
|
||||
|
||||
def start(%{url: url} = args) when is_binary(url) do
|
||||
url_hash = Card.url_to_hash(url)
|
||||
|
||||
args =
|
||||
args
|
||||
|> Map.put(:url_hash, url_hash)
|
||||
|
||||
__MODULE__.enqueue("rich_media_backfill", args)
|
||||
end
|
||||
|
||||
def perform(%Oban.Job{args: %{"op" => "rich_media_backfill", "url" => url} = args})
|
||||
when is_binary(url) do
|
||||
run(args)
|
||||
end
|
||||
|
||||
def run(%{"url" => url, "url_hash" => url_hash} = args) do
|
||||
case Parser.parse(url) do
|
||||
{:ok, fields} ->
|
||||
{:ok, card} = Card.create(url, fields)
|
||||
|
||||
maybe_schedule_expiration(url, fields)
|
||||
|
||||
if Map.has_key?(args, "activity_id") do
|
||||
stream_update(args)
|
||||
end
|
||||
|
||||
warm_cache(url_hash, card)
|
||||
:ok
|
||||
|
||||
{:error, {:invalid_metadata, fields}} ->
|
||||
Logger.debug("Rich media incomplete or invalid metadata for #{url}: #{inspect(fields)}")
|
||||
negative_cache(url_hash, :timer.minutes(30))
|
||||
|
||||
{:error, :body_too_large} ->
|
||||
Logger.error("Rich media error for #{url}: :body_too_large")
|
||||
negative_cache(url_hash, :timer.minutes(30))
|
||||
|
||||
{:error, {:content_type, type}} ->
|
||||
Logger.debug("Rich media error for #{url}: :content_type is #{type}")
|
||||
negative_cache(url_hash, :timer.minutes(30))
|
||||
|
||||
e ->
|
||||
Logger.debug("Rich media error for #{url}: #{inspect(e)}")
|
||||
{:error, e}
|
||||
end
|
||||
end
|
||||
|
||||
def run(e) do
|
||||
Logger.error("Rich media failure - invalid args: #{inspect(e)}")
|
||||
{:discard, :invalid}
|
||||
end
|
||||
|
||||
defp maybe_schedule_expiration(url, fields) do
|
||||
case TTL.process(fields, url) do
|
||||
{:ok, ttl} when is_number(ttl) ->
|
||||
timestamp = DateTime.from_unix!(ttl)
|
||||
|
||||
RichMediaExpirationWorker.new(%{"url" => url}, scheduled_at: timestamp)
|
||||
|> Oban.insert()
|
||||
|
||||
_ ->
|
||||
:ok
|
||||
end
|
||||
end
|
||||
|
||||
defp stream_update(%{"activity_id" => activity_id}) do
|
||||
Logger.info("Rich media backfill: streaming update for activity #{activity_id}")
|
||||
|
||||
Pleroma.Activity.get_by_id(activity_id)
|
||||
|> Pleroma.Activity.normalize()
|
||||
|> Pleroma.Web.ActivityPub.ActivityPub.stream_out()
|
||||
end
|
||||
|
||||
defp warm_cache(key, val), do: @cachex.put(:rich_media_cache, key, val)
|
||||
|
||||
def negative_cache(key, ttl \\ :timer.minutes(30)) do
|
||||
@cachex.put(:rich_media_cache, key, nil, ttl: ttl)
|
||||
{:discard, :error}
|
||||
end
|
||||
end
|
149
lib/pleroma/web/rich_media/card.ex
Normal file
149
lib/pleroma/web/rich_media/card.ex
Normal file
|
@ -0,0 +1,149 @@
|
|||
defmodule Pleroma.Web.RichMedia.Card do
|
||||
use Ecto.Schema
|
||||
import Ecto.Changeset
|
||||
import Ecto.Query
|
||||
|
||||
alias Pleroma.Activity
|
||||
alias Pleroma.HTML
|
||||
alias Pleroma.Object
|
||||
alias Pleroma.Repo
|
||||
alias Pleroma.Web.RichMedia.Backfill
|
||||
alias Pleroma.Web.RichMedia.Parser
|
||||
|
||||
@cachex Pleroma.Config.get([:cachex, :provider], Cachex)
|
||||
@config_impl Application.compile_env(:pleroma, [__MODULE__, :config_impl], Pleroma.Config)
|
||||
|
||||
@type t :: %__MODULE__{}
|
||||
|
||||
schema "rich_media_card" do
|
||||
field(:url_hash, :binary)
|
||||
field(:fields, :map)
|
||||
|
||||
timestamps()
|
||||
end
|
||||
|
||||
@doc false
|
||||
def changeset(card, attrs) do
|
||||
card
|
||||
|> cast(attrs, [:url_hash, :fields])
|
||||
|> validate_required([:url_hash, :fields])
|
||||
|> unique_constraint(:url_hash)
|
||||
end
|
||||
|
||||
@spec create(String.t(), map()) :: {:ok, t()}
|
||||
def create(url, fields) do
|
||||
url_hash = url_to_hash(url)
|
||||
|
||||
fields = Map.put_new(fields, "url", url)
|
||||
|
||||
%__MODULE__{}
|
||||
|> changeset(%{url_hash: url_hash, fields: fields})
|
||||
|> Repo.insert(on_conflict: {:replace, [:fields]}, conflict_target: :url_hash)
|
||||
end
|
||||
|
||||
@spec delete(String.t()) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} | :ok
|
||||
def delete(url) do
|
||||
url_hash = url_to_hash(url)
|
||||
@cachex.del(:rich_media_cache, url_hash)
|
||||
|
||||
case get_by_url(url) do
|
||||
%__MODULE__{} = card -> Repo.delete(card)
|
||||
nil -> :ok
|
||||
end
|
||||
end
|
||||
|
||||
@spec get_by_url(String.t() | nil) :: t() | nil | :error
|
||||
def get_by_url(url) when is_binary(url) do
|
||||
if @config_impl.get([:rich_media, :enabled]) do
|
||||
url_hash = url_to_hash(url)
|
||||
|
||||
@cachex.fetch!(:rich_media_cache, url_hash, fn _ ->
|
||||
result =
|
||||
__MODULE__
|
||||
|> where(url_hash: ^url_hash)
|
||||
|> Repo.one()
|
||||
|
||||
case result do
|
||||
%__MODULE__{} = card -> {:commit, card}
|
||||
_ -> {:ignore, nil}
|
||||
end
|
||||
end)
|
||||
else
|
||||
:error
|
||||
end
|
||||
end
|
||||
|
||||
def get_by_url(nil), do: nil
|
||||
|
||||
@spec get_or_backfill_by_url(String.t(), map()) :: t() | nil
|
||||
def get_or_backfill_by_url(url, backfill_opts \\ %{}) do
|
||||
case get_by_url(url) do
|
||||
%__MODULE__{} = card ->
|
||||
card
|
||||
|
||||
nil ->
|
||||
backfill_opts = Map.put(backfill_opts, :url, url)
|
||||
|
||||
Backfill.start(backfill_opts)
|
||||
|
||||
nil
|
||||
|
||||
:error ->
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
@spec get_by_activity(Activity.t()) :: t() | nil | :error
|
||||
# Fake/Draft activity
|
||||
def get_by_activity(%Activity{id: "pleroma:fakeid"} = activity) do
|
||||
with %Object{} = object <- Object.normalize(activity, fetch: false),
|
||||
url when not is_nil(url) <- HTML.extract_first_external_url_from_object(object) do
|
||||
case get_by_url(url) do
|
||||
# Cache hit
|
||||
%__MODULE__{} = card ->
|
||||
card
|
||||
|
||||
# Cache miss, but fetch for rendering the Draft
|
||||
_ ->
|
||||
with {:ok, fields} <- Parser.parse(url),
|
||||
{:ok, card} <- create(url, fields) do
|
||||
card
|
||||
else
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
else
|
||||
_ ->
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
def get_by_activity(activity) do
|
||||
with %Object{} = object <- Object.normalize(activity, fetch: false),
|
||||
{_, nil} <- {:cached, get_cached_url(object, activity.id)} do
|
||||
nil
|
||||
else
|
||||
{:cached, url} ->
|
||||
get_or_backfill_by_url(url, %{activity_id: activity.id})
|
||||
|
||||
_ ->
|
||||
:error
|
||||
end
|
||||
end
|
||||
|
||||
@spec url_to_hash(String.t()) :: String.t()
|
||||
def url_to_hash(url) do
|
||||
:crypto.hash(:sha256, url) |> Base.encode16(case: :lower)
|
||||
end
|
||||
|
||||
defp get_cached_url(object, activity_id) do
|
||||
key = "URL|#{activity_id}"
|
||||
|
||||
@cachex.fetch!(:scrubber_cache, key, fn _ ->
|
||||
url = HTML.extract_first_external_url_from_object(object)
|
||||
Activity.HTML.add_cache_key_for(activity_id, key)
|
||||
|
||||
{:commit, url}
|
||||
end)
|
||||
end
|
||||
end
|
|
@ -3,85 +3,13 @@
|
|||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
defmodule Pleroma.Web.RichMedia.Helpers do
|
||||
alias Pleroma.Activity
|
||||
alias Pleroma.Config
|
||||
alias Pleroma.HTML
|
||||
alias Pleroma.Object
|
||||
alias Pleroma.Web.RichMedia.Parser
|
||||
|
||||
@options [
|
||||
max_body: 2_000_000,
|
||||
receive_timeout: 2_000
|
||||
]
|
||||
|
||||
@spec validate_page_url(URI.t() | binary()) :: :ok | :error
|
||||
defp validate_page_url(page_url) when is_binary(page_url) do
|
||||
validate_tld = Config.get([Pleroma.Formatter, :validate_tld])
|
||||
|
||||
page_url
|
||||
|> Linkify.Parser.url?(validate_tld: validate_tld)
|
||||
|> parse_uri(page_url)
|
||||
end
|
||||
|
||||
defp validate_page_url(%URI{host: host, scheme: "https", authority: authority})
|
||||
when is_binary(authority) do
|
||||
cond do
|
||||
host in Config.get([:rich_media, :ignore_hosts], []) ->
|
||||
:error
|
||||
|
||||
get_tld(host) in Config.get([:rich_media, :ignore_tld], []) ->
|
||||
:error
|
||||
|
||||
true ->
|
||||
:ok
|
||||
end
|
||||
end
|
||||
|
||||
defp validate_page_url(_), do: :error
|
||||
|
||||
defp parse_uri(true, url) do
|
||||
url
|
||||
|> URI.parse()
|
||||
|> validate_page_url
|
||||
end
|
||||
|
||||
defp parse_uri(_, _), do: :error
|
||||
|
||||
defp get_tld(host) do
|
||||
host
|
||||
|> String.split(".")
|
||||
|> Enum.reverse()
|
||||
|> hd
|
||||
end
|
||||
|
||||
def fetch_data_for_object(object) do
|
||||
with true <- Config.get([:rich_media, :enabled]),
|
||||
{:ok, page_url} <-
|
||||
HTML.extract_first_external_url_from_object(object),
|
||||
:ok <- validate_page_url(page_url),
|
||||
{:ok, rich_media} <- Parser.parse(page_url) do
|
||||
%{page_url: page_url, rich_media: rich_media}
|
||||
else
|
||||
_ -> %{}
|
||||
end
|
||||
end
|
||||
|
||||
def fetch_data_for_activity(%Activity{data: %{"type" => "Create"}} = activity) do
|
||||
with true <- Config.get([:rich_media, :enabled]),
|
||||
%Object{} = object <- Object.normalize(activity, fetch: false) do
|
||||
fetch_data_for_object(object)
|
||||
else
|
||||
_ -> %{}
|
||||
end
|
||||
end
|
||||
|
||||
def fetch_data_for_activity(_), do: %{}
|
||||
|
||||
def rich_media_get(url) do
|
||||
headers = [{"user-agent", Pleroma.Application.user_agent() <> "; Bot"}]
|
||||
|
||||
head_check =
|
||||
case Pleroma.HTTP.head(url, headers, @options) do
|
||||
case Pleroma.HTTP.head(url, headers, http_options()) do
|
||||
# If the HEAD request didn't reach the server for whatever reason,
|
||||
# we assume the GET that comes right after won't either
|
||||
{:error, _} = e ->
|
||||
|
@ -96,7 +24,7 @@ def rich_media_get(url) do
|
|||
:ok
|
||||
end
|
||||
|
||||
with :ok <- head_check, do: Pleroma.HTTP.get(url, headers, @options)
|
||||
with :ok <- head_check, do: Pleroma.HTTP.get(url, headers, http_options())
|
||||
end
|
||||
|
||||
defp check_content_type(headers) do
|
||||
|
@ -112,12 +40,13 @@ defp check_content_type(headers) do
|
|||
end
|
||||
end
|
||||
|
||||
@max_body @options[:max_body]
|
||||
defp check_content_length(headers) do
|
||||
max_body = Keyword.get(http_options(), :max_body)
|
||||
|
||||
case List.keyfind(headers, "content-length", 0) do
|
||||
{_, maybe_content_length} ->
|
||||
case Integer.parse(maybe_content_length) do
|
||||
{content_length, ""} when content_length <= @max_body -> :ok
|
||||
{content_length, ""} when content_length <= max_body -> :ok
|
||||
{_, ""} -> {:error, :body_too_large}
|
||||
_ -> :ok
|
||||
end
|
||||
|
@ -126,4 +55,11 @@ defp check_content_length(headers) do
|
|||
:ok
|
||||
end
|
||||
end
|
||||
|
||||
defp http_options do
|
||||
[
|
||||
pool: :media,
|
||||
max_body: Config.get([:rich_media, :max_body], 5_000_000)
|
||||
]
|
||||
end
|
||||
end
|
||||
|
|
|
@ -1,161 +1,41 @@
|
|||
# Pleroma: A lightweight social networking server
|
||||
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
|
||||
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
defmodule Pleroma.Web.RichMedia.Parser do
|
||||
require Logger
|
||||
|
||||
@cachex Pleroma.Config.get([:cachex, :provider], Cachex)
|
||||
@config_impl Application.compile_env(:pleroma, [__MODULE__, :config_impl], Pleroma.Config)
|
||||
|
||||
defp parsers do
|
||||
Pleroma.Config.get([:rich_media, :parsers])
|
||||
end
|
||||
|
||||
def parse(nil), do: {:error, "No URL provided"}
|
||||
def parse(nil), do: nil
|
||||
|
||||
if Pleroma.Config.get(:env) == :test do
|
||||
@spec parse(String.t()) :: {:ok, map()} | {:error, any()}
|
||||
def parse(url), do: parse_with_timeout(url)
|
||||
else
|
||||
@spec parse(String.t()) :: {:ok, map()} | {:error, any()}
|
||||
def parse(url) do
|
||||
with {:ok, data} <- get_cached_or_parse(url),
|
||||
{:ok, _} <- set_ttl_based_on_image(data, url) do
|
||||
{:ok, data}
|
||||
end
|
||||
end
|
||||
|
||||
defp get_cached_or_parse(url) do
|
||||
case @cachex.fetch(:rich_media_cache, url, fn ->
|
||||
case parse_with_timeout(url) do
|
||||
{:ok, _} = res ->
|
||||
{:commit, res}
|
||||
|
||||
{:error, reason} = e ->
|
||||
# Unfortunately we have to log errors here, instead of doing that
|
||||
# along with ttl setting at the bottom. Otherwise we can get log spam
|
||||
# if more than one process was waiting for the rich media card
|
||||
# while it was generated. Ideally we would set ttl here as well,
|
||||
# so we don't override it number_of_waiters_on_generation
|
||||
# times, but one, obviously, can't set ttl for not-yet-created entry
|
||||
# and Cachex doesn't support returning ttl from the fetch callback.
|
||||
log_error(url, reason)
|
||||
{:commit, e}
|
||||
end
|
||||
end) do
|
||||
{action, res} when action in [:commit, :ok] ->
|
||||
case res do
|
||||
{:ok, _data} = res ->
|
||||
res
|
||||
|
||||
{:error, reason} = e ->
|
||||
if action == :commit, do: set_error_ttl(url, reason)
|
||||
e
|
||||
end
|
||||
|
||||
{:error, e} ->
|
||||
{:error, {:cachex_error, e}}
|
||||
end
|
||||
end
|
||||
|
||||
defp set_error_ttl(_url, :body_too_large), do: :ok
|
||||
defp set_error_ttl(_url, {:content_type, _}), do: :ok
|
||||
|
||||
# The TTL is not set for the errors above, since they are unlikely to change
|
||||
# with time
|
||||
|
||||
defp set_error_ttl(url, _reason) do
|
||||
ttl = Pleroma.Config.get([:rich_media, :failure_backoff], 60_000)
|
||||
@cachex.expire(:rich_media_cache, url, ttl)
|
||||
:ok
|
||||
end
|
||||
|
||||
defp log_error(url, {:invalid_metadata, data}) do
|
||||
Logger.debug(fn -> "Incomplete or invalid metadata for #{url}: #{inspect(data)}" end)
|
||||
end
|
||||
|
||||
defp log_error(url, reason) do
|
||||
Logger.warning(fn -> "Rich media error for #{url}: #{inspect(reason)}" end)
|
||||
@spec parse(String.t()) :: {:ok, map()} | {:error, any()}
|
||||
def parse(url) do
|
||||
with {_, true} <- {:config, @config_impl.get([:rich_media, :enabled])},
|
||||
:ok <- validate_page_url(url),
|
||||
{:ok, data} <- parse_url(url) do
|
||||
data = Map.put(data, "url", url)
|
||||
{:ok, data}
|
||||
else
|
||||
{:config, _} -> {:error, :rich_media_disabled}
|
||||
e -> e
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Set the rich media cache based on the expiration time of image.
|
||||
|
||||
Adopt behaviour `Pleroma.Web.RichMedia.Parser.TTL`
|
||||
|
||||
## Example
|
||||
|
||||
defmodule MyModule do
|
||||
@behaviour Pleroma.Web.RichMedia.Parser.TTL
|
||||
def ttl(data, url) do
|
||||
image_url = Map.get(data, :image)
|
||||
# do some parsing in the url and get the ttl of the image
|
||||
# and return ttl is unix time
|
||||
parse_ttl_from_url(image_url)
|
||||
end
|
||||
end
|
||||
|
||||
Define the module in the config
|
||||
|
||||
config :pleroma, :rich_media,
|
||||
ttl_setters: [MyModule]
|
||||
"""
|
||||
@spec set_ttl_based_on_image(map(), String.t()) ::
|
||||
{:ok, Integer.t() | :noop} | {:error, :no_key}
|
||||
def set_ttl_based_on_image(data, url) do
|
||||
case get_ttl_from_image(data, url) do
|
||||
{:ok, ttl} when is_number(ttl) ->
|
||||
ttl = ttl * 1000
|
||||
|
||||
case @cachex.expire_at(:rich_media_cache, url, ttl) do
|
||||
{:ok, true} -> {:ok, ttl}
|
||||
{:ok, false} -> {:error, :no_key}
|
||||
end
|
||||
|
||||
_ ->
|
||||
{:ok, :noop}
|
||||
end
|
||||
end
|
||||
|
||||
defp get_ttl_from_image(data, url) do
|
||||
[:rich_media, :ttl_setters]
|
||||
|> Pleroma.Config.get()
|
||||
|> Enum.reduce({:ok, nil}, fn
|
||||
module, {:ok, _ttl} ->
|
||||
module.ttl(data, url)
|
||||
|
||||
_, error ->
|
||||
error
|
||||
end)
|
||||
end
|
||||
|
||||
def parse_url(url) do
|
||||
defp parse_url(url) do
|
||||
with {:ok, %Tesla.Env{body: html}} <- Pleroma.Web.RichMedia.Helpers.rich_media_get(url),
|
||||
{:ok, html} <- Floki.parse_document(html) do
|
||||
html
|
||||
|> maybe_parse()
|
||||
|> Map.put("url", url)
|
||||
|> clean_parsed_data()
|
||||
|> check_parsed_data()
|
||||
end
|
||||
end
|
||||
|
||||
def parse_with_timeout(url) do
|
||||
try do
|
||||
task =
|
||||
Task.Supervisor.async_nolink(Pleroma.TaskSupervisor, fn ->
|
||||
parse_url(url)
|
||||
end)
|
||||
|
||||
Task.await(task, 5000)
|
||||
catch
|
||||
:exit, {:timeout, _} ->
|
||||
Logger.warning("Timeout while fetching rich media for #{url}")
|
||||
{:error, :timeout}
|
||||
end
|
||||
end
|
||||
|
||||
defp maybe_parse(html) do
|
||||
Enum.reduce_while(parsers(), %{}, fn parser, acc ->
|
||||
case parser.parse(html, acc) do
|
||||
|
@ -181,4 +61,46 @@ defp clean_parsed_data(data) do
|
|||
end)
|
||||
|> Map.new()
|
||||
end
|
||||
|
||||
@spec validate_page_url(URI.t() | binary()) :: :ok | :error
|
||||
defp validate_page_url(page_url) when is_binary(page_url) do
|
||||
validate_tld = @config_impl.get([Pleroma.Formatter, :validate_tld])
|
||||
|
||||
page_url
|
||||
|> Linkify.Parser.url?(validate_tld: validate_tld)
|
||||
|> parse_uri(page_url)
|
||||
end
|
||||
|
||||
defp validate_page_url(%URI{host: host, scheme: "https"}) do
|
||||
cond do
|
||||
Linkify.Parser.ip?(host) ->
|
||||
:error
|
||||
|
||||
host in @config_impl.get([:rich_media, :ignore_hosts], []) ->
|
||||
:error
|
||||
|
||||
get_tld(host) in @config_impl.get([:rich_media, :ignore_tld], []) ->
|
||||
:error
|
||||
|
||||
true ->
|
||||
:ok
|
||||
end
|
||||
end
|
||||
|
||||
defp validate_page_url(_), do: :error
|
||||
|
||||
defp parse_uri(true, url) do
|
||||
url
|
||||
|> URI.parse()
|
||||
|> validate_page_url
|
||||
end
|
||||
|
||||
defp parse_uri(_, _), do: :error
|
||||
|
||||
defp get_tld(host) do
|
||||
host
|
||||
|> String.split(".")
|
||||
|> Enum.reverse()
|
||||
|> hd
|
||||
end
|
||||
end
|
||||
|
|
|
@ -3,5 +3,18 @@
|
|||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
defmodule Pleroma.Web.RichMedia.Parser.TTL do
|
||||
@callback ttl(Map.t(), String.t()) :: Integer.t() | nil
|
||||
@callback ttl(map(), String.t()) :: integer() | nil
|
||||
|
||||
@spec process(map(), String.t()) :: {:ok, integer() | nil}
|
||||
def process(data, url) do
|
||||
[:rich_media, :ttl_setters]
|
||||
|> Pleroma.Config.get()
|
||||
|> Enum.reduce_while({:ok, nil}, fn
|
||||
module, acc ->
|
||||
case module.ttl(data, url) do
|
||||
ttl when is_number(ttl) -> {:halt, {:ok, ttl}}
|
||||
_ -> {:cont, acc}
|
||||
end
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
# Pleroma: A lightweight social networking server
|
||||
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
|
||||
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
defmodule Pleroma.Web.RichMedia.Parser.TTL.AwsSignedUrl do
|
||||
|
@ -7,25 +7,26 @@ defmodule Pleroma.Web.RichMedia.Parser.TTL.AwsSignedUrl do
|
|||
|
||||
@impl true
|
||||
def ttl(data, _url) do
|
||||
image = Map.get(data, :image)
|
||||
image = Map.get(data, "image")
|
||||
|
||||
if is_aws_signed_url(image) do
|
||||
if aws_signed_url?(image) do
|
||||
image
|
||||
|> parse_query_params()
|
||||
|> format_query_params()
|
||||
|> get_expiration_timestamp()
|
||||
else
|
||||
{:error, "Not aws signed url #{inspect(image)}"}
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
defp is_aws_signed_url(image) when is_binary(image) and image != "" do
|
||||
defp aws_signed_url?(image) when is_binary(image) and image != "" do
|
||||
%URI{host: host, query: query} = URI.parse(image)
|
||||
|
||||
String.contains?(host, "amazonaws.com") and String.contains?(query, "X-Amz-Expires")
|
||||
is_binary(host) and String.contains?(host, "amazonaws.com") and
|
||||
is_binary(query) and String.contains?(query, "X-Amz-Expires")
|
||||
end
|
||||
|
||||
defp is_aws_signed_url(_), do: nil
|
||||
defp aws_signed_url?(_), do: nil
|
||||
|
||||
defp parse_query_params(image) do
|
||||
%URI{query: query} = URI.parse(image)
|
||||
|
@ -45,6 +46,6 @@ defp get_expiration_timestamp(params) when is_map(params) do
|
|||
|> Map.get("X-Amz-Date")
|
||||
|> Timex.parse("{ISO:Basic:Z}")
|
||||
|
||||
{:ok, Timex.to_unix(date) + String.to_integer(Map.get(params, "X-Amz-Expires"))}
|
||||
Timex.to_unix(date) + String.to_integer(Map.get(params, "X-Amz-Expires"))
|
||||
end
|
||||
end
|
||||
|
|
20
lib/pleroma/web/rich_media/parser/ttl/opengraph.ex
Normal file
20
lib/pleroma/web/rich_media/parser/ttl/opengraph.ex
Normal file
|
@ -0,0 +1,20 @@
|
|||
# Pleroma: A lightweight social networking server
|
||||
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
defmodule Pleroma.Web.RichMedia.Parser.TTL.Opengraph do
|
||||
@behaviour Pleroma.Web.RichMedia.Parser.TTL
|
||||
|
||||
@impl true
|
||||
def ttl(%{"ttl" => ttl_string}, _url) when is_binary(ttl_string) do
|
||||
try do
|
||||
ttl = String.to_integer(ttl_string)
|
||||
now = DateTime.utc_now() |> DateTime.to_unix()
|
||||
now + ttl
|
||||
rescue
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
def ttl(_, _), do: nil
|
||||
end
|
|
@ -1,5 +1,5 @@
|
|||
# Pleroma: A lightweight social networking server
|
||||
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
|
||||
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
defmodule Pleroma.Web.RichMedia.Parsers.OEmbed do
|
||||
|
|
|
@ -144,7 +144,14 @@ defmodule Pleroma.Web.Router do
|
|||
})
|
||||
end
|
||||
|
||||
pipeline :optional_http_signature do
|
||||
plug(Pleroma.Web.Plugs.EnsureUserPublicKeyPlug)
|
||||
plug(Pleroma.Web.Plugs.HTTPSignaturePlug)
|
||||
plug(Pleroma.Web.Plugs.MappedSignatureToIdentityPlug)
|
||||
end
|
||||
|
||||
pipeline :http_signature do
|
||||
plug(Pleroma.Web.Plugs.EnsureUserPublicKeyPlug)
|
||||
plug(Pleroma.Web.Plugs.HTTPSignaturePlug)
|
||||
plug(Pleroma.Web.Plugs.MappedSignatureToIdentityPlug)
|
||||
plug(Pleroma.Web.Plugs.EnsureHTTPSignaturePlug)
|
||||
|
@ -745,7 +752,7 @@ defmodule Pleroma.Web.Router do
|
|||
scope "/", Pleroma.Web do
|
||||
# Note: html format is supported only if static FE is enabled
|
||||
# Note: http signature is only considered for json requests (no auth for non-json requests)
|
||||
pipe_through([:accepts_html_xml_json, :http_signature, :static_fe])
|
||||
pipe_through([:accepts_html_xml_json, :optional_http_signature, :static_fe])
|
||||
|
||||
# Note: returns user _profile_ for json requests, redirects to user _feed_ for non-json ones
|
||||
get("/users/:nickname", Feed.UserController, :feed_redirect, as: :user_feed)
|
||||
|
|
|
@ -9,13 +9,13 @@
|
|||
xmlns:ostatus="http://ostatus.org/schema/1.0"
|
||||
xmlns:statusnet="http://status.net/schema/api/1/">
|
||||
|
||||
<id><%= '#{url(~p"/tags/#{@tag}")}.rss' %></id>
|
||||
<id><%= "#{url(~p"/tags/#{@tag}")}.rss" %></id>
|
||||
<title>#<%= @tag %></title>
|
||||
|
||||
<subtitle><%= Gettext.dpgettext("static_pages", "tag feed description", "These are public toots tagged with #%{tag}. You can interact with them if you have an account anywhere in the fediverse.", tag: @tag) %></subtitle>
|
||||
<logo><%= feed_logo() %></logo>
|
||||
<updated><%= most_recent_update(@activities) %></updated>
|
||||
<link rel="self" href="<%= '#{url(~p"/tags/#{@tag}")}.atom' %>" type="application/atom+xml"/>
|
||||
<link rel="self" href="<%= "#{url(~p"/tags/#{@tag}")}.atom" %>" type="application/atom+xml"/>
|
||||
<%= for activity <- @activities do %>
|
||||
<%= render @view_module, "_tag_activity.atom", Map.merge(assigns, prepare_activity(activity, actor: true)) %>
|
||||
<% end %>
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
|
||||
<title>#<%= @tag %></title>
|
||||
<description><%= Gettext.dpgettext("static_pages", "tag feed description", "These are public toots tagged with #%{tag}. You can interact with them if you have an account anywhere in the fediverse.", tag: @tag) %></description>
|
||||
<link><%= '#{url(~p"/tags/#{@tag}")}.rss' %></link>
|
||||
<link><%= "#{url(~p"/tags/#{@tag}")}.rss" %></link>
|
||||
<webfeeds:logo><%= feed_logo() %></webfeeds:logo>
|
||||
<webfeeds:accentColor>2b90d9</webfeeds:accentColor>
|
||||
<%= for activity <- @activities do %>
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue