diff --git a/lib/lita/handlers/google_images.rb b/lib/lita/handlers/google_images.rb index 792e62f..30f73af 100644 --- a/lib/lita/handlers/google_images.rb +++ b/lib/lita/handlers/google_images.rb @@ -29,7 +29,7 @@ def fetch(response) if data["responseStatus"] == 200 choice = data["responseData"]["results"].sample if choice - response.reply "#{choice["unescapedUrl"]}#.png" + response.reply ensure_extension(choice["unescapedUrl"]) else response.reply %{No images found for "#{query}".} end @@ -43,6 +43,14 @@ def fetch(response) private + def ensure_extension(url) + if [".gif", ".jpg", ".jpeg", ".png"].any? { |ext| url.end_with?(ext) } + url + else + "#{url}#.png" + end + end + def safe_value safe = Lita.config.handlers.google_images.safe_search || "active" safe = safe.to_s.downcase diff --git a/spec/lita/handlers/google_images_spec.rb b/spec/lita/handlers/google_images_spec.rb index 8f83ba7..2094115 100644 --- a/spec/lita/handlers/google_images_spec.rb +++ b/spec/lita/handlers/google_images_spec.rb @@ -17,6 +17,26 @@ it "replies with a matching image URL on success" do allow(response).to receive(:body).and_return(<<-JSON.chomp +{ + "responseStatus": 200, + "responseData": { + "results": [ + { + "unescapedUrl": "http://www.example.com/path/to/an/image" + } + ] + } +} +JSON + ) + send_command("image carl") + expect(replies.last).to eq( + "http://www.example.com/path/to/an/image#.png" + ) + end + + it "doesn't append a fake file extension if the image URL has a common image extension" do + allow(response).to receive(:body).and_return(<<-JSON.chomp { "responseStatus": 200, "responseData": { @@ -31,7 +51,7 @@ ) send_command("image carl") expect(replies.last).to eq( - "http://www.example.com/path/to/an/image.jpg#.png" + "http://www.example.com/path/to/an/image.jpg" ) end