Compare commits

...

131 Commits

Author SHA1 Message Date
Your New SJW Waifu 6a9c7c0d68 Merge remote-tracking branch 'upstream/develop' into neckbeard 2024-01-23 18:37:38 -06:00
feld 626c22961f Merge branch 'dialyzer-fixes' into 'develop'
More dialyzer fixes

See merge request pleroma/pleroma!4042
2024-01-23 00:16:55 +00:00
Mark Felder 3a8594e927 MastodonAPI.Controller.StatusController: fix dialyzer error
lib/pleroma/web/mastodon_api/controllers/status_controller.ex:333:pattern_match
The pattern can never match the type.

Pattern:
{:ok, _activity}

Type:
{:error, _}
2024-01-22 18:37:29 -05:00
Mark Felder 138b3cb608 Clear up missing function dialyzer errors for :eldap 2024-01-22 18:37:29 -05:00
Mark Felder 115b2ad638 MRF.KeywordPolicy: fix dialyzer error
lib/pleroma/web/activity_pub/mrf/keyword_policy.ex:13:neg_guard_fail
Guard test:
not is_binary(_string :: binary())

can never succeed.
2024-01-22 18:37:29 -05:00
Mark Felder 0dd65246ea MRF.HashtagPolicy: fix dialyzer error
lib/pleroma/web/activity_pub/mrf/hashtag_policy.ex:87:exact_eq
The test <<_::32>> == <<_::48>> can never evaluate to 'true'.
2024-01-22 18:37:19 -05:00
Mark Felder 5f71928f6b MRF.InlineQuotePolicy: fix dialyzer error
lib/pleroma/web/activity_pub/mrf/inline_quote_policy.ex:60:callback_type_mismatch
Type mismatch for @callback config_description/0 in Pleroma.Web.ActivityPub.MRF.Policy behaviour.

Expected type:
%{
  :description => binary(),
  :key => atom(),
  :label => binary(),
  :related_policy => binary(),
  :children => [map()]
}

Actual type:
%{
  :children => [
    %{
      :description => <<_::808>>,
      :key => :template,
      :suggestions => [any(), ...],
      :type => :string
    },
    ...
  ],
  :description => <<_::336>>,
  :key => :mrf_inline_quote,
  :label => <<_::184>>,
  :related_policy => <<_::360>>,
  :type => :group
}
2024-01-22 18:37:13 -05:00
Mark Felder a7fa6f18dc Pleroma.Migrators.Support.BaseMigrator: Fix dialyzer errors
lib/pleroma/migrators/context_objects_deletion_migrator.ex:13:exact_eq
The test :error | float() == 0 can never evaluate to 'true'.

lib/pleroma/migrators/hashtags_table_migrator.ex:13:exact_eq
The test :error | float() == 0 can never evaluate to 'true'.
2024-01-22 18:37:13 -05:00
Mark Felder 6ce7011a2e Pleroma.Gun.ConnectionPool.WorkerSupervisor: fix dialyzer error
lib/pleroma/gun/connection_pool/worker_supervisor.ex:24:guard_fail
The guard clause:

when _ :: true === nil

can never succeed.
2024-01-22 18:37:13 -05:00
Mark Felder 65d49ac090 Pleroma.HTTP.AdapterHelper: fix dialyzer errors
lib/pleroma/http/adapter_helper.ex:18:unknown_type
Unknown type: Connection.host/0.

lib/pleroma/http/adapter_helper.ex:19:unknown_type
Unknown type: Connection.host/0.

lib/pleroma/http/adapter_helper.ex:19:unknown_type
Unknown type: Connection.proxy_type/0.
2024-01-22 18:37:13 -05:00
Mark Felder c74c5f479a Pleroma.Migrators.Support.BaseMigratorState: fix dialyzer error
lib/pleroma/migrators/support/base_migrator_state.ex:10:unknown_type
Unknown type: Pleroma.DataMigration.t/0.
2024-01-22 18:37:13 -05:00
Mark Felder 36355d3ed9 Pleroma.Web.ActivityPub.Builder: fix dialyzer error
lib/pleroma/web/activity_pub/builder.ex:205:unknown_type
Unknown type: Pleroma.Web.CommonAPI.ActivityDraft.t/0.
2024-01-22 18:37:13 -05:00
Mark Felder 39da451b6d Pleroma.Web.ActivityPub.Builder: fix dialyzer errors
lib/pleroma/web/activity_pub/builder.ex:35:unknown_type
Unknown type: Activity.t/0.

lib/pleroma/web/activity_pub/builder.ex:40:unknown_type
Unknown type: Activity.t/0.

lib/pleroma/web/activity_pub/builder.ex:144:unknown_type
Unknown type: Activity.t/0.
________________________________________________________________________________
lib/pleroma/web/activity_pub/builder.ex:204:unknown_type
Unknown type: Pleroma.Web.CommonAPI.ActivityDraft.t/0.
2024-01-22 18:37:13 -05:00
Mark Felder 10f3a2833f Pleroma.User.Query: fix dialyzer error
lib/pleroma/user/query.ex:74:unknown_type
Unknown type: Query.t/0.
2024-01-22 18:37:13 -05:00
Mark Felder 40feac086f Pleroma.User: fix dialyzer errors
lib/pleroma/user.ex:1514:unknown_type
Unknown type: Pleroma.UserRelationship.t/0.

lib/pleroma/user.ex:2629:unknown_type
Unknown type: Pleroma.UserRelationship.t/0.

lib/pleroma/user.ex:2638:unknown_type
Unknown type: Pleroma.UserRelationship.t/0.
2024-01-22 18:37:13 -05:00
Mark Felder 1361856213 Pleroma.User.Backup: fix some dialyzer errors
lib/pleroma/user/backup.ex:207:call
The function call will not succeed.

:zip.create(
  string(),
  [:"\"actor.json\"", :"\"outbox.json\"", :"\"likes.json\"", :"\"bookmarks.json\""],
  [{:cwd, binary()}, ...]
)

will never return since the success typing is:
(
  atom() | [atom() | [any()] | char()],
  [
    atom()
    | [atom() | [any()] | char()]
    | {atom() | [atom() | [any()] | char()], binary()}
    | {atom() | [atom() | [any()] | char()], binary(),
       {:file_info, :undefined | non_neg_integer(),
        :device | :directory | :other | :regular | :symlink | :undefined,
        :none | :read | :read_write | :undefined | :write,
        :undefined | non_neg_integer() | {_, _}, :undefined | non_neg_integer() | {_, _},
        :undefined | non_neg_integer() | {_, _}, :undefined | non_neg_integer(),
        :undefined | non_neg_integer(), :undefined | non_neg_integer(),
        :undefined | non_neg_integer(), :undefined | non_neg_integer(),
        :undefined | non_neg_integer(), :undefined | non_neg_integer()}}
  ],
  [
    :cooked
    | :memory
    | :verbose
    | {:comment, string()}
    | {:compress, :all | [[any()]] | {:add, [any()]} | {:del, [any()]}}
    | {:cwd, string()}
    | {:uncompress, :all | [[any()]] | {:add, [any()]} | {:del, [any()]}}
  ]
) ::
  {:error, _}
  | {:ok,
     atom() | [atom() | [any()] | char()] | {atom() | [atom() | [any()] | char()], binary()}}

and the contract is
(name, fileList, options) :: retValue
when name: :file.name(),
     fileList: [:FileSpec],
     fileSpec:
       :file.name() | {:file.name(), binary()} | {:file.name(), binary(), :file.file_info()},
     options: [:Option],
     option: create_option(),
     retValue:
       {:ok, FileName :: filename()}
       | {:ok, {FileName :: filename(), binary()}}
       | {:error, Reason :: term()}
2024-01-22 18:37:13 -05:00
Mark Felder bff47479a7 Exile: fix for MacOS dev environments 2024-01-22 18:37:13 -05:00
Mark Felder 38ebefce9c Announcement: fix dialyzer errors and add typespec for the changeset
It was possible for this to raise (no_local_return) because the data key could be missing from the params
2024-01-22 18:37:13 -05:00
Mark Felder eb4dd50f53 Use config to control inclusion of test emoji 2024-01-22 18:37:13 -05:00
Mark Felder 6df93e61c4 Use config to determine sending to the streamer registry instead of MIX_ENV compile time function definition 2024-01-22 18:37:13 -05:00
Mark Felder 653b14e1c7 Use config to control Uploader callback timeout 2024-01-22 18:37:13 -05:00
Mark Felder 8efae57d67 Dialyzer: suppress Mix.Task errors
Callback info about the 'Elixir.Mix.Task' behaviour is not available.
2024-01-22 18:37:13 -05:00
feld f7b3681eb0 Merge branch 'exile-macos' into 'develop'
Exile: fix for MacOS dev environments

See merge request pleroma/pleroma!4041
2024-01-22 21:11:38 +00:00
Mark Felder 1632a3fec9 Exile: fix for MacOS dev environments 2024-01-22 15:35:12 -05:00
feld d802e65cd3 Merge branch 'exile-bsds' into 'develop'
Exile: switch to fork with BSD compile fix

See merge request pleroma/pleroma!4040
2024-01-22 18:59:59 +00:00
Mark Felder fff235433e Exile: switch to fork with BSD compile fix 2024-01-22 13:44:20 -05:00
lain 52aadc09e9 Merge branch 'exile' into 'develop'
Replace custom fifo implementation with Exile

See merge request pleroma/pleroma!4039
2024-01-22 16:49:30 +00:00
Mark Felder 0ac010ba3f Replace custom fifo implementation with Exile
This is for streaming media to ffmpeg thumbnailer. The existing implementation relies on undocumented behavior.

Erlang open_port/2 does not officially support passing a string of a file path for opening. The specs clearly state you are to provide one of the following for open_port/2:

    {spawn, Command :: string() | binary()} |
    {spawn_driver, Command :: string() | binary()} |
    {spawn_executable, FileName :: file:name_all()} |
    {fd, In :: integer() >= 0, Out :: integer() >= 0}

Our method technically works but is strongly discouraged as it can block the scheduler and dialyzer throws errors as it recognizes we're breaking the contract and some of the functions we wrote may never return.

This is indirectly covered by the Erlang FAQ section "9.12 Why can't I open devices (e.g. a serial port) like normal files?"
https://www.erlang.org/faq/problems#idm1127
2024-01-22 10:13:17 -05:00
feld 548434f85c Merge branch 'new-pipelines' into 'develop'
Fix testing cache policy, really.

See merge request pleroma/pleroma!4038
2024-01-21 04:36:24 +00:00
Mark Felder 951a82f2d7 Fix testing cache policy 2024-01-21 04:35:31 +00:00
feld 12b689a81e Merge branch 'new-pipelines' into 'develop'
Fix testing cache policy

See merge request pleroma/pleroma!4037
2024-01-21 04:34:06 +00:00
Mark Felder badd7654fd Fix testing cache policy 2024-01-21 04:29:13 +00:00
feld 931fa4cb78 Merge branch 'new-pipelines' into 'develop'
New CI pipelines

See merge request pleroma/pleroma!4036
2024-01-21 04:17:51 +00:00
Mark Felder 518ddd458c Clarify formatting and cycles versions 2024-01-21 04:14:41 +00:00
Mark Felder 8f0051d739 Rename 1.15 image to include otp25, clarify test names 2024-01-21 04:10:20 +00:00
Mark Felder 058fa5471a Fix the image name 2024-01-21 04:06:17 +00:00
Mark Felder aee971bd26 Only need amd64 for now 2024-01-21 03:59:26 +00:00
Mark Felder 06813d4a0e Reorganize ci scripts 2024-01-21 03:58:53 +00:00
Mark Felder 68f421c203 Use our own 1.15 ci-base image 2024-01-20 22:53:07 -05:00
Mark Felder 1790400313 Add Dialyxir with manual job execution 2024-01-20 22:49:37 -05:00
Mark Felder 06ac829eb4 Spec building should be in build stage 2024-01-20 22:45:29 -05:00
Mark Felder df31ec0d52 Linting as a separate stage 2024-01-20 22:43:41 -05:00
Mark Felder a0518a4ee1 Add a build and test pipeline for elixir 1.15 with a new naming convention 2024-01-20 22:37:38 -05:00
feld 1edfce4322 Merge branch 'dialyzer-fixes' into 'develop'
Dialyzer fixes

See merge request pleroma/pleroma!4035
2024-01-21 00:54:25 +00:00
Mark Felder dcd0102800 Credo 2024-01-20 19:39:13 -05:00
Mark Felder cca9d6aeaa Dialyzer fixes 2024-01-20 19:29:29 -05:00
Mark Felder 2330100371 Use config to control starting all HTTP pools in test env 2024-01-20 19:10:57 -05:00
Mark Felder 17877f612e Use config to control streamer registry 2024-01-20 18:51:20 -05:00
Mark Felder 4bb57d4f25 Use config to control background migrators 2024-01-20 18:47:25 -05:00
Mark Felder c7eda0b24a Use config to control loading of custom modules 2024-01-20 18:43:53 -05:00
Mark Felder 029aaf3d74 Use config to control max_restarts 2024-01-20 18:41:04 -05:00
Mark Felder 65ac513776 Dialyzer: fix pattern match coverage 2024-01-20 17:58:47 -05:00
Mark Felder 88042109a3 Dialyzer: fix pattern match coverage 2024-01-20 17:56:32 -05:00
Mark Felder 7f649a7a19 Dialyzer: remove function that will never match 2024-01-20 17:50:21 -05:00
Mark Felder 2fbb67add7 Fix typo in typespec 2024-01-20 17:48:12 -05:00
Mark Felder ea26add540 Fix incorrect type definition for maybe_direct_follow/2 2024-01-20 17:43:34 -05:00
Mark Felder 38d01ff511 Fix invalid types 2024-01-20 17:37:27 -05:00
Mark Felder 83eece7764 Fix invalid type
lib/pleroma/web/auth/authenticator.ex:8:unknown_type
Unknown type: User.t/0.
2024-01-20 17:33:37 -05:00
Mark Felder 4f07116108 Fix invalid type
lib/pleroma/web/activity_pub/publisher.ex:31:unknown_type
Unknown type: Map.t/0.
2024-01-20 17:32:19 -05:00
Mark Felder ec5ae83da6 Fix invalid types
lib/pleroma/web/activity_pub/mrf/policy.ex:6:unknown_type
Unknown type: Map.t/0.

lib/pleroma/web/activity_pub/mrf/policy.ex:7:unknown_type
Unknown type: Map.t/0.
2024-01-20 17:31:07 -05:00
Mark Felder 2061a1d917 Fix invalid type
lib/pleroma/uploaders/uploader.ex:43:unknown_type
Unknown type: Map.t/0.
2024-01-20 17:29:27 -05:00
Mark Felder 551e90cd52 Fix invalid type
lib/pleroma/upload.ex:89:unknown_type
Unknown type: Map.t/0.
2024-01-20 17:28:54 -05:00
Mark Felder f050a75b92 Fix invalid types due to typos
lib/pleroma/web/feed/feed_view.ex:135:unknown_type
Unknown type: NativeDateTime.t/0.

lib/pleroma/web/feed/feed_view.ex:148:unknown_type
Unknown type: NativeDateTime.t/0.
2024-01-20 17:22:40 -05:00
Mark Felder e5120a2703 Fix invalid type due to typos
lib/pleroma/web/o_auth/authorization.ex:61:unknown_type
Unknown type: Authtorizatiton.t/0.
2024-01-20 17:21:12 -05:00
Mark Felder 65dfaa6cb9 Fix invalid type due to late aliasing
lib/pleroma/web/o_auth/token/query.ex:12:unknown_type
Unknown type: Token.t/0.
2024-01-20 17:18:16 -05:00
Mark Felder 09ae0ab24a Fix invalid type
lib/pleroma/web/rich_media/parser.ex:105:unknown_type
Unknown type: Integer.t/0.
2024-01-20 17:16:10 -05:00
Mark Felder 467a65af90 Fix invalid types
lib/pleroma/web/rich_media/parser/ttl.ex:6:unknown_type
Unknown type: Integer.t/0.

lib/pleroma/web/rich_media/parser/ttl.ex:6:unknown_type
Unknown type: Map.t/0.
2024-01-20 17:14:56 -05:00
Mark Felder e3f52ee13f Fix invalid types
lib/pleroma/web/streamer.ex:37:unknown_type
Unknown type: Map.t/0.
________________________________________________________________________________
lib/pleroma/web/streamer.ex:63:unknown_type
Unknown type: Map.t/0.
2024-01-20 17:14:10 -05:00
Mark Felder 593c7e26d4 Fix invalid type
lib/pleroma/migrators/hashtags_table_migrator.ex:103:unknown_type
Unknown type: Map.t/0.
2024-01-20 17:13:27 -05:00
Mark Felder 559aeb5dd0 Add missing type Pleroma.Emoji.t()
lib/pleroma/emoji/loader.ex:23:unknown_type
Unknown type: Pleroma.Emoji.t/0.
2024-01-20 17:08:18 -05:00
Mark Felder 8ed506a370 Fix invalid type
lib/pleroma/docs/json.ex:21:unknown_type
Unknown type: Map.t/0.
2024-01-20 17:05:55 -05:00
Mark Felder 0b7d214211 Fix invalid typespec references to Ecto.Changeset.t() 2024-01-20 16:47:50 -05:00
Mark Felder dc8045d766 FlakeId.Ecto.CompatType.t() does not exist
This type is not exported and usable. FlakeId intends to return the type as :uuid, so we replace it in the typespecs with Ecto.UUID.t() which assuages the dialyzer errors

e.g.,

lib/pleroma/bookmark.ex:25:unknown_type
Unknown type: FlakeId.Ecto.CompatType.t/0.
2024-01-20 16:36:01 -05:00
Mark Felder b16a01ba9d Pleroma.ApplicationRequirements: fix dialyzer errors
lib/pleroma/application_requirements.ex:19:unknown_type
Unknown type: Pleroma.ApplicationRequirements.VerifyError.t/0.

lib/pleroma/application_requirements.ex:199:pattern_match_cov
The pattern
variable_result

can never match, because previous clauses completely cover the type
:ok.
2024-01-20 16:10:11 -05:00
Mark Felder df1d390a49 Pleroma.Activity.Queries: fix dialyzer error
lib/pleroma/activity/queries.ex:12:unknown_type
Unknown type: Activity.t/0.
2024-01-20 16:01:32 -05:00
Mark Felder 2a28377be0 Fix mix task pleroma.instance dialyzer error
lib/mix/tasks/pleroma/instance.ex:356:pattern_match_cov
The pattern
:variable_

can never match, because previous clauses completely cover the type
%{
  :anonymize => boolean(),
  :dedupe => boolean(),
  :read_description => boolean(),
  :strip_location => boolean()
}.
2024-01-20 15:55:33 -05:00
Haelwenn 3c65a2899d Merge branch 'handle_object_fetch_failures' into 'develop'
Handle object fetch failures gracefully

See merge request pleroma/pleroma!4015
2024-01-19 18:43:00 +00:00
Haelwenn 81a13b4b9e Merge branch 'api-docs' into 'develop'
Update API docs for my changes

See merge request pleroma/pleroma!4033
2024-01-18 02:19:58 +00:00
marcin mikołajczak b39403a48f Update API docs for my changes
Signed-off-by: marcin mikołajczak <git@mkljczk.pl>
2024-01-17 17:13:21 +01:00
Haelwenn 4c20713ecd Merge branch 'otp26' into 'develop'
OTP26 support

See merge request pleroma/pleroma!4025
2024-01-17 09:51:56 +00:00
Haelwenn 355487041a We are unsure if OTP27 will bring more breaking changes 2024-01-16 11:22:34 -05:00
Mark Felder e44f6a2ab3 Skip tests on MacOS/Darwin that have always failed 2024-01-15 20:18:43 -05:00
Mark Felder 012ab87605 Pleroma.Web.MastodonAPI.SubscriptionControllerTest: disable async and use on_exit/1 to ensure web push config gets restored 2024-01-16 00:59:44 +00:00
Mark Felder ad363c62c3 Fix StatusController test by using the get_query_parameter/2 helper to reliably retrieve the max_id value 2024-01-15 17:32:57 -05:00
Mark Felder 8bd8ee03c2 Add Pleroma.Test.Helpers.get_query_parameter/2 to retrieve specific query parameter values 2024-01-15 17:32:15 -05:00
Mark Felder 4cbf11d32c Fix ChatController tests validating prev/next URLs by sorting the query parameters before comparison 2024-01-15 17:12:06 -05:00
Mark Felder e7c6410192 Add Pleroma.Support.Helpers.uri_query_sort/1 for easy sorting of a URL's query parameters 2024-01-15 17:08:24 -05:00
Haelwenn 9b39bc6aa8 Merge branch 'mrf-regex-error' into 'develop'
MRF: Log sensible regex error for subdomain_match

See merge request pleroma/pleroma!4026
2024-01-15 08:24:54 +00:00
Haelwenn c29430b018 Merge branch 'mrf-steal-emoji-extname' into 'develop'
MRF.StealEmojiPolicy: Properly add fallback extension to filenames missing one

See merge request pleroma/pleroma!4029
2024-01-15 08:24:24 +00:00
Mark Felder 12c052551b Allow the Remote Fetcher to attempt fetching an unreachable instance 2024-01-14 14:05:43 -05:00
tusooa d3a4f5b7d7 Merge branch 'nil-contentMap' into 'develop'
Support objects with a nil contentMap (firefish)

Closes #3231

See merge request pleroma/pleroma!4030
2024-01-13 22:23:21 +00:00
feld 9cc46c5538 Merge branch 'qtfaststart-fix' into 'develop'
Fix MediaProxy crashing on some videos

See merge request pleroma/pleroma!4024
2024-01-13 04:35:32 +00:00
Haelwenn (lanodan) Monnier 7651198508 Support objects with a nil contentMap (firefish)
Closes: https://git.pleroma.social/pleroma/pleroma/-/issues/3231
2024-01-11 07:16:45 +01:00
Haelwenn (lanodan) Monnier 4ca65c6182 MRF.StealEmojiPolicy: Properly add fallback extension to filenames missing one 2024-01-07 19:37:35 +01:00
Haelwenn (lanodan) Monnier 6af49270a9 MRF: Log sensible error for subdomains_regex 2024-01-02 15:37:41 +01:00
Lain Soykaf fc910f9bb9 Linting 2023-12-30 11:45:16 +04:00
Lain Soykaf 8883fa326a Mix: Update http_signatures version 2023-12-30 11:44:23 +04:00
Mark Felder c6acd2abb3 Revert grammar leak from bad merge 2023-12-29 23:31:48 -05:00
Mark Felder 63a74f7b6d Support for Erlang OTP 26 2023-12-29 23:22:31 -05:00
Mark Felder 04366492b2 ConfigDB export to file does not have a consistent order.
Just test a few values to prove it was written
2023-12-29 23:18:45 -05:00
Mark Felder 1b5168ae02 Phoenix detects the webfinger requests with content-type application/jrd+json as "jrd" now 2023-12-29 23:18:45 -05:00
Mark Felder 347e5f33c7 Fix regex string match due to OTP26 key order change
OTP25:
"<http://localhost:4001/api/v1/favourites?limit=1&max_id=Ad1FhzPIS7gcHjUcoC&offset=0>; rel=\"next\""

OTP26:
"<http://localhost:4001/api/v1/favourites?offset=0&limit=1&max_id=Ad1FmOIAXiSNgygflA>; rel=\"next\""
2023-12-29 23:18:45 -05:00
Mark Felder 0820c23988 Fix Chat controller tests failing due to OTP26 key order change 2023-12-29 23:18:45 -05:00
Mark Felder d4dd21303a Remove call to Pleroma.Web.Endpoint.config_change/2
This is not necessary for the tests to pass and breaks other tests as this change doesn't get cleanly reverted causing the hostname to stay set this way and leak into other test causing failures with "sub.example.com" not matching "localhost"
2023-12-29 22:51:40 -05:00
Mark Felder 36b3867787 Fix test "transforms config to tuples"
This should have never worked. The default empty values for the other MRF Simple options will always be there.
2023-12-29 22:50:26 -05:00
Mark Felder b51ba39dd1 Update Floki to get the :attributes_as_maps feature to allow us to compare equality of parsed documents without issues of key ordering 2023-12-29 22:50:26 -05:00
Mark Felder e121e06214 Implement a custom uri_equal?/2 to fix comparisons of URLs with unordered query parameters 2023-12-29 22:50:26 -05:00
Mark Felder e7d6b835ae Fix tests by leveraging Keyword.equal?/2 2023-12-29 22:50:26 -05:00
Mark Felder 50edef5bc1 Change QTFastStart to recover gracefully if it encounters an error during bitstring matching
This fixes issues with internal errors when trying to serve the video
2023-12-29 14:12:44 -05:00
Mark Felder f17f92105b Oban jobs should be discarded on permanent errors 2023-12-28 23:52:59 -05:00
Mark Felder aa070c7daf Handle 401s as I have observed it in the wild 2023-12-28 23:09:33 -05:00
Mark Felder a6fd251e44 Improve test descriptions 2023-12-27 22:37:06 -05:00
Mark Felder ad0a5deb67 Prevent requeuing Remote Fetcher jobs that exceed thread depth 2023-12-27 22:28:41 -05:00
Mark Felder a2708f7fe3 Leverage existing atoms as return errors for the object fetcher 2023-12-27 22:01:59 -05:00
Mark Felder 287f2c9719 Formatting 2023-12-27 21:55:07 -05:00
Mark Felder 882267e3ec Remove duplicate log messages from Transmogrifier
Object fetch errors are logged in the fetcher module
2023-12-27 21:39:29 -05:00
Mark Felder becb070603 Conslidate log messages for object fetcher failures and leverage Logger.metadata 2023-12-27 21:22:51 -05:00
Mark Felder 6c9929b809 Set Logger level to error 2023-12-27 20:18:14 -05:00
Mark Felder be0cca9afd RemoteFetcherWorker Oban job tests 2023-12-27 16:08:57 -05:00
Mark Felder 53db65678d Separate files for each distinct sentence in the changelog 2023-12-27 15:44:31 -05:00
Mark Felder d4c77103d1 Fix detection of user follower collection being private
We were overzealous with matching on a raw error from the object fetch that should have never been relied on like this. If we can't fetch successfully we should assume that the collection is private.

Building a more expressive and universal error struct to match on may be something to consider.
2023-12-27 15:27:39 -05:00
Mark Felder 5f51094138 Update changelog 2023-12-27 11:09:42 -05:00
Mark Felder 73c4c6d7de Revert "Mark instances as unreachable when returning a 403 from an object fetch"
This reverts commit d472bafec1.
2023-12-26 17:20:36 -05:00
Mark Felder 9c0040124a Skip remote fetch jobs for unreachable instances 2023-12-26 16:28:05 -05:00
Mark Felder 5f6966cd9f Remove mistaken duplicate fetch 2023-12-26 16:23:41 -05:00
Mark Felder c4f0a3b570 Changelogs 2023-12-26 16:08:36 -05:00
Mark Felder c6b38441f1 Cancel remote fetch jobs for deleted objects 2023-12-26 16:05:44 -05:00
Mark Felder 67dd81e825 Consolidate the HTTP status code checking into the private get_object/1 2023-12-26 16:05:28 -05:00
Mark Felder d472bafec1 Mark instances as unreachable when returning a 403 from an object fetch
This is a definite sign the instance is blocked and they are enforcing authorized_fetch
2023-12-26 15:54:21 -05:00
Mark Felder 603e9f6a92 Fix Transmogrifier tests
These tests relied on the removed Fetcher.fetch_object_from_id!/2 function injecting the error tuple into a log message with the exact words "Object containment failed."

We will keep this behavior by generating a similar log message, but perhaps this should do a better job of matching on the error tuple returned by Transmogrifier.handle_incoming/1
2023-12-26 14:22:06 -05:00
Mark Felder ea0ec5fbcf Remove Fetcher.fetch_object_from_id!/2
It was only being called once and can be replaced with a case statement.
2023-12-26 14:20:35 -05:00
105 changed files with 686 additions and 414 deletions

View File

@ -28,6 +28,7 @@ cache: &global_cache_policy
stages:
- check-changelog
- build
- lint
- test
- benchmark
- deploy
@ -71,7 +72,7 @@ check-changelog:
tags:
- amd64
build:
build-1.12.3:
extends:
- .build_changes_policy
- .using-ci-base
@ -79,10 +80,20 @@ build:
script:
- mix compile --force
build-1.15.7-otp-25:
extends:
- .build_changes_policy
- .using-ci-base
stage: build
image: git.pleroma.social:5050/pleroma/pleroma/ci-base:elixir-1.15
allow_failure: true
script:
- mix compile --force
spec-build:
extends:
- .using-ci-base
stage: test
stage: build
rules:
- changes:
- ".gitlab-ci.yml"
@ -110,7 +121,7 @@ benchmark:
- mix ecto.migrate
- mix pleroma.load_testing
unit-testing:
unit-testing-1.12.3:
extends:
- .build_changes_policy
- .using-ci-base
@ -118,12 +129,11 @@ unit-testing:
cache: &testing_cache_policy
<<: *global_cache_policy
policy: pull
services:
services: &testing_services
- name: postgres:13-alpine
alias: postgres
command: ["postgres", "-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off"]
script:
script: &testing_script
- mix ecto.create
- mix ecto.migrate
- mix test --cover --preload-modules
@ -134,27 +144,32 @@ unit-testing:
coverage_format: cobertura
path: coverage.xml
unit-testing-erratic:
unit-testing-1.15.7-otp-25:
extends:
- .build_changes_policy
- .using-ci-base
stage: test
image: git.pleroma.social:5050/pleroma/pleroma/ci-base:elixir-1.15-otp25
allow_failure: true
cache: *testing_cache_policy
services: *testing_services
script: *testing_script
unit-testing-1.12-erratic:
extends:
- .build_changes_policy
- .using-ci-base
stage: test
retry: 2
allow_failure: true
cache: &testing_cache_policy
<<: *global_cache_policy
policy: pull
services:
- name: postgres:13-alpine
alias: postgres
command: ["postgres", "-c", "fsync=off", "-c", "synchronous_commit=off", "-c", "full_page_writes=off"]
cache: *testing_cache_policy
services: *testing_services
script:
- mix ecto.create
- mix ecto.migrate
- mix test --only=erratic
unit-testing-rum:
unit-testing-1.12-rum:
extends:
- .build_changes_policy
- .using-ci-base
@ -173,10 +188,10 @@ unit-testing-rum:
- "mix ecto.migrate --migrations-path priv/repo/optional_migrations/rum_indexing/"
- mix test --preload-modules
lint:
formatting-1.13:
extends: .build_changes_policy
image: &current_elixir elixir:1.13-alpine
stage: test
image: &formatting_elixir elixir:1.13-alpine
stage: lint
cache: *testing_cache_policy
before_script: &current_bfr_script
- apk update
@ -187,25 +202,38 @@ lint:
script:
- mix format --check-formatted
analysis:
extends:
- .build_changes_policy
- .using-ci-base
stage: test
cache: *testing_cache_policy
script:
- mix credo --strict --only=warnings,todo,fixme,consistency,readability
cycles:
cycles-1.13:
extends: .build_changes_policy
image: *current_elixir
stage: test
image: *formatting_elixir
stage: lint
cache: {}
before_script: *current_bfr_script
script:
- mix compile
- mix xref graph --format cycles --label compile | awk '{print $0} END{exit ($0 != "No cycles found")}'
analysis:
extends:
- .build_changes_policy
- .using-ci-base
stage: lint
cache: *testing_cache_policy
script:
- mix credo --strict --only=warnings,todo,fixme,consistency,readability
dialyzer:
extends:
- .build_changes_policy
- .using-ci-base
stage: lint
allow_failure: true
when: manual
cache: *testing_cache_policy
tags:
- feld
script:
- mix dialyzer
docs-deploy:
stage: deploy
cache: *testing_cache_policy

View File

View File

View File

View File

0
changelog.d/exile.skip Normal file
View File

View File

@ -0,0 +1 @@
Remote object fetch failures will prevent the object fetch job from retrying if the object request returns 401, 403, 404, 410, or exceeds the maximum thread depth.

View File

@ -0,0 +1 @@
MRF: Log sensible error for subdomains_regex

View File

@ -0,0 +1 @@
MRF.StealEmojiPolicy: Properly add fallback extension to filenames missing one

View File

@ -0,0 +1 @@
Federated timeline removal of hashtags via MRF HashtagPolicy

View File

@ -0,0 +1 @@
Support objects with a null contentMap (firefish)

1
changelog.d/otp26.add Normal file
View File

@ -0,0 +1 @@
Support for Erlang OTP 26

View File

@ -0,0 +1 @@
MediaProxy Preview failures prevented when encountering certain video files

View File

@ -1 +0,0 @@
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t git.pleroma.social:5050/pleroma/pleroma/ci-base:latest --push .

View File

@ -0,0 +1 @@
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t git.pleroma.social:5050/pleroma/pleroma/ci-base:elixir-1.12 --push .

View File

@ -0,0 +1,8 @@
FROM elixir:1.12.3
# Single RUN statement, otherwise intermediate images are created
# https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#run
RUN apt-get update &&\
apt-get install -y libmagic-dev cmake libimage-exiftool-perl ffmpeg &&\
mix local.hex --force &&\
mix local.rebar --force

View File

@ -0,0 +1 @@
docker buildx build --platform linux/amd64 -t git.pleroma.social:5050/pleroma/pleroma/ci-base:elixir-1.15-otp25 --push .

View File

@ -79,6 +79,10 @@ IO.puts("RUM enabled: #{rum_enabled}")
config :pleroma, Pleroma.ReverseProxy.Client, Pleroma.ReverseProxy.ClientMock
config :pleroma, Pleroma.Application,
background_migrators: false,
streamer_registry: false
if File.exists?("./config/benchmark.secret.exs") do
import_config "benchmark.secret.exs"
else

View File

@ -904,6 +904,15 @@ config :pleroma, Pleroma.Search.Meilisearch,
private_key: nil,
initial_indexing_chunk_size: 100_000
config :pleroma, Pleroma.Application,
background_migrators: true,
internal_fetch: true,
load_custom_modules: true,
max_restarts: 3,
streamer_registry: true
config :pleroma, Pleroma.Uploaders.Uploader, timeout: 30_000
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env()}.exs"

View File

@ -162,6 +162,18 @@ peer_module =
config :pleroma, Pleroma.Cluster, peer_module: peer_module
config :pleroma, Pleroma.Application,
background_migrators: false,
internal_fetch: false,
load_custom_modules: false,
max_restarts: 100,
streamer_registry: false,
test_http_pools: true
config :pleroma, Pleroma.Uploaders.Uploader, timeout: 1_000
config :pleroma, Pleroma.Emoji.Loader, test_emoji: true
if File.exists?("./config/test.secret.exs") do
import_config "test.secret.exs"
else

View File

@ -1,6 +1,6 @@
# Differences in Mastodon API responses from vanilla Mastodon
A Pleroma instance can be identified by "<Mastodon version> (compatible; Pleroma <version>)" present in `version` field in response from `/api/v1/instance`
A Pleroma instance can be identified by "<Mastodon version> (compatible; Pleroma <version>)" present in `version` field in response from `/api/v1/instance` and `/api/v2/instance`
## Flake IDs
@ -39,6 +39,7 @@ Has these additional fields under the `pleroma` object:
- `emoji_reactions`: A list with emoji / reaction maps. The format is `{name: "☕", count: 1, me: true}`. Contains no information about the reacting users, for that use the `/statuses/:id/reactions` endpoint.
- `parent_visible`: If the parent of this post is visible to the user or not.
- `pinned_at`: a datetime (iso8601) when status was pinned, `null` otherwise.
- `quotes_count`: the count of status quotes.
The `GET /api/v1/statuses/:id/source` endpoint additionally has the following attributes:
@ -304,19 +305,27 @@ Has these additional parameters (which are the same as in Pleroma-API):
`GET /api/v1/instance` has additional fields
- `max_toot_chars`: The maximum characters per post
- `max_media_attachments`: Maximum number of post media attachments
- `chat_limit`: The maximum characters per chat message
- `description_limit`: The maximum characters per image description
- `poll_limits`: The limits of polls
- `shout_limit`: The maximum characters per Shoutbox message
- `upload_limit`: The maximum upload file size
- `avatar_upload_limit`: The same for avatars
- `background_upload_limit`: The same for backgrounds
- `banner_upload_limit`: The same for banners
- `background_image`: A background image that frontends can use
- `pleroma.metadata.account_activation_required`: Whether users are required to confirm their emails before signing in
- `pleroma.metadata.birthday_required`: Whether users are required to provide their birth day when signing in
- `pleroma.metadata.birthday_min_age`: The minimum user age (in days)
- `pleroma.metadata.features`: A list of supported features
- `pleroma.metadata.federation`: The federation restrictions of this instance
- `pleroma.metadata.fields_limits`: A list of values detailing the length and count limitation for various instance-configurable fields.
- `pleroma.metadata.post_formats`: A list of the allowed post format types
- `vapid_public_key`: The public key needed for push messages
- `pleroma.stats.mau`: Monthly active user count
- `pleroma.vapid_public_key`: The public key needed for push messages
In, `GET /api/v2/instance` Pleroma-specific fields are all moved into `pleroma` object. `max_toot_chars`, `poll_limits` and `upload_limit` are replaced with their MastoAPI counterparts.
## Push Subscription

View File

@ -129,7 +129,7 @@ The `/api/v1/pleroma/*` path is backwards compatible with `/api/pleroma/*` (`/ap
* method: `GET`
* Authentication: required
* OAuth scope: `write:security`
* Response: JSON. Returns `{"codes": codes}`when successful, otherwise HTTP 422 `{"error": "[error message]"}`
* Response: JSON. Returns `{"codes": codes}` when successful, otherwise HTTP 422 `{"error": "[error message]"}`
## `/api/v1/pleroma/admin/`
See [Admin-API](admin_api.md)
@ -251,6 +251,15 @@ See [Admin-API](admin_api.md)
]
```
## `/api/v1/pleroma/accounts/:id/endorsements`
### Returns users endorsed by a user
* Method `GET`
* Authentication: not required
* Params:
* `id`: the id of the account for whom to return results
* Response: JSON, returns a list of Mastodon Account entities
## `/api/v1/pleroma/accounts/update_*`
### Set and clear account avatar, banner, and background
@ -266,6 +275,14 @@ See [Admin-API](admin_api.md)
* Authentication: not required
* Response: 204 No Content
## `/api/v1/pleroma/statuses/:id/quotes`
### Gets quotes for a given status
* Method `GET`
* Authentication: not required
* Params:
* `id`: the id of the status
* Response: JSON, returns a list of Mastodon Status entities
## `/api/v1/pleroma/mascot`
### Gets user mascot image
* Method `GET`
@ -372,6 +389,15 @@ See [Admin-API](admin_api.md)
* `alias`: the nickname of the alias to delete, e.g. `foo@example.org`.
* Response: JSON. Returns `{"status": "success"}` if the change was successful, `{"error": "[error message]"}` otherwise
## `/api/v1/pleroma/remote_interaction`
## Interact with profile or status from remote account
* Metod `POST`
* Authentication: not required
* Params:
* `ap_id`: Profile or status ActivityPub ID
* `profile`: Remote profile webfinger
* Response: JSON. Returns `{"url": "[redirect url]"}` on success, `{"error": "[error message]"}` otherwise
# Pleroma Conversations
Pleroma Conversations have the same general structure that Mastodon Conversations have. The behavior differs in the following ways when using these endpoints:

View File

@ -2,7 +2,7 @@
* PostgreSQL >=9.6
* Elixir >=1.11.0 <1.15
* Erlang OTP >=22.2.0 <26
* Erlang OTP >=22.2.0 (supported: <27)
* git
* file / libmagic
* gcc or clang

View File

@ -352,6 +352,4 @@ defmodule Mix.Tasks.Pleroma.Instance do
enabled_filters
end
defp upload_filters(_), do: []
end

View File

@ -9,7 +9,7 @@ defmodule Pleroma.Activity.Queries do
import Ecto.Query, only: [from: 2, where: 3]
@type query :: Ecto.Queryable.t() | Activity.t()
@type query :: Ecto.Queryable.t() | Pleroma.Activity.t()
alias Pleroma.Activity
alias Pleroma.User

View File

@ -23,19 +23,21 @@ defmodule Pleroma.Announcement do
timestamps(type: :utc_datetime)
end
def change(struct, params \\ %{}) do
struct
|> cast(validate_params(struct, params), [:data, :starts_at, :ends_at, :rendered])
@doc "Generates changeset for %Pleroma.Announcement{}"
@spec changeset(%__MODULE__{}, map()) :: %Ecto.Changeset{}
def changeset(announcement \\ %__MODULE__{}, params \\ %{data: %{}}) do
announcement
|> cast(validate_params(announcement, params), [:data, :starts_at, :ends_at, :rendered])
|> validate_required([:data])
end
defp validate_params(struct, params) do
defp validate_params(announcement, params) do
base_data =
%{
"content" => "",
"all_day" => false
}
|> Map.merge((struct && struct.data) || %{})
|> Map.merge((announcement && announcement.data) || %{})
merged_data =
Map.merge(base_data, params.data)
@ -61,13 +63,13 @@ defmodule Pleroma.Announcement do
end
def add(params) do
changeset = change(%__MODULE__{}, params)
changeset = changeset(%__MODULE__{}, params)
Repo.insert(changeset)
end
def update(announcement, params) do
changeset = change(announcement, params)
changeset = changeset(announcement, params)
Repo.update(changeset)
end

View File

@ -14,7 +14,6 @@ defmodule Pleroma.Application do
@name Mix.Project.config()[:name]
@version Mix.Project.config()[:version]
@repository Mix.Project.config()[:source_url]
@mix_env Mix.env()
def name, do: @name
def version, do: @version
@ -98,7 +97,7 @@ defmodule Pleroma.Application do
{Task.Supervisor, name: Pleroma.TaskSupervisor}
] ++
cachex_children() ++
http_children(adapter, @mix_env) ++
http_children(adapter) ++
[
Pleroma.Stats,
Pleroma.JobQueueMonitor,
@ -106,8 +105,9 @@ defmodule Pleroma.Application do
{Oban, Config.get(Oban)},
Pleroma.Web.Endpoint
] ++
task_children(@mix_env) ++
dont_run_in_test(@mix_env) ++
task_children() ++
streamer_registry() ++
background_migrators() ++
shout_child(shout_enabled?()) ++
[Pleroma.Gopher.Server]
@ -116,12 +116,7 @@ defmodule Pleroma.Application do
# If we have a lot of caches, default max_restarts can cause test
# resets to fail.
# Go for the default 3 unless we're in test
max_restarts =
if @mix_env == :test do
100
else
3
end
max_restarts = Application.get_env(:pleroma, __MODULE__)[:max_restarts]
opts = [strategy: :one_for_one, name: Pleroma.Supervisor, max_restarts: max_restarts]
result = Supervisor.start_link(children, opts)
@ -159,7 +154,7 @@ defmodule Pleroma.Application do
raise "Invalid custom modules"
{:ok, modules, _warnings} ->
if @mix_env != :test do
if Application.get_env(:pleroma, __MODULE__)[:load_custom_modules] do
Enum.each(modules, fn mod ->
Logger.info("Custom module loaded: #{inspect(mod)}")
end)
@ -213,24 +208,30 @@ defmodule Pleroma.Application do
defp shout_enabled?, do: Config.get([:shout, :enabled])
defp dont_run_in_test(env) when env in [:test, :benchmark], do: []
defp dont_run_in_test(_) do
[
{Registry,
[
name: Pleroma.Web.Streamer.registry(),
keys: :duplicate,
partitions: System.schedulers_online()
]}
] ++ background_migrators()
defp streamer_registry do
if Application.get_env(:pleroma, __MODULE__)[:streamer_registry] do
[
{Registry,
[
name: Pleroma.Web.Streamer.registry(),
keys: :duplicate,
partitions: System.schedulers_online()
]}
]
else
[]
end
end
defp background_migrators do
[
Pleroma.Migrators.HashtagsTableMigrator,
Pleroma.Migrators.ContextObjectsDeletionMigrator
]
if Application.get_env(:pleroma, __MODULE__)[:background_migrators] do
[
Pleroma.Migrators.HashtagsTableMigrator,
Pleroma.Migrators.ContextObjectsDeletionMigrator
]
else
[]
end
end
defp shout_child(true) do
@ -242,37 +243,43 @@ defmodule Pleroma.Application do
defp shout_child(_), do: []
defp task_children(:test) do
[
defp task_children do
children = [
%{
id: :web_push_init,
start: {Task, :start_link, [&Pleroma.Web.Push.init/0]},
restart: :temporary
}
]
end
defp task_children(_) do
[
%{
id: :web_push_init,
start: {Task, :start_link, [&Pleroma.Web.Push.init/0]},
restart: :temporary
},
%{
id: :internal_fetch_init,
start: {Task, :start_link, [&Pleroma.Web.ActivityPub.InternalFetchActor.init/0]},
restart: :temporary
}
]
if Application.get_env(:pleroma, __MODULE__)[:internal_fetch] do
children ++
[
%{
id: :internal_fetch_init,
start: {Task, :start_link, [&Pleroma.Web.ActivityPub.InternalFetchActor.init/0]},
restart: :temporary
}
]
else
children
end
end
# start hackney and gun pools in tests
defp http_children(_, :test) do
http_children(Tesla.Adapter.Hackney, nil) ++ http_children(Tesla.Adapter.Gun, nil)
defp http_children(adapter) do
if Application.get_env(:pleroma, __MODULE__)[:test_http_pools] do
http_children_hackney() ++ http_children_gun()
else
cond do
match?(Tesla.Adapter.Hackney, adapter) -> http_children_hackney()
match?(Tesla.Adapter.Gun, adapter) -> http_children_gun()
true -> []
end
end
end
defp http_children(Tesla.Adapter.Hackney, _) do
defp http_children_hackney do
pools = [:federation, :media]
pools =
@ -288,13 +295,11 @@ defmodule Pleroma.Application do
end
end
defp http_children(Tesla.Adapter.Gun, _) do
defp http_children_gun do
Pleroma.Gun.ConnectionPool.children() ++
[{Task, &Pleroma.HTTP.AdapterHelper.Gun.limiter_setup/0}]
end
defp http_children(_, _), do: []
@spec limiters_setup() :: :ok
def limiters_setup do
config = Config.get(ConcurrentLimiter, [])

View File

@ -7,7 +7,10 @@ defmodule Pleroma.ApplicationRequirements do
The module represents the collection of validations to runs before start server.
"""
defmodule VerifyError, do: defexception([:message])
defmodule VerifyError do
defexception([:message])
@type t :: %__MODULE__{}
end
alias Pleroma.Config
alias Pleroma.Helpers.MediaHelper
@ -193,8 +196,6 @@ defmodule Pleroma.ApplicationRequirements do
end
end
defp check_system_commands!(result), do: result
defp check_repo_pool_size!(:ok) do
if Pleroma.Config.get([Pleroma.Repo, :pool_size], 10) != 10 and
not Pleroma.Config.get([:dangerzone, :override_repo_pool_size], false) do

View File

@ -22,8 +22,8 @@ defmodule Pleroma.Bookmark do
timestamps()
end
@spec create(FlakeId.Ecto.CompatType.t(), FlakeId.Ecto.CompatType.t()) ::
{:ok, Bookmark.t()} | {:error, Changeset.t()}
@spec create(Ecto.UUID.t(), Ecto.UUID.t()) ::
{:ok, Bookmark.t()} | {:error, Ecto.Changeset.t()}
def create(user_id, activity_id) do
attrs = %{
user_id: user_id,
@ -37,7 +37,7 @@ defmodule Pleroma.Bookmark do
|> Repo.insert()
end
@spec for_user_query(FlakeId.Ecto.CompatType.t()) :: Ecto.Query.t()
@spec for_user_query(Ecto.UUID.t()) :: Ecto.Query.t()
def for_user_query(user_id) do
Bookmark
|> where(user_id: ^user_id)
@ -52,8 +52,8 @@ defmodule Pleroma.Bookmark do
|> Repo.one()
end
@spec destroy(FlakeId.Ecto.CompatType.t(), FlakeId.Ecto.CompatType.t()) ::
{:ok, Bookmark.t()} | {:error, Changeset.t()}
@spec destroy(Ecto.UUID.t(), Ecto.UUID.t()) ::
{:ok, Bookmark.t()} | {:error, Ecto.Changeset.t()}
def destroy(user_id, activity_id) do
from(b in Bookmark,
where: b.user_id == ^user_id,

View File

@ -42,7 +42,7 @@ defmodule Pleroma.Chat do
|> unique_constraint(:user_id, name: :chats_user_id_recipient_index)
end
@spec get_by_user_and_id(User.t(), FlakeId.Ecto.CompatType.t()) ::
@spec get_by_user_and_id(User.t(), Ecto.UUID.t()) ::
{:ok, t()} | {:error, :not_found}
def get_by_user_and_id(%User{id: user_id}, id) do
from(c in __MODULE__,
@ -52,17 +52,17 @@ defmodule Pleroma.Chat do
|> Repo.find_resource()
end
@spec get_by_id(FlakeId.Ecto.CompatType.t()) :: t() | nil
@spec get_by_id(Ecto.UUID.t()) :: t() | nil
def get_by_id(id) do
Repo.get(__MODULE__, id)
end
@spec get(FlakeId.Ecto.CompatType.t(), String.t()) :: t() | nil
@spec get(Ecto.UUID.t(), String.t()) :: t() | nil
def get(user_id, recipient) do
Repo.get_by(__MODULE__, user_id: user_id, recipient: recipient)
end
@spec get_or_create(FlakeId.Ecto.CompatType.t(), String.t()) ::
@spec get_or_create(Ecto.UUID.t(), String.t()) ::
{:ok, t()} | {:error, Ecto.Changeset.t()}
def get_or_create(user_id, recipient) do
%__MODULE__{}
@ -75,7 +75,7 @@ defmodule Pleroma.Chat do
)
end
@spec bump_or_create(FlakeId.Ecto.CompatType.t(), String.t()) ::
@spec bump_or_create(Ecto.UUID.t(), String.t()) ::
{:ok, t()} | {:error, Ecto.Changeset.t()}
def bump_or_create(user_id, recipient) do
%__MODULE__{}
@ -87,7 +87,7 @@ defmodule Pleroma.Chat do
)
end
@spec for_user_query(FlakeId.Ecto.CompatType.t()) :: Ecto.Query.t()
@spec for_user_query(Ecto.UUID.t()) :: Ecto.Query.t()
def for_user_query(user_id) do
from(c in Chat,
where: c.user_id == ^user_id,

View File

@ -54,7 +54,7 @@ defmodule Pleroma.ConfigDB do
@spec get_by_params(map()) :: ConfigDB.t() | nil
def get_by_params(%{group: _, key: _} = params), do: Repo.get_by(ConfigDB, params)
@spec changeset(ConfigDB.t(), map()) :: Changeset.t()
@spec changeset(ConfigDB.t(), map()) :: Ecto.Changeset.t()
def changeset(config, params \\ %{}) do
config
|> cast(params, [:key, :group, :value])
@ -138,7 +138,7 @@ defmodule Pleroma.ConfigDB do
end
end
@spec update_or_create(map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
@spec update_or_create(map()) :: {:ok, ConfigDB.t()} | {:error, Ecto.Changeset.t()}
def update_or_create(params) do
params = Map.put(params, :value, to_elixir_types(params[:value]))
search_opts = Map.take(params, [:group, :key])
@ -175,7 +175,7 @@ defmodule Pleroma.ConfigDB do
end)
end
@spec delete(ConfigDB.t() | map()) :: {:ok, ConfigDB.t()} | {:error, Changeset.t()}
@spec delete(ConfigDB.t() | map()) :: {:ok, ConfigDB.t()} | {:error, Ecto.Changeset.t()}
def delete(%ConfigDB{} = config), do: Repo.delete(config)
def delete(params) do

View File

@ -12,6 +12,8 @@ defmodule Pleroma.DataMigration do
import Ecto.Changeset
import Ecto.Query
@type t :: %__MODULE__{}
schema "data_migrations" do
field(:name, :string)
field(:state, State, default: :pending)

View File

@ -18,7 +18,7 @@ defmodule Pleroma.Docs.JSON do
:persistent_term.put(@term, Pleroma.Docs.Generator.convert_to_strings(descriptions))
end
@spec compiled_descriptions :: Map.t()
@spec compiled_descriptions :: map()
def compiled_descriptions do
:persistent_term.get(@term)
end

View File

@ -8,10 +8,12 @@ defmodule Pleroma.EctoType.ActivityPub.ObjectValidators.BareUri do
def type, do: :string
def cast(uri) when is_binary(uri) do
case URI.parse(uri) do
%URI{scheme: nil} -> :error
%URI{} -> {:ok, uri}
_ -> :error
parsed = URI.parse(uri)
if is_nil(parsed.scheme) do
:error
else
{:ok, uri}
end
end

View File

@ -24,6 +24,8 @@ defmodule Pleroma.Emoji do
defstruct [:code, :file, :tags, :safe_code, :safe_file]
@type t :: %__MODULE__{}
@doc "Build emoji struct"
def build({code, file, tags}) do
%__MODULE__{

View File

@ -15,8 +15,6 @@ defmodule Pleroma.Emoji.Loader do
require Logger
@mix_env Mix.env()
@type pattern :: Regex.t() | module() | String.t()
@type patterns :: pattern() | [pattern()]
@type group_patterns :: keyword(patterns())
@ -79,7 +77,7 @@ defmodule Pleroma.Emoji.Loader do
# for testing emoji.txt entries we do not want exposed in normal operation
test_emoji =
if @mix_env == :test do
if Application.get_env(:pleroma, __MODULE__)[:test_emoji] do
load_from_file("test/config/emoji.txt", emoji_groups)
else
[]

View File

@ -21,7 +21,7 @@ defmodule Pleroma.Gun.ConnectionPool.WorkerSupervisor do
def start_worker(opts, retry \\ false) do
case DynamicSupervisor.start_child(__MODULE__, {Pleroma.Gun.ConnectionPool.Worker, opts}) do
{:error, :max_children} ->
if retry or free_pool() == :error do
if Enum.any?([retry, free_pool()], &match?(&1, :error)) do
:telemetry.execute([:pleroma, :connection_pool, :provision_failure], %{opts: opts})
{:error, :pool_full}
else

View File

@ -43,89 +43,28 @@ defmodule Pleroma.Helpers.MediaHelper do
def video_framegrab(url) do
with executable when is_binary(executable) <- System.find_executable("ffmpeg"),
{:ok, env} <- HTTP.get(url, [], pool: :media),
{:ok, fifo_path} <- mkfifo(),
args = [
"-y",
"-i",
fifo_path,
"-vframes",
"1",
"-f",
"mjpeg",
"-loglevel",
"error",
"-"
] do
run_fifo(fifo_path, env, executable, args)
{:ok, pid} <- StringIO.open(env.body) do
body_stream = IO.binstream(pid, 1)
Exile.stream!(
[
executable,
"-i",
"pipe:0",
"-vframes",
"1",
"-f",
"mjpeg",
"pipe:1"
],
input: body_stream,
ignore_epipe: true,
stderr: :disable
)
|> Enum.into(<<>>)
else
nil -> {:error, {:ffmpeg, :command_not_found}}
{:error, _} = error -> error
end
end
defp run_fifo(fifo_path, env, executable, args) do
pid =
Port.open({:spawn_executable, executable}, [
:use_stdio,
:stream,
:exit_status,
:binary,
args: args
])
fifo = Port.open(to_charlist(fifo_path), [:eof, :binary, :stream, :out])
fix = Pleroma.Helpers.QtFastStart.fix(env.body)
true = Port.command(fifo, fix)
:erlang.port_close(fifo)
loop_recv(pid)
after
File.rm(fifo_path)
end
defp mkfifo do
path = Path.join(System.tmp_dir!(), "pleroma-media-preview-pipe-#{Ecto.UUID.generate()}")
case System.cmd("mkfifo", [path]) do
{_, 0} ->
spawn(fifo_guard(path))
{:ok, path}
{_, err} ->
{:error, {:fifo_failed, err}}
end
end
defp fifo_guard(path) do
pid = self()
fn ->
ref = Process.monitor(pid)
receive do
{:DOWN, ^ref, :process, ^pid, _} ->
File.rm(path)
end
end
end
defp loop_recv(pid) do
loop_recv(pid, <<>>)
end
defp loop_recv(pid, acc) do
receive do
{^pid, {:data, data}} ->
loop_recv(pid, acc <> data)
{^pid, {:exit_status, 0}} ->
{:ok, acc}
{^pid, {:exit_status, status}} ->
{:error, status}
after
5000 ->
:erlang.port_close(pid)
{:error, :timeout}
end
end
end

View File

@ -40,16 +40,21 @@ defmodule Pleroma.Helpers.QtFastStart do
got_mdat,
acc
) do
full_size = (size - 8) * 8
<<data::bits-size(full_size), rest::bits>> = rest
try do
full_size = (size - 8) * 8
<<data::bits-size(full_size), rest::bits>> = rest
acc = [
{fourcc, pos, pos + size, size,
<<size::integer-big-size(32), fourcc::bits-size(32), data::bits>>}
| acc
]
acc = [
{fourcc, pos, pos + size, size,
<<size::integer-big-size(32), fourcc::bits-size(32), data::bits>>}
| acc
]
fix(rest, pos + size, got_moov || fourcc == "moov", got_mdat || fourcc == "mdat", acc)
fix(rest, pos + size, got_moov || fourcc == "moov", got_mdat || fourcc == "mdat", acc)
rescue
_ ->
:abort
end
end
defp fix(<<>>, _pos, _, _, acc) do

View File

@ -15,8 +15,8 @@ defmodule Pleroma.HTTP.AdapterHelper do
require Logger
@type proxy ::
{Connection.host(), pos_integer()}
| {Connection.proxy_type(), Connection.host(), pos_integer()}
{host(), pos_integer()}
| {proxy_type(), host(), pos_integer()}
@callback options(keyword(), URI.t()) :: keyword()

View File

@ -100,7 +100,7 @@ defmodule Pleroma.Migrators.HashtagsTableMigrator do
|> where([_o, hashtags_objects], is_nil(hashtags_objects.object_id))
end
@spec transfer_object_hashtags(Map.t()) :: {:noop | :ok | :error, integer()}
@spec transfer_object_hashtags(map()) :: {:noop | :ok | :error, integer()}
defp transfer_object_hashtags(object) do
embedded_tags = if Map.has_key?(object, :tag), do: object.tag, else: object.data["tag"]
hashtags = Object.object_data_hashtags(%{"tag" => embedded_tags})

View File

@ -188,10 +188,11 @@ defmodule Pleroma.Migrators.Support.BaseMigrator do
end
defp fault_rate do
with failures_count when is_integer(failures_count) <- failures_count() do
with failures_count when is_integer(failures_count) <- failures_count(),
true <- failures_count > 0 do
failures_count / Enum.max([get_stat(:affected_count, 0), 1])
else
_ -> :error
_ -> 0
end
end

View File

@ -177,7 +177,10 @@ defmodule Pleroma.Object do
ap_id
Keyword.get(options, :fetch) ->
Fetcher.fetch_object_from_id!(ap_id, options)
case Fetcher.fetch_object_from_id(ap_id, options) do
{:ok, object} -> object
_ -> nil
end
true ->
get_cached_by_ap_id(ap_id)

View File

@ -72,20 +72,25 @@ defmodule Pleroma.Object.Fetcher do
{:object, data, Object.normalize(activity, fetch: false)} do
{:ok, object}
else
{:allowed_depth, false} ->
{:error, "Max thread distance exceeded."}
{:allowed_depth, false} = e ->
log_fetch_error(id, e)
{:error, :allowed_depth}
{:containment, _} ->
{:error, "Object containment failed."}
{:containment, reason} = e ->
log_fetch_error(id, e)
{:error, reason}
{:transmogrifier, {:error, {:reject, e}}} ->
{:reject, e}
{:transmogrifier, {:error, {:reject, reason}}} = e ->
log_fetch_error(id, e)
{:reject, reason}
{:transmogrifier, {:reject, e}} ->
{:reject, e}
{:transmogrifier, {:reject, reason}} = e ->
log_fetch_error(id, e)
{:reject, reason}
{:transmogrifier, _} = e ->
{:error, e}
{:transmogrifier, reason} = e ->
log_fetch_error(id, e)
{:error, reason}
{:object, data, nil} ->
reinject_object(%Object{}, data)
@ -96,14 +101,21 @@ defmodule Pleroma.Object.Fetcher do
{:fetch_object, %Object{} = object} ->
{:ok, object}
{:fetch, {:error, error}} ->
{:error, error}
{:fetch, {:error, reason}} = e ->
log_fetch_error(id, e)
{:error, reason}
e ->
e
log_fetch_error(id, e)
{:error, e}
end
end
defp log_fetch_error(id, error) do
Logger.metadata(object: id)
Logger.error("Object rejected while fetching #{id} #{inspect(error)}")
end
defp prepare_activity_params(data) do
%{
"type" => "Create",
@ -117,26 +129,6 @@ defmodule Pleroma.Object.Fetcher do
|> Maps.put_if_present("bcc", data["bcc"])
end
def fetch_object_from_id!(id, options \\ []) do
with {:ok, object} <- fetch_object_from_id(id, options) do
object
else
{:error, %Tesla.Mock.Error{}} ->
nil
{:error, "Object has been deleted"} ->
nil
{:reject, reason} ->
Logger.info("Rejected #{id} while fetching: #{inspect(reason)}")
nil
e ->
Logger.error("Error while fetching #{id}: #{inspect(e)}")
nil
end
end
defp make_signature(id, date) do
uri = URI.parse(id)
@ -227,8 +219,11 @@ defmodule Pleroma.Object.Fetcher do
{:error, {:content_type, nil}}
end
{:ok, %{status: code}} when code in [401, 403] ->
{:error, :forbidden}
{:ok, %{status: code}} when code in [404, 410] ->
{:error, "Object has been deleted"}
{:error, :not_found}
{:error, e} ->
{:error, e}

View File

@ -55,12 +55,6 @@ defmodule Pleroma.ReleaseTasks do
{:error, term} when is_binary(term) ->
IO.puts(:stderr, "The database for #{inspect(@repo)} couldn't be created: #{term}")
{:error, term} ->
IO.puts(
:stderr,
"The database for #{inspect(@repo)} couldn't be created: #{inspect(term)}"
)
end
end
end

View File

@ -23,8 +23,8 @@ defmodule Pleroma.ReportNote do
timestamps()
end
@spec create(FlakeId.Ecto.CompatType.t(), FlakeId.Ecto.CompatType.t(), String.t()) ::
{:ok, ReportNote.t()} | {:error, Changeset.t()}
@spec create(Ecto.UUID.t(), Ecto.UUID.t(), String.t()) ::
{:ok, ReportNote.t()} | {:error, Ecto.Changeset.t()}
def create(user_id, activity_id, content) do
attrs = %{
user_id: user_id,
@ -38,8 +38,8 @@ defmodule Pleroma.ReportNote do
|> Repo.insert()
end
@spec destroy(FlakeId.Ecto.CompatType.t()) ::
{:ok, ReportNote.t()} | {:error, Changeset.t()}
@spec destroy(Ecto.UUID.t()) ::
{:ok, ReportNote.t()} | {:error, Ecto.Changeset.t()}
def destroy(id) do
from(r in ReportNote, where: r.id == ^id)
|> Repo.one()

View File

@ -81,9 +81,9 @@ defmodule Pleroma.ReverseProxy do
import Plug.Conn
@type option() ::
{:max_read_duration, :timer.time() | :infinity}
{:max_read_duration, non_neg_integer() | :infinity}
| {:max_body_length, non_neg_integer() | :infinity}
| {:failed_request_ttl, :timer.time() | :infinity}
| {:failed_request_ttl, non_neg_integer() | :infinity}
| {:http, []}
| {:req_headers, [{String.t(), String.t()}]}
| {:resp_headers, [{String.t(), String.t()}]}

View File

@ -86,7 +86,7 @@ defmodule Pleroma.Upload do
end
end
@spec store(source, options :: [option()]) :: {:ok, Map.t()} | {:error, any()}
@spec store(source, options :: [option()]) :: {:ok, map()} | {:error, any()}
@doc "Store a file. If using a `Plug.Upload{}` as the source, be sure to use `Majic.Plug` to ensure its content_type and filename is correct."
def store(upload, opts \\ []) do
opts = get_opts(opts)

View File

@ -5,8 +5,6 @@
defmodule Pleroma.Uploaders.Uploader do
import Pleroma.Web.Gettext
@mix_env Mix.env()
@moduledoc """
Defines the contract to put and get an uploaded file to any backend.
"""
@ -40,7 +38,7 @@ defmodule Pleroma.Uploaders.Uploader do
@callback delete_file(file :: String.t()) :: :ok | {:error, String.t()}
@callback http_callback(Plug.Conn.t(), Map.t()) ::
@callback http_callback(Plug.Conn.t(), map()) ::
{:ok, Plug.Conn.t()}
| {:ok, Plug.Conn.t(), file_spec()}
| {:error, Plug.Conn.t(), String.t()}
@ -75,10 +73,5 @@ defmodule Pleroma.Uploaders.Uploader do
end
end
defp callback_timeout do
case @mix_env do
:test -> 1_000
_ -> 30_000
end
end
defp callback_timeout, do: Application.get_env(:pleroma, __MODULE__)[:timeout]
end

View File

@ -672,7 +672,7 @@ defmodule Pleroma.User do
|> validate_inclusion(:actor_type, ["Person", "Service"])
end
@spec update_as_admin(User.t(), map()) :: {:ok, User.t()} | {:error, Changeset.t()}
@spec update_as_admin(User.t(), map()) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
def update_as_admin(user, params) do
params = Map.put(params, "password_confirmation", params["password"])
changeset = update_as_admin_changeset(user, params)
@ -693,7 +693,7 @@ defmodule Pleroma.User do
|> put_change(:password_reset_pending, false)
end
@spec reset_password(User.t(), map()) :: {:ok, User.t()} | {:error, Changeset.t()}
@spec reset_password(User.t(), map()) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
def reset_password(%User{} = user, params) do
reset_password(user, user, params)
end
@ -1011,7 +1011,7 @@ defmodule Pleroma.User do
def maybe_send_confirmation_email(_), do: {:ok, :noop}
@spec send_confirmation_email(Uset.t()) :: User.t()
@spec send_confirmation_email(User.t()) :: User.t()
def send_confirmation_email(%User{} = user) do
user
|> Pleroma.Emails.UserEmail.account_confirmation_email()
@ -1048,7 +1048,8 @@ defmodule Pleroma.User do
def needs_update?(_), do: true
@spec maybe_direct_follow(User.t(), User.t()) :: {:ok, User.t()} | {:error, String.t()}
@spec maybe_direct_follow(User.t(), User.t()) ::
{:ok, User.t(), User.t()} | {:error, String.t()}
# "Locked" (self-locked) users demand explicit authorization of follow requests
def maybe_direct_follow(%User{} = follower, %User{local: true, is_locked: true} = followed) do
@ -1783,14 +1784,14 @@ defmodule Pleroma.User do
BackgroundWorker.enqueue("user_activation", %{"user_id" => user.id, "status" => status})
end
@spec set_activation([User.t()], boolean()) :: {:ok, User.t()} | {:error, Changeset.t()}
@spec set_activation([User.t()], boolean()) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
def set_activation(users, status) when is_list(users) do
Repo.transaction(fn ->
for user <- users, do: set_activation(user, status)
end)
end
@spec set_activation(User.t(), boolean()) :: {:ok, User.t()} | {:error, Changeset.t()}
@spec set_activation(User.t(), boolean()) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
def set_activation(%User{} = user, status) do
with {:ok, user} <- set_activation_status(user, status) do
user
@ -1868,7 +1869,7 @@ defmodule Pleroma.User do
|> update_and_set_cache()
end
@spec purge_user_changeset(User.t()) :: Changeset.t()
@spec purge_user_changeset(User.t()) :: Ecto.Changeset.t()
def purge_user_changeset(user) do
# "Right to be forgotten"
# https://gdpr.eu/right-to-be-forgotten/
@ -2359,7 +2360,7 @@ defmodule Pleroma.User do
updated_user
end
@spec set_confirmation(User.t(), boolean()) :: {:ok, User.t()} | {:error, Changeset.t()}
@spec set_confirmation(User.t(), boolean()) :: {:ok, User.t()} | {:error, Ecto.Changeset.t()}
def set_confirmation(%User{} = user, bool) do
user
|> confirmation_changeset(set_confirmation: bool)
@ -2537,7 +2538,7 @@ defmodule Pleroma.User do
|> update_and_set_cache()
end
@spec confirmation_changeset(User.t(), keyword()) :: Changeset.t()
@spec confirmation_changeset(User.t(), keyword()) :: Ecto.Changeset.t()
def confirmation_changeset(user, set_confirmation: confirmed?) do
params =
if confirmed? do
@ -2555,7 +2556,7 @@ defmodule Pleroma.User do
cast(user, params, [:is_confirmed, :confirmation_token])
end
@spec approval_changeset(User.t(), keyword()) :: Changeset.t()
@spec approval_changeset(User.t(), keyword()) :: Ecto.Changeset.t()
def approval_changeset(user, set_approval: approved?) do
cast(user, %{is_approved: approved?}, [:is_approved])
end

View File

@ -22,6 +22,8 @@ defmodule Pleroma.User.Backup do
alias Pleroma.Web.ActivityPub.UserView
alias Pleroma.Workers.BackupWorker
@type t :: %__MODULE__{}
schema "backups" do
field(:content_type, :string)
field(:file_name, :string)
@ -195,6 +197,7 @@ defmodule Pleroma.User.Backup do
end
@files ['actor.json', 'outbox.json', 'likes.json', 'bookmarks.json']
@spec export(Pleroma.User.Backup.t(), pid()) :: {:ok, String.t()} | :error
def export(%__MODULE__{} = backup, caller_pid) do
backup = Repo.preload(backup, :user)
dir = backup_tempdir(backup)
@ -204,9 +207,11 @@ defmodule Pleroma.User.Backup do
:ok <- statuses(dir, backup.user, caller_pid),
:ok <- likes(dir, backup.user, caller_pid),
:ok <- bookmarks(dir, backup.user, caller_pid),
{:ok, zip_path} <- :zip.create(String.to_charlist(dir <> ".zip"), @files, cwd: dir),
{:ok, zip_path} <- :zip.create(backup.file_name, @files, cwd: dir),
{:ok, _} <- File.rm_rf(dir) do
{:ok, to_string(zip_path)}
{:ok, zip_path}
else
_ -> :error
end
end
@ -382,6 +387,8 @@ defmodule Pleroma.User.Backup.Processor do
[:file_size, :processed, :state]
)
|> Repo.update()
else
e -> {:error, e}
end
end
end

View File

@ -71,7 +71,7 @@ defmodule Pleroma.User.Query do
@equal_criteria [:email]
@contains_criteria [:ap_id, :nickname]
@spec build(Query.t(), criteria()) :: Query.t()
@spec build(Ecto.Query.t(), criteria()) :: Ecto.Query.t()
def build(query \\ base_query(), criteria) do
prepare_query(query, criteria)
end

View File

@ -64,7 +64,7 @@ defmodule Pleroma.UserInviteToken do
end
@spec update_invite(UserInviteToken.t(), map()) ::
{:ok, UserInviteToken.t()} | {:error, Changeset.t()}
{:ok, UserInviteToken.t()} | {:error, Ecto.Changeset.t()}
def update_invite(invite, changes) do
change(invite, changes) |> Repo.update()
end

View File

@ -14,6 +14,8 @@ defmodule Pleroma.UserRelationship do
alias Pleroma.User
alias Pleroma.UserRelationship
@type t :: %__MODULE__{}
schema "user_relationships" do
belongs_to(:source, User, type: FlakeId.Ecto.CompatType)
belongs_to(:target, User, type: FlakeId.Ecto.CompatType)

View File

@ -499,7 +499,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
end
@spec fetch_latest_direct_activity_id_for_context(String.t(), keyword() | map()) ::
FlakeId.Ecto.CompatType.t() | nil
Ecto.UUID.t() | nil
def fetch_latest_direct_activity_id_for_context(context, opts \\ %{}) do
context
|> fetch_activities_for_context_query(Map.merge(%{skip_preload: true}, opts))
@ -1698,9 +1698,7 @@ defmodule Pleroma.Web.ActivityPub.ActivityPub do
Fetcher.fetch_and_contain_remote_object_from_id(first) do
{:ok, false}
else
{:error, {:ok, %{status: code}}} when code in [401, 403] -> {:ok, true}
{:error, _} = e -> e
e -> {:error, e}
{:error, _} -> {:ok, true}
end
end

View File

@ -9,6 +9,7 @@ defmodule Pleroma.Web.ActivityPub.Builder do
This module encodes our addressing policies and general shape of our objects.
"""
alias Pleroma.Activity
alias Pleroma.Emoji
alias Pleroma.Object
alias Pleroma.User

View File

@ -1,5 +1,5 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
# Copyright © 2017-2023 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF do
@ -139,7 +139,16 @@ defmodule Pleroma.Web.ActivityPub.MRF do
@spec subdomains_regex([String.t()]) :: [Regex.t()]
def subdomains_regex(domains) when is_list(domains) do
for domain <- domains, do: ~r(^#{String.replace(domain, "*.", "(.*\\.)*")}$)i
for domain <- domains do
try do
target = String.replace(domain, "*.", "(.*\\.)*")
~r<^#{target}$>i
rescue
e ->
Logger.error("MRF: Invalid subdomain Regex: #{domain}")
reraise e, __STACKTRACE__
end
end
end
@spec subdomain_match?([Regex.t()], String.t()) :: boolean()

View File

@ -56,8 +56,6 @@ defmodule Pleroma.Web.ActivityPub.MRF.AntiFollowbotPolicy do
nick_score + name_score + actor_type_score
end
defp determine_if_followbot(_), do: 0.0
defp bot_allowed?(%{"object" => target}, bot_actor) do
%User{} = user = normalize_by_ap_id(target)

View File

@ -84,7 +84,7 @@ defmodule Pleroma.Web.ActivityPub.MRF.HashtagPolicy do
if hashtags != [] do
with {:ok, message} <- check_reject(message, hashtags),
{:ok, message} <-
(if "type" == "Create" do
(if type == "Create" do
check_ftl_removal(message, hashtags)
else
{:ok, message}

View File

@ -62,7 +62,6 @@ defmodule Pleroma.Web.ActivityPub.MRF.InlineQuotePolicy do
key: :mrf_inline_quote,
related_policy: "Pleroma.Web.ActivityPub.MRF.InlineQuotePolicy",
label: "MRF Inline Quote Policy",
type: :group,
description: "Force quote url to appear in post content.",
children: [
%{

View File

@ -10,15 +10,12 @@ defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicy do
@moduledoc "Reject or Word-Replace messages with a keyword or regex"
@behaviour Pleroma.Web.ActivityPub.MRF.Policy
defp string_matches?(string, _) when not is_binary(string) do
false
end
defp string_matches?(string, pattern) when is_binary(pattern) do
String.contains?(string, pattern)
end
defp string_matches?(string, pattern) do
defp string_matches?(string, %Regex{} = pattern) do
String.match?(string, pattern)
end

View File

@ -3,8 +3,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRF.Policy do
@callback filter(Map.t()) :: {:ok | :reject, Map.t()}
@callback describe() :: {:ok | :error, Map.t()}
@callback filter(map()) :: {:ok | :reject, map()}
@callback describe() :: {:ok | :error, map()}
@callback config_description() :: %{
optional(:children) => [map()],
key: atom(),

View File

@ -34,7 +34,9 @@ defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicy do
|> Path.basename()
|> Path.extname()
file_path = Path.join(emoji_dir_path, shortcode <> (extension || ".png"))
extension = if extension == "", do: ".png", else: extension
file_path = Path.join(emoji_dir_path, shortcode <> extension)
case File.write(file_path, response.body) do
:ok ->

View File

@ -28,7 +28,7 @@ defmodule Pleroma.Web.ActivityPub.Publisher do
@doc """
Enqueue publishing a single activity.
"""
@spec enqueue_one(Map.t(), Keyword.t()) :: {:ok, %Oban.Job{}}
@spec enqueue_one(map(), Keyword.t()) :: {:ok, %Oban.Job{}}
def enqueue_one(%{} = params, worker_args \\ []) do
PublisherWorker.enqueue(
"publish_one",

View File

@ -23,7 +23,6 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
import Ecto.Query
require Logger
require Pleroma.Constants
@doc """
@ -155,8 +154,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
|> Map.put("context", replied_object.data["context"] || object["conversation"])
|> Map.drop(["conversation", "inReplyToAtomUri"])
else
e ->
Logger.warning("Couldn't fetch #{inspect(in_reply_to_id)}, error: #{inspect(e)}")
_ ->
object
end
else
@ -181,8 +179,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
{:quoting?, _} ->
object
e ->
Logger.warning("Couldn't fetch #{inspect(quote_url)}, error: #{inspect(e)}")
_ ->
object
end
end
@ -339,6 +336,10 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
def fix_tag(object), do: object
def fix_content_map(%{"contentMap" => nil} = object) do
Map.drop(object, ["contentMap"])
end
# content map usually only has one language so this will do for now.
def fix_content_map(%{"contentMap" => content_map} = object) do
content_groups = Map.to_list(content_map)
@ -852,8 +853,7 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier do
relative_object do
Map.put(data, "object", external_url)
else
{:fetch, e} ->
Logger.error("Couldn't fetch #{object} #{inspect(e)}")
{:fetch, _} ->
data
_ ->

View File

@ -5,7 +5,7 @@
defmodule Pleroma.Web.Auth.Authenticator do
@callback get_user(Plug.Conn.t()) :: {:ok, user :: struct()} | {:error, any()}
@callback create_from_registration(Plug.Conn.t(), registration :: struct()) ::
{:ok, User.t()} | {:error, any()}
{:ok, Pleroma.User.t()} | {:error, any()}
@callback get_registration(Plug.Conn.t()) :: {:ok, registration :: struct()} | {:error, any()}
@callback handle_error(Plug.Conn.t(), any()) :: any()
@callback auth_template() :: String.t() | nil

View File

@ -505,7 +505,7 @@ defmodule Pleroma.Web.CommonAPI do
end
end
@spec unpin(String.t(), User.t()) :: {:ok, User.t()} | {:error, term()}
@spec unpin(String.t(), User.t()) :: {:ok, Activity.t()} | {:error, term()}
def unpin(id, user) do
with %Activity{} = activity <- create_activity_by_id(id),
{:ok, unpin_data, _} <- Builder.unpin(user, activity.object),

View File

@ -14,6 +14,8 @@ defmodule Pleroma.Web.CommonAPI.ActivityDraft do
import Pleroma.Web.Gettext
import Pleroma.Web.Utils.Guards, only: [not_empty_string: 1]
@type t :: %__MODULE__{}
defstruct valid?: true,
errors: [],
user: nil,

View File

@ -132,7 +132,7 @@ defmodule Pleroma.Web.Feed.FeedView do
|> safe_to_string()
end
@spec to_rfc3339(String.t() | NativeDateTime.t()) :: String.t()
@spec to_rfc3339(String.t() | NaiveDateTime.t()) :: String.t()
def to_rfc3339(date) when is_binary(date) do
date
|> Timex.parse!("{ISO:Extended}")
@ -145,7 +145,7 @@ defmodule Pleroma.Web.Feed.FeedView do
|> Timex.format!("{RFC3339}")
end
@spec to_rfc2822(String.t() | DateTime.t() | NativeDateTime.t()) :: String.t()
@spec to_rfc2822(String.t() | DateTime.t() | NaiveDateTime.t()) :: String.t()
def to_rfc2822(datestr) when is_binary(datestr) do
datestr
|> Timex.parse!("{ISO:Extended}")

View File

@ -40,6 +40,7 @@ defmodule Pleroma.Web.MastodonAPI.InstanceView do
background_image: Pleroma.Web.Endpoint.url() <> Keyword.get(instance, :background_image),
shout_limit: Config.get([:shout, :limit]),
description_limit: Keyword.get(instance, :description_limit),
chat_limit: Keyword.get(instance, :chat_limit),
pleroma: pleroma_configuration(instance)
})
end
@ -222,6 +223,7 @@ defmodule Pleroma.Web.MastodonAPI.InstanceView do
banner_upload_limit: Keyword.get(instance, :banner_upload_limit),
background_image:
Pleroma.Web.Endpoint.url() <> Keyword.get(instance, :background_image),
chat_limit: Keyword.get(instance, :chat_limit),
description_limit: Keyword.get(instance, :description_limit),
shout_limit: Config.get([:shout, :limit])
})

View File

@ -28,7 +28,7 @@ defmodule Pleroma.Web.OAuth.Authorization do
end
@spec create_authorization(App.t(), User.t() | %{}, [String.t()] | nil) ::
{:ok, Authorization.t()} | {:error, Changeset.t()}
{:ok, Authorization.t()} | {:error, Ecto.Changeset.t()}
def create_authorization(%App{} = app, %User{} = user, scopes \\ nil) do
%{
scopes: scopes || app.scopes,
@ -39,7 +39,7 @@ defmodule Pleroma.Web.OAuth.Authorization do
|> Repo.insert()
end
@spec create_changeset(map()) :: Changeset.t()
@spec create_changeset(map()) :: Ecto.Changeset.t()
def create_changeset(attrs \\ %{}) do
%Authorization{}
|> cast(attrs, [:user_id, :app_id, :scopes, :valid_until])
@ -58,7 +58,7 @@ defmodule Pleroma.Web.OAuth.Authorization do
put_change(changeset, :valid_until, NaiveDateTime.add(NaiveDateTime.utc_now(), lifespan))
end
@spec use_changeset(Authtorizatiton.t(), map()) :: Changeset.t()
@spec use_changeset(Authorization.t(), map()) :: Ecto.Changeset.t()
def use_changeset(%Authorization{} = auth, params) do
auth
|> cast(params, [:used])
@ -66,7 +66,7 @@ defmodule Pleroma.Web.OAuth.Authorization do
end
@spec use_token(Authorization.t()) ::
{:ok, Authorization.t()} | {:error, Changeset.t()} | {:error, String.t()}
{:ok, Authorization.t()} | {:error, Ecto.Changeset.t()} | {:error, String.t()}
def use_token(%Authorization{used: false, valid_until: valid_until} = auth) do
if NaiveDateTime.diff(NaiveDateTime.utc_now(), valid_until) < 0 do
Repo.update(use_changeset(auth, %{used: true}))

View File

@ -56,7 +56,8 @@ defmodule Pleroma.Web.OAuth.Token do
|> Repo.find_resource()
end
@spec exchange_token(App.t(), Authorization.t()) :: {:ok, Token.t()} | {:error, Changeset.t()}
@spec exchange_token(App.t(), Authorization.t()) ::
{:ok, Token.t()} | {:error, Ecto.Changeset.t()}
def exchange_token(app, auth) do
with {:ok, auth} <- Authorization.use_token(auth),
true <- auth.app_id == app.id do
@ -95,7 +96,7 @@ defmodule Pleroma.Web.OAuth.Token do
|> validate_required([:valid_until])
end
@spec create(App.t(), User.t(), map()) :: {:ok, Token} | {:error, Changeset.t()}
@spec create(App.t(), User.t(), map()) :: {:ok, Token} | {:error, Ecto.Changeset.t()}
def create(%App{} = app, %User{} = user, attrs \\ %{}) do
with {:ok, token} <- do_create(app, user, attrs) do
if Pleroma.Config.get([:oauth2, :clean_expired_tokens]) do

View File

@ -9,10 +9,10 @@ defmodule Pleroma.Web.OAuth.Token.Query do
import Ecto.Query, only: [from: 2]
@type query :: Ecto.Queryable.t() | Token.t()
alias Pleroma.Web.OAuth.Token
@type query :: Ecto.Queryable.t() | Token.t()
@spec get_by_refresh_token(query, String.t()) :: query
def get_by_refresh_token(query \\ Token, refresh_token) do
from(q in query, where: q.refresh_token == ^refresh_token)

View File

@ -102,7 +102,7 @@ defmodule Pleroma.Web.RichMedia.Parser do
ttl_setters: [MyModule]
"""
@spec set_ttl_based_on_image(map(), String.t()) ::
{:ok, Integer.t() | :noop} | {:error, :no_key}
{:ok, integer() | :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) ->

View File

@ -3,5 +3,5 @@
# 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
end

View File

@ -182,7 +182,7 @@ defmodule Pleroma.Web.Router do
end
pipeline :well_known do
plug(:accepts, ["json", "jrd+json", "xml", "xrd+xml"])
plug(:accepts, ["json", "jrd", "jrd+json", "xml", "xrd+xml"])
end
pipeline :config do

View File

@ -20,7 +20,6 @@ defmodule Pleroma.Web.Streamer do
alias Pleroma.Web.Plugs.OAuthScopesPlug
alias Pleroma.Web.StreamerView
@mix_env Mix.env()
@registry Pleroma.Web.StreamerRegistry
def registry, do: @registry
@ -34,7 +33,7 @@ defmodule Pleroma.Web.Streamer do
stream :: String.t(),
User.t() | nil,
Token.t() | nil,
Map.t() | nil
map() | nil
) ::
{:ok, topic :: String.t()} | {:error, :bad_topic} | {:error, :unauthorized}
def get_topic_and_add_socket(stream, user, oauth_token, params \\ %{}) do
@ -60,7 +59,7 @@ defmodule Pleroma.Web.Streamer do
end
@doc "Expand and authorizes a stream"
@spec get_topic(stream :: String.t() | nil, User.t() | nil, Token.t() | nil, Map.t()) ::
@spec get_topic(stream :: String.t() | nil, User.t() | nil, Token.t() | nil, map()) ::
{:ok, topic :: String.t() | nil} | {:error, :bad_topic}
def get_topic(stream, user, oauth_token, params \\ %{})
@ -396,25 +395,20 @@ defmodule Pleroma.Web.Streamer do
end
end
# In test environment, only return true if the registry is started.
# In benchmark environment, returns false.
# In any other environment, always returns true.
cond do
@mix_env == :test ->
def should_env_send? do
case Process.whereis(@registry) do
nil ->
false
# In dev/prod the streamer registry is expected to be started, so return true
# In test it is possible to have the registry started for a test so it will check
# In benchmark it will never find the process alive and return false
def should_env_send? do
if Application.get_env(:pleroma, Pleroma.Application)[:streamer_registry] do
true
else
case Process.whereis(@registry) do
nil ->
false
pid ->
Process.alive?(pid)
end
pid ->
Process.alive?(pid)
end
@mix_env == :benchmark ->
def should_env_send?, do: false
true ->
def should_env_send?, do: true
end
end
end

View File

@ -30,7 +30,7 @@ defmodule Pleroma.Web.WebFinger.WebFingerController do
end
def webfinger(%{assigns: %{format: format}} = conn, %{"resource" => resource})
when format in ["json", "jrd+json"] do
when format in ["jrd", "json", "jrd+json"] do
with {:ok, response} <- WebFinger.webfinger(resource, "JSON") do
json(conn, response)
else

View File

@ -9,7 +9,22 @@ defmodule Pleroma.Workers.RemoteFetcherWorker do
@impl Oban.Worker
def perform(%Job{args: %{"op" => "fetch_remote", "id" => id} = args}) do
{:ok, _object} = Fetcher.fetch_object_from_id(id, depth: args["depth"])
case Fetcher.fetch_object_from_id(id, depth: args["depth"]) do
{:ok, _object} ->
:ok
{:error, :forbidden} ->
{:discard, :forbidden}
{:error, :not_found} ->
{:discard, :not_found}
{:error, :allowed_depth} ->
{:discard, :allowed_depth}
_ ->
:error
end
end
@impl Oban.Worker

16
mix.exs
View File

@ -10,6 +10,7 @@ defmodule Pleroma.Mixfile do
compilers: Mix.compilers(),
elixirc_options: [warnings_as_errors: warnings_as_errors()],
xref: [exclude: [:eldap]],
dialyzer: [plt_add_apps: [:mix, :eldap]],
start_permanent: Mix.env() == :prod,
aliases: aliases(),
deps: deps(),
@ -156,14 +157,11 @@ defmodule Pleroma.Mixfile do
{:phoenix_swoosh, "~> 1.1"},
{:gen_smtp, "~> 0.13"},
{:ex_syslogger, "~> 1.4"},
{:floki, "~> 0.27"},
{:floki, "~> 0.35"},
{:timex, "~> 3.6"},
{:ueberauth, "~> 0.4"},
# {:linkify, "~> 0.5.2"},
{:linkify,
git: "https://git.froth.zone/sam/linkify.git",
branch: "master"},
{:http_signatures, "~> 0.1.1"},
{:linkify, "~> 0.5.3"},
{:http_signatures, "~> 0.1.2"},
{:telemetry, "~> 1.0.0", override: true},
{:poolboy, "~> 1.5"},
{:prom_ex, "~> 1.9"},
@ -187,6 +185,9 @@ defmodule Pleroma.Mixfile do
{:vix, "~> 0.26.0"},
{:elixir_make, "~> 0.7.7", override: true},
{:blurhash, "~> 0.1.0", hex: :rinpatch_blurhash},
{:exile,
git: "https://git.pleroma.social/pleroma/elixir-libraries/exile.git",
ref: "0d6337cf68e7fbc8a093cae000955aa93b067f91"},
## dev & test
{:ex_doc, "~> 0.22", only: :dev, runtime: false},
@ -197,7 +198,8 @@ defmodule Pleroma.Mixfile do
{:hackney, "~> 1.18.0", override: true},
{:mox, "~> 1.0", only: :test},
{:websockex, "~> 0.4.3", only: :test},
{:benchee, "~> 1.0", only: :benchmark}
{:benchee, "~> 1.0", only: :benchmark},
{:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false}
] ++ oauth_deps()
end

View File

@ -27,6 +27,7 @@
"db_connection": {:hex, :db_connection, "2.6.0", "77d835c472b5b67fc4f29556dee74bf511bbafecdcaf98c27d27fa5918152086", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "c2f992d15725e721ec7fbc1189d4ecdb8afef76648c746a8e1cad35e3b8a35f3"},
"decimal": {:hex, :decimal, "2.1.1", "5611dca5d4b2c3dd497dec8f68751f1f1a54755e8ed2a966c2633cf885973ad6", [:mix], [], "hexpm", "53cfe5f497ed0e7771ae1a475575603d77425099ba5faef9394932b35020ffcc"},
"deep_merge": {:hex, :deep_merge, "1.0.0", "b4aa1a0d1acac393bdf38b2291af38cb1d4a52806cf7a4906f718e1feb5ee961", [:mix], [], "hexpm", "ce708e5f094b9cd4e8f2be4f00d2f4250c4095be93f8cd6d018c753894885430"},
"dialyxir": {:hex, :dialyxir, "1.4.3", "edd0124f358f0b9e95bfe53a9fcf806d615d8f838e2202a9f430d59566b6b53b", [:mix], [{:erlex, ">= 0.2.6", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "bf2cfb75cd5c5006bec30141b131663299c661a864ec7fbbc72dfa557487a986"},
"earmark": {:hex, :earmark, "1.4.22", "ea3e45c6359446dc308be0a64ce82a03260d973de7d0625a762e6d352ff57958", [:mix], [{:earmark_parser, "~> 1.4.23", [hex: :earmark_parser, repo: "hexpm", optional: false]}], "hexpm", "1caf5145665a42fd76d5317286b0c171861fb1c04f86ab103dde76868814fdfb"},
"earmark_parser": {:hex, :earmark_parser, "1.4.32", "fa739a0ecfa34493de19426681b23f6814573faee95dfd4b4aafe15a7b5b32c6", [:mix], [], "hexpm", "b8b0dd77d60373e77a3d7e8afa598f325e49e8663a51bcc2b88ef41838cca755"},
"eblurhash": {:git, "https://github.com/zotonic/eblurhash.git", "bc37ceb426ef021ee9927fb249bb93f7059194ab", [ref: "bc37ceb426ef021ee9927fb249bb93f7059194ab"]},
@ -35,7 +36,8 @@
"ecto_psql_extras": {:hex, :ecto_psql_extras, "0.7.14", "7a20cfe913b0476542b43870e67386461258734896035e3f284039fd18bd4c4c", [:mix], [{:ecto_sql, "~> 3.7", [hex: :ecto_sql, repo: "hexpm", optional: false]}, {:postgrex, "~> 0.16.0 or ~> 0.17.0", [hex: :postgrex, repo: "hexpm", optional: false]}, {:table_rex, "~> 3.1.1", [hex: :table_rex, repo: "hexpm", optional: false]}], "hexpm", "22f5f98592dd597db9416fcef00effae0787669fdcb6faf447e982b553798e98"},
"ecto_sql": {:hex, :ecto_sql, "3.10.2", "6b98b46534b5c2f8b8b5f03f126e75e2a73c64f3c071149d32987a5378b0fdbd", [:mix], [{:db_connection, "~> 2.4.1 or ~> 2.5", [hex: :db_connection, repo: "hexpm", optional: false]}, {:ecto, "~> 3.10.0", [hex: :ecto, repo: "hexpm", optional: false]}, {:myxql, "~> 0.6.0", [hex: :myxql, repo: "hexpm", optional: true]}, {:postgrex, "~> 0.16.0 or ~> 0.17.0 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:tds, "~> 2.1.1 or ~> 2.2", [hex: :tds, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "68c018debca57cb9235e3889affdaec7a10616a4e3a80c99fa1d01fdafaa9007"},
"eimp": {:hex, :eimp, "1.0.14", "fc297f0c7e2700457a95a60c7010a5f1dcb768a083b6d53f49cd94ab95a28f22", [:rebar3], [{:p1_utils, "1.0.18", [hex: :p1_utils, repo: "hexpm", optional: false]}], "hexpm", "501133f3112079b92d9e22da8b88bf4f0e13d4d67ae9c15c42c30bd25ceb83b6"},
"elixir_make": {:hex, :elixir_make, "0.7.7", "7128c60c2476019ed978210c245badf08b03dbec4f24d05790ef791da11aa17c", [:mix], [{:castore, "~> 0.1 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}], "hexpm", "5bc19fff950fad52bbe5f211b12db9ec82c6b34a9647da0c2224b8b8464c7e6c"},
"elixir_make": {:hex, :elixir_make, "0.7.8", "505026f266552ee5aabca0b9f9c229cbb496c689537c9f922f3eb5431157efc7", [:mix], [{:castore, "~> 0.1 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:certifi, "~> 2.0", [hex: :certifi, repo: "hexpm", optional: true]}], "hexpm", "7a71945b913d37ea89b06966e1342c85cfe549b15e6d6d081e8081c493062c07"},
"erlex": {:hex, :erlex, "0.2.6", "c7987d15e899c7a2f34f5420d2a2ea0d659682c06ac607572df55a43753aa12e", [:mix], [], "hexpm", "2ed2e25711feb44d52b17d2780eabf998452f6efda104877a3881c2f8c0c0c75"},
"esbuild": {:hex, :esbuild, "0.5.0", "d5bb08ff049d7880ee3609ed5c4b864bd2f46445ea40b16b4acead724fb4c4a3", [:mix], [{:castore, ">= 0.0.0", [hex: :castore, repo: "hexpm", optional: false]}], "hexpm", "f183a0b332d963c4cfaf585477695ea59eef9a6f2204fdd0efa00e099694ffe5"},
"eternal": {:hex, :eternal, "1.2.2", "d1641c86368de99375b98d183042dd6c2b234262b8d08dfd72b9eeaafc2a1abd", [:mix], [], "hexpm", "2c9fe32b9c3726703ba5e1d43a1d255a4f3f2d8f8f9bc19f094c7cb1a7a9e782"},
"ex_aws": {:hex, :ex_aws, "2.1.9", "dc4865ecc20a05190a34a0ac5213e3e5e2b0a75a0c2835e923ae7bfeac5e3c31", [:mix], [{:configparser_ex, "~> 4.0", [hex: :configparser_ex, repo: "hexpm", optional: true]}, {:hackney, "~> 1.9", [hex: :hackney, repo: "hexpm", optional: true]}, {:jason, "~> 1.1", [hex: :jason, repo: "hexpm", optional: true]}, {:jsx, "~> 3.0", [hex: :jsx, repo: "hexpm", optional: true]}, {:sweet_xml, "~> 0.6", [hex: :sweet_xml, repo: "hexpm", optional: true]}], "hexpm", "3e6c776703c9076001fbe1f7c049535f042cb2afa0d2cbd3b47cbc4e92ac0d10"},
@ -44,20 +46,21 @@
"ex_doc": {:hex, :ex_doc, "0.29.4", "6257ecbb20c7396b1fe5accd55b7b0d23f44b6aa18017b415cb4c2b91d997729", [:mix], [{:earmark_parser, "~> 1.4.31", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1", [hex: :makeup_erlang, repo: "hexpm", optional: false]}], "hexpm", "2c6699a737ae46cb61e4ed012af931b57b699643b24dabe2400a8168414bc4f5"},
"ex_machina": {:hex, :ex_machina, "2.7.0", "b792cc3127fd0680fecdb6299235b4727a4944a09ff0fa904cc639272cd92dc7", [:mix], [{:ecto, "~> 2.2 or ~> 3.0", [hex: :ecto, repo: "hexpm", optional: true]}, {:ecto_sql, "~> 3.0", [hex: :ecto_sql, repo: "hexpm", optional: true]}], "hexpm", "419aa7a39bde11894c87a615c4ecaa52d8f107bbdd81d810465186f783245bf8"},
"ex_syslogger": {:hex, :ex_syslogger, "1.5.2", "72b6aa2d47a236e999171f2e1ec18698740f40af0bd02c8c650bf5f1fd1bac79", [:mix], [{:poison, ">= 1.5.0", [hex: :poison, repo: "hexpm", optional: true]}, {:syslog, "~> 1.1.0", [hex: :syslog, repo: "hexpm", optional: false]}], "hexpm", "ab9fab4136dbc62651ec6f16fa4842f10cf02ab4433fa3d0976c01be99398399"},
"exile": {:git, "https://git.pleroma.social/pleroma/elixir-libraries/exile.git", "0d6337cf68e7fbc8a093cae000955aa93b067f91", [ref: "0d6337cf68e7fbc8a093cae000955aa93b067f91"]},
"expo": {:hex, :expo, "0.4.1", "1c61d18a5df197dfda38861673d392e642649a9cef7694d2f97a587b2cfb319b", [:mix], [], "hexpm", "2ff7ba7a798c8c543c12550fa0e2cbc81b95d4974c65855d8d15ba7b37a1ce47"},
"fast_html": {:hex, :fast_html, "2.0.5", "c61760340606c1077ff1f196f17834056cb1dd3d5cb92a9f2cabf28bc6221c3c", [:make, :mix], [{:elixir_make, "~> 0.4", [hex: :elixir_make, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 0.2.0", [hex: :nimble_pool, repo: "hexpm", optional: false]}], "hexpm", "605f4f4829443c14127694ebabb681778712ceecb4470ec32aa31012330e6506"},
"fast_sanitize": {:hex, :fast_sanitize, "0.2.3", "67b93dfb34e302bef49fec3aaab74951e0f0602fd9fa99085987af05bd91c7a5", [:mix], [{:fast_html, "~> 2.0", [hex: :fast_html, repo: "hexpm", optional: false]}, {:plug, "~> 1.8", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "e8ad286d10d0386e15d67d0ee125245ebcfbc7d7290b08712ba9013c8c5e56e2"},
"file_system": {:hex, :file_system, "0.2.10", "fb082005a9cd1711c05b5248710f8826b02d7d1784e7c3451f9c1231d4fc162d", [:mix], [], "hexpm", "41195edbfb562a593726eda3b3e8b103a309b733ad25f3d642ba49696bf715dc"},
"finch": {:hex, :finch, "0.16.0", "40733f02c89f94a112518071c0a91fe86069560f5dbdb39f9150042f44dcfb1a", [:mix], [{:castore, "~> 0.1 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: false]}, {:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.3", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 0.2.6 or ~> 1.0", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "f660174c4d519e5fec629016054d60edd822cdfe2b7270836739ac2f97735ec5"},
"flake_id": {:hex, :flake_id, "0.1.0", "7716b086d2e405d09b647121a166498a0d93d1a623bead243e1f74216079ccb3", [:mix], [{:base62, "~> 1.2", [hex: :base62, repo: "hexpm", optional: false]}, {:ecto, ">= 2.0.0", [hex: :ecto, repo: "hexpm", optional: true]}], "hexpm", "31fc8090fde1acd267c07c36ea7365b8604055f897d3a53dd967658c691bd827"},
"floki": {:hex, :floki, "0.34.3", "5e2dcaec5d7c228ce5b1d3501502e308b2d79eb655e4191751a1fe491c37feac", [:mix], [], "hexpm", "9577440eea5b97924b4bf3c7ea55f7b8b6dce589f9b28b096cc294a8dc342341"},
"floki": {:hex, :floki, "0.35.2", "87f8c75ed8654b9635b311774308b2760b47e9a579dabf2e4d5f1e1d42c39e0b", [:mix], [], "hexpm", "6b05289a8e9eac475f644f09c2e4ba7e19201fd002b89c28c1293e7bd16773d9"},
"gen_smtp": {:hex, :gen_smtp, "0.15.0", "9f51960c17769b26833b50df0b96123605a8024738b62db747fece14eb2fbfcc", [:rebar3], [], "hexpm", "29bd14a88030980849c7ed2447b8db6d6c9278a28b11a44cafe41b791205440f"},
"gettext": {:hex, :gettext, "0.22.2", "6bfca374de34ecc913a28ba391ca184d88d77810a3e427afa8454a71a51341ac", [:mix], [{:expo, "~> 0.4.0", [hex: :expo, repo: "hexpm", optional: false]}], "hexpm", "8a2d389673aea82d7eae387e6a2ccc12660610080ae7beb19452cfdc1ec30f60"},
"gun": {:hex, :gun, "2.0.1", "160a9a5394800fcba41bc7e6d421295cf9a7894c2252c0678244948e3336ad73", [:make, :rebar3], [{:cowlib, "2.12.1", [hex: :cowlib, repo: "hexpm", optional: false]}], "hexpm", "a10bc8d6096b9502205022334f719cc9a08d9adcfbfc0dbee9ef31b56274a20b"},
"hackney": {:hex, :hackney, "1.18.1", "f48bf88f521f2a229fc7bae88cf4f85adc9cd9bcf23b5dc8eb6a1788c662c4f6", [:rebar3], [{:certifi, "~>2.9.0", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "~>6.1.0", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "~>1.0.0", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "~>1.1", [hex: :mimerl, repo: "hexpm", optional: false]}, {:parse_trans, "3.3.1", [hex: :parse_trans, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "~>1.1.0", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}, {:unicode_util_compat, "~>0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "a4ecdaff44297e9b5894ae499e9a070ea1888c84afdd1fd9b7b2bc384950128e"},
"hpax": {:hex, :hpax, "0.1.2", "09a75600d9d8bbd064cdd741f21fc06fc1f4cf3d0fcc335e5aa19be1a7235c84", [:mix], [], "hexpm", "2c87843d5a23f5f16748ebe77969880e29809580efdaccd615cd3bed628a8c13"},
"html_entities": {:hex, :html_entities, "0.5.2", "9e47e70598da7de2a9ff6af8758399251db6dbb7eebe2b013f2bbd2515895c3c", [:mix], [], "hexpm", "c53ba390403485615623b9531e97696f076ed415e8d8058b1dbaa28181f4fdcc"},
"http_signatures": {:hex, :http_signatures, "0.1.1", "ca7ebc1b61542b163644c8c3b1f0e0f41037d35f2395940d3c6c7deceab41fd8", [:mix], [], "hexpm", "cc3b8a007322cc7b624c0c15eec49ee58ac977254ff529a3c482f681465942a3"},
"http_signatures": {:hex, :http_signatures, "0.1.2", "ed1cc7043abcf5bb4f30d68fb7bad9d618ec1a45c4ff6c023664e78b67d9c406", [:mix], [], "hexpm", "f08aa9ac121829dae109d608d83c84b940ef2f183ae50f2dd1e9a8bc619d8be7"},
"httpoison": {:hex, :httpoison, "1.8.2", "9eb9c63ae289296a544842ef816a85d881d4a31f518a0fec089aaa744beae290", [:mix], [{:hackney, "~> 1.17", [hex: :hackney, repo: "hexpm", optional: false]}], "hexpm", "2bb350d26972e30c96e2ca74a1aaf8293d61d0742ff17f01e0279fef11599921"},
"idna": {:hex, :idna, "6.1.1", "8a63070e9f7d0c62eb9d9fcb360a7de382448200fbbd1b106cc96d3d8099df8d", [:rebar3], [{:unicode_util_compat, "~>0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "92376eb7894412ed19ac475e4a86f7b413c1b9fbb5bd16dccd57934157944cea"},
"inet_cidr": {:hex, :inet_cidr, "1.0.4", "a05744ab7c221ca8e395c926c3919a821eb512e8f36547c062f62c4ca0cf3d6e", [:mix], [], "hexpm", "64a2d30189704ae41ca7dbdd587f5291db5d1dda1414e0774c29ffc81088c1bc"},

View File

@ -182,8 +182,8 @@ defmodule Mix.Tasks.Pleroma.ConfigTest do
assert File.exists?(temp_file)
{:ok, file} = File.read(temp_file)
assert file ==
"import Config\n\nconfig :pleroma, :instance,\n name: \"Pleroma\",\n email: \"example@example.com\",\n notify_email: \"noreply@example.com\",\n description: \"A Pleroma instance, an alternative fediverse server\",\n limit: 5000,\n chat_limit: 5000,\n remote_limit: 100_000,\n upload_limit: 16_000_000,\n avatar_upload_limit: 2_000_000,\n background_upload_limit: 4_000_000,\n banner_upload_limit: 4_000_000,\n poll_limits: %{\n max_expiration: 31_536_000,\n max_option_chars: 200,\n max_options: 20,\n min_expiration: 0\n },\n registrations_open: true,\n federating: true,\n federation_incoming_replies_max_depth: 100,\n federation_reachability_timeout_days: 7,\n allow_relay: true,\n public: true,\n quarantined_instances: [],\n managed_config: true,\n static_dir: \"instance/static/\",\n allowed_post_formats: [\"text/plain\", \"text/html\", \"text/markdown\", \"text/bbcode\"],\n autofollowed_nicknames: [],\n max_pinned_statuses: 1,\n attachment_links: false,\n max_report_comment_size: 1000,\n safe_dm_mentions: false,\n healthcheck: false,\n remote_post_retention_days: 90,\n skip_thread_containment: true,\n limit_to_local_content: :unauthenticated,\n user_bio_length: 5000,\n user_name_length: 100,\n max_account_fields: 10,\n max_remote_account_fields: 20,\n account_field_name_length: 512,\n account_field_value_length: 2048,\n external_user_synchronization: true,\n extended_nickname_format: true,\n multi_factor_authentication: [\n totp: [digits: 6, period: 30],\n backup_codes: [number: 2, length: 6]\n ]\n"
assert file =~ "import Config\n"
assert file =~ "A Pleroma instance, an alternative fediverse server"
end
end

View File

@ -145,6 +145,7 @@ defmodule Pleroma.ActivityTest do
setup do: clear_config([:instance, :limit_to_local_content])
@tag :skip_darwin
test "finds utf8 text in statuses", %{
japanese_activity: japanese_activity,
user: user

View File

@ -125,13 +125,12 @@ defmodule Pleroma.Config.DeprecationWarningsTest do
media_removal: ["some.removal", {"some.other.instance", "Some reason"}]
)
expected_config = [
expected_config =
{:media_removal, [{"some.removal", ""}, {"some.other.instance", "Some reason"}]}
]
capture_log(fn -> DeprecationWarnings.warn() end)
assert Config.get([:mrf_simple]) == expected_config
assert expected_config in Config.get([:mrf_simple])
end
test "doesn't give a warning with correct config" do

View File

@ -9,14 +9,16 @@ defmodule Pleroma.HealthcheckTest do
test "system_info/0" do
result = Healthcheck.system_info() |> Map.from_struct()
assert Map.keys(result) == [
keys = Map.keys(result)
assert Keyword.equal?(keys, [
:active,
:healthy,
:idle,
:job_queue_stats,
:memory_used,
:pool_size
]
])
end
describe "check_health/1" do

View File

@ -7,6 +7,8 @@ defmodule Pleroma.MFA.TOTPTest do
alias Pleroma.MFA.TOTP
import Pleroma.Tests.Helpers, only: [uri_equal?: 2]
test "create provisioning_uri to generate qrcode" do
uri =
TOTP.provisioning_uri("test-secrcet", "test@example.com",
@ -15,7 +17,9 @@ defmodule Pleroma.MFA.TOTPTest do
period: 60
)
assert uri ==
assert uri_equal?(
uri,
"otpauth://totp/test@example.com?digits=8&issuer=Plerome-42&period=60&secret=test-secrcet"
)
end
end

View File

@ -101,8 +101,7 @@ defmodule Pleroma.Object.FetcherTest do
test "it returns thread depth exceeded error if thread depth is exceeded" do
clear_config([:instance, :federation_incoming_replies_max_depth], 0)
assert {:error, "Max thread distance exceeded."} =
Fetcher.fetch_object_from_id(@ap_id, depth: 1)
assert {:error, :allowed_depth} = Fetcher.fetch_object_from_id(@ap_id, depth: 1)
end
test "it fetches object if max thread depth is restricted to 0 and depth is not specified" do
@ -220,14 +219,14 @@ defmodule Pleroma.Object.FetcherTest do
end
test "handle HTTP 410 Gone response" do
assert {:error, "Object has been deleted"} ==
assert {:error, :not_found} ==
Fetcher.fetch_and_contain_remote_object_from_id(
"https://mastodon.example.org/users/userisgone"
)
end
test "handle HTTP 404 response" do
assert {:error, "Object has been deleted"} ==
assert {:error, :not_found} ==
Fetcher.fetch_and_contain_remote_object_from_id(
"https://mastodon.example.org/users/userisgone404"
)

View File

@ -29,13 +29,13 @@ defmodule Pleroma.Repo.Migrations.AutolinkerToLinkifyTest do
%{value: new_opts} = ConfigDB.get_by_params(%{group: :pleroma, key: Pleroma.Formatter})
assert new_opts == [
assert Keyword.equal?(new_opts,
class: false,
extra: true,
new_window: false,
rel: "testing",
strip_prefix: false
]
)
clear_config(Pleroma.Formatter, new_opts)
assert new_opts == Pleroma.Config.get(Pleroma.Formatter)
@ -67,6 +67,6 @@ defmodule Pleroma.Repo.Migrations.AutolinkerToLinkifyTest do
strip_prefix: false
]
assert migration.transform_opts(old_opts) == expected_opts
assert Keyword.equal?(migration.transform_opts(old_opts), expected_opts)
end
end

View File

@ -26,13 +26,13 @@ defmodule Pleroma.Repo.Migrations.FixMalformedFormatterConfigTest do
%{value: new_opts} = ConfigDB.get_by_params(%{group: :pleroma, key: Pleroma.Formatter})
assert new_opts == [
assert Keyword.equal?(new_opts,
class: false,
extra: true,
new_window: false,
rel: "F",
strip_prefix: false
]
)
clear_config(Pleroma.Formatter, new_opts)
assert new_opts == Pleroma.Config.get(Pleroma.Formatter)

View File

@ -60,6 +60,33 @@ defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicyTest do
|> File.exists?()
end
test "works with unknown extension", %{path: path} do
message = %{
"type" => "Create",
"object" => %{
"emoji" => [{"firedfox", "https://example.org/emoji/firedfox"}],
"actor" => "https://example.org/users/admin"
}
}
fullpath = Path.join(path, "firedfox.png")
Tesla.Mock.mock(fn %{method: :get, url: "https://example.org/emoji/firedfox"} ->
%Tesla.Env{status: 200, body: File.read!("test/fixtures/image.jpg")}
end)
clear_config(:mrf_steal_emoji, hosts: ["example.org"], size_limit: 284_468)
refute "firedfox" in installed()
refute File.exists?(path)
assert {:ok, _message} = StealEmojiPolicy.filter(message)
assert "firedfox" in installed()
assert File.exists?(path)
assert File.exists?(fullpath)
end
test "reject regex shortcode", %{message: message} do
refute "firedfox" in installed()

View File

@ -1,10 +1,13 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
# Copyright © 2017-2023 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.ActivityPub.MRFTest do
use ExUnit.Case
use Pleroma.Tests.Helpers
import ExUnit.CaptureLog
alias Pleroma.Web.ActivityPub.MRF
test "subdomains_regex/1" do
@ -61,6 +64,14 @@ defmodule Pleroma.Web.ActivityPub.MRFTest do
refute MRF.subdomain_match?(regexes, "EXAMPLE.COM")
refute MRF.subdomain_match?(regexes, "example.com")
end
@tag capture_log: true
test "logs sensible error on accidental wildcard" do
assert_raise Regex.CompileError, fn ->
assert capture_log(MRF.subdomains_regex(["*unsafe.tld"])) =~
"MRF: Invalid subdomain Regex: *unsafe.tld"
end
end
end
describe "instance_list_from_tuples/1" do

View File

@ -221,6 +221,19 @@ defmodule Pleroma.Web.ActivityPub.Transmogrifier.NoteHandlingTest do
"<p><span class=\"h-card\"><a href=\"http://localtesting.pleroma.lol/users/lain\" class=\"u-url mention\">@<span>lain</span></a></span></p>"
end
test "it works for incoming notices with a nil contentMap (firefish)" do
data =
File.read!("test/fixtures/mastodon-post-activity-contentmap.json")
|> Jason.decode!()
|> Map.put("contentMap", nil)
{:ok, %Activity{data: data, local: false}} = Transmogrifier.handle_incoming(data)
object = Object.normalize(data["object"], fetch: false)
assert object.data["content"] ==
"<p><span class=\"h-card\"><a href=\"http://localtesting.pleroma.lol/users/lain\" class=\"u-url mention\">@<span>lain</span></a></span></p>"
end
test "it works for incoming notices with to/cc not being an array (kroeg)" do
data = File.read!("test/fixtures/kroeg-post-activity.json") |> Jason.decode!()

View File

@ -132,7 +132,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
assert {:ok, activity} = Transmogrifier.handle_incoming(message)
object = Object.normalize(activity)
assert [%{"type" => "Mention"}, %{"type" => "Link"}] = object.data["tag"]
end) =~ "Error while fetching"
end) =~ "Object rejected while fetching"
end
test "it accepts quote posts" do
@ -410,7 +410,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
assert capture_log(fn ->
{:error, _} = Transmogrifier.handle_incoming(data)
end) =~ "Object containment failed"
end) =~ "Object rejected while fetching"
end
test "it rejects activities which reference objects that have an incorrect attribution (variant 1)" do
@ -425,7 +425,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
assert capture_log(fn ->
{:error, _} = Transmogrifier.handle_incoming(data)
end) =~ "Object containment failed"
end) =~ "Object rejected while fetching"
end
test "it rejects activities which reference objects that have an incorrect attribution (variant 2)" do
@ -440,7 +440,7 @@ defmodule Pleroma.Web.ActivityPub.TransmogrifierTest do
assert capture_log(fn ->
{:error, _} = Transmogrifier.handle_incoming(data)
end) =~ "Object containment failed"
end) =~ "Object rejected while fetching"
end
end

View File

@ -42,6 +42,7 @@ defmodule Pleroma.Web.MastodonAPI.SearchControllerTest do
end
end
@tag :skip_darwin
test "search", %{conn: conn} do
user = insert(:user)
user_two = insert(:user, %{nickname: "shp@shitposter.club"})

View File

@ -12,6 +12,7 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
alias Pleroma.Object
alias Pleroma.Repo
alias Pleroma.ScheduledActivity
alias Pleroma.Tests.Helpers
alias Pleroma.Tests.ObanHelpers
alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub
@ -2191,7 +2192,10 @@ defmodule Pleroma.Web.MastodonAPI.StatusControllerTest do
# Using the header for pagination works correctly
[next, _] = get_resp_header(result, "link") |> hd() |> String.split(", ")
[_, max_id] = Regex.run(~r/max_id=([^&]+)/, next)
[next_url, _next_rel] = String.split(next, ";")
next_url = String.trim_trailing(next_url, ">") |> String.trim_leading("<")
max_id = Helpers.get_query_parameter(next_url, "max_id")
assert max_id == third_favorite.id

View File

@ -3,7 +3,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
use Pleroma.Web.ConnCase, async: true
use Pleroma.Web.ConnCase, async: false
import Pleroma.Factory
@ -35,17 +35,20 @@ defmodule Pleroma.Web.MastodonAPI.SubscriptionControllerTest do
defmacro assert_error_when_disable_push(do: yield) do
quote do
vapid_details = Application.get_env(:web_push_encryption, :vapid_details, [])
Application.put_env(:web_push_encryption, :vapid_details, [])
assert %{"error" => "Web push subscription is disabled on this Pleroma instance"} ==
unquote(yield)
Application.put_env(:web_push_encryption, :vapid_details, vapid_details)
end
end
describe "when disabled" do
setup do
vapid_config = Application.get_env(:web_push_encryption, :vapid_details)
Application.put_env(:web_push_encryption, :vapid_details, [])
on_exit(fn -> Application.put_env(:web_push_encryption, :vapid_details, vapid_config) end)
end
test "POST returns error", %{conn: conn} do
assert_error_when_disable_push do
conn

View File

@ -7,6 +7,7 @@ defmodule Pleroma.Web.PleromaAPI.ChatControllerTest do
alias Pleroma.Chat
alias Pleroma.Chat.MessageReference
alias Pleroma.Object
alias Pleroma.Tests.Helpers
alias Pleroma.UnstubbedConfigMock, as: ConfigMock
alias Pleroma.User
alias Pleroma.Web.ActivityPub.ActivityPub
@ -212,36 +213,63 @@ defmodule Pleroma.Web.PleromaAPI.ChatControllerTest do
result = json_response_and_validate_schema(response, 200)
[next, prev] = get_resp_header(response, "link") |> hd() |> String.split(", ")
api_endpoint = "/api/v1/pleroma/chats/"
api_endpoint = Pleroma.Web.Endpoint.url() <> "/api/v1/pleroma/chats/"
[next_url, next_rel] = String.split(next, ";")
next_url = String.trim_trailing(next_url, ">") |> String.trim_leading("<")
next_url_sorted = Helpers.uri_query_sort(next_url)
assert String.match?(
next,
~r(#{api_endpoint}.*/messages\?limit=\d+&max_id=.*; rel=\"next\"$)
next_url_sorted,
~r(#{api_endpoint}.*/messages\?limit=\d+&max_id=.*&offset=\d+$)
)
assert next_rel =~ "next"
[prev_url, prev_rel] = String.split(prev, ";")
prev_url = String.trim_trailing(prev_url, ">") |> String.trim_leading("<")
prev_url_sorted = Helpers.uri_query_sort(prev_url)
assert String.match?(
prev,
~r(#{api_endpoint}.*/messages\?limit=\d+&min_id=.*; rel=\"prev\"$)
prev_url_sorted,
~r(#{api_endpoint}.*/messages\?limit=\d+&min_id=.*&offset=\d+$)
)
assert prev_rel =~ "prev"
assert length(result) == 20
response =
get(conn, "/api/v1/pleroma/chats/#{chat.id}/messages?max_id=#{List.last(result)["id"]}")
response = get(conn, "#{api_endpoint}#{chat.id}/messages?max_id=#{List.last(result)["id"]}")
result = json_response_and_validate_schema(response, 200)
[next, prev] = get_resp_header(response, "link") |> hd() |> String.split(", ")
assert String.match?(
next,
~r(#{api_endpoint}.*/messages\?limit=\d+&max_id=.*; rel=\"next\"$)
)
[next_url, next_rel] = String.split(next, ";")
next_url = String.trim_trailing(next_url, ">") |> String.trim_leading("<")
next_url_sorted = Helpers.uri_query_sort(next_url)
assert String.match?(
prev,
~r(#{api_endpoint}.*/messages\?limit=\d+&max_id=.*&min_id=.*; rel=\"prev\"$)
next_url_sorted,
~r(#{api_endpoint}.*/messages\?limit=\d+&max_id=.*&offset=\d+$)
)
assert next_rel =~ "next"
[prev_url, prev_rel] = String.split(prev, ";")
prev_url = String.trim_trailing(prev_url, ">") |> String.trim_leading("<")
prev_url_sorted = Helpers.uri_query_sort(prev_url)
assert String.match?(
prev_url_sorted,
~r(#{api_endpoint}.*/messages\?limit=\d+&max_id=.*&min_id=.*&offset=\d+$)
)
assert prev_rel =~ "prev"
assert length(result) == 10
end

Some files were not shown because too many files have changed in this diff Show More