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