diff --git a/lib/yt/models/content_detail.rb b/lib/yt/models/content_detail.rb index 0777dc53..48e4fe47 100644 --- a/lib/yt/models/content_detail.rb +++ b/lib/yt/models/content_detail.rb @@ -14,6 +14,8 @@ def initialize(options = {}) end # @return [Integer] the duration of the video (in seconds). + # Returns 0 for ongoing live broadcasts and premieres, since the + # YouTube API does not report a duration until they have ended. has_attribute :duration, default: 0 do |value| to_seconds value end @@ -59,6 +61,8 @@ def length # such as minutes is not part of the standard either; in this context, # it will be interpreted as "0 minutes and 2 seconds". def to_seconds(iso8601_duration) + return iso8601_duration.to_i unless iso8601_duration.is_a? String + match = iso8601_duration.match %r{^P(?:|(?\d*?)W)(?:|(?\d*?)D)(?:|T(?:|(?\d*?)H)(?:|(?\d*?)M)(?:|(?\d*?)S))$} weeks = (match[:weeks] || '0').to_i days = (match[:days] || '0').to_i diff --git a/lib/yt/models/video.rb b/lib/yt/models/video.rb index d3f133fb..e4e7ba23 100644 --- a/lib/yt/models/video.rb +++ b/lib/yt/models/video.rb @@ -245,10 +245,14 @@ def self_declared_made_for_kids? # @!attribute [r] duration # @return [Integer] the duration of the video (in seconds). + # Returns 0 for ongoing live broadcasts and premieres, since the + # YouTube API does not report a duration until they have ended. delegate :duration, to: :content_detail # @!attribute [r] duration # @return [String] the length of the video as an ISO 8601 time, HH:MM:SS. + # Returns "00:00:00" for ongoing live broadcasts and premieres, since + # the YouTube API does not report a duration until they have ended. delegate :length, to: :content_detail # @return [Boolean] whether the video is available in 3D. diff --git a/spec/models/content_detail_spec.rb b/spec/models/content_detail_spec.rb index 901fef7c..27f248ff 100644 --- a/spec/models/content_detail_spec.rb +++ b/spec/models/content_detail_spec.rb @@ -41,6 +41,11 @@ let(:data) { {"duration"=>"PT51S"} } it { expect(content_detail.duration).to eq 51 } end + + context 'given a content_detail without a duration (e.g. an upcoming premiere)' do + let(:data) { {} } + it { expect(content_detail.duration).to eq 0 } + end end describe '#length' do @@ -48,5 +53,10 @@ let(:data) { {"duration"=>"PT1H18M52S"} } it { expect(content_detail.length).to eq '01:18:52' } end + + context 'given a content_detail without a duration (e.g. an upcoming premiere)' do + let(:data) { {} } + it { expect(content_detail.length).to eq '00:00:00' } + end end end \ No newline at end of file