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