Fork of Pleroma with site-specific changes and feature branches https://git.pleroma.social/pleroma/pleroma
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

655 rindas
19KB

  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2021 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, 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("/api/pleroma/emoji/packs?page=#{opts[:page]}&page_size=#{opts[:page_size]}")
  183. |> http_get()
  184. end
  185. end
  186. @spec list_local(keyword()) :: {:ok, map(), non_neg_integer()}
  187. def list_local(opts) do
  188. with {:ok, results} <- list_packs_dir() do
  189. all_packs =
  190. results
  191. |> Enum.map(fn name ->
  192. case load_pack(name) do
  193. {:ok, pack} -> pack
  194. _ -> nil
  195. end
  196. end)
  197. |> Enum.reject(&is_nil/1)
  198. packs =
  199. all_packs
  200. |> paginate(opts[:page], opts[:page_size])
  201. |> Map.new(fn pack -> {pack.name, validate_pack(pack)} end)
  202. {:ok, packs, length(all_packs)}
  203. end
  204. end
  205. @spec get_archive(String.t()) :: {:ok, binary()} | {:error, atom()}
  206. def get_archive(name) do
  207. with {:ok, pack} <- load_pack(name),
  208. :ok <- validate_downloadable(pack) do
  209. {:ok, fetch_archive(pack)}
  210. end
  211. end
  212. @spec download(String.t(), String.t(), String.t()) :: {:ok, t()} | {:error, atom()}
  213. def download(name, url, as) do
  214. uri = url |> String.trim() |> URI.parse()
  215. with :ok <- validate_shareable_packs_available(uri),
  216. {:ok, remote_pack} <-
  217. uri |> URI.merge("/api/pleroma/emoji/pack?name=#{name}") |> http_get(),
  218. {:ok, %{sha: sha, url: url} = pack_info} <- fetch_pack_info(remote_pack, uri, name),
  219. {:ok, archive} <- download_archive(url, sha),
  220. pack <- copy_as(remote_pack, as || name),
  221. {:ok, _} = unzip(archive, pack_info, remote_pack, pack) do
  222. # Fallback can't contain a pack.json file, since that would cause the fallback-src-sha256
  223. # in it to depend on itself
  224. if pack_info[:fallback] do
  225. save_pack(pack)
  226. else
  227. {:ok, pack}
  228. end
  229. end
  230. end
  231. @spec save_metadata(map(), t()) :: {:ok, t()} | {:error, File.posix()}
  232. def save_metadata(metadata, %__MODULE__{} = pack) do
  233. pack
  234. |> Map.put(:pack, metadata)
  235. |> save_pack()
  236. end
  237. @spec update_metadata(String.t(), map()) :: {:ok, t()} | {:error, File.posix()}
  238. def update_metadata(name, data) do
  239. with {:ok, pack} <- load_pack(name) do
  240. if fallback_sha_changed?(pack, data) do
  241. update_sha_and_save_metadata(pack, data)
  242. else
  243. save_metadata(data, pack)
  244. end
  245. end
  246. end
  247. @spec load_pack(String.t()) :: {:ok, t()} | {:error, :file.posix()}
  248. def load_pack(name) do
  249. pack_file = Path.join([emoji_path(), name, "pack.json"])
  250. with {:ok, _} <- File.stat(pack_file),
  251. {:ok, pack_data} <- File.read(pack_file) do
  252. pack =
  253. from_json(
  254. pack_data,
  255. %{
  256. pack_file: pack_file,
  257. path: Path.dirname(pack_file),
  258. name: name
  259. }
  260. )
  261. files_count =
  262. pack.files
  263. |> Map.keys()
  264. |> length()
  265. {:ok, Map.put(pack, :files_count, files_count)}
  266. end
  267. end
  268. @spec emoji_path() :: Path.t()
  269. defp emoji_path do
  270. [:instance, :static_dir]
  271. |> Pleroma.Config.get!()
  272. |> Path.join("emoji")
  273. end
  274. defp validate_emoji_not_exists(shortcode, force \\ false)
  275. defp validate_emoji_not_exists(_shortcode, true), do: :ok
  276. defp validate_emoji_not_exists(shortcode, _) do
  277. if Emoji.exist?(shortcode) do
  278. {:error, :already_exists}
  279. else
  280. :ok
  281. end
  282. end
  283. defp write_pack_contents(path) do
  284. pack = %__MODULE__{
  285. files: files_from_path(path),
  286. path: path,
  287. pack_file: Path.join(path, "pack.json")
  288. }
  289. case save_pack(pack) do
  290. {:ok, _pack} -> Path.basename(path)
  291. _ -> nil
  292. end
  293. end
  294. defp files_from_path(path) do
  295. txt_path = Path.join(path, "emoji.txt")
  296. if File.exists?(txt_path) do
  297. # There's an emoji.txt file, it's likely from a pack installed by the pack manager.
  298. # Make a pack.json file from the contents of that emoji.txt file
  299. # FIXME: Copy-pasted from Pleroma.Emoji/load_from_file_stream/2
  300. # Create a map of shortcodes to filenames from emoji.txt
  301. txt_path
  302. |> File.read!()
  303. |> String.split("\n")
  304. |> Enum.map(&String.trim/1)
  305. |> Enum.map(fn line ->
  306. case String.split(line, ~r/,\s*/) do
  307. # This matches both strings with and without tags
  308. # and we don't care about tags here
  309. [name, file | _] ->
  310. file_dir_name = Path.dirname(file)
  311. if String.ends_with?(path, file_dir_name) do
  312. {name, Path.basename(file)}
  313. else
  314. {name, file}
  315. end
  316. _ ->
  317. nil
  318. end
  319. end)
  320. |> Enum.reject(&is_nil/1)
  321. |> Map.new()
  322. else
  323. # If there's no emoji.txt, assume all files
  324. # that are of certain extensions from the config are emojis and import them all
  325. pack_extensions = Pleroma.Config.get!([:emoji, :pack_extensions])
  326. Emoji.Loader.make_shortcode_to_file_map(path, pack_extensions)
  327. end
  328. end
  329. defp validate_pack(pack) do
  330. info =
  331. if downloadable?(pack) do
  332. archive = fetch_archive(pack)
  333. archive_sha = :crypto.hash(:sha256, archive) |> Base.encode16()
  334. pack.pack
  335. |> Map.put("can-download", true)
  336. |> Map.put("download-sha256", archive_sha)
  337. else
  338. Map.put(pack.pack, "can-download", false)
  339. end
  340. Map.put(pack, :pack, info)
  341. end
  342. defp downloadable?(pack) do
  343. # If the pack is set as shared, check if it can be downloaded
  344. # That means that when asked, the pack can be packed and sent to the remote
  345. # Otherwise, they'd have to download it from external-src
  346. pack.pack["share-files"] &&
  347. Enum.all?(pack.files, fn {_, file} ->
  348. pack.path
  349. |> Path.join(file)
  350. |> File.exists?()
  351. end)
  352. end
  353. defp create_archive_and_cache(pack, hash) do
  354. files = ['pack.json' | Enum.map(pack.files, fn {_, file} -> to_charlist(file) end)]
  355. {:ok, {_, result}} =
  356. :zip.zip('#{pack.name}.zip', files, [:memory, cwd: to_charlist(pack.path)])
  357. ttl_per_file = Pleroma.Config.get!([:emoji, :shared_pack_cache_seconds_per_file])
  358. overall_ttl = :timer.seconds(ttl_per_file * Enum.count(files))
  359. @cachex.put(
  360. :emoji_packs_cache,
  361. pack.name,
  362. # if pack.json MD5 changes, the cache is not valid anymore
  363. %{hash: hash, pack_data: result},
  364. # Add a minute to cache time for every file in the pack
  365. ttl: overall_ttl
  366. )
  367. result
  368. end
  369. defp save_pack(pack) do
  370. with {:ok, json} <- Jason.encode(pack, pretty: true),
  371. :ok <- File.write(pack.pack_file, json) do
  372. {:ok, pack}
  373. end
  374. end
  375. defp from_json(json, attrs) do
  376. map = Jason.decode!(json)
  377. pack_attrs =
  378. attrs
  379. |> Map.merge(%{
  380. files: map["files"],
  381. pack: map["pack"]
  382. })
  383. struct(__MODULE__, pack_attrs)
  384. end
  385. defp validate_shareable_packs_available(uri) do
  386. with {:ok, %{"links" => links}} <- uri |> URI.merge("/.well-known/nodeinfo") |> http_get(),
  387. # Get the actual nodeinfo address and fetch it
  388. {:ok, %{"metadata" => %{"features" => features}}} <-
  389. links |> List.last() |> Map.get("href") |> http_get() do
  390. if Enum.member?(features, "shareable_emoji_packs") do
  391. :ok
  392. else
  393. {:error, :not_shareable}
  394. end
  395. end
  396. end
  397. defp validate_not_empty(list) do
  398. if Enum.all?(list, fn i -> is_binary(i) and i != "" end) do
  399. :ok
  400. else
  401. {:error, :empty_values}
  402. end
  403. end
  404. defp save_file(%Plug.Upload{path: upload_path}, pack, filename) do
  405. file_path = Path.join(pack.path, filename)
  406. create_subdirs(file_path)
  407. with {:ok, _} <- File.copy(upload_path, file_path) do
  408. :ok
  409. end
  410. end
  411. defp put_emoji(pack, shortcode, filename) do
  412. files = Map.put(pack.files, shortcode, filename)
  413. %{pack | files: files, files_count: length(Map.keys(files))}
  414. end
  415. defp delete_emoji(pack, shortcode) do
  416. files = Map.delete(pack.files, shortcode)
  417. %{pack | files: files}
  418. end
  419. defp rename_file(pack, filename, new_filename) do
  420. old_path = Path.join(pack.path, filename)
  421. new_path = Path.join(pack.path, new_filename)
  422. create_subdirs(new_path)
  423. with :ok <- File.rename(old_path, new_path) do
  424. remove_dir_if_empty(old_path, filename)
  425. end
  426. end
  427. defp create_subdirs(file_path) do
  428. with true <- String.contains?(file_path, "/"),
  429. path <- Path.dirname(file_path),
  430. false <- File.exists?(path) do
  431. File.mkdir_p!(path)
  432. end
  433. end
  434. defp remove_file(pack, shortcode) do
  435. with {:ok, filename} <- get_filename(pack, shortcode),
  436. emoji <- Path.join(pack.path, filename),
  437. :ok <- File.rm(emoji) do
  438. remove_dir_if_empty(emoji, filename)
  439. end
  440. end
  441. defp remove_dir_if_empty(emoji, filename) do
  442. dir = Path.dirname(emoji)
  443. if String.contains?(filename, "/") and File.ls!(dir) == [] do
  444. File.rmdir!(dir)
  445. else
  446. :ok
  447. end
  448. end
  449. defp get_filename(pack, shortcode) do
  450. with %{^shortcode => filename} when is_binary(filename) <- pack.files,
  451. file_path <- Path.join(pack.path, filename),
  452. {:ok, _} <- File.stat(file_path) do
  453. {:ok, filename}
  454. else
  455. {:error, _} = error ->
  456. error
  457. _ ->
  458. {:error, :doesnt_exist}
  459. end
  460. end
  461. defp http_get(%URI{} = url), do: url |> to_string() |> http_get()
  462. defp http_get(url) do
  463. with {:ok, %{body: body}} <- Pleroma.HTTP.get(url, [], pool: :default) do
  464. Jason.decode(body)
  465. end
  466. end
  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. defp validate_downloadable(pack) do
  480. if downloadable?(pack), do: :ok, else: {:error, :cant_download}
  481. end
  482. defp copy_as(remote_pack, local_name) do
  483. path = Path.join(emoji_path(), local_name)
  484. %__MODULE__{
  485. name: local_name,
  486. path: path,
  487. files: remote_pack["files"],
  488. pack_file: Path.join(path, "pack.json")
  489. }
  490. end
  491. defp unzip(archive, pack_info, remote_pack, local_pack) do
  492. with :ok <- File.mkdir_p!(local_pack.path) do
  493. files = Enum.map(remote_pack["files"], fn {_, path} -> to_charlist(path) end)
  494. # Fallback cannot contain a pack.json file
  495. files = if pack_info[:fallback], do: files, else: ['pack.json' | files]
  496. :zip.unzip(archive, cwd: to_charlist(local_pack.path), file_list: files)
  497. end
  498. end
  499. defp fetch_pack_info(remote_pack, uri, name) do
  500. case remote_pack["pack"] do
  501. %{"share-files" => true, "can-download" => true, "download-sha256" => sha} ->
  502. {:ok,
  503. %{
  504. sha: sha,
  505. url: URI.merge(uri, "/api/pleroma/emoji/packs/archive?name=#{name}") |> to_string()
  506. }}
  507. %{"fallback-src" => src, "fallback-src-sha256" => sha} when is_binary(src) ->
  508. {:ok,
  509. %{
  510. sha: sha,
  511. url: src,
  512. fallback: true
  513. }}
  514. _ ->
  515. {:error, "The pack was not set as shared and there is no fallback src to download from"}
  516. end
  517. end
  518. defp download_archive(url, sha) do
  519. with {:ok, %{body: archive}} <- Pleroma.HTTP.get(url) do
  520. if Base.decode16!(sha) == :crypto.hash(:sha256, archive) do
  521. {:ok, archive}
  522. else
  523. {:error, :invalid_checksum}
  524. end
  525. end
  526. end
  527. defp fetch_archive(pack) do
  528. hash = :crypto.hash(:md5, File.read!(pack.pack_file))
  529. case @cachex.get!(:emoji_packs_cache, pack.name) do
  530. %{hash: ^hash, pack_data: archive} -> archive
  531. _ -> create_archive_and_cache(pack, hash)
  532. end
  533. end
  534. defp fallback_sha_changed?(pack, data) do
  535. is_binary(data[:"fallback-src"]) and data[:"fallback-src"] != pack.pack["fallback-src"]
  536. end
  537. defp update_sha_and_save_metadata(pack, data) do
  538. with {:ok, %{body: zip}} <- Pleroma.HTTP.get(data[:"fallback-src"]),
  539. :ok <- validate_has_all_files(pack, zip) do
  540. fallback_sha = :sha256 |> :crypto.hash(zip) |> Base.encode16()
  541. data
  542. |> Map.put("fallback-src-sha256", fallback_sha)
  543. |> save_metadata(pack)
  544. end
  545. end
  546. defp validate_has_all_files(pack, zip) do
  547. with {:ok, f_list} <- :zip.unzip(zip, [:memory]) do
  548. # Check if all files from the pack.json are in the archive
  549. pack.files
  550. |> Enum.all?(fn {_, from_manifest} ->
  551. List.keyfind(f_list, to_charlist(from_manifest), 0)
  552. end)
  553. |> if(do: :ok, else: {:error, :incomplete})
  554. end
  555. end
  556. end