ぼざクリタグ広場 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.
 
 
 
 
 

74 lines
2.0 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: nil, published_before: nil, page_token: nil
  11. get_json('/search', {
  12. part: 'snippet',
  13. type: 'video',
  14. q:,
  15. order: 'date',
  16. maxResults: 50,
  17. regionCode: 'JP',
  18. relevanceLanguage: 'ja',
  19. publishedAfter: published_after&.iso8601,
  20. publishedBefore: published_before&.iso8601,
  21. pageToken: page_token }.compact)
  22. end
  23. def videos ids
  24. return { 'items' => [] } if ids.empty?
  25. get_json('/videos', part: 'snippet,status,contentDetails', id: ids.join(','))
  26. end
  27. def playlist_items playlist_id:, page_token: nil
  28. get_json('/playlistItems', {
  29. part: 'snippet,contentDetails,status',
  30. playlistId: playlist_id,
  31. maxResults: 50,
  32. pageToken: page_token }.compact)
  33. end
  34. def channel id: nil, handle: nil
  35. raise ArgumentError, 'id or handle is required' if id.present? == handle.present?
  36. params = { part: 'snippet,contentDetails' }
  37. params[:id] = id if id.present?
  38. params[:forHandle] = handle if handle.present?
  39. get_json('/channels', params)
  40. end
  41. private
  42. def get_json path, params
  43. uri = URI(ENDPOINT + path)
  44. uri.query = URI.encode_www_form(params.merge(key: @api_key))
  45. response = Net::HTTP.start(uri.host,
  46. uri.port,
  47. use_ssl: true,
  48. open_timeout: 10,
  49. read_timeout: 30) do |http|
  50. http.get(uri)
  51. end
  52. unless response.is_a?(Net::HTTPSuccess)
  53. raise "YouTube API error: #{ response.code } #{ response.body }"
  54. end
  55. JSON.parse(response.body)
  56. end
  57. end
  58. end