LasseRafn / ui-avatars

MIT License
1.05k stars 138 forks source link

Gravatar strips the spaces in the name from default URL #62

Closed christos closed 3 years ago

christos commented 3 years ago

It would seem that Gravatar strips any (encoded) spaces from the default URL (?d=DEFAULT_IMAGE_URL) breaking the expected image result.

Using the example from the README:

curl -I "https://www.gravatar.com/avatar/EMAIL_MD5?d=https%3A%2F%2Fui-avatars.com%2Fapi%2F/Lasse+Rafn/128"

HTTP/2 302
server: nginx
date: Thu, 04 Mar 2021 14:55:06 GMT
content-type: text/html; charset=utf-8
content-length: 0
location: https://i2.wp.com/ui-avatars.com/api//LasseRafn/128?ssl=1
last-modified: Wed, 11 Jan 1984 08:00:00 GMT
link: <https://www.gravatar.com/avatar/EMAIL_MD5?d=https%3A%2F%2Fui-avatars.com%2Fapi%2F/Lasse+Rafn/128>; rel="canonical"
CleanShot 2021-03-04 at 15 57 30@2x

Is there any way to encode first and last names separately in the URL path components so as not to loose the spaces?

(Awesome service BTW!)

LasseRafn commented 3 years ago

Hi, thanks man!

As far as I remember, it works if you url encode the entire URL (and not use + instead of space) so the ui-avatars url would actually be:

https%3A%2F%2Fui-avatars.com%2Fapi%2FLasse%2BRafn

And full url:

https://www.gravatar.com/avatar/EMAIL_MD5?d=https%3A%2F%2Fui-avatars.com%2Fapi%2FLasse%2BRafn

And the output is: Lasse+Rafn

Let me know if this doesn't work 😄

christos commented 3 years ago

Hey @LasseRafn

That did the trick, thanks!

I needed to first CGI escape the name, then URL encode the resulting URL. Here is the Ruby code for anyone who stumbles upon this issue in the future.

  def gravatar_url(user)
    email_md5 = Digest::MD5.hexdigest(user.email)
    full_name = CGI.escape(user.full_name)
    fallback_url = ERB::Util.url_encode("https://ui-avatars.com/api/#{full_name}")

    "https://www.gravatar.com/avatar/#{email_md5}?d=#{fallback_url}"
  end
LasseRafn commented 3 years ago

Awesome! Glad you managed to solve it and thanks for sharing solution 🙌🏻