How to get video on a channel using youtube_it gem

How can I use git youtube_it for Ruby on Rails to get videos from youtube channel ( https://www.youtube.com/channel/UCwHnsUEYrQUTUxC4dvrv0QQ )?

Or can you advise me another stone that can help me?

+4
source share
1 answer

this is how i do it.

I have this in my config / initializers / youtube_it.rb:

$youtube_it = YouTubeIt::Client.new(dev_key: ENV['YOUTUBE_KEY'])

Get the first page of the video:

    query = {
      author: channel_url.split('/').last,
      order_by: 'published',
      page: 1,
    }

    # scraping from newesr to oldest
    videos = $youtube_it.videos_by(query).videos

And here is an example of scrambling, where you plan the task to periodically call the cleaning method.

The method first clears from the latest videos to the oldest. It backward_scrape_doneis then set to true, and then discards only new videos.

class Import < ActiveRecord::Base

  def scrape
    query = {
      author: channel_url.split('/').last,
      order_by: 'published',
    }

    query[:page] = cursor

    # scraping from newesr to oldest
    videos = fetch_videos(query)


    if videos.count == 0
      # we've reached the end
      self.backward_scrape_done = true
      self.cursor = 0
    end

    for video in videos
      add_video video
    end

    # next time scrape next page
    self.cursor = cursor + 1

  ensure
    self.scraped_at = Time.now
    self.save!
  end

  def fetch_videos(query)
    $youtube_it.videos_by(query).videos
  end


  def add_video video
    url = video.player_url.
      gsub(/[?&]feature=youtube_gdata_player/, '')

    # skip this video if its already there
    if Video.where(youtube_url: url).first
      self.cursor = 0
      save
      return
    end

    video = YoutubeVideo.create!(
      title: video.title,
      duration: video.duration,
      description: video.description,
      youtube_url: url,
    )
  end
end

, !

. youtube API V2, , API, , yt gem, :

https://github.com/Fullscreen/yt

+1

Source: https://habr.com/ru/post/1546573/


All Articles