12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- require 'dotenv/load'
- require 'json'
- require 'open-uri'
- require 'twitter'
-
- Dotenv.load
-
- TWITTER_CONSUMER_KEY = ENV["TWITTER_CONSUMER_KEY"]
- TWITTER_CONSUMER_SECRET = ENV["TWITTER_CONSUMER_SECRET"]
- TWITTER_ACCESS_TOKEN = ENV["TWITTER_ACCESS_TOKEN"]
- TWITTER_ACCESS_TOKEN_SECRET = ENV["TWITTER_ACCESS_TOKEN_SECRET"]
-
- YOUTUBE_DL_PATH = `which youtube-dl`.chomp
- FFMPEG_PATH = `which ffmpeg`.chomp
- FFPROBE_PATH = `which ffprobe`.chomp
-
- VIDEO_PATH = "/tmp/video.mp4"
- FRAME_PATH = "/tmp/frame.png"
-
- PLAYLIST_ID = ENV["PLAYLIST_ID"]
-
- throw "TWITTER_CONSUMER_KEY is required" unless TWITTER_CONSUMER_KEY
- throw "TWITTER_CONSUMER_SECRET is required" unless TWITTER_CONSUMER_SECRET
- throw "TWITTER_ACCESS_TOKEN is required" unless TWITTER_ACCESS_TOKEN
- throw "TWITTER_ACCESS_TOKEN_SECRET is required" unless TWITTER_ACCESS_TOKEN_SECRET
-
- throw "PLAYLIST_ID is required" unless PLAYLIST_ID
-
- throw "Can't find youtube-dl" if YOUTUBE_DL_PATH.empty?
- throw "Can't find ffprobe" if FFPROBE_PATH.empty?
- throw "Can't find ffmpeg" if FFMPEG_PATH.empty?
-
- class YouTubeService
- def initialize(playlist_id)
- @playlist_id = playlist_id
- end
-
- def fetch_random_frame_of_random_video
- download_random_video
- extract_frame
- delete_video
- end
-
- def download_random_video
- `#{YOUTUBE_DL_PATH} --playlist-random --max-downloads 1 -o #{VIDEO_PATH} -f mp4 #{@playlist_id}`
- end
-
- def extract_frame
- length = get_video_length
- random_second = rand(0..length)
- `#{FFMPEG_PATH} -v error -ss #{random_second} -i #{VIDEO_PATH} -frames 1 -y #{FRAME_PATH}`
- end
-
- def get_video_length
- `#{FFPROBE_PATH} -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 #{VIDEO_PATH}`.chomp.to_i
- end
-
- def delete_video
- `rm #{VIDEO_PATH}`
- end
-
- def delete_frame
- `rm #{FRAME_PATH}`
- end
- end
-
- class TwitterService
- def initialize(key, secret, token, token_secret)
- @twitter = Twitter::REST::Client.new do |config|
- config.consumer_key = key
- config.consumer_secret = secret
- config.access_token = token
- config.access_token_secret = token_secret
- end
- end
-
- def tweet_image(filepath)
- @twitter.update_with_media(String.new, File.new(filepath))
- end
- end
-
- youtube = YouTubeService.new(PLAYLIST_ID)
- youtube.fetch_random_frame_of_random_video
- twitter = TwitterService.new(
- TWITTER_CONSUMER_KEY,
- TWITTER_CONSUMER_SECRET,
- TWITTER_ACCESS_TOKEN,
- TWITTER_ACCESS_TOKEN_SECRET,
- )
- twitter.tweet_image(FRAME_PATH)
- youtube.delete_frame
|