ぼざクリタグ広場 https://hub.nizika.monster
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

69 lines
1.8 KiB

  1. require 'json'
  2. require 'net/http'
  3. require 'uri'
  4. module Youtube
  5. class ApiClient
  6. ENDPOINT = 'https://www.googleapis.com/youtube/v3'
  7. def initialize api_key: ENV.fetch('YOUTUBE_API_KEY')
  8. @api_key = api_key
  9. end
  10. def search_videos q:, published_after:, page_token: nil
  11. get_json('/search', {
  12. part: 'snippet',
  13. type: 'video',
  14. q: q,
  15. order: 'date',
  16. maxResults: 50,
  17. publishedAfter: published_after.iso8601,
  18. pageToken: page_token }.compact)
  19. end
  20. def videos ids
  21. return { 'items' => [] } if ids.empty?
  22. get_json('/videos', part: 'snippet,status,contentDetails', id: ids.join(','))
  23. end
  24. def playlist_items playlist_id:, page_token: nil
  25. get_json('/playlistItems', {
  26. part: 'snippet,contentDetails,status',
  27. playlistId: playlist_id,
  28. maxResults: 50,
  29. pageToken: page_token }.compact)
  30. end
  31. def channel id: nil, handle: nil
  32. params = { part: 'snippet,contentDetails' }
  33. params[:id] = id if id
  34. params[:forHandle] = handle if handle
  35. get_json('/channels', params)
  36. end
  37. private
  38. def get_json path, params
  39. uri = URI(ENDPOINT + path)
  40. uri.query = URI.encode_www_form(params.merge(key: @api_key))
  41. response = Net::HTTP.start(uri.host,
  42. uri.port,
  43. use_ssl: true,
  44. open_timeout: 10,
  45. read_timeout: 30) do |http|
  46. http.get(uri)
  47. end
  48. unless response.is_a?(Net::HTTPSuccess)
  49. raise "YouTube API error: #{ response.code } #{ response.body }"
  50. end
  51. JSON.parse(response.body)
  52. end
  53. end
  54. end