twitter_api.ex 9.96 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
lain's avatar
lain committed
4
  alias Pleroma.Web.TwitterAPI.Representers.{ActivityRepresenter, UserRepresenter}
lain's avatar
lain committed
5

6
7
  import Ecto.Query

lain's avatar
lain committed
8
  def to_for_user_and_mentions(user, mentions) do
9
10
11
12
13
    default_to = [
      User.ap_followers(user),
      "https://www.w3.org/ns/activitystreams#Public"
    ]

lain's avatar
lain committed
14
    default_to ++ Enum.map(mentions, fn ({_, %{ap_id: ap_id}}) -> ap_id end)
lain's avatar
lain committed
15
16
17
  end

  def format_input(text, mentions) do
lain's avatar
lain committed
18
    HtmlSanitizeEx.strip_tags(text)
lain's avatar
lain committed
19
20
21
    |> String.replace("\n", "<br>")
    |> add_user_links(mentions)
  end
22

lain's avatar
lain committed
23
24
25
26
27
28
  def attachments_from_ids(ids) do
    Enum.map(ids || [], fn (media_id) ->
      Repo.get(Object, media_id).data
    end)
  end

lain's avatar
lain committed
29
30
31
32
33
34
  def get_replied_to_activity(id) when not is_nil(id) do
    Repo.get(Activity, id)
  end

  def get_replied_to_activity(_), do: nil

lain's avatar
lain committed
35
36
37
38
39
40
  def create_status(user = %User{}, data = %{"status" => status}) do
    attachments = attachments_from_ids(data["media_ids"])
    context = ActivityPub.generate_context_id
    mentions = parse_mentions(status)
    content_html = format_input(status, mentions)
    to = to_for_user_and_mentions(user, mentions)
41
    date = make_date()
42

lain's avatar
lain committed
43
44
    inReplyTo = get_replied_to_activity(data["in_reply_to_status_id"])

45
46
    # Wire up reply info.
    [to, context, object, additional] =
lain's avatar
lain committed
47
48
      if inReplyTo do
      context = inReplyTo.data["context"]
49
50
51
52
53
54
55
56
57
58
59
      to = to ++ [inReplyTo.data["actor"]]

      object = %{
        "type" => "Note",
        "to" => to,
        "content" => content_html,
        "published" => date,
        "context" => context,
        "attachment" => attachments,
        "actor" => user.ap_id,
        "inReplyTo" => inReplyTo.data["object"]["id"],
lain's avatar
lain committed
60
        "inReplyToStatusId" => inReplyTo.id,
61
      }
62
      additional = %{}
63
64

      [to, context, object, additional]
lain's avatar
lain committed
65
      else
66
      object = %{
lain's avatar
lain committed
67
        "type" => "Note",
68
69
        "to" => to,
        "content" => content_html,
70
        "published" => date,
71
        "context" => context,
lain's avatar
lain committed
72
73
        "attachment" => attachments,
        "actor" => user.ap_id
74
75
      }
      [to, context, object, %{}]
lain's avatar
lain committed
76
    end
77
78

    ActivityPub.create(to, user, context, object, additional, data)
lain's avatar
lain committed
79
80
  end

lain's avatar
lain committed
81
  def fetch_friend_statuses(user, opts \\ %{}) do
82
    ActivityPub.fetch_activities([user.ap_id | user.following], opts)
83
    |> activities_to_statuses(%{for: user})
lain's avatar
lain committed
84
85
  end

86
  def fetch_public_statuses(user, opts \\ %{}) do
lain's avatar
lain committed
87
    ActivityPub.fetch_public_activities(opts)
88
    |> activities_to_statuses(%{for: user})
lain's avatar
lain committed
89
  end
lain's avatar
lain committed
90

dtluna's avatar
dtluna committed
91
  def fetch_user_statuses(user, opts \\ %{}) do
92
    ActivityPub.fetch_activities([], opts)
dtluna's avatar
dtluna committed
93
94
95
    |> activities_to_statuses(%{for: user})
  end

dtluna's avatar
dtluna committed
96
97
98
99
100
  def fetch_mentions(user, opts \\ %{}) do
    ActivityPub.fetch_activities([user.ap_id], opts)
    |> activities_to_statuses(%{for: user})
  end

101
  def fetch_conversation(user, id) do
102
    with context when is_binary(context) <- conversation_id_to_context(id),
103
104
105
106
107
         activities <- ActivityPub.fetch_activities_for_context(context),
         statuses <- activities |> activities_to_statuses(%{for: user})
    do
      statuses
    else e ->
108
      IO.inspect(e)
109
110
111
112
113
114
115
116
117
118
      []
    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
119
  def follow(%User{} = follower, params) do
120
    with { :ok, %User{} = followed } <- get_user(params),
dtluna's avatar
dtluna committed
121
122
123
124
         { :ok, follower } <- User.follow(follower, followed),
         { :ok, activity } <- ActivityPub.insert(%{
           "type" => "Follow",
           "actor" => follower.ap_id,
dtluna's avatar
dtluna committed
125
           "object" => followed.ap_id,
126
           "published" => make_date()
dtluna's avatar
dtluna committed
127
         })
lain's avatar
lain committed
128
    do
dtluna's avatar
dtluna committed
129
      { :ok, follower, followed, activity }
130
131
    else
      err -> err
lain's avatar
lain committed
132
133
134
    end
  end

dtluna's avatar
dtluna committed
135
136
137
  def unfollow(%User{} = follower, params) do
    with { :ok, %User{} = unfollowed } <- get_user(params),
         { :ok, follower } <- User.unfollow(follower, unfollowed)
lain's avatar
lain committed
138
    do
dtluna's avatar
dtluna committed
139
      { :ok, follower, unfollowed}
140
141
    else
      err -> err
lain's avatar
lain committed
142
143
144
    end
  end

lain's avatar
lain committed
145
146
147
148
149
150
151
152
153
154
155
156
157
  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
158
159
160
161
162
163
164
165
166
167
168
169
170
  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
171
172
173
174
175
176
177
178
179
180
181
182
183
  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

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

lain's avatar
lain committed
187
188
189
190
    url = List.first(object.data["url"])
    href = url["href"]
    type = url["mediaType"]

191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
    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
213
214
  end

215
216
217
218
219
220
221
  def parse_mentions(text) do
    # Modified from https://www.w3.org/TR/html5/forms.html#valid-e-mail-address
    regex = ~r/@[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@?[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*/

    Regex.scan(regex, text)
    |> List.flatten
    |> Enum.uniq
lain's avatar
lain committed
222
    |> Enum.map(fn ("@" <> match = full_match) -> {full_match, User.get_cached_by_nickname(match)} end)
223
224
225
226
227
228
229
    |> Enum.filter(fn ({_match, user}) -> user end)
  end

  def add_user_links(text, mentions) do
    Enum.reduce(mentions, text, fn ({match, %User{ap_id: ap_id}}, text) -> String.replace(text, match, "<a href='#{ap_id}'>#{match}</a>") end)
  end

lain's avatar
lain committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
  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
      {:ok, UserRepresenter.to_map(user)}
    else
      {:error, changeset} ->
246
247
        errors = Ecto.Changeset.traverse_errors(changeset, fn {msg, _opts} -> msg end)
      |> Poison.encode!
lain's avatar
lain committed
248
      {:error, %{error: errors}}
lain's avatar
lain committed
249
250
251
    end
  end

252
  def get_user(user \\ nil, params) do
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    case params do
      %{ "user_id" => user_id } ->
        case target = Repo.get(User, user_id) do
          nil ->
            {:error, "No user with such user_id"}
          _ ->
            {:ok, target}
        end
      %{ "screen_name" => nickname } ->
        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
272
          {:error, "You need to specify screen_name or user_id"}
273
274
275
276
        end
    end
  end

277
  defp activities_to_statuses(activities, opts) do
lain's avatar
lain committed
278
    Enum.map(activities, fn(activity) ->
lain's avatar
lain committed
279
      activity_to_status(activity, opts)
lain's avatar
lain committed
280
281
    end)
  end
lain's avatar
lain committed
282

lain's avatar
lain committed
283
284
285
  # 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
286
    user = User.get_cached_by_ap_id(actor)
lain's avatar
lain committed
287
288
289
290
291
    [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
292
293
294
295
296
297
298
299
300
301
  # 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

lain's avatar
lain committed
302
303
  defp activity_to_status(activity, opts) do
    actor = get_in(activity.data, ["actor"])
lain's avatar
lain committed
304
305
    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
306
    mentioned_users = Enum.map(activity.data["to"] || [], fn (ap_id) ->
lain's avatar
lain committed
307
308
309
310
      User.get_cached_by_ap_id(ap_id)
    end)
    |> Enum.filter(&(&1))

311
    ActivityRepresenter.to_map(activity, Map.merge(opts, %{user: user, mentioned: mentioned_users}))
lain's avatar
lain committed
312
  end
dtluna's avatar
dtluna committed
313
314
315
316

  defp make_date do
    DateTime.utc_now() |> DateTime.to_iso8601
  end
317
318

  def context_to_conversation_id(context) do
lain's avatar
lain committed
319
320
321
322
323
324
325
326
327
328
    {:ok, id} = Repo.transaction(fn ->
      with %Object{id: id} <- Object.get_by_ap_id(context) do
        id
      else _e ->
        changeset = Object.context_mapping(context)
        {:ok, %{id: id}} = Repo.insert(changeset)
        id
      end
    end)
    id
329
330
331
332
333
334
335
336
337
  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
338
end