Skip to content

Instantly share code, notes, and snippets.

@brookemckim
Created September 15, 2011 20:08
Show Gist options
  • Save brookemckim/1220327 to your computer and use it in GitHub Desktop.
Save brookemckim/1220327 to your computer and use it in GitHub Desktop.
Swapping multi-bitrate HLS playlists with a single sub-playlist
require 'nokogiri'
require 'open-uri'
require 'httparty'
require 'pathname'
class CategoryItem
attr_accessor :title, :description, :feed, :element
def initialize(node)
@element = node
@title = node[:title]
@description = node[:description]
@feed = node[:feed]
end
end
class Category
attr_accessor :title, :description, :items, :sd_image, :hd_image, :element
def initialize(node)
@element = node
@title = node[:title]
@description = node[:description]
@sd_image = node[:sd_image]
@hd_image = node[:hd_image]
@items = []
node.children.each do |child|
@items << CategoryItem.new(child) if child.element?
end
end
end
class Playlist
attr_reader :url, :file, :playlists
def initialize(url)
@file = HTTParty.get(url).body
@playlists = []
parse
end
def parse
@file.each_line do |line|
@playlists << line.strip if has_playlist?(line)
end
end
private
def has_playlist?(str)
true if /.m3u8/.match(str)
end
end
class FeedItem
attr_accessor :stream_url, :title, :description, :element, :playlist
def initialize(node)
@element = node
@title = node.at_xpath("title").content
@description = node.at_xpath("description").content
@stream_url = node.at_xpath("*/streamUrl").content
@playlist = Playlist.new(@stream_url)
end
def playlists
playlist.playlists
end
end
class Feed
attr_accessor :items, :element, :filename
def initialize(node, filename)
@element = node
@filename = filename
@items = []
node.xpath("//item").each do |item|
@items << FeedItem.new(item)
end
end
end
# Original Feed Url
url = ""
# Where to save the modified files
output_path = ""
categories = []
feeds = []
doc = Nokogiri::XML(open(url))
doc.xpath("//category").each do |category|
categories << Category.new(category)
end
categories.each do |cat|
cat.items.each do |item|
feeds << Feed.new(Nokogiri::XML(open(item.feed)), Pathname.new(item.feed).basename.to_s)
end
end
feeds.each do |feed|
feed.items.each do |item|
item.element.at_xpath("*/streamUrl").content = item.playlists[0]
end
puts "Saving #{feed.filename}"
File.open(File.join(output_path, feed.filename), "w") do |f|
f << feed.element.to_xml
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment