Skip to content

Instantly share code, notes, and snippets.

@neonichu
Created January 12, 2014 21:28
Show Gist options
  • Select an option

  • Save neonichu/8390810 to your computer and use it in GitHub Desktop.

Select an option

Save neonichu/8390810 to your computer and use it in GitHub Desktop.
This script gets the URL of your frontmost Safari tab, finds the YouTube MP4 URL for it and passes it to your AppleTV. You need to install the rb-appscript and airplay gems first. Tested on OS X 10.9 only.
#!/usr/bin/env ruby
##
## This script gets the URL of your frontmost Safari tab, finds the
## YouTube MP4 URL for it and passes it to your AppleTV.
##
require 'airplay/cli'
require 'appscript'
require 'net/http'
def get_safari_url()
url = Appscript::app('Safari').documents[1].URL.get
if not /youtube\.com/.match(url) then
puts 'Your frontmost Safari tab does not contain a YouTube video.'
exit 1
end
return url
end
def get_youtube_mp4(yt_url)
yt_uid = yt_url.split('=').last
yt_url = 'http://www.youtube.com/get_video_info?video_id=' + yt_uid
res = Net::HTTP.get_response(URI(yt_url))
map = res.body.split('url_encoded_fmt_stream_map=').last
map = URI.decode(map.split('&').first)
map.split(',').each { |fragment|
type = ''
video_url = ''
fragment.split('&').each { |parameter|
if /^sig=/.match(parameter) then
video_url = video_url + '&signature=' + parameter.split('=').last
elsif /^url/.match(parameter) then
url = parameter.split('=').last
video_url = URI.decode(url) + video_url
elsif /^type/.match(parameter) then
type = URI.decode(parameter.split('=').last)
end
}
if /^video\/mp4/.match(type) then
return video_url
end
}
end
begin
video_url = get_youtube_mp4(get_safari_url())
Airplay::CLI.play(video_url,
{ device: Airplay.devices.first })
rescue Interrupt
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment