Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Media Upload #51

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions server/lib/publisher/url_encoder.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
defmodule URLEncoder do
@doc """
Encodes a URL if it's not already encoded.
Returns {:ok, encoded_url} if successful, {:error, reason} otherwise.

## Examples

iex> URLEncoder.encode("https://example.com/path with spaces")
{:ok, "https://example.com/path%20with%20spaces"}

iex> URLEncoder.encode("https://example.com/path%20already%20encoded")
{:ok, "https://example.com/path%20already%20encoded"}

"""
def maybe_encode(url) when is_binary(url) do
cond do
already_encoded?(url) ->
{:ok, url}

valid_url?(url) ->
{:ok, URI.encode(url)}

true ->
{:error, "Invalid URL format"}
end
end

def maybe_encode(_), do: {:error, "URL must be a string"}

defp already_encoded?(url) do
String.match?(url, ~r/%[0-9A-Fa-f]{2}/)
end

defp valid_url?(url) do
uri = URI.parse(url)
!is_nil(uri.scheme) && !is_nil(uri.host)
end
end
15 changes: 8 additions & 7 deletions server/lib/publisher/wordpress/media.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ defmodule Publisher.WordPress.Media do
ext = extension_from_url(url)
filename = [slug, ext] |> Enum.join(".")

{:ok, resp} = Req.get(url)
{:ok, encoded_url} = URLEncoder.maybe_encode(url)
{:ok, resp} = Req.get(encoded_url)

response = if post_id do
upload_media(req, post_id, filename, content_type(resp), resp.body)
else
upload_media(req, filename, content_type(resp), resp.body)
end
response =
if post_id do
upload_media(req, post_id, filename, content_type(resp), resp.body)
else
upload_media(req, filename, content_type(resp), resp.body)
end

with {:ok, response} <- response,
{:ok, _} <- extract_status(response),
Expand All @@ -32,7 +34,6 @@ defmodule Publisher.WordPress.Media do
else
error -> error
end

end

defp content_type(resp) do
Expand Down
Loading