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