Merge remote-tracking branch 'origin/develop' into reactions
authorlain <lain@soykaf.club>
Mon, 30 Sep 2019 11:57:54 +0000 (13:57 +0200)
committerlain <lain@soykaf.club>
Mon, 30 Sep 2019 11:57:54 +0000 (13:57 +0200)
13 files changed:
1  2 
docs/api/pleroma_api.md
lib/pleroma/constants.ex
lib/pleroma/emoji.ex
lib/pleroma/web/activity_pub/activity_pub.ex
lib/pleroma/web/activity_pub/transmogrifier.ex
lib/pleroma/web/activity_pub/utils.ex
lib/pleroma/web/common_api/common_api.ex
lib/pleroma/web/pleroma_api/controllers/pleroma_api_controller.ex
lib/pleroma/web/router.ex
test/emoji_test.exs
test/web/activity_pub/activity_pub_test.exs
test/web/activity_pub/transmogrifier_test.exs
test/web/common_api/common_api_test.exs

index 3f12e38b9509e72b35c49fddf8d6a2a4cb4a285d,41889a0efa88f0c36d3a4feb8c24a39dda5e9fe0..7862e6301d61ca780d45446579a023a8375ecce0
@@@ -366,27 -366,108 +366,133 @@@ The status posting endpoint takes an ad
      * `recipients`: A list of ids of users that should receive posts to this conversation. This will replace the current list of recipients, so submit the full list. The owner of owner of the conversation will always be part of the set of recipients, though.
  * Response: JSON, statuses (200 - healthy, 503 unhealthy)
  
+ ## `GET /api/pleroma/emoji/packs`
+ ### Lists the custom emoji packs on the server
+ * Method `GET`
+ * Authentication: not required
+ * Params: None
+ * Response: JSON, "ok" and 200 status and the JSON hashmap of "pack name" to "pack contents"
+ ## `PUT /api/pleroma/emoji/packs/:name`
+ ### Creates an empty custom emoji pack
+ * Method `PUT`
+ * Authentication: required
+ * Params: None
+ * Response: JSON, "ok" and 200 status or 409 if the pack with that name already exists
+ ## `DELETE /api/pleroma/emoji/packs/:name`
+ ### Delete a custom emoji pack
+ * Method `DELETE`
+ * Authentication: required
+ * Params: None
+ * Response: JSON, "ok" and 200 status or 500 if there was an error deleting the pack
+ ## `POST /api/pleroma/emoji/packs/:name/update_file`
+ ### Update a file in a custom emoji pack
+ * Method `POST`
+ * Authentication: required
+ * Params: 
+     * if the `action` is `add`, adds an emoji named `shortcode` to the pack `pack_name`,
+       that means that the emoji file needs to be uploaded with the request
+       (thus requiring it to be a multipart request) and be named `file`.
+       There can also be an optional `filename` that will be the new emoji file name
+       (if it's not there, the name will be taken from the uploaded file).
+     * if the `action` is `update`, changes emoji shortcode
+       (from `shortcode` to `new_shortcode` or moves the file (from the current filename to `new_filename`)
+     * if the `action` is `remove`, removes the emoji named `shortcode` and it's associated file
+ * Response: JSON, updated "files" section of the pack and 200 status, 409 if the trying to use a shortcode
+   that is already taken, 400 if there was an error with the shortcode, filename or file (additional info
+   in the "error" part of the response JSON)
+ ## `POST /api/pleroma/emoji/packs/:name/update_metadata`
+ ### Updates (replaces) pack metadata
+ * Method `POST`
+ * Authentication: required
+ * Params: 
+   * `new_data`: new metadata to replace the old one
+ * Response: JSON, updated "metadata" section of the pack and 200 status or 400 if there was a
+   problem with the new metadata (the error is specified in the "error" part of the response JSON)
+ ## `POST /api/pleroma/emoji/packs/download_from`
+ ### Requests the instance to download the pack from another instance
+ * Method `POST`
+ * Authentication: required
+ * Params: 
+   * `instance_address`: the address of the instance to download from
+   * `pack_name`: the pack to download from that instance
+ * Response: JSON, "ok" and 200 status if the pack was downloaded, or 500 if there were
+   errors downloading the pack
+ ## `POST /api/pleroma/emoji/packs/list_from`
+ ### Requests the instance to list the packs from another instance
+ * Method `POST`
+ * Authentication: required
+ * Params:
+   * `instance_address`: the address of the instance to download from
+ * Response: JSON with the pack list, same as if the request was made to that instance's
+   list endpoint directly + 200 status
+ ## `GET /api/pleroma/emoji/packs/:name/download_shared`
+ ### Requests a local pack from the instance
+ * Method `GET`
+ * Authentication: not required
+ * Params: None
+ * Response: the archive of the pack with a 200 status code, 403 if the pack is not set as shared,
+   404 if the pack does not exist
+ ## `GET /api/v1/pleroma/accounts/:id/scrobbles`
+ ### Requests a list of current and recent Listen activities for an account
+ * Method `GET`
+ * Authentication: not required
+ * Params: None
+ * Response: An array of media metadata entities.
+ * Example response:
+ ```json
+ [
+    {
+        "account": {...},
+        "id": "1234",
+        "title": "Some Title",
+        "artist": "Some Artist",
+        "album": "Some Album",
+        "length": 180000,
+        "created_at": "2019-09-28T12:40:45.000Z"
+    }
+ ]
+ ```
+ ## `POST /api/v1/pleroma/scrobble`
+ ### Creates a new Listen activity for an account
+ * Method `POST`
+ * Authentication: required
+ * Params:
+   * `title`: the title of the media playing
+   * `album`: the album of the media playing [optional]
+   * `artist`: the artist of the media playing [optional]
+   * `length`: the length of the media playing [optional]
+ * Response: the newly created media metadata entity representing the Listen activity
++
 +# Emoji Reactions
 +
 +Emoji reactions work a lot like favourites do. They make it possible to react to a post with a single emoji character.
 +
 +## `POST /api/v1/pleroma/statuses/:id/react_with_emoji`
 +### React to a post with a unicode emoji
 +* Method: `POST`
 +* Authentication: required
 +* Params: `emoji`: A single character unicode emoji
 +* Response: JSON, the status.
 +
 +## `GET /api/v1/pleroma/statuses/:id/emoji_reactions_by`
 +### Get an object of emoji to account mappings with accounts that reacted to the post
 +* Method: `GET`
 +* Authentication: optional
 +* Params: None
 +* Response: JSON, a map of emoji to account list mappings.
 +* Example Response:
 +```json
 +{
 +  "😀" => [{"id" => "xyz.."...}, {"id" => "zyx..."}],
 +  "🗡" => [{"id" => "abc..."}] 
 +}
 +```
index ef14185435273507e5e699d959646bfb11fa99b2,0bf20cdd0ecb8b384b93b194ed3d73d043e2fbb6..7d775c3c2669af493532e080c331a974c6ee0234
@@@ -6,4 -6,16 +6,18 @@@ defmodule Pleroma.Constants d
    use Const
  
    const(as_public, do: "https://www.w3.org/ns/activitystreams#Public")
+   const(object_internal_fields,
+     do: [
++      "reactions",
++      "reactions_count",
+       "likes",
+       "like_count",
+       "announcements",
+       "announcement_count",
+       "emoji",
+       "context_id",
+       "deleted_activity_id"
+     ]
+   )
  end
index 65f2d5f390113e759723fe49797c2a9eae1dbc17,bafad2ae9fa915a947ed24fae8cf2f8c57e6e3a2..abfd49aaae4f4dfab340722a7f51273bbc4228f9
@@@ -79,216 -95,7 +95,38 @@@ defmodule Pleroma.Emoji d
      {:ok, state}
    end
  
-   defp load do
-     emoji_dir_path =
-       Path.join(
-         Pleroma.Config.get!([:instance, :static_dir]),
-         "emoji"
-       )
-     emoji_groups = Pleroma.Config.get([:emoji, :groups])
-     case File.ls(emoji_dir_path) do
-       {:error, :enoent} ->
-         # The custom emoji directory doesn't exist,
-         # don't do anything
-         nil
-       {:error, e} ->
-         # There was some other error
-         Logger.error("Could not access the custom emoji directory #{emoji_dir_path}: #{e}")
-       {:ok, results} ->
-         grouped =
-           Enum.group_by(results, fn file -> File.dir?(Path.join(emoji_dir_path, file)) end)
-         packs = grouped[true] || []
-         files = grouped[false] || []
-         # Print the packs we've found
-         Logger.info("Found emoji packs: #{Enum.join(packs, ", ")}")
-         if not Enum.empty?(files) do
-           Logger.warn(
-             "Found files in the emoji folder. These will be ignored, please move them to a subdirectory\nFound files: #{
-               Enum.join(files, ", ")
-             }"
-           )
-         end
-         emojis =
-           Enum.flat_map(
-             packs,
-             fn pack -> load_pack(Path.join(emoji_dir_path, pack), emoji_groups) end
-           )
-         true = :ets.insert(@ets, emojis)
-     end
-     # Compat thing for old custom emoji handling & default emoji,
-     # it should run even if there are no emoji packs
-     shortcode_globs = Pleroma.Config.get([:emoji, :shortcode_globs], [])
-     emojis =
-       (load_from_file("config/emoji.txt", emoji_groups) ++
-          load_from_file("config/custom_emoji.txt", emoji_groups) ++
-          load_from_globs(shortcode_globs, emoji_groups))
-       |> Enum.reject(fn value -> value == nil end)
-     true = :ets.insert(@ets, emojis)
-     :ok
-   end
-   defp load_pack(pack_dir, emoji_groups) do
-     pack_name = Path.basename(pack_dir)
-     emoji_txt = Path.join(pack_dir, "emoji.txt")
-     if File.exists?(emoji_txt) do
-       load_from_file(emoji_txt, emoji_groups)
-     else
-       extensions = Pleroma.Config.get([:emoji, :pack_extensions])
-       Logger.info(
-         "No emoji.txt found for pack \"#{pack_name}\", assuming all #{Enum.join(extensions, ", ")} files are emoji"
-       )
-       make_shortcode_to_file_map(pack_dir, extensions)
-       |> Enum.map(fn {shortcode, rel_file} ->
-         filename = Path.join("/emoji/#{pack_name}", rel_file)
-         {shortcode, filename, [to_string(match_extra(emoji_groups, filename))]}
-       end)
-     end
-   end
-   def make_shortcode_to_file_map(pack_dir, exts) do
-     find_all_emoji(pack_dir, exts)
-     |> Enum.map(&Path.relative_to(&1, pack_dir))
-     |> Enum.map(fn f -> {f |> Path.basename() |> Path.rootname(), f} end)
-     |> Enum.into(%{})
-   end
-   def find_all_emoji(dir, exts) do
-     Enum.reduce(
-       File.ls!(dir),
-       [],
-       fn f, acc ->
-         filepath = Path.join(dir, f)
-         if File.dir?(filepath) do
-           acc ++ find_all_emoji(filepath, exts)
-         else
-           acc ++ [filepath]
-         end
-       end
-     )
-     |> Enum.filter(fn f -> Path.extname(f) in exts end)
-   end
-   defp load_from_file(file, emoji_groups) do
-     if File.exists?(file) do
-       load_from_file_stream(File.stream!(file), emoji_groups)
-     else
-       []
-     end
-   end
-   defp load_from_file_stream(stream, emoji_groups) do
-     stream
-     |> Stream.map(&String.trim/1)
-     |> Stream.map(fn line ->
-       case String.split(line, ~r/,\s*/) do
-         [name, file] ->
-           {name, file, [to_string(match_extra(emoji_groups, file))]}
-         [name, file | tags] ->
-           {name, file, tags}
-         _ ->
-           nil
-       end
-     end)
-     |> Enum.to_list()
-   end
-   defp load_from_globs(globs, emoji_groups) do
-     static_path = Path.join(:code.priv_dir(:pleroma), "static")
-     paths =
-       Enum.map(globs, fn glob ->
-         Path.join(static_path, glob)
-         |> Path.wildcard()
-       end)
-       |> Enum.concat()
-     Enum.map(paths, fn path ->
-       tag = match_extra(emoji_groups, Path.join("/", Path.relative_to(path, static_path)))
-       shortcode = Path.basename(path, Path.extname(path))
-       external_path = Path.join("/", Path.relative_to(path, static_path))
-       {shortcode, external_path, [to_string(tag)]}
-     end)
-   end
-   @doc """
-   Finds a matching group for the given emoji filename
-   """
-   @spec match_extra(group_patterns(), String.t()) :: atom() | nil
-   def match_extra(group_patterns, filename) do
-     match_group_patterns(group_patterns, fn pattern ->
-       case pattern do
-         %Regex{} = regex -> Regex.match?(regex, filename)
-         string when is_binary(string) -> filename == string
-       end
-     end)
-   end
-   defp match_group_patterns(group_patterns, matcher) do
-     Enum.find_value(group_patterns, fn {group, patterns} ->
-       patterns =
-         patterns
-         |> List.wrap()
-         |> Enum.map(fn pattern ->
-           if String.contains?(pattern, "*") do
-             ~r(#{String.replace(pattern, "*", ".*")})
-           else
-             pattern
-           end
-         end)
-       Enum.any?(patterns, matcher) && group
-     end)
+   defp update_emojis(emojis) do
+     :ets.insert(@ets, emojis)
    end
 +
 +  @external_resource "lib/pleroma/emoji-data.txt"
 +
 +  emojis =
 +    @external_resource
 +    |> File.read!()
 +    |> String.split("\n")
 +    |> Enum.filter(fn line -> line != "" and not String.starts_with?(line, "#") end)
 +    |> Enum.map(fn line ->
 +      line
 +      |> String.split(";", parts: 2)
 +      |> hd()
 +      |> String.trim()
 +      |> String.split("..")
 +      |> case do
 +        [number] ->
 +          <<String.to_integer(number, 16)::utf8>>
 +
 +        [first, last] ->
 +          String.to_integer(first, 16)..String.to_integer(last, 16)
 +          |> Enum.map(&<<&1::utf8>>)
 +      end
 +    end)
 +    |> List.flatten()
 +    |> Enum.uniq()
 +
 +  for emoji <- emojis do
 +    def is_unicode_emoji?(unquote(emoji)), do: true
 +  end
 +
 +  def is_unicode_emoji?(_), do: false
  end
index cb5755ccc31a85d8c249165f35434f2842f1d7cb,63877248a62efc7de3fbecc08fd921efc08adbf2..3da08398b1b72386d3b83fe467a32a829e78cc8c
@@@ -993,23 -968,12 +989,12 @@@ defmodule Pleroma.Web.ActivityPub.Trans
          %{"url" => href, "mediaType" => media_type, "name" => data["name"], "type" => "Document"}
        end)
  
-     object
-     |> Map.put("attachment", attachments)
+     Map.put(object, "attachment", attachments)
    end
  
 -  defp strip_internal_fields(object) do
 +  def strip_internal_fields(object) do
      object
-     |> Map.drop([
-       "reactions",
-       "reaction_count",
-       "likes",
-       "like_count",
-       "announcements",
-       "announcement_count",
-       "emoji",
-       "context_id",
-       "deleted_activity_id"
-     ])
+     |> Map.drop(Pleroma.Constants.object_internal_fields())
    end
  
    defp strip_internal_tags(%{"tag" => tags} = object) do
Simple merge
index 3e1aa481897cacebef0270a75a0f97ca647e43eb,2ec017ff87e1316f38ac70208babce335330059a..0706e7ffcc9ee0306d1bb292a9c0f14a7cc0773e
@@@ -123,25 -114,10 +114,20 @@@ defmodule Pleroma.Web.CommonAPI d
      end
    end
  
-   def vote(user, object, choices) do
-     with "Question" <- object.data["type"],
-          {:author, false} <- {:author, object.data["actor"] == user.ap_id},
-          {:existing_votes, []} <- {:existing_votes, Utils.get_existing_votes(user.ap_id, object)},
-          {options, max_count} <- get_options_and_max_count(object),
-          option_count <- Enum.count(options),
-          {:choice_check, {choices, true}} <-
-            {:choice_check, normalize_and_validate_choice_indices(choices, option_count)},
-          {:count_check, true} <- {:count_check, Enum.count(choices) <= max_count} do
 +  def react_with_emoji(id, user, emoji) do
 +    with %Activity{} = activity <- Activity.get_by_id(id),
 +         object <- Object.normalize(activity) do
 +      ActivityPub.react_with_emoji(user, object, emoji)
 +    else
 +      _ ->
 +        {:error, dgettext("errors", "Could not add reaction emoji")}
 +    end
 +  end
 +
+   def vote(user, %{data: %{"type" => "Question"}} = object, choices) do
+     with :ok <- validate_not_author(object, user),
+          :ok <- validate_existing_votes(user, object),
+          {:ok, options, choices} <- normalize_and_validate_choices(choices, object) do
        answer_activities =
          Enum.map(choices, fn index ->
            answer_data = make_answer_data(user, object, Enum.at(options, index)["name"])
index d41091d93aecf39ce392ae4ca29c13a85236bb11,d17ccf84d0778ff5de3972f365a8a5df12e12f76..474b8d079bb5edabde423f0c38cc8492cc1e779b
@@@ -5,16 -5,11 +5,16 @@@
  defmodule Pleroma.Web.PleromaAPI.PleromaAPIController do
    use Pleroma.Web, :controller
  
-   import Pleroma.Web.ControllerHelper, only: [add_link_headers: 7]
+   import Pleroma.Web.ControllerHelper, only: [add_link_headers: 2]
  
 +  alias Pleroma.Activity
    alias Pleroma.Conversation.Participation
    alias Pleroma.Notification
 +  alias Pleroma.Object
 +  alias Pleroma.User
    alias Pleroma.Web.ActivityPub.ActivityPub
 +  alias Pleroma.Web.CommonAPI
 +  alias Pleroma.Web.MastodonAPI.AccountView
    alias Pleroma.Web.MastodonAPI.ConversationView
    alias Pleroma.Web.MastodonAPI.NotificationView
    alias Pleroma.Web.MastodonAPI.StatusView
index 6354510cf634c49825fd3f8c2c415c282c307a43,e50a600876ef032f16b008a6746a72ea07ffa0c1..0b13990cbc30128fe2cd1fa3661f0a2a99d1a824
@@@ -278,9 -298,19 +304,20 @@@ defmodule Pleroma.Web.Router d
      scope [] do
        pipe_through(:oauth_write)
        patch("/conversations/:id", PleromaAPIController, :update_conversation)
 +      post("/statuses/:id/react_with_emoji", PleromaAPIController, :react_with_emoji)
        post("/notifications/read", PleromaAPIController, :read_notification)
      end
+     scope [] do
+       pipe_through(:oauth_write)
+       post("/scrobble", ScrobbleController, :new_scrobble)
+     end
+   end
+   scope "/api/v1/pleroma", Pleroma.Web.PleromaAPI do
+     pipe_through([:api, :oauth_read_or_public])
+     get("/accounts/:id/scrobbles", ScrobbleController, :user_scrobbles)
    end
  
    scope "/api/v1", Pleroma.Web.MastodonAPI do
Simple merge