upload emoji zip file
[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 add_file(String.t(), String.t(), Path.t(), Plug.Upload.t()) ::
69 {:ok, t()}
70 | {:error, File.posix() | atom()}
71 def add_file(%Pack{} = pack, _, _, %Plug.Upload{content_type: "application/zip"} = file) do
72 with {:ok, zip_items} <- :zip.table(to_charlist(file.path)) do
73 emojies =
74 for {_, path, s, _, _, _} <- zip_items, elem(s, 2) == :regular do
75 filename = Path.basename(path)
76 shortcode = Path.basename(filename, Path.extname(filename))
77
78 %{
79 path: path,
80 filename: path,
81 shortcode: shortcode,
82 exist: not is_nil(Pleroma.Emoji.get(shortcode))
83 }
84 end
85 |> Enum.group_by(& &1[:exist])
86
87 case Map.get(emojies, false, []) do
88 [_ | _] = new_emojies ->
89 {:ok, tmp_dir} = Pleroma.Utils.tmp_dir("emoji")
90
91 try do
92 {:ok, _emoji_files} =
93 :zip.unzip(
94 to_charlist(file.path),
95 [
96 {:file_list, Enum.map(new_emojies, & &1[:path])},
97 {:cwd, tmp_dir}
98 ]
99 )
100
101 {_, updated_pack} =
102 Enum.map_reduce(new_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
126 _ ->
127 {:ok, pack}
128 end
129 end
130 end
131
132 def add_file(%Pack{} = pack, shortcode, filename, file) do
133 with :ok <- validate_not_empty([shortcode, filename]),
134 :ok <- validate_emoji_not_exists(shortcode),
135 {:ok, updated_pack} <- do_add_file(pack, shortcode, filename, file) do
136 Emoji.reload()
137 {:ok, updated_pack}
138 end
139 end
140
141 defp do_add_file(pack, shortcode, filename, file) do
142 with :ok <- save_file(file, pack, filename),
143 {:ok, updated_pack} <-
144 pack
145 |> put_emoji(shortcode, filename)
146 |> save_pack() do
147 {:ok, updated_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(String.t()) :: {:ok, map()} | {:error, atom()}
202 def list_remote(url) do
203 uri = url |> String.trim() |> URI.parse()
204
205 with :ok <- validate_shareable_packs_available(uri) do
206 uri
207 |> URI.merge("/api/pleroma/emoji/packs")
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} <- uri |> URI.merge("/api/pleroma/emoji/packs/#{name}") |> http_get(),
248 {:ok, %{sha: sha, url: url} = pack_info} <- fetch_pack_info(remote_pack, uri, name),
249 {:ok, archive} <- download_archive(url, sha),
250 pack <- copy_as(remote_pack, as || name),
251 {:ok, _} = unzip(archive, pack_info, remote_pack, pack) do
252 # Fallback can't contain a pack.json file, since that would cause the fallback-src-sha256
253 # in it to depend on itself
254 if pack_info[:fallback] do
255 save_pack(pack)
256 else
257 {:ok, pack}
258 end
259 end
260 end
261
262 @spec save_metadata(map(), t()) :: {:ok, t()} | {:error, File.posix()}
263 def save_metadata(metadata, %__MODULE__{} = pack) do
264 pack
265 |> Map.put(:pack, metadata)
266 |> save_pack()
267 end
268
269 @spec update_metadata(String.t(), map()) :: {:ok, t()} | {:error, File.posix()}
270 def update_metadata(name, data) do
271 with {:ok, pack} <- load_pack(name) do
272 if fallback_sha_changed?(pack, data) do
273 update_sha_and_save_metadata(pack, data)
274 else
275 save_metadata(data, pack)
276 end
277 end
278 end
279
280 @spec load_pack(String.t()) :: {:ok, t()} | {:error, :not_found}
281 def load_pack(name) do
282 pack_file = Path.join([emoji_path(), name, "pack.json"])
283
284 if File.exists?(pack_file) do
285 pack =
286 pack_file
287 |> File.read!()
288 |> from_json()
289 |> Map.put(:pack_file, pack_file)
290 |> Map.put(:path, Path.dirname(pack_file))
291 |> Map.put(:name, name)
292
293 files_count =
294 pack.files
295 |> Map.keys()
296 |> length()
297
298 {:ok, Map.put(pack, :files_count, files_count)}
299 else
300 {:error, :not_found}
301 end
302 end
303
304 @spec emoji_path() :: Path.t()
305 defp emoji_path do
306 [:instance, :static_dir]
307 |> Pleroma.Config.get!()
308 |> Path.join("emoji")
309 end
310
311 defp validate_emoji_not_exists(shortcode, force \\ false)
312 defp validate_emoji_not_exists(_shortcode, true), do: :ok
313
314 defp validate_emoji_not_exists(shortcode, _) do
315 case Emoji.get(shortcode) do
316 nil -> :ok
317 _ -> {:error, :already_exists}
318 end
319 end
320
321 defp write_pack_contents(path) do
322 pack = %__MODULE__{
323 files: files_from_path(path),
324 path: path,
325 pack_file: Path.join(path, "pack.json")
326 }
327
328 case save_pack(pack) do
329 {:ok, _pack} -> Path.basename(path)
330 _ -> nil
331 end
332 end
333
334 defp files_from_path(path) do
335 txt_path = Path.join(path, "emoji.txt")
336
337 if File.exists?(txt_path) do
338 # There's an emoji.txt file, it's likely from a pack installed by the pack manager.
339 # Make a pack.json file from the contents of that emoji.txt file
340
341 # FIXME: Copy-pasted from Pleroma.Emoji/load_from_file_stream/2
342
343 # Create a map of shortcodes to filenames from emoji.txt
344 txt_path
345 |> File.read!()
346 |> String.split("\n")
347 |> Enum.map(&String.trim/1)
348 |> Enum.map(fn line ->
349 case String.split(line, ~r/,\s*/) do
350 # This matches both strings with and without tags
351 # and we don't care about tags here
352 [name, file | _] ->
353 file_dir_name = Path.dirname(file)
354
355 if String.ends_with?(path, file_dir_name) do
356 {name, Path.basename(file)}
357 else
358 {name, file}
359 end
360
361 _ ->
362 nil
363 end
364 end)
365 |> Enum.reject(&is_nil/1)
366 |> Map.new()
367 else
368 # If there's no emoji.txt, assume all files
369 # that are of certain extensions from the config are emojis and import them all
370 pack_extensions = Pleroma.Config.get!([:emoji, :pack_extensions])
371 Emoji.Loader.make_shortcode_to_file_map(path, pack_extensions)
372 end
373 end
374
375 defp validate_pack(pack) do
376 info =
377 if downloadable?(pack) do
378 archive = fetch_archive(pack)
379 archive_sha = :crypto.hash(:sha256, archive) |> Base.encode16()
380
381 pack.pack
382 |> Map.put("can-download", true)
383 |> Map.put("download-sha256", archive_sha)
384 else
385 Map.put(pack.pack, "can-download", false)
386 end
387
388 Map.put(pack, :pack, info)
389 end
390
391 defp downloadable?(pack) do
392 # If the pack is set as shared, check if it can be downloaded
393 # That means that when asked, the pack can be packed and sent to the remote
394 # Otherwise, they'd have to download it from external-src
395 pack.pack["share-files"] &&
396 Enum.all?(pack.files, fn {_, file} ->
397 pack.path
398 |> Path.join(file)
399 |> File.exists?()
400 end)
401 end
402
403 defp create_archive_and_cache(pack, hash) do
404 files = ['pack.json' | Enum.map(pack.files, fn {_, file} -> to_charlist(file) end)]
405
406 {:ok, {_, result}} =
407 :zip.zip('#{pack.name}.zip', files, [:memory, cwd: to_charlist(pack.path)])
408
409 ttl_per_file = Pleroma.Config.get!([:emoji, :shared_pack_cache_seconds_per_file])
410 overall_ttl = :timer.seconds(ttl_per_file * Enum.count(files))
411
412 Cachex.put!(
413 :emoji_packs_cache,
414 pack.name,
415 # if pack.json MD5 changes, the cache is not valid anymore
416 %{hash: hash, pack_data: result},
417 # Add a minute to cache time for every file in the pack
418 ttl: overall_ttl
419 )
420
421 result
422 end
423
424 defp save_pack(pack) do
425 with {:ok, json} <- Jason.encode(pack, pretty: true),
426 :ok <- File.write(pack.pack_file, json) do
427 {:ok, pack}
428 end
429 end
430
431 defp from_json(json) do
432 map = Jason.decode!(json)
433
434 struct(__MODULE__, %{files: map["files"], pack: map["pack"]})
435 end
436
437 defp validate_shareable_packs_available(uri) do
438 with {:ok, %{"links" => links}} <- uri |> URI.merge("/.well-known/nodeinfo") |> http_get(),
439 # Get the actual nodeinfo address and fetch it
440 {:ok, %{"metadata" => %{"features" => features}}} <-
441 links |> List.last() |> Map.get("href") |> http_get() do
442 if Enum.member?(features, "shareable_emoji_packs") do
443 :ok
444 else
445 {:error, :not_shareable}
446 end
447 end
448 end
449
450 defp validate_not_empty(list) do
451 if Enum.all?(list, fn i -> is_binary(i) and i != "" end) do
452 :ok
453 else
454 {:error, :empty_values}
455 end
456 end
457
458 defp save_file(%Plug.Upload{path: upload_path}, pack, filename) do
459 file_path = Path.join(pack.path, filename)
460 create_subdirs(file_path)
461
462 with {:ok, _} <- File.copy(upload_path, file_path) do
463 :ok
464 end
465 end
466
467 defp put_emoji(pack, shortcode, filename) do
468 files = Map.put(pack.files, shortcode, filename)
469 %{pack | files: files}
470 end
471
472 defp delete_emoji(pack, shortcode) do
473 files = Map.delete(pack.files, shortcode)
474 %{pack | files: files}
475 end
476
477 defp rename_file(pack, filename, new_filename) do
478 old_path = Path.join(pack.path, filename)
479 new_path = Path.join(pack.path, new_filename)
480 create_subdirs(new_path)
481
482 with :ok <- File.rename(old_path, new_path) do
483 remove_dir_if_empty(old_path, filename)
484 end
485 end
486
487 defp create_subdirs(file_path) do
488 if String.contains?(file_path, "/") do
489 file_path
490 |> Path.dirname()
491 |> File.mkdir_p!()
492 end
493 end
494
495 defp remove_file(pack, shortcode) do
496 with {:ok, filename} <- get_filename(pack, shortcode),
497 emoji <- Path.join(pack.path, filename),
498 :ok <- File.rm(emoji) do
499 remove_dir_if_empty(emoji, filename)
500 end
501 end
502
503 defp remove_dir_if_empty(emoji, filename) do
504 dir = Path.dirname(emoji)
505
506 if String.contains?(filename, "/") and File.ls!(dir) == [] do
507 File.rmdir!(dir)
508 else
509 :ok
510 end
511 end
512
513 defp get_filename(pack, shortcode) do
514 with %{^shortcode => filename} when is_binary(filename) <- pack.files,
515 true <- pack.path |> Path.join(filename) |> File.exists?() do
516 {:ok, filename}
517 else
518 _ -> {:error, :doesnt_exist}
519 end
520 end
521
522 defp http_get(%URI{} = url), do: url |> to_string() |> http_get()
523
524 defp http_get(url) do
525 with {:ok, %{body: body}} <- url |> Pleroma.HTTP.get() do
526 Jason.decode(body)
527 end
528 end
529
530 defp list_packs_dir do
531 emoji_path = emoji_path()
532 # Create the directory first if it does not exist. This is probably the first request made
533 # with the API so it should be sufficient
534 with {:create_dir, :ok} <- {:create_dir, File.mkdir_p(emoji_path)},
535 {:ls, {:ok, results}} <- {:ls, File.ls(emoji_path)} do
536 {:ok, Enum.sort(results)}
537 else
538 {:create_dir, {:error, e}} -> {:error, :create_dir, e}
539 {:ls, {:error, e}} -> {:error, :ls, e}
540 end
541 end
542
543 defp validate_downloadable(pack) do
544 if downloadable?(pack), do: :ok, else: {:error, :cant_download}
545 end
546
547 defp copy_as(remote_pack, local_name) do
548 path = Path.join(emoji_path(), local_name)
549
550 %__MODULE__{
551 name: local_name,
552 path: path,
553 files: remote_pack["files"],
554 pack_file: Path.join(path, "pack.json")
555 }
556 end
557
558 defp unzip(archive, pack_info, remote_pack, local_pack) do
559 with :ok <- File.mkdir_p!(local_pack.path) do
560 files = Enum.map(remote_pack["files"], fn {_, path} -> to_charlist(path) end)
561 # Fallback cannot contain a pack.json file
562 files = if pack_info[:fallback], do: files, else: ['pack.json' | files]
563
564 :zip.unzip(archive, cwd: to_charlist(local_pack.path), file_list: files)
565 end
566 end
567
568 defp fetch_pack_info(remote_pack, uri, name) do
569 case remote_pack["pack"] do
570 %{"share-files" => true, "can-download" => true, "download-sha256" => sha} ->
571 {:ok,
572 %{
573 sha: sha,
574 url: URI.merge(uri, "/api/pleroma/emoji/packs/#{name}/archive") |> to_string()
575 }}
576
577 %{"fallback-src" => src, "fallback-src-sha256" => sha} when is_binary(src) ->
578 {:ok,
579 %{
580 sha: sha,
581 url: src,
582 fallback: true
583 }}
584
585 _ ->
586 {:error, "The pack was not set as shared and there is no fallback src to download from"}
587 end
588 end
589
590 defp download_archive(url, sha) do
591 with {:ok, %{body: archive}} <- Tesla.get(url) do
592 if Base.decode16!(sha) == :crypto.hash(:sha256, archive) do
593 {:ok, archive}
594 else
595 {:error, :invalid_checksum}
596 end
597 end
598 end
599
600 defp fetch_archive(pack) do
601 hash = :crypto.hash(:md5, File.read!(pack.pack_file))
602
603 case Cachex.get!(:emoji_packs_cache, pack.name) do
604 %{hash: ^hash, pack_data: archive} -> archive
605 _ -> create_archive_and_cache(pack, hash)
606 end
607 end
608
609 defp fallback_sha_changed?(pack, data) do
610 is_binary(data[:"fallback-src"]) and data[:"fallback-src"] != pack.pack["fallback-src"]
611 end
612
613 defp update_sha_and_save_metadata(pack, data) do
614 with {:ok, %{body: zip}} <- Tesla.get(data[:"fallback-src"]),
615 :ok <- validate_has_all_files(pack, zip) do
616 fallback_sha = :sha256 |> :crypto.hash(zip) |> Base.encode16()
617
618 data
619 |> Map.put("fallback-src-sha256", fallback_sha)
620 |> save_metadata(pack)
621 end
622 end
623
624 defp validate_has_all_files(pack, zip) do
625 with {:ok, f_list} <- :zip.unzip(zip, [:memory]) do
626 # Check if all files from the pack.json are in the archive
627 pack.files
628 |> Enum.all?(fn {_, from_manifest} ->
629 List.keyfind(f_list, to_charlist(from_manifest), 0)
630 end)
631 |> if(do: :ok, else: {:error, :incomplete})
632 end
633 end
634 end