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