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