lib/yt/annotations/for.rb in yt-annotations-1.3.2 vs lib/yt/annotations/for.rb in yt-annotations-1.4.0

- old
+ new

@@ -1,7 +1,8 @@ require 'yt/annotations/branding' require 'yt/annotations/card' +require 'yt/annotations/end_screen' require 'yt/annotations/featured' require 'yt/annotations/label' require 'yt/annotations/note' require 'yt/annotations/speech' require 'yt/annotations/spotlight' @@ -10,25 +11,44 @@ module Yt module Annotations module For def for(video_id) - request = Net::HTTP::Get.new "/annotations_invideo?video_id=#{video_id}" - options = ['www.youtube.com', 443, {use_ssl: true}] - response = Net::HTTP.start(*options) {|http| http.request request} - xml_to_annotations(Hash.from_xml response.body).sort_by &:starts_at + (annotations(video_id) + end_screens(video_id)).sort_by &:starts_at end private + def annotations(video_id) + data = fetch "/annotations_invideo?video_id=#{video_id}" + xml_to_annotations(Hash.from_xml data) + end + + def end_screens(video_id) + data = fetch "/get_endscreen?v=#{video_id}" + data = data.partition("\n").last + data.present? ? json_to_annotations(JSON data) : [] + end + + def fetch(path) + request = Net::HTTP::Get.new path + options = ['www.youtube.com', 443, {use_ssl: true}] + response = Net::HTTP.start(*options) {|http| http.request request} + response.body + end + def xml_to_annotations(xml) annotations = xml['document']['annotations'] annotations = Array.wrap (annotations || {})['annotation'] annotations = merge_highlights annotations annotations = exclude_drawers annotations annotations.map{|data| annotation_class(data).new data} end + def json_to_annotations(json) + annotations = json['elements'] + annotations.map{|data| Annotations::EndScreen.new data} + end def annotation_class(data) case data['style'] when 'anchored', 'speech' then Annotations::Speech when 'branding' then Annotations::Branding