predator_pics/get_random_image.rb

50 lines
1.9 KiB
Ruby
Raw Normal View History

2024-11-13 13:27:23 +00:00
=begin
Copyright (C) 2024 Hexaitos
This file is part of "Predator Pics"
Predator Pics is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
Predator Pics is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Foobar. If not, see <https://www.gnu.org/licenses/>.
Contact: me@bateleur.org, me@hexaitos.com.
=end
2024-11-10 13:12:42 +00:00
def get_random_image(photos)
random_photo = photos.sample
conn = Faraday.new(url: 'https://commons.wikimedia.org/w/api.php') do |faraday|
2024-11-13 13:27:23 +00:00
faraday.adapter Faraday.default_adapter
2024-11-10 13:12:42 +00:00
end
params = {
action: 'query',
prop: 'imageinfo',
2024-11-13 13:27:23 +00:00
titles: "#{random_photo}",
2024-11-10 13:12:42 +00:00
iiprop: 'url|user|extmetadata',
iiurlwidth: 1000,
2024-11-13 13:27:23 +00:00
format: 'json'
2024-11-10 13:12:42 +00:00
}
response = conn.get do |req|
req.params = params
end
begin
data = JSON.parse(response.body)
info = data['query']['pages'].values.first
user = info['imageinfo'].first['user']
user_url = info['imageinfo'].first['extmetadata']['Artist']['value']
url = info['imageinfo'].first['url']
license = info['imageinfo'].first['extmetadata']['LicenseShortName']['value']
license_url = info['imageinfo'].first['extmetadata']['LicenseUrl']['value']
desc = info['imageinfo'].first['extmetadata']['ImageDescription']['value']
thumb = info['imageinfo'].first['thumburl']
rescue
puts "ERROR OCCURRED"
return {:user => user, :url => url, :thumb => thumb, :license => license, :desc => desc, :license_url => license_url, :user_url => user_url}
end
2024-11-10 13:12:42 +00:00
return {:user => user, :url => url, :thumb => thumb, :license => license, :desc => desc, :license_url => license_url, :user_url => user_url}
2024-11-10 13:12:42 +00:00
end