federator.ex 5.89 KB
Newer Older
1
defmodule Pleroma.Web.Federator do
lain's avatar
lain committed
2
  use GenServer
3
  alias Pleroma.User
lain's avatar
lain committed
4
  alias Pleroma.Activity
lain's avatar
lain committed
5
  alias Pleroma.Web.{WebFinger, Websub}
6
  alias Pleroma.Web.ActivityPub.ActivityPub
lain's avatar
lain committed
7
  alias Pleroma.Web.ActivityPub.Transmogrifier
8 9
  require Logger

lain's avatar
lain committed
10
  @websub Application.get_env(:pleroma, :websub)
11
  @ostatus Application.get_env(:pleroma, :ostatus)
lain's avatar
lain committed
12
  @httpoison Application.get_env(:pleroma, :httpoison)
lain's avatar
lain committed
13 14 15
  @max_jobs 10

  def start_link do
lain's avatar
lain committed
16
    spawn(fn ->
lain's avatar
lain committed
17
      Process.sleep(1000 * 60 * 1) # 1 minute
lain's avatar
lain committed
18 19
      enqueue(:refresh_subscriptions, nil)
    end)
20
    GenServer.start_link(__MODULE__, %{
lain's avatar
lain committed
21
          in: {:sets.new(), []},
lain's avatar
lain committed
22
          out: {:sets.new(), []}
23
                         }, name: __MODULE__)
lain's avatar
lain committed
24
  end
25

lain's avatar
lain committed
26 27 28 29
  def handle(:refresh_subscriptions, _) do
    Logger.debug("Federator running refresh subscriptions")
    Websub.refresh_subscriptions()
    spawn(fn ->
lain's avatar
lain committed
30
      Process.sleep(1000 * 60 * 60 * 6) # 6 hours
lain's avatar
lain committed
31 32 33 34
      enqueue(:refresh_subscriptions, nil)
    end)
  end

lain's avatar
lain committed
35 36 37 38 39 40 41 42 43
  def handle(:request_subscription, websub) do
    Logger.debug("Refreshing #{websub.topic}")
    with {:ok, websub } <- Websub.request_subscription(websub) do
      Logger.debug("Successfully refreshed #{websub.topic}")
    else
      _e -> Logger.debug("Couldn't refresh #{websub.topic}")
    end
  end

44
  def handle(:publish, activity) do
lain's avatar
lain committed
45
    Logger.debug(fn -> "Running publish for #{activity.data["id"]}" end)
46
    with actor when not is_nil(actor) <- User.get_cached_by_ap_id(activity.data["actor"]) do
lain's avatar
lain committed
47
      {:ok, actor} = WebFinger.ensure_keys_present(actor)
48
      if ActivityPub.is_public?(activity) do
lain's avatar
lain committed
49
        Logger.info(fn -> "Sending #{activity.data["id"]} out via websub" end)
50
        Websub.publish(Pleroma.Web.OStatus.feed_path(actor), actor, activity)
51

52 53 54
        Logger.info(fn -> "Sending #{activity.data["id"]} out via salmon" end)
        Pleroma.Web.Salmon.publish(actor, activity)
      end
lain's avatar
lain committed
55 56

      Logger.info(fn -> "Sending #{activity.data["id"]} out via AP" end)
57
      Pleroma.Web.ActivityPub.ActivityPub.publish(actor, activity)
58 59 60 61
    end
  end

  def handle(:verify_websub, websub) do
lain's avatar
lain committed
62
    Logger.debug(fn -> "Running websub verification for #{websub.id} (#{websub.topic}, #{websub.callback})" end)
lain's avatar
lain committed
63
    @websub.verify(websub)
64 65
  end

66 67 68 69 70
  def handle(:incoming_doc, doc) do
    Logger.debug("Got document, trying to parse")
    @ostatus.handle_incoming(doc)
  end

lain's avatar
lain committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84
  def handle(:incoming_ap_doc, params) do
    with {:ok, _user} <- ap_enabled_actor(params["actor"]),
         nil <- Activity.get_by_ap_id(params["id"]),
         {:ok, activity} <- Transmogrifier.handle_incoming(params) do
    else
      %Activity{} ->
        Logger.info("Already had #{params["id"]}")
      e ->
        # Just drop those for now
        Logger.info("Unhandled activity")
        Logger.info(Poison.encode!(params, [pretty: 2]))
    end
  end

lain's avatar
lain committed
85 86 87 88
  def handle(:publish_single_ap, params) do
    ActivityPub.publish_one(params)
  end

lain's avatar
lain committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102
  def handle(:publish_single_websub, %{xml: xml, topic: topic, callback: callback, secret: secret}) do
    signature = @websub.sign(secret || "", xml)
    Logger.debug(fn -> "Pushing #{topic} to #{callback}" end)

    with {:ok, %{status_code: code}} <- @httpoison.post(callback, xml, [
                  {"Content-Type", "application/atom+xml"},
                  {"X-Hub-Signature", "sha1=#{signature}"}
                ], timeout: 10000, recv_timeout: 20000) do
      Logger.debug(fn -> "Pushed to #{callback}, code #{code}" end)
    else e ->
        Logger.debug(fn -> "Couldn't push to #{callback}, #{inspect(e)}" end)
    end
  end

Thog's avatar
Thog committed
103
  def handle(type, _) do
lain's avatar
lain committed
104
    Logger.debug(fn -> "Unknown task: #{type}" end)
105 106 107
    {:error, "Don't know what do do with this"}
  end

lain's avatar
lain committed
108
  def enqueue(type, payload, priority \\ 1) do
109 110 111
    if Mix.env == :test do
      handle(type, payload)
    else
lain's avatar
lain committed
112
      GenServer.cast(__MODULE__, {:enqueue, type, payload, priority})
lain's avatar
lain committed
113 114 115 116
    end
  end

  def maybe_start_job(running_jobs, queue) do
lain's avatar
lain committed
117
    if (:sets.size(running_jobs) < @max_jobs) && queue != [] do
lain's avatar
lain committed
118
      {{type, payload}, queue} = queue_pop(queue)
lain's avatar
lain committed
119 120 121 122 123
      {:ok, pid} = Task.start(fn -> handle(type, payload) end)
      mref = Process.monitor(pid)
      {:sets.add_element(mref, running_jobs), queue}
    else
      {running_jobs, queue}
124 125
    end
  end
lain's avatar
lain committed
126

lain's avatar
lain committed
127
  def handle_cast({:enqueue, type, payload, priority}, state) when type in [:incoming_doc] do
128
    %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
lain's avatar
lain committed
129
    i_queue = enqueue_sorted(i_queue, {type, payload}, 1)
130 131 132 133
    {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
    {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
  end

lain's avatar
lain committed
134
  def handle_cast({:enqueue, type, payload, priority}, state) do
135
    %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
lain's avatar
lain committed
136
    o_queue = enqueue_sorted(o_queue, {type, payload}, 1)
137 138
    {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)
    {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
lain's avatar
lain committed
139 140
  end

Thog's avatar
Thog committed
141 142 143 144 145
  def handle_cast(m, state) do
    IO.inspect("Unknown: #{inspect(m)}, #{inspect(state)}")
    {:noreply, state}
  end

146 147 148 149 150 151 152 153
  def handle_info({:DOWN, ref, :process, _pid, _reason}, state) do
    %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}} = state
    i_running_jobs = :sets.del_element(ref, i_running_jobs)
    o_running_jobs = :sets.del_element(ref, o_running_jobs)
    {i_running_jobs, i_queue} = maybe_start_job(i_running_jobs, i_queue)
    {o_running_jobs, o_queue} = maybe_start_job(o_running_jobs, o_queue)

    {:noreply, %{in: {i_running_jobs, i_queue}, out: {o_running_jobs, o_queue}}}
lain's avatar
lain committed
154
  end
lain's avatar
lain committed
155 156 157 158 159 160 161 162 163

  def enqueue_sorted(queue, element, priority) do
    [%{item: element, priority: priority} | queue]
    |> Enum.sort_by(fn (%{priority: priority}) -> priority end)
  end

  def queue_pop([%{item: element} | queue]) do
    {element, queue}
  end
lain's avatar
lain committed
164 165 166 167 168 169 170 171 172

  def ap_enabled_actor(id) do
    user = User.get_by_ap_id(id)
    if User.ap_enabled?(user) do
      {:ok, user}
    else
      ActivityPub.make_user_from_ap_id(id)
    end
  end
173
end