commit: 3deab222dc3a9ed0e6bbd7d7c3a5e834a6361074
parent fd59c289e863d304403c694419d17bff4927373c
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date: Mon, 26 Dec 2022 15:40:56 +0100
XML: Return tuples for string_from_xpath/2
Diffstat:
2 files changed, 19 insertions(+), 25 deletions(-)
diff --git a/lib/news_parse_ex.ex b/lib/news_parse_ex.ex
@@ -6,24 +6,23 @@ defmodule NewsParseEx do
alias NewsParseEx.XML
def get_feed_type(doc) do
- root_name = XML.string_from_xpath(~s[name()], doc)
-
- if root_name != "feed" do
- {:error, "XML root isn't <feed> but #{root_name}"}
- end
-
- case XML.string_from_xpath(~s[/feed/namespace::*], doc) do
- "http://www.w3.org/2005/Atom" -> {:ok, :atom}
- e -> {:error, e}
+ with {_, {:ok, "feed"}} <- {:root_name, XML.string_from_xpath(~s[name()], doc)},
+ {:ok, namespace} <- XML.string_from_xpath(~s[/feed/namespace::*], doc) do
+ case namespace do
+ "http://www.w3.org/2005/Atom" -> {:ok, :atom}
+ e -> {:error, e}
+ end
+ else
+ {:root_name, name} -> {:error, "XML root isn't <feed> but <#{name}>"}
end
end
- def get_feed_title(doc, :atom), do: {:ok, XML.string_from_xpath(~s[/feed/title/text()], doc)}
- def get_feed_id(doc, :atom), do: {:ok, XML.string_from_xpath(~s[/feed/id/text()], doc)}
+ def get_feed_title(doc, :atom), do: XML.string_from_xpath(~s[/feed/title/text()], doc)
+ def get_feed_id(doc, :atom), do: XML.string_from_xpath(~s[/feed/id/text()], doc)
def get_feed_last_update(doc, :atom) do
- XML.string_from_xpath(~s[/feed/updated/text()], doc)
- |> DateTime.from_iso8601()
+ {:ok, updated} = XML.string_from_xpath(~s[/feed/updated/text()], doc)
+ DateTime.from_iso8601(updated)
end
def parse(str) when is_bitstring(str) do
diff --git a/lib/xml.ex b/lib/xml.ex
@@ -1,5 +1,6 @@
# Pleroma: A lightweight social networking server
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
+# Copyright © 2022 Haelwenn (lanodan) Monnier <contact+news_parse_ex@hacktivis.me>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule NewsParseEx.XML do
@@ -8,20 +9,14 @@ defmodule NewsParseEx.XML do
def string_from_xpath(_, :error), do: nil
def string_from_xpath(xpath, doc) do
- try do
- {:xmlObj, :string, res} = :xmerl_xpath.string('string(#{xpath})', doc)
+ {:xmlObj, :string, res} = :xmerl_xpath.string('string(#{xpath})', doc)
- res =
- res
- |> to_string
- |> String.trim()
+ res =
+ res
+ |> to_string
+ |> String.trim()
- if res == "", do: nil, else: res
- catch
- _e ->
- Logger.debug("Couldn't find xpath #{xpath} in XML doc")
- nil
- end
+ {:ok, res}
end
def parse_document(text) do