total rebase
[anni] / lib / pleroma / emoji / pack.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Emoji.Pack do
6   @derive {Jason.Encoder, only: [:files, :pack, :files_count]}
7   defstruct files: %{},
8             files_count: 0,
9             pack_file: nil,
10             path: nil,
11             pack: %{},
12             name: nil
13
14   @type t() :: %__MODULE__{
15           files: %{String.t() => Path.t()},
16           files_count: non_neg_integer(),
17           pack_file: Path.t(),
18           path: Path.t(),
19           pack: map(),
20           name: String.t()
21         }
22
23   @cachex Pleroma.Config.get([:cachex, :provider], Cachex)
24
25   alias Pleroma.Emoji
26   alias Pleroma.Emoji.Pack
27   alias Pleroma.Utils
28
29   @spec create(String.t()) :: {:ok, t()} | {:error, File.posix()} | {:error, :empty_values}
30   def create(name) do
31     with :ok <- validate_not_empty([name]),
32          dir <- Path.join(emoji_path(), name),
33          :ok <- File.mkdir(dir) do
34       save_pack(%__MODULE__{pack_file: Path.join(dir, "pack.json")})
35     end
36   end
37
38   defp paginate(entities, 1, page_size), do: Enum.take(entities, page_size)
39
40   defp paginate(entities, page, page_size) do
41     entities
42     |> Enum.chunk_every(page_size)
43     |> Enum.at(page - 1)
44   end
45
46   @spec show(keyword()) :: {:ok, t()} | {:error, atom()}
47   def show(opts) do
48     name = opts[:name]
49
50     with :ok <- validate_not_empty([name]),
51          {:ok, pack} <- load_pack(name) do
52       shortcodes =
53         pack.files
54         |> Map.keys()
55         |> Enum.sort()
56         |> paginate(opts[:page], opts[:page_size])
57
58       pack = Map.put(pack, :files, Map.take(pack.files, shortcodes))
59
60       {:ok, validate_pack(pack)}
61     end
62   end
63
64   @spec delete(String.t()) ::
65           {:ok, [binary()]} | {:error, File.posix(), binary()} | {:error, :empty_values}
66   def delete(name) do
67     with :ok <- validate_not_empty([name]),
68          pack_path <- Path.join(emoji_path(), name) do
69       File.rm_rf(pack_path)
70     end
71   end
72
73   @spec unpack_zip_emojies(list(tuple())) :: list(map())
74   defp unpack_zip_emojies(zip_files) do
75     Enum.reduce(zip_files, [], fn
76       {_, path, s, _, _, _}, acc when elem(s, 2) == :regular ->
77         with(
78           filename <- Path.basename(path),
79           shortcode <- Path.basename(filename, Path.extname(filename)),
80           false <- Emoji.exist?(shortcode)
81         ) do
82           [%{path: path, filename: path, shortcode: shortcode} | acc]
83         else
84           _ -> acc
85         end
86
87       _, acc ->
88         acc
89     end)
90   end
91
92   @spec add_file(t(), String.t(), Path.t(), Plug.Upload.t()) ::
93           {:ok, t()}
94           | {:error, File.posix() | atom()}
95   def add_file(%Pack{} = pack, _, _, %Plug.Upload{content_type: "application/zip"} = file) do
96     with {:ok, zip_files} <- :zip.table(to_charlist(file.path)),
97          [_ | _] = emojies <- unpack_zip_emojies(zip_files),
98          {:ok, tmp_dir} <- Utils.tmp_dir("emoji") do
99       try do
100         {:ok, _emoji_files} =
101           :zip.unzip(
102             to_charlist(file.path),
103             [{:file_list, Enum.map(emojies, & &1[:path])}, {:cwd, String.to_charlist(tmp_dir)}]
104           )
105
106         {_, updated_pack} =
107           Enum.map_reduce(emojies, pack, fn item, emoji_pack ->
108             emoji_file = %Plug.Upload{
109               filename: item[:filename],
110               path: Path.join(tmp_dir, item[:path])
111             }
112
113             {:ok, updated_pack} =
114               do_add_file(
115                 emoji_pack,
116                 item[:shortcode],
117                 to_string(item[:filename]),
118                 emoji_file
119               )
120
121             {item, updated_pack}
122           end)
123
124         Emoji.reload()
125
126         {:ok, updated_pack}
127       after
128         File.rm_rf(tmp_dir)
129       end
130     else
131       {:error, _} = error ->
132         error
133
134       _ ->
135         {:ok, pack}
136     end
137   end
138
139   def add_file(%Pack{} = pack, shortcode, filename, %Plug.Upload{} = file) do
140     with :ok <- validate_not_empty([shortcode, filename]),
141          :ok <- validate_emoji_not_exists(shortcode),
142          {:ok, updated_pack} <- do_add_file(pack, shortcode, filename, file) do
143       Emoji.reload()
144       {:ok, updated_pack}
145     end
146   end
147
148   defp do_add_file(pack, shortcode, filename, file) do
149     with :ok <- save_file(file, pack, filename) do
150       pack
151       |> put_emoji(shortcode, filename)
152       |> save_pack()
153     end
154   end
155
156   @spec delete_file(t(), String.t()) ::
157           {:ok, t()} | {:error, File.posix() | atom()}
158   def delete_file(%Pack{} = pack, shortcode) do
159     with :ok <- validate_not_empty([shortcode]),
160          :ok <- remove_file(pack, shortcode),
161          {:ok, updated_pack} <- pack |> delete_emoji(shortcode) |> save_pack() do
162       Emoji.reload()
163       {:ok, updated_pack}
164     end
165   end
166
167   @spec update_file(t(), String.t(), String.t(), String.t(), boolean()) ::
168           {:ok, t()} | {:error, File.posix() | atom()}
169   def update_file(%Pack{} = pack, shortcode, new_shortcode, new_filename, force) do
170     with :ok <- validate_not_empty([shortcode, new_shortcode, new_filename]),
171          {:ok, filename} <- get_filename(pack, shortcode),
172          :ok <- validate_emoji_not_exists(new_shortcode, force),
173          :ok <- rename_file(pack, filename, new_filename),
174          {:ok, updated_pack} <-
175            pack
176            |> delete_emoji(shortcode)
177            |> put_emoji(new_shortcode, new_filename)
178            |> save_pack() do
179       Emoji.reload()
180       {:ok, updated_pack}
181     end
182   end
183
184   @spec import_from_filesystem() :: {:ok, [String.t()]} | {:error, File.posix() | atom()}
185   def import_from_filesystem do
186     emoji_path = emoji_path()
187
188     with {:ok, %{access: :read_write}} <- File.stat(emoji_path),
189          {:ok, results} <- File.ls(emoji_path) do
190       names =
191         results
192         |> Enum.map(&Path.join(emoji_path, &1))
193         |> Enum.reject(fn path ->
194           File.dir?(path) and File.exists?(Path.join(path, "pack.json"))
195         end)
196         |> Enum.map(&write_pack_contents/1)
197         |> Enum.reject(&is_nil/1)
198
199       {:ok, names}
200     else
201       {:ok, %{access: _}} -> {:error, :no_read_write}
202       e -> e
203     end
204   end
205
206   @spec list_remote(keyword()) :: {:ok, map()} | {:error, atom()}
207   def list_remote(opts) do
208     uri = opts[:url] |> String.trim() |> URI.parse()
209
210     with :ok <- validate_shareable_packs_available(uri) do
211       uri
212       |> URI.merge(
213         "/api/v1/pleroma/emoji/packs?page=#{opts[:page]}&page_size=#{opts[:page_size]}"
214       )
215       |> http_get()
216     end
217   end
218
219   @spec list_local(keyword()) :: {:ok, map(), non_neg_integer()}
220   def list_local(opts) do
221     with {:ok, results} <- list_packs_dir() do
222       all_packs =
223         results
224         |> Enum.map(fn name ->
225           case load_pack(name) do
226             {:ok, pack} -> pack
227             _ -> nil
228           end
229         end)
230         |> Enum.reject(&is_nil/1)
231
232       packs =
233         all_packs
234         |> paginate(opts[:page], opts[:page_size])
235         |> Map.new(fn pack -> {pack.name, validate_pack(pack)} end)
236
237       {:ok, packs, length(all_packs)}
238     end
239   end
240
241   @spec get_archive(String.t()) :: {:ok, binary()} | {:error, atom()}
242   def get_archive(name) do
243     with {:ok, pack} <- load_pack(name),
244          :ok <- validate_downloadable(pack) do
245       {:ok, fetch_archive(pack)}
246     end
247   end
248
249   @spec download(String.t(), String.t(), String.t()) :: {:ok, t()} | {:error, atom()}
250   def download(name, url, as) do
251     uri = url |> String.trim() |> URI.parse()
252
253     with :ok <- validate_shareable_packs_available(uri),
254          {:ok, %{"files_count" => files_count}} <-
255            uri |> URI.merge("/api/v1/pleroma/emoji/pack?name=#{name}&page_size=0") |> http_get(),
256          {:ok, remote_pack} <-
257            uri
258            |> URI.merge("/api/v1/pleroma/emoji/pack?name=#{name}&page_size=#{files_count}")
259            |> http_get(),
260          {:ok, %{sha: sha, url: url} = pack_info} <- fetch_pack_info(remote_pack, uri, name),
261          {:ok, archive} <- download_archive(url, sha),
262          pack <- copy_as(remote_pack, as || name),
263          {:ok, _} = unzip(archive, pack_info, remote_pack, pack) do
264       # Fallback can't contain a pack.json file, since that would cause the fallback-src-sha256
265       # in it to depend on itself
266       if pack_info[:fallback] do
267         save_pack(pack)
268       else
269         {:ok, pack}
270       end
271     end
272   end
273
274   @spec save_metadata(map(), t()) :: {:ok, t()} | {:error, File.posix()}
275   def save_metadata(metadata, %__MODULE__{} = pack) do
276     pack
277     |> Map.put(:pack, metadata)
278     |> save_pack()
279   end
280
281   @spec update_metadata(String.t(), map()) :: {:ok, t()} | {:error, File.posix()}
282   def update_metadata(name, data) do
283     with {:ok, pack} <- load_pack(name) do
284       if fallback_sha_changed?(pack, data) do
285         update_sha_and_save_metadata(pack, data)
286       else
287         save_metadata(data, pack)
288       end
289     end
290   end
291
292   @spec load_pack(String.t()) :: {:ok, t()} | {:error, :file.posix()}
293   def load_pack(name) do
294     name = Path.basename(name)
295     pack_file = Path.join([emoji_path(), name, "pack.json"])
296
297     with {:ok, _} <- File.stat(pack_file),
298          {:ok, pack_data} <- File.read(pack_file) do
299       pack =
300         from_json(
301           pack_data,
302           %{
303             pack_file: pack_file,
304             path: Path.dirname(pack_file),
305             name: name
306           }
307         )
308
309       files_count =
310         pack.files
311         |> Map.keys()
312         |> length()
313
314       {:ok, Map.put(pack, :files_count, files_count)}
315     end
316   end
317
318   @spec emoji_path() :: Path.t()
319   defp emoji_path do
320     [:instance, :static_dir]
321     |> Pleroma.Config.get!()
322     |> Path.join("emoji")
323   end
324
325   defp validate_emoji_not_exists(shortcode, force \\ false)
326   defp validate_emoji_not_exists(_shortcode, true), do: :ok
327
328   defp validate_emoji_not_exists(shortcode, _) do
329     if Emoji.exist?(shortcode) do
330       {:error, :already_exists}
331     else
332       :ok
333     end
334   end
335
336   defp write_pack_contents(path) do
337     pack = %__MODULE__{
338       files: files_from_path(path),
339       path: path,
340       pack_file: Path.join(path, "pack.json")
341     }
342
343     case save_pack(pack) do
344       {:ok, _pack} -> Path.basename(path)
345       _ -> nil
346     end
347   end
348
349   defp files_from_path(path) do
350     txt_path = Path.join(path, "emoji.txt")
351
352     if File.exists?(txt_path) do
353       # There's an emoji.txt file, it's likely from a pack installed by the pack manager.
354       # Make a pack.json file from the contents of that emoji.txt file
355
356       # FIXME: Copy-pasted from Pleroma.Emoji/load_from_file_stream/2
357
358       # Create a map of shortcodes to filenames from emoji.txt
359       txt_path
360       |> File.read!()
361       |> String.split("\n")
362       |> Enum.map(&String.trim/1)
363       |> Enum.map(fn line ->
364         case String.split(line, ~r/,\s*/) do
365           # This matches both strings with and without tags
366           # and we don't care about tags here
367           [name, file | _] ->
368             file_dir_name = Path.dirname(file)
369
370             if String.ends_with?(path, file_dir_name) do
371               {name, Path.basename(file)}
372             else
373               {name, file}
374             end
375
376           _ ->
377             nil
378         end
379       end)
380       |> Enum.reject(&is_nil/1)
381       |> Map.new()
382     else
383       # If there's no emoji.txt, assume all files
384       # that are of certain extensions from the config are emojis and import them all
385       pack_extensions = Pleroma.Config.get!([:emoji, :pack_extensions])
386       Emoji.Loader.make_shortcode_to_file_map(path, pack_extensions)
387     end
388   end
389
390   defp validate_pack(pack) do
391     info =
392       if downloadable?(pack) do
393         archive = fetch_archive(pack)
394         archive_sha = :crypto.hash(:sha256, archive) |> Base.encode16()
395
396         pack.pack
397         |> Map.put("can-download", true)
398         |> Map.put("download-sha256", archive_sha)
399       else
400         Map.put(pack.pack, "can-download", false)
401       end
402
403     Map.put(pack, :pack, info)
404   end
405
406   defp downloadable?(pack) do
407     # If the pack is set as shared, check if it can be downloaded
408     # That means that when asked, the pack can be packed and sent to the remote
409     # Otherwise, they'd have to download it from external-src
410     pack.pack["share-files"] &&
411       Enum.all?(pack.files, fn {_, file} ->
412         pack.path
413         |> Path.join(file)
414         |> File.exists?()
415       end)
416   end
417
418   defp create_archive_and_cache(pack, hash) do
419     files = ['pack.json' | Enum.map(pack.files, fn {_, file} -> to_charlist(file) end)]
420
421     {:ok, {_, result}} =
422       :zip.zip('#{pack.name}.zip', files, [:memory, cwd: to_charlist(pack.path)])
423
424     ttl_per_file = Pleroma.Config.get!([:emoji, :shared_pack_cache_seconds_per_file])
425     overall_ttl = :timer.seconds(ttl_per_file * Enum.count(files))
426
427     @cachex.put(
428       :emoji_packs_cache,
429       pack.name,
430       # if pack.json MD5 changes, the cache is not valid anymore
431       %{hash: hash, pack_data: result},
432       # Add a minute to cache time for every file in the pack
433       ttl: overall_ttl
434     )
435
436     result
437   end
438
439   defp save_pack(pack) do
440     with {:ok, json} <- Jason.encode(pack, pretty: true),
441          :ok <- File.write(pack.pack_file, json) do
442       {:ok, pack}
443     end
444   end
445
446   defp from_json(json, attrs) do
447     map = Jason.decode!(json)
448
449     pack_attrs =
450       attrs
451       |> Map.merge(%{
452         files: map["files"],
453         pack: map["pack"]
454       })
455
456     struct(__MODULE__, pack_attrs)
457   end
458
459   defp validate_shareable_packs_available(uri) do
460     with {:ok, %{"links" => links}} <- uri |> URI.merge("/.well-known/nodeinfo") |> http_get(),
461          # Get the actual nodeinfo address and fetch it
462          {:ok, %{"metadata" => %{"features" => features}}} <-
463            links |> List.last() |> Map.get("href") |> http_get() do
464       if Enum.member?(features, "shareable_emoji_packs") do
465         :ok
466       else
467         {:error, :not_shareable}
468       end
469     end
470   end
471
472   defp validate_not_empty(list) do
473     if Enum.all?(list, fn i -> is_binary(i) and i != "" end) do
474       :ok
475     else
476       {:error, :empty_values}
477     end
478   end
479
480   defp save_file(%Plug.Upload{path: upload_path}, pack, filename) do
481     file_path = Path.join(pack.path, filename)
482     create_subdirs(file_path)
483
484     with {:ok, _} <- File.copy(upload_path, file_path) do
485       :ok
486     end
487   end
488
489   defp put_emoji(pack, shortcode, filename) do
490     files = Map.put(pack.files, shortcode, filename)
491     %{pack | files: files, files_count: length(Map.keys(files))}
492   end
493
494   defp delete_emoji(pack, shortcode) do
495     files = Map.delete(pack.files, shortcode)
496     %{pack | files: files}
497   end
498
499   defp rename_file(pack, filename, new_filename) do
500     old_path = Path.join(pack.path, filename)
501     new_path = Path.join(pack.path, new_filename)
502     create_subdirs(new_path)
503
504     with :ok <- File.rename(old_path, new_path) do
505       remove_dir_if_empty(old_path, filename)
506     end
507   end
508
509   defp create_subdirs(file_path) do
510     with true <- String.contains?(file_path, "/"),
511          path <- Path.dirname(file_path),
512          false <- File.exists?(path) do
513       File.mkdir_p!(path)
514     end
515   end
516
517   defp remove_file(pack, shortcode) do
518     with {:ok, filename} <- get_filename(pack, shortcode),
519          emoji <- Path.join(pack.path, filename),
520          :ok <- File.rm(emoji) do
521       remove_dir_if_empty(emoji, filename)
522     end
523   end
524
525   defp remove_dir_if_empty(emoji, filename) do
526     dir = Path.dirname(emoji)
527
528     if String.contains?(filename, "/") and File.ls!(dir) == [] do
529       File.rmdir!(dir)
530     else
531       :ok
532     end
533   end
534
535   defp get_filename(pack, shortcode) do
536     with %{^shortcode => filename} when is_binary(filename) <- pack.files,
537          file_path <- Path.join(pack.path, filename),
538          {:ok, _} <- File.stat(file_path) do
539       {:ok, filename}
540     else
541       {:error, _} = error ->
542         error
543
544       _ ->
545         {:error, :doesnt_exist}
546     end
547   end
548
549   defp http_get(%URI{} = url), do: url |> to_string() |> http_get()
550
551   defp http_get(url) do
552     with {:ok, %{body: body}} <- Pleroma.HTTP.get(url, [], pool: :default) do
553       Jason.decode(body)
554     end
555   end
556
557   defp list_packs_dir do
558     emoji_path = emoji_path()
559     # Create the directory first if it does not exist. This is probably the first request made
560     # with the API so it should be sufficient
561     with {:create_dir, :ok} <- {:create_dir, File.mkdir_p(emoji_path)},
562          {:ls, {:ok, results}} <- {:ls, File.ls(emoji_path)} do
563       {:ok, Enum.sort(results)}
564     else
565       {:create_dir, {:error, e}} -> {:error, :create_dir, e}
566       {:ls, {:error, e}} -> {:error, :ls, e}
567     end
568   end
569
570   defp validate_downloadable(pack) do
571     if downloadable?(pack), do: :ok, else: {:error, :cant_download}
572   end
573
574   defp copy_as(remote_pack, local_name) do
575     path = Path.join(emoji_path(), local_name)
576
577     %__MODULE__{
578       name: local_name,
579       path: path,
580       files: remote_pack["files"],
581       pack_file: Path.join(path, "pack.json")
582     }
583   end
584
585   defp unzip(archive, pack_info, remote_pack, local_pack) do
586     with :ok <- File.mkdir_p!(local_pack.path) do
587       files = Enum.map(remote_pack["files"], fn {_, path} -> to_charlist(path) end)
588       # Fallback cannot contain a pack.json file
589       files = if pack_info[:fallback], do: files, else: ['pack.json' | files]
590
591       :zip.unzip(archive, cwd: to_charlist(local_pack.path), file_list: files)
592     end
593   end
594
595   defp fetch_pack_info(remote_pack, uri, name) do
596     case remote_pack["pack"] do
597       %{"share-files" => true, "can-download" => true, "download-sha256" => sha} ->
598         {:ok,
599          %{
600            sha: sha,
601            url: URI.merge(uri, "/api/v1/pleroma/emoji/packs/archive?name=#{name}") |> to_string()
602          }}
603
604       %{"fallback-src" => src, "fallback-src-sha256" => sha} when is_binary(src) ->
605         {:ok,
606          %{
607            sha: sha,
608            url: src,
609            fallback: true
610          }}
611
612       _ ->
613         {:error, "The pack was not set as shared and there is no fallback src to download from"}
614     end
615   end
616
617   defp download_archive(url, sha) do
618     with {:ok, %{body: archive}} <- Pleroma.HTTP.get(url) do
619       if Base.decode16!(sha) == :crypto.hash(:sha256, archive) do
620         {:ok, archive}
621       else
622         {:error, :invalid_checksum}
623       end
624     end
625   end
626
627   defp fetch_archive(pack) do
628     hash = :crypto.hash(:md5, File.read!(pack.pack_file))
629
630     case @cachex.get!(:emoji_packs_cache, pack.name) do
631       %{hash: ^hash, pack_data: archive} -> archive
632       _ -> create_archive_and_cache(pack, hash)
633     end
634   end
635
636   defp fallback_sha_changed?(pack, data) do
637     is_binary(data[:"fallback-src"]) and data[:"fallback-src"] != pack.pack["fallback-src"]
638   end
639
640   defp update_sha_and_save_metadata(pack, data) do
641     with {:ok, %{body: zip}} <- Pleroma.HTTP.get(data[:"fallback-src"]),
642          :ok <- validate_has_all_files(pack, zip) do
643       fallback_sha = :sha256 |> :crypto.hash(zip) |> Base.encode16()
644
645       data
646       |> Map.put("fallback-src-sha256", fallback_sha)
647       |> save_metadata(pack)
648     end
649   end
650
651   defp validate_has_all_files(pack, zip) do
652     with {:ok, f_list} <- :zip.unzip(zip, [:memory]) do
653       # Check if all files from the pack.json are in the archive
654       pack.files
655       |> Enum.all?(fn {_, from_manifest} ->
656         List.keyfind(f_list, to_charlist(from_manifest), 0)
657       end)
658       |> if(do: :ok, else: {:error, :incomplete})
659     end
660   end
661 end