clacks/lib/clacks/timeline.ex

80 lines
2.1 KiB
Elixir

defmodule Clacks.Timeline do
alias Clacks.{Repo, Actor, Activity, User}
import Clacks.Paginator
import Ecto.Query
@public "https://www.w3.org/ns/activitystreams#Public"
@timeline_types ["Create", "Announce"]
@spec actor_timeline(
actor :: Actor.t(),
params :: map(),
only_public :: boolean(),
actors :: boolean()
) :: [
Activity.t()
]
def actor_timeline(actor, params, only_public \\ true, actors \\ false) do
Activity
|> restrict_to_actor(actor.ap_id)
|> restrict_to_types(@timeline_types)
|> restrict_to_public(only_public)
|> paginate(params)
|> limit(^Map.get(params, "limit", 20))
|> join_with_actors(actors)
|> Repo.all()
end
@spec home_timeline(user :: User.t(), params :: map(), actors :: boolean()) :: [
Activity.t()
]
def home_timeline(user, params, actors \\ false) do
user =
case user.actor do
%Ecto.Association.NotLoaded{} ->
Repo.preload(user, :actor)
_ ->
user
end
Activity
|> where(
[a],
fragment("?->>'actor'", a.data) == ^user.actor.ap_id or
fragment("?->>'actor'", a.data) in ^user.actor.followers
)
|> restrict_to_types(@timeline_types)
|> paginate(params)
|> limit(^Map.get(params, "limit", 20))
|> join_with_actors(actors)
|> Repo.all()
end
defp restrict_to_actor(query, actor_id) do
where(query, [a], fragment("?->>'actor'", a.data) == ^actor_id)
end
defp restrict_to_types(query, types) do
where(query, [a], fragment("?->>'type'", a.data) in ^types)
end
defp restrict_to_public(query, true) do
where(
query,
[a],
fragment("?->'to' \\? ?", a.data, @public) or fragment("?->'cc' \\? ?", a.data, @public)
)
end
defp restrict_to_public(query, false), do: query
defp join_with_actors(query, true) do
query
|> join(:left, [o], a in Actor, on: a.ap_id == fragment("?->>'actor'", o.data))
|> select([o, a], {o, a})
end
defp join_with_actors(query, false), do: query
end