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