twitter_api.ex 10.1 KB
Newer Older
lain's avatar
lain committed
1
defmodule Pleroma.Web.TwitterAPI.TwitterAPI do
lain's avatar
lain committed
2
  alias Pleroma.{User, Activity, Repo, Object}
lain's avatar
lain committed
3
  alias Pleroma.Web.ActivityPub.ActivityPub
dtluna's avatar
dtluna committed
4
5
  alias Pleroma.Web.TwitterAPI.Representers.ActivityRepresenter
  alias Pleroma.Web.TwitterAPI.UserView
6
  alias Pleroma.Web.OStatus
lain's avatar
lain committed
7
  alias Pleroma.Formatter
lain's avatar
lain committed
8

lain's avatar
lain committed
9
  import Pleroma.Web.TwitterAPI.Utils
10

11
12
  @httpoison Application.get_env(:pleroma, :httpoison)

lain's avatar
lain committed
13
  def to_for_user_and_mentions(user, mentions, inReplyTo) do
14
    default_to = [
lain's avatar
lain committed
15
      user.follower_address,
16
17
      "https://www.w3.org/ns/activitystreams#Public"
    ]
lain's avatar
lain committed
18

lain's avatar
lain committed
19
20
21
22
23
24
    to = default_to ++ Enum.map(mentions, fn ({_, %{ap_id: ap_id}}) -> ap_id end)
    if inReplyTo do
      Enum.uniq([inReplyTo.data["actor"] | to])
    else
      to
    end
lain's avatar
lain committed
25
  end
26

lain's avatar
lain committed
27
28
29
  def get_replied_to_activity(id) when not is_nil(id) do
    Repo.get(Activity, id)
  end
30

lain's avatar
lain committed
31
  def get_replied_to_activity(_), do: nil
32

lain's avatar
lain committed
33
  def create_status(%User{} = user, %{"status" => status} = data) do
lain's avatar
lain committed
34
    with attachments <- attachments_from_ids(data["media_ids"]),
35
         mentions <- Formatter.parse_mentions(status),
lain's avatar
lain committed
36
37
38
39
         inReplyTo <- get_replied_to_activity(data["in_reply_to_status_id"]),
         to <- to_for_user_and_mentions(user, mentions, inReplyTo),
         content_html <- make_content_html(status, mentions, attachments),
         context <- make_context(inReplyTo),
lain's avatar
lain committed
40
41
         tags <- Formatter.parse_tags(status),
         object <- make_note_data(user.ap_id, to, context, content_html, attachments, inReplyTo, tags) do
42
43
44
      res = ActivityPub.create(to, user, context, object)
      User.update_note_count(user)
      res
lain's avatar
lain committed
45
    end
lain's avatar
lain committed
46
47
  end

lain's avatar
lain committed
48
  def fetch_friend_statuses(user, opts \\ %{}) do
49
    ActivityPub.fetch_activities([user.ap_id | user.following], opts)
50
    |> activities_to_statuses(%{for: user})
lain's avatar
lain committed
51
52
  end

53
  def fetch_public_statuses(user, opts \\ %{}) do
lain's avatar
lain committed
54
55
56
57
58
59
    opts = Map.put(opts, "local_only", true)
    ActivityPub.fetch_public_activities(opts)
    |> activities_to_statuses(%{for: user})
  end

  def fetch_public_and_external_statuses(user, opts \\ %{}) do
lain's avatar
lain committed
60
    ActivityPub.fetch_public_activities(opts)
61
    |> activities_to_statuses(%{for: user})
lain's avatar
lain committed
62
  end
lain's avatar
lain committed
63

dtluna's avatar
dtluna committed
64
  def fetch_user_statuses(user, opts \\ %{}) do
65
    ActivityPub.fetch_activities([], opts)
dtluna's avatar
dtluna committed
66
67
68
    |> activities_to_statuses(%{for: user})
  end

dtluna's avatar
dtluna committed
69
70
71
72
73
  def fetch_mentions(user, opts \\ %{}) do
    ActivityPub.fetch_activities([user.ap_id], opts)
    |> activities_to_statuses(%{for: user})
  end

74
  def fetch_conversation(user, id) do
75
    with context when is_binary(context) <- conversation_id_to_context(id),
76
77
78
79
         activities <- ActivityPub.fetch_activities_for_context(context),
         statuses <- activities |> activities_to_statuses(%{for: user})
    do
      statuses
lain's avatar
lain committed
80
    else _e ->
81
82
83
84
85
86
87
88
89
90
      []
    end
  end

  def fetch_status(user, id) do
    with %Activity{} = activity <- Repo.get(Activity, id) do
      activity_to_status(activity, %{for: user})
    end
  end

dtluna's avatar
dtluna committed
91
  def follow(%User{} = follower, params) do
lain's avatar
lain committed
92
93
    with {:ok, %User{} = followed} <- get_user(params),
         {:ok, follower} <- User.follow(follower, followed),
94
         {:ok, activity} <- ActivityPub.follow(follower, followed)
lain's avatar
lain committed
95
    do
lain's avatar
lain committed
96
      {:ok, follower, followed, activity}
97
98
    else
      err -> err
lain's avatar
lain committed
99
100
101
    end
  end

dtluna's avatar
dtluna committed
102
103
  def unfollow(%User{} = follower, params) do
    with { :ok, %User{} = unfollowed } <- get_user(params),
dtluna's avatar
dtluna committed
104
105
106
107
         { :ok, follower, follow_activity } <- User.unfollow(follower, unfollowed),
         { :ok, _activity } <- ActivityPub.insert(%{
           "type" => "Undo",
           "actor" => follower.ap_id,
108
           "object" => follow_activity.data["id"], # get latest Follow for these users
dtluna's avatar
dtluna committed
109
110
           "published" => make_date()
         })
lain's avatar
lain committed
111
    do
dtluna's avatar
dtluna committed
112
      { :ok, follower, unfollowed }
113
114
    else
      err -> err
lain's avatar
lain committed
115
116
117
    end
  end

lain's avatar
lain committed
118
119
120
121
122
123
124
125
126
127
128
129
130
  def favorite(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
    object = Object.get_by_ap_id(object["id"])

    {:ok, _like_activity, object} = ActivityPub.like(user, object)
    new_data = activity.data
    |> Map.put("object", object.data)

    status = %{activity | data: new_data}
    |> activity_to_status(%{for: user})

    {:ok, status}
  end

lain's avatar
lain committed
131
132
133
134
135
136
137
138
139
140
141
142
143
  def unfavorite(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
    object = Object.get_by_ap_id(object["id"])

    {:ok, object} = ActivityPub.unlike(user, object)
    new_data = activity.data
    |> Map.put("object", object.data)

    status = %{activity | data: new_data}
    |> activity_to_status(%{for: user})

    {:ok, status}
  end

lain's avatar
lain committed
144
145
146
147
148
149
150
151
152
153
154
155
156
  def retweet(%User{} = user, %Activity{data: %{"object" => object}} = activity) do
    object = Object.get_by_ap_id(object["id"])

    {:ok, _announce_activity, object} = ActivityPub.announce(user, object)
    new_data = activity.data
    |> Map.put("object", object.data)

    status = %{activity | data: new_data}
    |> activity_to_status(%{for: user})

    {:ok, status}
  end

157
  def upload(%Plug.Upload{} = file, format \\ "xml") do
lain's avatar
lain committed
158
159
    {:ok, object} = ActivityPub.upload(file)

lain's avatar
lain committed
160
161
162
163
    url = List.first(object.data["url"])
    href = url["href"]
    type = url["mediaType"]

164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
    case format do
      "xml" ->
        # Fake this as good as possible...
        """
        <?xml version="1.0" encoding="UTF-8"?>
        <rsp stat="ok" xmlns:atom="http://www.w3.org/2005/Atom">
        <mediaid>#{object.id}</mediaid>
        <media_id>#{object.id}</media_id>
        <media_id_string>#{object.id}</media_id_string>
        <media_url>#{href}</media_url>
        <mediaurl>#{href}</mediaurl>
        <atom:link rel="enclosure" href="#{href}" type="#{type}"></atom:link>
        </rsp>
        """
      "json" ->
        %{
          media_id: object.id,
          media_id_string: "#{object.id}}",
          media_url: href,
          size: 0
        } |> Poison.encode!
    end
lain's avatar
lain committed
186
187
  end

lain's avatar
lain committed
188
189
190
191
192
193
194
195
196
197
198
199
200
  def register_user(params) do
    params = %{
      nickname: params["nickname"],
      name: params["fullname"],
      bio: params["bio"],
      email: params["email"],
      password: params["password"],
      password_confirmation: params["confirm"]
    }

    changeset = User.register_changeset(%User{}, params)

    with {:ok, user} <- Repo.insert(changeset) do
dtluna's avatar
dtluna committed
201
      {:ok, user}
lain's avatar
lain committed
202
203
    else
      {:error, changeset} ->
204
205
        errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
      |> Poison.encode!
lain's avatar
lain committed
206
      {:error, %{error: errors}}
lain's avatar
lain committed
207
208
209
    end
  end

lain's avatar
lain committed
210
211
212
213
214
215
216
217
  def get_by_id_or_nickname(id_or_nickname) do
    if !is_integer(id_or_nickname) && :error == Integer.parse(id_or_nickname) do
      Repo.get_by(User, nickname: id_or_nickname)
    else
      Repo.get(User, id_or_nickname)
    end
  end

218
  def get_user(user \\ nil, params) do
219
    case params do
lain's avatar
lain committed
220
      %{"user_id" => user_id} ->
lain's avatar
lain committed
221
        case target = get_by_id_or_nickname(user_id) do
222
223
224
225
226
          nil ->
            {:error, "No user with such user_id"}
          _ ->
            {:ok, target}
        end
lain's avatar
lain committed
227
      %{"screen_name" => nickname} ->
228
229
230
231
232
233
234
235
236
237
        case target = Repo.get_by(User, nickname: nickname) do
          nil ->
            {:error, "No user with such screen_name"}
          _ ->
            {:ok, target}
        end
      _ ->
        if user do
          {:ok, user}
        else
dtluna's avatar
dtluna committed
238
          {:error, "You need to specify screen_name or user_id"}
239
240
241
242
        end
    end
  end

243
  defp activities_to_statuses(activities, opts) do
lain's avatar
lain committed
244
    Enum.map(activities, fn(activity) ->
lain's avatar
lain committed
245
      activity_to_status(activity, opts)
lain's avatar
lain committed
246
247
    end)
  end
lain's avatar
lain committed
248

lain's avatar
lain committed
249
250
251
  # For likes, fetch the liked activity, too.
  defp activity_to_status(%Activity{data: %{"type" => "Like"}} = activity, opts) do
    actor = get_in(activity.data, ["actor"])
lain's avatar
lain committed
252
    user = User.get_cached_by_ap_id(actor)
lain's avatar
lain committed
253
254
255
256
257
    [liked_activity] = Activity.all_by_object_ap_id(activity.data["object"])

    ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, liked_activity: liked_activity}))
  end

lain's avatar
lain committed
258
259
260
261
262
263
264
265
266
267
  # For announces, fetch the announced activity and the user.
  defp activity_to_status(%Activity{data: %{"type" => "Announce"}} = activity, opts) do
    actor = get_in(activity.data, ["actor"])
    user = User.get_cached_by_ap_id(actor)
    [announced_activity] = Activity.all_by_object_ap_id(activity.data["object"])
    announced_actor = User.get_cached_by_ap_id(announced_activity.data["actor"])

    ActivityRepresenter.to_map(activity, Map.merge(opts, %{users: [user, announced_actor], announced_activity: announced_activity}))
  end

268
269
270
271
272
273
  defp activity_to_status(%Activity{data: %{"type" => "Delete"}} = activity, opts) do
    actor = get_in(activity.data, ["actor"])
    user = User.get_cached_by_ap_id(actor)
    ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user}))
  end

lain's avatar
lain committed
274
275
  defp activity_to_status(activity, opts) do
    actor = get_in(activity.data, ["actor"])
lain's avatar
lain committed
276
277
    user = User.get_cached_by_ap_id(actor)
    # mentioned_users = Repo.all(from user in User, where: user.ap_id in ^activity.data["to"])
lain's avatar
lain committed
278
    mentioned_users = Enum.map(activity.data["to"] || [], fn (ap_id) ->
lain's avatar
lain committed
279
280
281
282
283
      if ap_id do
        User.get_cached_by_ap_id(ap_id)
      else
        nil
      end
lain's avatar
lain committed
284
285
286
    end)
    |> Enum.filter(&(&1))

287
    ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, mentioned: mentioned_users}))
lain's avatar
lain committed
288
  end
dtluna's avatar
dtluna committed
289
290
291
292

  defp make_date do
    DateTime.utc_now() |> DateTime.to_iso8601
  end
293
294

  def context_to_conversation_id(context) do
lain's avatar
lain committed
295
296
    with %Object{id: id} <- Object.get_cached_by_ap_id(context) do
      id
297
298
299
300
301
302
303
304
      else _e ->
        changeset = Object.context_mapping(context)
        case Repo.insert(changeset) do
          {:ok, %{id: id}} -> id
          # This should be solved by an upsert, but it seems ecto
          # has problems accessing the constraint inside the jsonb.
          {:error, _} -> Object.get_cached_by_ap_id(context).id
        end
lain's avatar
lain committed
305
    end
306
307
308
309
310
311
312
313
314
  end

  def conversation_id_to_context(id) do
    with %Object{data: %{"id" => context}} <- Repo.get(Object, id) do
      context
    else _e ->
      {:error, "No such conversation"}
    end
  end
lain's avatar
lain committed
315
316

  def get_external_profile(for_user, uri) do
317
    with {:ok, %User{} = user} <- OStatus.find_or_make_user(uri) do
318
319
320
321
      with url <- user.info["topic"],
           {:ok, %{body: body}} <- @httpoison.get(url, [], follow_redirect: true, timeout: 10000, recv_timeout: 20000) do
        OStatus.handle_incoming(body)
      end
dtluna's avatar
dtluna committed
322
      {:ok, UserView.render("show.json", %{user: user, for: for_user})}
lain's avatar
lain committed
323
    else _e ->
324
        {:error, "Couldn't find user"}
lain's avatar
lain committed
325
326
    end
  end
lain's avatar
lain committed
327
end