logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://hacktivis.me/git/pleroma.git

pack.ex (19316B)


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