repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/id3/v2_header_test.rb
test/wahwah/id3/v2_header_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::ID3::V2HeaderTest < Minitest::Test def test_header content = StringIO.new("ID3\x04\x00\x00\x00\x00\x00-".b) header = WahWah::ID3::V2Header.new(content) assert !header.has_extended_header? assert header.valid? assert_equal 55, header.size assert_equal 4, header.major_version end def test_has_extended_header content = StringIO.new("ID3\x04\x00@\x00\x00\x00 \x00\x00\x00\f\x01 \x05\x065uMx".b) header = WahWah::ID3::V2Header.new(content) assert header.has_extended_header? assert header.valid? assert_equal 42, header.size assert_equal 4, header.major_version end def test_invalid_header content = StringIO.new("id3\x04\x00\x00\x00\x00\x00-".b) header = WahWah::ID3::V2Header.new(content) assert !header.valid? end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/id3/v1_test.rb
test/wahwah/id3/v1_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::ID3::V1Test < Minitest::Test def test_parse content = StringIO.new("TAGChina Girl\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Iggy Pop\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00The Idiot\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x001977Iggy Pop Rocks\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05\x11".b) tag = WahWah::ID3::V1.new(content) assert_equal "v1", tag.version assert_equal 128, tag.size assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_equal 5, tag.track assert_equal ["Iggy Pop Rocks"], tag.comments end def test_no_track_number content = StringIO.new("TAGChina Girl\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Iggy Pop\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00The Idiot\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x001977Iggy Pop Rockssssssssssssssss\x00\x11".b) tag = WahWah::ID3::V1.new(content) assert_equal "v1", tag.version assert_equal 128, tag.size assert_equal "China Girl", tag.title assert_equal "Iggy Pop", tag.artist assert_equal "The Idiot", tag.album assert_equal "1977", tag.year assert_equal "Rock", tag.genre assert_nil tag.track assert_equal ["Iggy Pop Rockssssssssssssssss"], tag.comments end def test_invalid_id3 content = StringIO.new("tagChina Girl\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Iggy Pop\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00The Idiot\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x001977Iggy Pop Rocks\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05\x11".b) tag = WahWah::ID3::V1.new(content) assert !tag.valid? end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/id3/image_frame_body_test.rb
test/wahwah/id3/image_frame_body_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::ID3::ImageFrameBodyTest < Minitest::Test def test_v2_image_frame_body content = "\x00JPG\x00\x00\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\x01\x02\x01\x00H\x00H\x00\x00\xFF\xE1\x1A\xE0Exif\x00\x00MM".b value = WahWah::ID3::ImageFrameBody.new(content, 2).value assert_equal "image/jpeg", value[:mime_type] assert_equal :other, value[:type] assert_equal "\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\x01\x02\x01\x00H\x00H\x00\x00\xFF\xE1\x1A\xE0Exif\x00\x00MM".b, value[:data] end def test_v3_4_image_frame_body content = "\x01image/jpeg\x00\x03\xFF\xFE\x00\x00\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\x01\x01\x00\x00H\x00H\x00\x00\xFF\xE1\x00\xCAExif\x00\x00MM".b value = WahWah::ID3::ImageFrameBody.new(content, 4).value assert_equal "image/jpeg", value[:mime_type] assert_equal :cover_front, value[:type] assert_equal "\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\x01\x01\x00\x00H\x00H\x00\x00\xFF\xE1\x00\xCAExif\x00\x00MM".b, value[:data] end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/id3/comment_frame_body_test.rb
test/wahwah/id3/comment_frame_body_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::ID3::CommentFrameBodyTest < Minitest::Test def test_iso_8859_1_encode_comment value = WahWah::ID3::CommentFrameBody.new("\x00eng\x00Iggy Pop Rocks".b, 4).value assert_equal "Iggy Pop Rocks", value assert_equal "UTF-8", value.encoding.name end def test_utf_16_encode_comment value = WahWah::ID3::CommentFrameBody.new("\x01eng\xFF\xFE\x00\x00\xFF\xFEI\x00g\x00g\x00y\x00 \x00P\x00o\x00p\x00 \x00R\x00o\x00c\x00k\x00s\x00".b, 4).value assert_equal "Iggy Pop Rocks", value assert_equal "UTF-8", value.encoding.name end def test_utf_16be_encode_comment value = WahWah::ID3::CommentFrameBody.new("\x02eng\x00\x00\x00I\x00g\x00g\x00y\x00 \x00P\x00o\x00p\x00 \x00R\x00o\x00c\x00k\x00s".b, 4).value assert_equal "Iggy Pop Rocks", value assert_equal "UTF-8", value.encoding.name end def test_utf_8_encode_comment value = WahWah::ID3::CommentFrameBody.new("\x03eng\x00Iggy Pop Rocks".b, 4).value assert_equal "Iggy Pop Rocks", value assert_equal "UTF-8", value.encoding.name end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/test/wahwah/asf/object_test.rb
test/wahwah/asf/object_test.rb
# frozen_string_literal: true require "test_helper" class WahWah::Asf::ObjectTest < Minitest::Test def test_parse content = StringIO.new("\xA1\xDC\xAB\x8CG\xA9\xCF\x11\x8E\xE4\x00\xC0\f Seh\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x9AA\x04\x00\x00\x00\x00\x00\x00\x80>\xD5\xDE\xB1\x9D\x01W\x00\x00\x00\x00\x00\x00\x00\xD0\xC2\xA2\x06\x00\x00\x00\x00\x10\xBD\xC9\x04\x00\x00\x00\x00\x1C\f\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x80\f\x00\x00\x80\f\x00\x00\x9F\xED\x02\x00".b) object = WahWah::Asf::Object.new(content) assert_equal 80, object.size assert_equal "8CABDCA1-A947-11CF-8EE4-00C00C205365", object.guid end def test_invalid_object content = StringIO.new("invalid\xA1\xDC\xAB\x8CG".b) object = WahWah::Asf::Object.new(content) assert !object.valid? end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah.rb
lib/wahwah.rb
# frozen_string_literal: true require "stringio" require "forwardable" require "zlib" require "pathname" require "wahwah/version" require "wahwah/errors" require "wahwah/helper" require "wahwah/tag_delegate" require "wahwah/lazy_read" require "wahwah/tag" require "wahwah/id3/v1" require "wahwah/id3/v2" require "wahwah/id3/v2_header" require "wahwah/id3/frame" require "wahwah/id3/frame_body" require "wahwah/id3/text_frame_body" require "wahwah/id3/genre_frame_body" require "wahwah/id3/comment_frame_body" require "wahwah/id3/image_frame_body" require "wahwah/id3/lyrics_frame_body" require "wahwah/mp3/mpeg_frame_header" require "wahwah/mp3/xing_header" require "wahwah/mp3/vbri_header" require "wahwah/riff/chunk" require "wahwah/flac/block" require "wahwah/flac/streaminfo_block" require "wahwah/ogg/page" require "wahwah/ogg/pages" require "wahwah/ogg/packets" require "wahwah/ogg/vorbis_comment" require "wahwah/ogg/vorbis_tag" require "wahwah/ogg/opus_tag" require "wahwah/ogg/flac_tag" require "wahwah/asf/object" require "wahwah/mp4/atom" require "wahwah/mp3_tag" require "wahwah/mp4_tag" require "wahwah/ogg_tag" require "wahwah/riff_tag" require "wahwah/asf_tag" require "wahwah/flac_tag" module WahWah FORMATE_MAPPING = { Mp3Tag: ["mp3"], OggTag: ["ogg", "oga", "opus"], RiffTag: ["wav"], FlacTag: ["flac"], AsfTag: ["wma"], Mp4Tag: ["m4a"] }.freeze def self.open(path_or_io) with_io path_or_io do |io, from_path| file_format = Helper.file_format io raise WahWahArgumentError, "No supported format found" unless support_formats.include? file_format FORMATE_MAPPING.each do |tag, formats| break const_get(tag).new(io, **from_path) if formats.include?(file_format) end end end def self.support_formats FORMATE_MAPPING.values.flatten end def self.with_io(path_or_io, &block) path_or_io = Pathname.new path_or_io if path_or_io.respond_to? :to_str if path_or_io.is_a? Pathname raise WahWahArgumentError, "File does not exist" unless File.exist? path_or_io raise WahWahArgumentError, "File is unreadable" unless File.readable? path_or_io raise WahWahArgumentError, "File is empty" if File.empty?(path_or_io) path_or_io.open do |io| block.call(io, from_path: true) end else block.call(path_or_io, from_path: false) end end private_class_method :with_io end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/tag.rb
lib/wahwah/tag.rb
# frozen_string_literal: true module WahWah class Tag INTEGER_ATTRIBUTES = %i[disc disc_total track track_total] INSPECT_ATTRIBUTES = %i[ title artist album albumartist composer comments track track_total genre year disc disc_total lyrics duration bitrate sample_rate bit_depth file_size ] attr_reader(*INSPECT_ATTRIBUTES) def initialize(io, from_path: false) @from_path = from_path @file_size = io.size @file_io = io # Rewinding at the start just in case some other helper class or parser already read from the file @file_io.rewind @comments = [] @images_data = [] parse if @file_size > 0 INTEGER_ATTRIBUTES.each do |attr_name| value = instance_variable_get("@#{attr_name}")&.to_i instance_variable_set("@#{attr_name}", value) end end def inspect inspect_id = ::Kernel.format "%x", (object_id * 2) inspect_attributes_values = INSPECT_ATTRIBUTES.map { |attr_name| "#{attr_name}: #{send(attr_name).inspect}" }.join(", ") "<#{self.class.name}:0x#{inspect_id} #{inspect_attributes_values}>" end def images return @images_data if @images_data.empty? @images ||= @images_data.map do |data| parse_image_data(data) end end private attr_accessor :from_path def parse raise WahWahNotImplementedError, "The parse method is not implemented" end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/version.rb
lib/wahwah/version.rb
# frozen_string_literal: true module WahWah VERSION = "1.6.7" end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/asf_tag.rb
lib/wahwah/asf_tag.rb
# frozen_string_literal: true module WahWah class AsfTag < Tag HEADER_OBJECT_CONTENT_SIZE = 6 HEADER_OBJECT_GUID = "75B22630-668E-11CF-A6D9-00AA0062CE6C" FILE_PROPERTIES_OBJECT_GUID = "8CABDCA1-A947-11CF-8EE4-00C00C205365" EXTENDED_CONTENT_DESCRIPTION_OBJECT_GUID = "D2D0A440-E307-11D2-97F0-00A0C95EA850" STREAM_PROPERTIES_OBJECT_GUID = "B7DC0791-A9B7-11CF-8EE6-00C00C205365" AUDIO_MEDIA_OBJECT_GUID = "F8699E40-5B4D-11CF-A8FD-00805F5C442B" CONTENT_DESCRIPTION_OBJECT_GUID = "75B22633-668E-11CF-A6D9-00AA0062CE6C" EXTENDED_CONTENT_DESCRIPTOR_NAME_MAPPING = { "WM/AlbumArtist" => :albumartist, "WM/AlbumTitle" => :album, "WM/Composer" => :composer, "WM/Genre" => :genre, "WM/PartOfSet" => :disc, "WM/TrackNumber" => :track, "WM/Year" => :year, "WM/Lyrics" => :lyrics } private # ASF files are logically composed of three types of top-level objects: # the Header Object, the Data Object, and the Index Object(s). # The Header Object is mandatory and must be placed at the beginning of every ASF file. # Of the three top-level ASF objects, the Header Object is the only one that contains other ASF objects. # All Unicode strings in ASF uses UTF-16, little endian, and the Byte-Order Marker (BOM) character is not present. def parse header_object = Asf::Object.new(@file_io) return unless header_object.valid? total_header_object_size = header_object.size + Asf::Object::HEADER_SIZE return unless header_object.guid == HEADER_OBJECT_GUID # Header Object contains 6 bytes useless data, so skip it. @file_io.seek(HEADER_OBJECT_CONTENT_SIZE, IO::SEEK_CUR) until total_header_object_size <= @file_io.pos sub_object = Asf::Object.new(@file_io) parse_sub_object(sub_object) end end def parse_sub_object(sub_object) case sub_object.guid when FILE_PROPERTIES_OBJECT_GUID parse_file_properties_object(sub_object) when EXTENDED_CONTENT_DESCRIPTION_OBJECT_GUID parse_extended_content_description_object(sub_object) when STREAM_PROPERTIES_OBJECT_GUID parse_stream_properties_object(sub_object) when CONTENT_DESCRIPTION_OBJECT_GUID parse_content_description_object(sub_object) else sub_object.skip end end # File Properties Object structure: # # Field name Field type Size (bits) # # Object ID GUID 128 # Object Size QWORD 64 # File ID GUID 128 # File Size QWORD 64 # Creation Date QWORD 64 # Data Packets Count QWORD 64 # Play Duration QWORD 64 # Send Duration QWORD 64 # Preroll QWORD 64 # Flags DWORD 32 # Broadcast Flag 1 (LSB) # Seekable Flag 1 # Reserved 30 # Minimum Data Packet Size DWORD 32 # Maximum Data Packet Size DWORD 32 # Maximum Bitrate DWORD 32 # # Play Duration Specifies the time needed to play the file in 100-nanosecond units. # The value of this field is invalid if the Broadcast Flag bit in the Flags field is set to 1. # # Preroll Specifies the amount of time to buffer data before starting to play the file, in millisecond units. # If this value is nonzero, the Play Duration field and all of the payload Presentation Time fields have been offset by this amount. def parse_file_properties_object(object) play_duration, preroll, flags = object.data.unpack("x40Q<x8Q<b32") @duration = play_duration / 10000000.0 - preroll / 1000.0 if flags[0] == "0" end # Extended Content Description Object structure: # # Field name Field type Size (bits) # # Object ID GUID 128 # Object Size QWORD 64 # Content Descriptors Count WORD 16 # Content Descriptors See text varies # # # The structure of each Content Descriptor: # # Field Name Field Type Size (bits) # # Descriptor Name Length WORD 16 # Descriptor Name WCHAR varies # Descriptor Value Data Type WORD 16 # Descriptor Value Length WORD 16 # Descriptor Value See text varies # # # Specifies the type of data stored in the Descriptor Value field. # The types are defined in the following table. # # Value Type Descriptor value length # # 0x0000 Unicode string varies # 0x0001 BYTE array varies # 0x0002 BOOL 32 # 0x0003 DWORD 32 # 0x0004 QWORD 64 # 0x0005 WORD 16 def parse_extended_content_description_object(object) object_data = StringIO.new(object.data) descriptors_count = object_data.read(2).unpack1("v") descriptors_count.times do name_length = object_data.read(2).unpack1("v") name = Helper.encode_to_utf8(object_data.read(name_length), source_encoding: "UTF-16LE") value_type, value_length = object_data.read(4).unpack("vv") value = object_data.read(value_length) attr_value = case value_type when 0 Helper.encode_to_utf8(value, source_encoding: "UTF-16LE") when 1 value when 2, 3 value.unpack1("V") when 4 value.unpack1("Q<") when 5 value.unpack1("v") end attr_name = EXTENDED_CONTENT_DESCRIPTOR_NAME_MAPPING[name] instance_variable_set("@#{attr_name}", attr_value) unless attr_name.nil? end end # Stream Properties Object structure: # # Field Name Field Type Size (bits) # Object ID GUID 128 # Object Size QWORD 64 # Stream Type GUID 128 # Error Correction Type GUID 128 # Time Offset QWORD 64 # Type-Specific Data Length DWORD 32 # Error Correction Data Length DWORD 32 # Flags WORD 16 # Stream Number 7 (LSB) # Reserved 8 # Encrypted Content Flag 1 # Reserved DWORD 32 # Type-Specific Data BYTE varies # Error Correction Data BYTE varies # # Stream Type specifies the type of the stream (for example, audio, video, and so on). # Any streams with unrecognized Stream Type values should be ignored. # # Audio media type Object structure: # # Field name Field type Size (bits) # # Codec ID / Format Tag WORD 16 # Number of Channels WORD 16 # Samples Per Second DWORD 32 # Average Number of Bytes Per Second DWORD 32 # Block Alignment WORD 16 # Bits Per Sample WORD 16 def parse_stream_properties_object(object) object_data = StringIO.new(object.data) stream_type, type_specific_data_length = object_data.read(54).unpack("a16x24V") stream_type_guid = Helper.byte_string_to_guid(stream_type) return unless stream_type_guid == AUDIO_MEDIA_OBJECT_GUID @sample_rate, bytes_per_second, @bit_depth = object_data.read(type_specific_data_length).unpack("x4VVx2v") @bitrate = (bytes_per_second * 8.0 / 1000).round end # Content Description Object structure: # # Field name Field type Size (bits) # # Object ID GUID 128 # Object Size QWORD 64 # Title Length WORD 16 # Author Length WORD 16 # Copyright Length WORD 16 # Description Length WORD 16 # Rating Length WORD 16 # Title WCHAR Varies # Author WCHAR Varies # Copyright WCHAR Varies # Description WCHAR Varies # Rating WCHAR Varies def parse_content_description_object(object) object_data = StringIO.new(object.data) title_length, author_length, copyright_length, description_length, _ = object_data.read(10).unpack("v" * 5) @title = Helper.encode_to_utf8(object_data.read(title_length), source_encoding: "UTF-16LE") @artist = Helper.encode_to_utf8(object_data.read(author_length), source_encoding: "UTF-16LE") object_data.seek(copyright_length, IO::SEEK_CUR) @comments.push(Helper.encode_to_utf8(object_data.read(description_length), source_encoding: "UTF-16LE")) end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/lazy_read.rb
lib/wahwah/lazy_read.rb
# frozen_string_literal: true module WahWah module LazyRead def self.prepended(base) base.class_eval do attr_reader :size end end def initialize(file_io, *arg) @file_io = file_io super(*arg) @position = @file_io.pos @data = get_data if @file_io.is_a?(StringIO) end def data if @file_io.closed? && @file_io.is_a?(File) @file_io = File.open(@file_io.path) @data = get_data @file_io.close end @data ||= get_data end def skip @file_io.seek(@position) @file_io.seek(size, IO::SEEK_CUR) end private def get_data @file_io.seek(@position) @file_io.read(size) end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/ogg_tag.rb
lib/wahwah/ogg_tag.rb
# frozen_string_literal: true module WahWah class OggTag < Tag extend TagDelegate tag_delegate :@tag, :title, :album, :albumartist, :track, :artist, :year, :genre, :disc, :composer, :sample_rate, :lyrics # Oggs require reading to the end of the file in order to calculate their # duration (as it's not stored in any header or metadata). Thus, if the # IO like object supplied to WahWah is a streaming download, getting the # duration would download the entire audio file, which may not be # desirable. Making it lazy in this manner allows the user to avoid that. def duration @duration ||= parse_duration end # Requires duration to calculate, so lazy as well. def bitrate @bitrate ||= parse_bitrate end private def packets @packets ||= Ogg::Packets.new(@file_io) end def pages @pages ||= Ogg::Pages.new(@file_io) end def parse identification_packet, comment_packet = packets.first(2) return if identification_packet.nil? || comment_packet.nil? @overhead_packets_size = identification_packet.size + comment_packet.size @tag = if identification_packet.start_with?("\x01vorbis") Ogg::VorbisTag.new(identification_packet, comment_packet) elsif identification_packet.start_with?("OpusHead") Ogg::OpusTag.new(identification_packet, comment_packet) elsif identification_packet.start_with?("\x7FFLAC") Ogg::FlacTag.new(identification_packet, comment_packet) end # Eagerly calculate duration and bitrate when open from path if from_path @duration = parse_duration @bitrate = parse_bitrate end @bit_depth = parse_bit_depth end def parse_duration return @tag.duration if @tag.respond_to? :duration last_page = pages.to_a.last pre_skip = @tag.respond_to?(:pre_skip) ? @tag.pre_skip : 0 (last_page.granule_position - pre_skip) / @tag.sample_rate.to_f end def parse_bitrate return @tag.bitrate if @tag.respond_to? :bitrate ((file_size - @overhead_packets_size) * 8.0 / duration / 1000).round end def parse_bit_depth @tag.bit_depth if @tag.respond_to? :bit_depth end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/errors.rb
lib/wahwah/errors.rb
# frozen_string_literal: true module WahWah class WahWahArgumentError < ArgumentError; end class WahWahNotImplementedError < RuntimeError; end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/riff_tag.rb
lib/wahwah/riff_tag.rb
# frozen_string_literal: true module WahWah class RiffTag < Tag extend TagDelegate # see https://exiftool.org/TagNames/RIFF.html#Info for more info INFO_ID_MAPPING = { INAM: :title, TITL: :title, IART: :artist, IPRD: :album, ICMT: :comment, ICRD: :year, YEAR: :year, IGNR: :genre, TRCK: :track } CHANNEL_MODE_INDEX = %w[Mono Stereo] tag_delegate :@id3_tag, :title, :artist, :album, :albumartist, :composer, :comments, :track, :track_total, :genre, :year, :disc, :disc_total, :images def channel_mode CHANNEL_MODE_INDEX[@channel - 1] end private def parse top_chunk = Riff::Chunk.new(@file_io) return unless top_chunk.valid? total_chunk_size = top_chunk.size + Riff::Chunk::HEADER_SIZE # The top "RIFF" chunks include an additional field in the first four bytes of the data field. # This additional field provides the form type of the field. # For wav file, the value of the type field is 'WAVE' return unless top_chunk.id == "RIFF" && top_chunk.type == "WAVE" until total_chunk_size <= @file_io.pos || @file_io.eof? sub_chunk = Riff::Chunk.new(@file_io) parse_sub_chunk(sub_chunk) end end def parse_sub_chunk(sub_chunk) return unless sub_chunk.valid? case sub_chunk.id when "fmt" parse_fmt_chunk(sub_chunk) when "data" parse_data_chunk(sub_chunk) when "LIST" parse_list_chunk(sub_chunk) when "id3", "ID3" parse_id3_chunk(sub_chunk) else sub_chunk.skip end end # The fmt chunk data structure: # Length Meaning Description # # 2(little endian) AudioFormat PCM = 1 (i.e. Linear quantization) # Values other than 1 indicate some # form of compression. # # 2(little endian) NumChannels Mono = 1, Stereo = 2, etc. # # 4(little endian) SampleRate 8000, 44100, etc. # # 4(little endian) ByteRate == SampleRate * NumChannels * BitsPerSample/8 # # 2(little endian) BlockAlign == NumChannels * BitsPerSample/8 # The number of bytes for one sample including # all channels. # # 2(little endian) BitsPerSample 8 bits = 8, 16 bits = 16, etc. def parse_fmt_chunk(chunk) _, @channel, @sample_rate, _, _, @bit_depth = chunk.data.unpack("vvVVvv") @bitrate = @sample_rate * @channel * @bit_depth / 1000 # There is a rare situation where the data chunk is not included in the top RIFF chunk. # In this case, the duration can not be got from the data chunk, some player even cannot play the file. # So try to estimate the duration from the file size and bitrate. # This may be inaccurate, but at least can get approximate duration. @duration = (@file_size * 8) / (@bitrate * 1000).to_f if @duration.nil? end def parse_data_chunk(chunk) @duration = chunk.size * 8 / (@bitrate * 1000).to_f chunk.skip end def parse_list_chunk(chunk) list_chunk_end_position = @file_io.pos + chunk.size # RIFF can be tagged with metadata in the INFO chunk. # And INFO chunk as a subchunk for LIST chunk. if chunk.type != "INFO" chunk.skip return end until list_chunk_end_position <= @file_io.pos info_chunk = Riff::Chunk.new(@file_io) unless INFO_ID_MAPPING.key? info_chunk.id.to_sym info_chunk.skip next end update_attribute(info_chunk) end end def parse_id3_chunk(chunk) @id3_tag = ID3::V2.new(StringIO.new(chunk.data)) end def update_attribute(chunk) attr_name = INFO_ID_MAPPING[chunk.id.to_sym] chunk_data = Helper.encode_to_utf8(chunk.data) case attr_name when :comment @comments.push(chunk_data) else instance_variable_set("@#{attr_name}", chunk_data) end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/mp4_tag.rb
lib/wahwah/mp4_tag.rb
# frozen_string_literal: true module WahWah class Mp4Tag < Tag META_ATOM_MAPPING = { "\xA9alb".b => :album, "\xA9ART".b => :artist, "\xA9cmt".b => :comment, "\xA9wrt".b => :composer, "\xA9day".b => :year, "\xA9gen".b => :genre, "\xA9nam".b => :title, "\xA9lyr".b => :lyrics, "covr".b => :image, "disk".b => :disc, "trkn".b => :track, "aART".b => :albumartist } META_ATOM_DECODE_BY_TYPE = { 0 => ->(data) { data }, # reserved 1 => ->(data) { Helper.encode_to_utf8(data) }, # UTF-8 2 => ->(data) { Helper.encode_to_utf8(data, "UTF-16BE") }, # UTF-16BE 3 => ->(data) { Helper.encode_to_utf8(data, "SJIS") }, # SJIS 13 => ->(data) { {data: data, mime_type: "image/jpeg", type: :cover} }, # JPEG 14 => ->(data) { {data: data, mime_type: "image/png", type: :cover} }, # PNG 21 => ->(data) { data.unpack1("i>") }, # Big endian signed integer 22 => ->(data) { data.unpack1("I>") }, # Big endian unsigned integer 23 => ->(data) { data.unpack1("g") }, # Big endian 32-bit floating point value 24 => ->(data) { data.unpack1("G") }, # Big endian 64-bit floating point value 65 => ->(data) { data.unpack1("c") }, # 8-bit signed integer 66 => ->(data) { data.unpack1("s>") }, # Big-endian 16-bit signed integer 67 => ->(data) { data.unpack1("l>") }, # Big-endian 32-bit signed integer 74 => ->(data) { data.unpack1("q>") }, # Big-endian 64-bit signed integer 75 => ->(data) { data.unpack1("C") }, # 8-bit unsigned integer 76 => ->(data) { data.unpack1("S>") }, # Big-endian 16-bit unsigned integer 77 => ->(data) { data.unpack1("L>") }, # Big-endian 32-bit unsigned integer 78 => ->(data) { data.unpack1("Q>") } # Big-endian 64-bit unsigned integer } private def parse movie_atom = Mp4::Atom.find(@file_io, "moov") return unless movie_atom.valid? parse_meta_list_atom movie_atom.find("meta", "ilst") parse_mvhd_atom movie_atom.find("mvhd") parse_stsd_atom movie_atom.find("trak", "mdia", "minf", "stbl", "stsd") end def parse_meta_list_atom(atom) return unless atom.valid? # The metadata item list atom holds a list of actual metadata values that are present in the metadata atom. # The metadata items are formatted as a list of items. # The metadata item list atom is of type ‘ilst’ and contains a number of metadata items, each of which is an atom. # each metadata item atom contains a Value Atom, to hold the value of the metadata item atom.children.each do |child_atom| attr_name = META_ATOM_MAPPING[child_atom.type] # The value of the metadata item is expressed as immediate data in a value atom. # The value atom starts with two fields: a type indicator, and a locale indicator. # Both the type and locale indicators are four bytes long. # There may be multiple ‘value’ entries, using different type data_atom = child_atom.find("data") next unless data_atom.valid? if attr_name == :image @images_data.push(data_atom) next end encoded_data_value = parse_meta_data_atom(data_atom) next if attr_name.nil? || encoded_data_value.nil? case attr_name when :comment @comments.push(encoded_data_value) when :track, :disc count, total_count = encoded_data_value.unpack("x2nn") instance_variable_set("@#{attr_name}", count) unless count.zero? instance_variable_set("@#{attr_name}_total", total_count) unless total_count.zero? else instance_variable_set("@#{attr_name}", encoded_data_value) end end end def parse_meta_data_atom(atom) data_type, data_value = atom.data.unpack("Nx4a*") META_ATOM_DECODE_BY_TYPE[data_type]&.call(data_value) end def parse_mvhd_atom(atom) return unless atom.valid? atom_data = StringIO.new(atom.data) version = atom_data.read(1).unpack1("c") # Skip flags atom_data.seek(3, IO::SEEK_CUR) if version == 0 # Skip creation and modification time atom_data.seek(8, IO::SEEK_CUR) time_scale, duration = atom_data.read(8).unpack("l>l>") elsif version == 1 # Skip creation and modification time atom_data.seek(16, IO::SEEK_CUR) time_scale, duration = atom_data.read(12).unpack("l>q>") end @duration = duration / time_scale.to_f end def parse_stsd_atom(atom) return unless atom.valid? mp4a_atom = atom.find("mp4a") esds_atom = atom.find("esds") alac_atom = atom.find("alac") @sample_rate = mp4a_atom.data.unpack1("x22I>") if mp4a_atom.valid? @bitrate = esds_atom.data.unpack1("x26I>") / 1000 if esds_atom.valid? # see https://github.com/macosforge/alac/blob/master/ALACMagicCookieDescription.txt for more info. if alac_atom.valid? atom_data = StringIO.new(alac_atom.data) atom_data.seek(45, IO::SEEK_CUR) @bit_depth = atom_data.read(1).unpack1("C") atom_data.seek(10, IO::SEEK_CUR) @bitrate = (atom_data.read(4).unpack1("I>") / 1000.to_f).round @sample_rate = atom_data.read(4).unpack1("I>") end end def parse_image_data(image_data_atom) parse_meta_data_atom(image_data_atom) end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/mp3_tag.rb
lib/wahwah/mp3_tag.rb
# frozen_string_literal: true module WahWah class Mp3Tag < Tag extend TagDelegate extend Forwardable def_delegator :@mpeg_frame_header, :version, :mpeg_version def_delegator :@mpeg_frame_header, :layer, :mpeg_layer def_delegator :@mpeg_frame_header, :kind, :mpeg_kind def_delegators :@mpeg_frame_header, :channel_mode, :sample_rate tag_delegate :@id3_tag, :title, :artist, :album, :albumartist, :composer, :comments, :track, :track_total, :genre, :year, :disc, :disc_total, :images, :lyrics def id3v2? @id3_tag.instance_of? ID3::V2 end def invalid_id3? @id3_tag.nil? end def id3_version @id3_tag&.version end def is_vbr? mpeg_frame_header.valid? && (xing_header.valid? || vbri_header.valid?) end private def parse @id3_tag = parse_id3_tag parse_duration if mpeg_frame_header.valid? end def parse_id3_tag @file_io.rewind signature = @file_io.read(6) @file_io.rewind if signature.start_with?("ID3".b) id3_v2_tag = ID3::V2.new(@file_io) id3_v2_tag if id3_v2_tag.valid? elsif ["\xFF\xFB".b, "\xFF\xF3".b, "\xFF\xF2".b].include? signature[...2] # It's important to only initialize an ID3v1 object as the last option, # as it requires reading to the end of the file. If the file is a # streaming download (using, for example, Down), that requires # downloading the whole file, which is not the case with ID3v2. id3_v1_tag = ID3::V1.new(@file_io.dup) id3_v1_tag if id3_v1_tag.valid? end end def parse_duration if is_vbr? @duration = frames_count * (mpeg_frame_header.samples_per_frame / sample_rate.to_f) @bitrate = (bytes_count * 8 / @duration / 1000).round unless @duration.zero? else @bitrate = mpeg_frame_header.frame_bitrate @duration = (file_size - (@id3_tag&.size || 0)) * 8 / (@bitrate * 1000).to_f unless @bitrate.to_i.zero? end end def mpeg_frame_header # Because id3v2 tag on the file header so skip id3v2 tag @mpeg_frame_header ||= Mp3::MpegFrameHeader.new(@file_io, id3v2? ? @id3_tag&.size : 0) end def xing_header @xing_header ||= Mp3::XingHeader.new(@file_io, xing_header_offset) end def vbri_header @vbri_header ||= Mp3::VbriHeader.new(@file_io, vbri_header_offset) end def xing_header_offset mpeg_frame_header_position = mpeg_frame_header.position mpeg_frame_header_size = Mp3::MpegFrameHeader::HEADER_SIZE mpeg_frame_side_info_size = if mpeg_version == "MPEG1" channel_mode == "Single Channel" ? 17 : 32 else channel_mode == "Single Channel" ? 9 : 17 end mpeg_frame_header_position + mpeg_frame_header_size + mpeg_frame_side_info_size end def vbri_header_offset mpeg_frame_header_position = mpeg_frame_header.position mpeg_frame_header_size = Mp3::MpegFrameHeader::HEADER_SIZE mpeg_frame_header_position + mpeg_frame_header_size + 32 end def frames_count return xing_header.frames_count if xing_header.valid? vbri_header.frames_count if vbri_header.valid? end def bytes_count return xing_header.bytes_count if xing_header.valid? vbri_header.bytes_count if vbri_header.valid? end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/tag_delegate.rb
lib/wahwah/tag_delegate.rb
# frozen_string_literal: true module WahWah module TagDelegate def tag_delegate(accessor, *attributes) attributes.each do |attr| define_method(attr) do tag = instance_variable_get(accessor) return super() if tag.nil? tag.send(attr) end end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/flac_tag.rb
lib/wahwah/flac_tag.rb
# frozen_string_literal: true module WahWah class FlacTag < Tag include Ogg::VorbisComment include Flac::StreaminfoBlock TAG_ID = "fLaC" private # FLAC structure: # # The four byte string "fLaC" # The STREAMINFO metadata block # Zero or more other metadata blocks # One or more audio frames def parse # Flac file maybe contain ID3 header on the start, so skip it if exists id3_header = ID3::V2Header.new(@file_io) id3_header.valid? ? @file_io.seek(id3_header.size) : @file_io.rewind return if @file_io.read(4) != TAG_ID loop do block = Flac::Block.new(@file_io) parse_block(block) break if block.is_last? || @file_io.eof? end end def parse_block(block) return unless block.valid? case block.type when "STREAMINFO" parse_streaminfo_block(block.data) when "VORBIS_COMMENT" parse_vorbis_comment(block.data) when "PICTURE" @images_data.push(block) block.skip else block.skip end end # PICTURE block data structure: # # Length(bit) Meaning # # 32 The picture type according to the ID3v2 APIC frame: # # 32 The length of the MIME type string in bytes. # # n*8 The MIME type string. # # 32 The length of the description string in bytes. # # n*8 The description of the picture, in UTF-8. # # 32 The width of the picture in pixels. # # 32 The height of the picture in pixels. # # 32 The color depth of the picture in bits-per-pixel. # # 32 For indexed-color pictures (e.g. GIF), the number of colors used, or 0 for non-indexed pictures. # # 32 The length of the picture data in bytes. # # n*8 The binary picture data. def parse_image_data(picture_block) block_content = StringIO.new(picture_block.data) type_index, mime_type_length = block_content.read(8).unpack("NN") mime_type = Helper.encode_to_utf8(block_content.read(mime_type_length)) description_length = block_content.read(4).unpack1("N") data_length = block_content.read(description_length + 20).unpack1("#{"x" * (description_length + 16)}N") data = block_content.read(data_length) {data: data, mime_type: mime_type, type: ID3::ImageFrameBody::TYPES[type_index]} end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/helper.rb
lib/wahwah/helper.rb
# frozen_string_literal: true module WahWah module Helper def self.encode_to_utf8(string, source_encoding: "") encoded_string = source_encoding.empty? ? string.force_encoding("utf-8") : string.encode("utf-8", source_encoding, invalid: :replace, undef: :replace, replace: "") encoded_string.valid_encoding? ? encoded_string.strip : "" end # ID3 size is encoded with four bytes where may the most significant # bit (bit 7) is set to zero in every byte, # making a total of 28 bits. The zeroed bits are ignored def self.id3_size_caculate(bits_string, has_zero_bit: true) if has_zero_bit bits_string.scan(/.{8}/).map { |byte_string| byte_string[1..] }.join.to_i(2) else bits_string.to_i(2) end end def self.split_with_terminator(string, terminator_size) terminator = ("\x00" * terminator_size).b (0...string.size).step(terminator_size).each do |index| if string[index...(index + terminator_size)] == terminator return [string[0...index], string[index + terminator_size..]] end end [] end def self.file_format(io) if io.respond_to?(:path) && io.path && !io.path.empty? file_format = file_format_from_extension io.path return file_format unless file_format.nil? || file_format.empty? end file_format_from_signature io end def self.byte_string_to_guid(byte_string) guid = byte_string.unpack("NnnA*").pack("VvvA*").unpack1("H*") [guid[0..7], guid[8..11], guid[12..15], guid[16..19], guid[20..]].join("-").upcase end def self.file_format_from_extension(file_path) File.extname(file_path).downcase[1..] end def self.file_format_from_signature(io) io.rewind signature = io.read(16) # Rewind after reading the signature to not mess with the file position io.rewind # Source: https://en.wikipedia.org/wiki/List_of_file_signatures # M4A is checked for first, since MP4 files start with a chunk size - # and that chunk size may incidentally match another signature. # No other formats would reasonably have "ftyp" as the next for bytes. return "m4a" if ["ftypM4A ".b, "ftyp3gp4".b, "ftypmp42".b].include?(signature[4...12]) # Handled separately simply because it requires two checks. return "wav" if signature.start_with?("RIFF".b) && signature[8...12] == "WAVE".b magic_numbers = { "fLaC".b => "flac", "\xFF\xFB".b => "mp3", "\xFF\xF3".b => "mp3", "\xFF\xF2".b => "mp3", "ID3".b => "mp3", "OggS".b => "ogg", "\x30\x26\xB2\x75\x8E\x66\xCF\x11\xA6\xD9\x00\xAA\x00\x62\xCE\x6C".b => "wma" } magic_numbers.each do |expected_signature, file_format| return file_format if signature.start_with? expected_signature end nil end private_class_method :file_format_from_extension, :file_format_from_signature end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/ogg/opus_tag.rb
lib/wahwah/ogg/opus_tag.rb
# frozen_string_literal: true module WahWah module Ogg class OpusTag include VorbisComment attr_reader :sample_rate, :pre_skip, *COMMET_FIELD_MAPPING.values def initialize(identification_packet, comment_packet) # Identification packet structure: # # 1) "OpusHead" # 2) [version] = read 8 bits as unsigned integer # 3) [audio_channels] = read 8 bit as unsigned integer # 4) [pre_skip] = read 16 bits as unsigned little endian integer # 5) [input_sample_rate] = read 32 bits as unsigned little endian integer # 6) [output_gain] = read 16 bits as unsigned little endian integer # 7) [channel_mapping_family] = read 8 bit as unsigned integer # 8) [channel_mapping_table] @sample_rate = 48000 @pre_skip = identification_packet[10..11].unpack1("v") comment_packet_id, comment_packet_body = [comment_packet[0..7], comment_packet[8..]] # Opus comment packet start with 'OpusTags' return unless comment_packet_id == "OpusTags" parse_vorbis_comment(comment_packet_body) end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/ogg/vorbis_comment.rb
lib/wahwah/ogg/vorbis_comment.rb
# frozen_string_literal: true module WahWah module Ogg # Vorbis comment structure: # # 1) [vendor_length] = read an unsigned integer of 32 bits # 2) [vendor_string] = read a UTF-8 vector as [vendor_length] octets # 3) [user_comment_list_length] = read an unsigned integer of 32 bits # 4) iterate [user_comment_list_length] times { # 5) [length] = read an unsigned integer of 32 bits # 6) this iteration’s user comment = read a UTF-8 vector as [length] octets # } # 7) [framing_bit] = read a single bit as boolean # 8) if ( [framing_bit] unset or end-of-packet ) then ERROR # 9) done. module VorbisComment COMMET_FIELD_MAPPING = { "TITLE" => :title, "ALBUM" => :album, "ALBUMARTIST" => :albumartist, "TRACKNUMBER" => :track, "ARTIST" => :artist, "DATE" => :year, "GENRE" => :genre, "DISCNUMBER" => :disc, "COMPOSER" => :composer, "LYRICS" => :lyrics } def parse_vorbis_comment(comment_content) comment_content = StringIO.new(comment_content) vendor_length = comment_content.read(4).unpack1("V") comment_content.seek(vendor_length, IO::SEEK_CUR) # Skip vendor_string comment_list_length = comment_content.read(4).unpack1("V") comment_list_length.times do comment_length = comment_content.read(4).unpack1("V") comment = Helper.encode_to_utf8(comment_content.read(comment_length)) field_name, field_value = comment.split("=", 2) attr_name = COMMET_FIELD_MAPPING[field_name&.upcase] field_value = field_value.to_i if %i[track disc].include? attr_name instance_variable_set("@#{attr_name}", field_value) unless attr_name.nil? end end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/ogg/page.rb
lib/wahwah/ogg/page.rb
# frozen_string_literal: true module WahWah module Ogg # The Ogg page header has the following format: # # 0 1 2 3 # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1| Byte # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | capture_pattern: Magic number for page start "OggS" | 0-3 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | version | header_type | granule_position | 4-7 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | | 8-11 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | | bitstream_serial_number | 12-15 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | | page_sequence_number | 16-19 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | | CRC_checksum | 20-23 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | |page_segments | segment_table | 24-27 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | ... | 28- # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # # # The fields in the page header have the following meaning: # # 1. capture_pattern: a 4 Byte field that signifies the beginning of a # page. It contains the magic numbers: # 0x4f 'O' # 0x67 'g' # 0x67 'g' # 0x53 'S' # It helps a decoder to find the page boundaries and regain # synchronisation after parsing a corrupted stream. Once the # capture pattern is found, the decoder verifies page sync and # integrity by computing and comparing the checksum. # 2. stream_structure_version: 1 Byte signifying the version number of # the Ogg file format used in this stream (this document specifies # version 0). # 3. header_type_flag: the bits in this 1 Byte field identify the # specific type of this page. # * bit 0x01 # set: page contains data of a packet continued from the previous # page # unset: page contains a fresh packet # * bit 0x02 # set: this is the first page of a logical bitstream (bos) # unset: this page is not a first page # * bit 0x04 # set: this is the last page of a logical bitstream (eos) # unset: this page is not a last page # 4. granule_position: an 8 Byte field containing position information. # For example, for an audio stream, it MAY contain the total number # of PCM samples encoded after including all frames finished on this # page. For a video stream it MAY contain the total number of video # frames encoded after this page. This is a hint for the decoder # and gives it some timing and position information. Its meaning is # dependent on the codec for that logical bitstream and specified in # a specific media mapping. A special value of -1 (in two's # complement) indicates that no packets finish on this page. # 5. bitstream_serial_number: a 4 Byte field containing the unique # serial number by which the logical bitstream is identified. # 6. page_sequence_number: a 4 Byte field containing the sequence # number of the page so the decoder can identify page loss. This # sequence number is increasing on each logical bitstream # separately. # 7. CRC_checksum: a 4 Byte field containing a 32 bit CRC checksum of # the page (including header with zero CRC field and page content). # The generator polynomial is 0x04c11db7. # 8. number_page_segments: 1 Byte giving the number of segment entries # encoded in the segment table. # 9. segment_table: number_page_segments Bytes containing the lacing # values of all segments in this page. Each Byte contains one # lacing value. class Page HEADER_SIZE = 27 HEADER_FORMAT = "A4CxQx12C" attr_reader :segments, :granule_position def initialize(file_io) header_content = file_io.read(HEADER_SIZE) @capture_pattern, @version, @granule_position, page_segments = header_content.unpack(HEADER_FORMAT) if header_content.size >= HEADER_SIZE return unless valid? segment_table = file_io.read(page_segments).unpack("C" * page_segments) @segments = segment_table.map { |segment_length| file_io.read(segment_length) } end def valid? @capture_pattern == "OggS" && @version == 0 end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/ogg/flac_tag.rb
lib/wahwah/ogg/flac_tag.rb
# frozen_string_literal: true module WahWah module Ogg class FlacTag include VorbisComment include Flac::StreaminfoBlock attr_reader :bitrate, :duration, :sample_rate, :bit_depth, *COMMET_FIELD_MAPPING.values def initialize(identification_packet, comment_packet) # Identification packet structure: # # The one-byte packet type 0x7F # The four-byte ASCII signature "FLAC", i.e. 0x46, 0x4C, 0x41, 0x43 # A one-byte binary major version number for the mapping, e.g. 0x01 for mapping version 1.0 # A one-byte binary minor version number for the mapping, e.g. 0x00 for mapping version 1.0 # A two-byte, big-endian binary number signifying the number of header (non-audio) packets, not including this one. # The four-byte ASCII native FLAC signature "fLaC" according to the FLAC format specification # The STREAMINFO metadata block for the stream. # # The first identification packet is followed by one or more header packets. # Each such packet will contain a single native FLAC metadata block. # The first of these must be a VORBIS_COMMENT block. id, streaminfo_block_data = identification_packet.unpack("x9A4A*") return unless id == "fLaC" streaminfo_block = Flac::Block.new(StringIO.new(streaminfo_block_data)) vorbis_comment_block = Flac::Block.new(StringIO.new(comment_packet)) parse_streaminfo_block(streaminfo_block.data) parse_vorbis_comment(vorbis_comment_block.data) end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/ogg/pages.rb
lib/wahwah/ogg/pages.rb
# frozen_string_literal: true module WahWah module Ogg class Pages include Enumerable def initialize(file_io) @file_io = file_io end def each @file_io.rewind until @file_io.eof? page = Ogg::Page.new(@file_io) break unless page.valid? yield page end end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/ogg/packets.rb
lib/wahwah/ogg/packets.rb
# frozen_string_literal: true module WahWah module Ogg # From Ogg's perspective, packets can be of any arbitrary size. A # specific media mapping will define how to group or break up packets # from a specific media encoder. As Ogg pages have a maximum size of # about 64 kBytes, sometimes a packet has to be distributed over # several pages. To simplify that process, Ogg divides each packet # into 255 byte long chunks plus a final shorter chunk. These chunks # are called "Ogg Segments". They are only a logical construct and do # not have a header for themselves. class Packets include Enumerable def initialize(file_io) @file_io = file_io end def each @file_io.rewind packet = +"" pages = Ogg::Pages.new(@file_io) pages.each do |page| page.segments.each do |segment| packet << segment # Ogg divides each packet into 255 byte long segments plus a final shorter segment. # So when segment length is less than 255 byte, it's the final segment. if segment.length < 255 yield packet packet = +"" end end end end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/ogg/vorbis_tag.rb
lib/wahwah/ogg/vorbis_tag.rb
# frozen_string_literal: true module WahWah module Ogg class VorbisTag include VorbisComment attr_reader :bitrate, :sample_rate, *COMMET_FIELD_MAPPING.values def initialize(identification_packet, comment_packet) # Identification packet structure: # # 1) "\x01vorbis" # 2) [vorbis_version] = read 32 bits as unsigned integer # 3) [audio_channels] = read 8 bit integer as unsigned # 4) [audio_sample_rate] = read 32 bits as unsigned integer # 5) [bitrate_maximum] = read 32 bits as signed integer # 6) [bitrate_nominal] = read 32 bits as signed integer # 7) [bitrate_minimum] = read 32 bits as signed integer # 8) [blocksize_0] = 2 exponent (read 4 bits as unsigned integer) # 9) [blocksize_1] = 2 exponent (read 4 bits as unsigned integer) # 10) [framing_flag] = read one bit @sample_rate, bitrate = identification_packet[12, 12].unpack("Vx4V") @bitrate = bitrate / 1000 comment_packet_id, comment_packet_body = [comment_packet[0..6], comment_packet[7..]] # Vorbis comment packet start with "\x03vorbis" return unless comment_packet_id == "\x03vorbis" parse_vorbis_comment(comment_packet_body) end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/riff/chunk.rb
lib/wahwah/riff/chunk.rb
# frozen_string_literal: true module WahWah module Riff # RIFF files consist entirely of "chunks". # All chunks have the following format: # 4 bytes: an ASCII identifier for this chunk (examples are "fmt " and "data"; note the space in "fmt "). # 4 bytes: an unsigned, little-endian 32-bit integer with the length of this chunk (except this field itself and the chunk identifier). # variable-sized field: the chunk data itself, of the size given in the previous field. # a pad byte, if the chunk's length is not even. # chunk identifiers, "RIFF" and "LIST", introduce a chunk that can contain subchunks. The RIFF and LIST chunk data (appearing after the identifier and length) have the following format: # 4 bytes: an ASCII identifier for this particular RIFF or LIST chunk (for RIFF in the typical case, these 4 bytes describe the content of the entire file, such as "AVI " or "WAVE"). # rest of data: subchunks. class Chunk prepend LazyRead HEADER_SIZE = 8 HEADER_FORMAT = "A4V" HEADER_TYPE_SIZE = 4 attr_reader :id, :type def initialize @id, @size = @file_io.read(HEADER_SIZE)&.unpack(HEADER_FORMAT) return unless valid? @type = @file_io.read(HEADER_TYPE_SIZE).unpack1("A4") if have_type? end def size @size += 1 if @size.odd? have_type? ? @size - HEADER_TYPE_SIZE : @size end def valid? @id && !@id.empty? && !@size.nil? && @size > 0 end private def have_type? %w[RIFF LIST].include? @id end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/mp3/mpeg_frame_header.rb
lib/wahwah/mp3/mpeg_frame_header.rb
# frozen_string_literal: true module WahWah module Mp3 # mpeg frame header structure: # # Position Length Meaning # 0 11 Frame sync to find the header (all bits are always set) # # 11 2 Audio version ID # 00 - MPEG Version 2.5 (unofficial extension of MPEG 2) # 01 - reserved # 10 - MPEG Version 2 (ISO/IEC 13818-3) # 11 - MPEG Version 1 (ISO/IEC 11172-3) # # 13 2 Layer index # 00 - reserved # 01 - Layer III # 10 - Layer II # 11 - Layer I # # 15 1 Protection bit # # 16 4 Bitrate index, see FRAME_BITRATE_INDEX constant # # 20 2 Sampling rate index, see SAMPLE_RATE_INDEX constant # # 22 1 Padding bit # # 23 1 Private bit # # 24 2 Channel mode # 00 - Stereo # 01 - Joint Stereo (Stereo) # 10 - Dual channel (Two mono channels) # 11 - Single channel (Mono) # # 26 2 Mode extension (Only used in Joint Stereo) # # 28 1 Copyright bit (only informative) # # 29 1 Original bit (only informative) # # 30 2 Emphasis class MpegFrameHeader HEADER_SIZE = 4 FRAME_BITRATE_INDEX = { "MPEG1 layer1" => [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0], "MPEG1 layer2" => [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0], "MPEG1 layer3" => [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0], "MPEG2 layer1" => [0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0], "MPEG2 layer2" => [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0], "MPEG2 layer3" => [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0], "MPEG2.5 layer1" => [0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0], "MPEG2.5 layer2" => [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0], "MPEG2.5 layer3" => [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0] } VERSIONS_INDEX = ["MPEG2.5", nil, "MPEG2", "MPEG1"] LAYER_INDEX = [nil, "layer3", "layer2", "layer1"] CHANNEL_MODE_INDEX = ["Stereo", "Joint Stereo", "Dual Channel", "Single Channel"] SAMPLE_RATE_INDEX = { "MPEG1" => [44100, 48000, 32000], "MPEG2" => [22050, 24000, 16000], "MPEG2.5" => [11025, 12000, 8000] } SAMPLES_PER_FRAME_INDEX = { "MPEG1 layer1" => 384, "MPEG1 layer2" => 1152, "MPEG1 layer3" => 1152, "MPEG2 layer1" => 384, "MPEG2 layer2" => 1152, "MPEG2 layer3" => 576, "MPEG2.5 layer1" => 384, "MPEG2.5 layer2" => 1152, "MPEG2.5 layer3" => 576 } attr_reader :version, :layer, :frame_bitrate, :channel_mode, :sample_rate def initialize(file_io, offset = 0) # mpeg frame header start with '11111111111' sync bits, # So look through file until find it. loop do file_io.rewind file_io.seek(offset) break if file_io.eof? header = file_io.read(HEADER_SIZE) sync_bits = header.unpack1("B11") if sync_bits == ("1" * 11).b @header = header.unpack1("B*") @position = offset parse break end offset += 1 end end def valid? !@header.nil? end def position return 0 unless valid? @position end def kind return if @version.nil? && @layer.nil? "#{@version} #{@layer}" end def samples_per_frame SAMPLES_PER_FRAME_INDEX[kind] end private def parse return unless valid? @version = VERSIONS_INDEX[@header[11..12].to_i(2)] @layer = LAYER_INDEX[@header[13..14].to_i(2)] @frame_bitrate = FRAME_BITRATE_INDEX[kind]&.fetch(@header[16..19].to_i(2)) @channel_mode = CHANNEL_MODE_INDEX[@header[24..25].to_i(2)] @sample_rate = SAMPLE_RATE_INDEX[@version]&.fetch(@header[20..21].to_i(2)) end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/mp3/xing_header.rb
lib/wahwah/mp3/xing_header.rb
# frozen_string_literal: true module WahWah module Mp3 # Xing header structure: # # Position Length Meaning # 0 4 VBR header ID in 4 ASCII chars, either 'Xing' or 'Info', # not NULL-terminated # # 4 4 Flags which indicate what fields are present, # flags are combined with a logical OR. Field is mandatory. # # 0x0001 - Frames field is present # 0x0002 - Bytes field is present # 0x0004 - TOC field is present # 0x0008 - Quality indicator field is present # # 8 4 Number of Frames as Big-Endian 32-bit unsigned (optional) # # 8 or 12 4 Number of Bytes in file as Big-Endian 32-bit unsigned (optional) # # 8,12 or 16 100 100 TOC entries for seeking as integral BYTE (optional) # # 8,12,16,108,112 or 116 4 Quality indicator as Big-Endian 32-bit unsigned # from 0 - best quality to 100 - worst quality (optional) class XingHeader attr_reader :frames_count, :bytes_count def initialize(file_io, offset = 0) file_io.seek(offset) @id, @flags = file_io.read(8)&.unpack("A4N") return unless valid? @frames_count = @flags & 1 == 1 ? file_io.read(4).unpack1("N") : 0 @bytes_count = @flags & 2 == 2 ? file_io.read(4).unpack1("N") : 0 end def valid? %w[Xing Info].include? @id end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/mp3/vbri_header.rb
lib/wahwah/mp3/vbri_header.rb
# frozen_string_literal: true module WahWah module Mp3 # VBRI header structure: # # Position Length Meaning # 0 4 VBR header ID in 4 ASCII chars, always 'VBRI', not NULL-terminated # # 4 2 Version ID as Big-Endian 16-bit unsigned # # 6 2 Delay as Big-Endian float # # 8 2 Quality indicator # # 10 4 Number of Bytes as Big-Endian 32-bit unsigned # # 14 4 Number of Frames as Big-Endian 32-bit unsigned # # 18 2 Number of entries within TOC table as Big-Endian 16-bit unsigned # # 20 2 Scale factor of TOC table entries as Big-Endian 32-bit unsigned # # 22 2 Size per table entry in bytes (max 4) as Big-Endian 16-bit unsigned # # 24 2 Frames per table entry as Big-Endian 16-bit unsigned # # 26 TOC entries for seeking as Big-Endian integral. # From size per table entry and number of entries, # you can calculate the length of this field. class VbriHeader HEADER_SIZE = 32 HEADER_FORMAT = "A4x6NN" attr_reader :frames_count, :bytes_count def initialize(file_io, offset = 0) file_io.seek(offset) @id, @bytes_count, @frames_count = file_io.read(HEADER_SIZE)&.unpack(HEADER_FORMAT) end def valid? @id == "VBRI" end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/flac/streaminfo_block.rb
lib/wahwah/flac/streaminfo_block.rb
# frozen_string_literal: true module WahWah module Flac module StreaminfoBlock STREAMINFO_BLOCK_SIZE = 34 # STREAMINFO block data structure: # # Length(bit) Meaning # # 16 The minimum block size (in samples) used in the stream. # # 16 The maximum block size (in samples) used in the stream. # (Minimum blocksize == maximum blocksize) implies a fixed-blocksize stream. # # 24 The minimum frame size (in bytes) used in the stream. # May be 0 to imply the value is not known. # # 24 The maximum frame size (in bytes) used in the stream. # May be 0 to imply the value is not known. # # 20 Sample rate in Hz. Though 20 bits are available, # the maximum sample rate is limited by the structure of frame headers to 655350Hz. # Also, a value of 0 is invalid. # # 3 (number of channels)-1. FLAC supports from 1 to 8 channels # # 5 (bits per sample)-1. FLAC supports from 4 to 32 bits per sample. # Currently the reference encoder and decoders only support up to 24 bits per sample. # # 36 Total samples in stream. 'Samples' means inter-channel sample, # i.e. one second of 44.1Khz audio will have 44100 samples regardless of the number of channels. # A value of zero here means the number of total samples is unknown. # # 128 MD5 signature of the unencoded audio data. def parse_streaminfo_block(block_data) return unless block_data.size == STREAMINFO_BLOCK_SIZE info_bits = block_data.unpack1("x10B64") @sample_rate = info_bits[0..19].to_i(2) @bit_depth = info_bits[23..27].to_i(2) + 1 total_samples = info_bits[28..].to_i(2) @duration = total_samples.to_f / @sample_rate if @sample_rate > 0 @bitrate = @sample_rate * @bit_depth / 1000 end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/flac/block.rb
lib/wahwah/flac/block.rb
# frozen_string_literal: true module WahWah module Flac class Block prepend LazyRead HEADER_SIZE = 4 HEADER_FORMAT = "B*" BLOCK_TYPE_INDEX = %w[STREAMINFO PADDING APPLICATION SEEKTABLE VORBIS_COMMENT CUESHEET PICTURE] attr_reader :type def initialize # Block header structure: # # Length(bit) Meaning # # 1 Last-metadata-block flag: # '1' if this block is the last metadata block before the audio blocks, '0' otherwise. # # 7 BLOCK_TYPE # 0 : STREAMINFO # 1 : PADDING # 2 : APPLICATION # 3 : SEEKTABLE # 4 : VORBIS_COMMENT # 5 : CUESHEET # 6 : PICTURE # 7-126 : reserved # 127 : invalid, to avoid confusion with a frame sync code # # 24 Length (in bytes) of metadata to follow # (does not include the size of the METADATA_BLOCK_HEADER) header_bits = @file_io.read(HEADER_SIZE).unpack1(HEADER_FORMAT) @last_flag = header_bits[0] @type = BLOCK_TYPE_INDEX[header_bits[1..7].to_i(2)] @size = header_bits[8..].to_i(2) end def valid? @size > 0 end def is_last? @last_flag.to_i == 1 end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/mp4/atom.rb
lib/wahwah/mp4/atom.rb
# frozen_string_literal: true module WahWah module Mp4 class Atom prepend LazyRead VERSIONED_ATOMS = %w[meta stsd] FLAGGED_ATOMS = %w[stsd] HEADER_SIZE = 8 HEADER_SIZE_FIELD_SIZE = 4 EXTENDED_HEADER_SIZE = 8 attr_reader :type def self.find(file_io, *atom_path) file_io.rewind atom_type = atom_path.shift until file_io.eof? atom = new(file_io) next unless atom.valid? file_io.seek(atom.size, IO::SEEK_CUR) next unless atom.type == atom_type return atom if atom_path.empty? return atom.find(*atom_path) end # Return empty atom if can not found new(StringIO.new("")) end # An atom header consists of the following fields: # # Atom size: # A 32-bit integer that indicates the size of the atom, including both the atom header and the atom’s contents, # including any contained atoms. Normally, the size field contains the actual size of the atom. # # Type: # A 32-bit integer that contains the type of the atom. # This can often be usefully treated as a four-character field with a mnemonic value . def initialize @size, @type = @file_io.read(HEADER_SIZE)&.unpack("Na4") # If the size field of an atom is set to 1, the type field is followed by a 64-bit extended size field, # which contains the actual size of the atom as a 64-bit unsigned integer. @size = @file_io.read(EXTENDED_HEADER_SIZE).unpack1("Q>") - EXTENDED_HEADER_SIZE if @size == 1 # If the size field of an atom is set to 0, which is allowed only for a top-level atom, # designates the last atom in the file and indicates that the atom extends to the end of the file. @size = @file_io.size if @size == 0 return unless valid? @size -= HEADER_SIZE end def valid? !@size.nil? && @size >= HEADER_SIZE end def find(*atom_path) child_atom_index = data.index(atom_path.first) # Return empty atom if can not found return self.class.new(StringIO.new("")) if child_atom_index.nil? # Because before atom type field there are 4 bytes of size field, # So the child_atom_index should reduce 4. self.class.find(StringIO.new(data[child_atom_index - HEADER_SIZE_FIELD_SIZE..]), *atom_path) end def children @children ||= parse_children_atoms end private def parse_children_atoms children_atoms = [] atoms_data = data # Some atoms data contain extra content before child atom data. # So reduce those extra content to get child atom data. atoms_data = atoms_data[4..] if VERSIONED_ATOMS.include? type # Skip 4 bytes for version atoms_data = atoms_data[4..] if FLAGGED_ATOMS.include? type # Skip 4 bytes for flag atoms_data_io = StringIO.new(atoms_data) until atoms_data_io.eof? atom = self.class.new(atoms_data_io) children_atoms.push(atom) atom.skip end children_atoms end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/id3/text_frame_body.rb
lib/wahwah/id3/text_frame_body.rb
# frozen_string_literal: true module WahWah module ID3 class TextFrameBody < FrameBody # Text frame boby structure: # # Text encoding $xx # Information <text string according to encoding> def parse encoding_id, text = @content.unpack("Ca*") @value = Helper.encode_to_utf8(text, source_encoding: ENCODING_MAPPING[encoding_id]) end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/id3/genre_frame_body.rb
lib/wahwah/id3/genre_frame_body.rb
# frozen_string_literal: true module WahWah module ID3 class GenreFrameBody < TextFrameBody def parse super # If value is numeric value, or contain numeric value in parens # can use as index for ID3v1 genre list @value = ID3::V1::GENRES[$1.to_i] if @value =~ /^\((\d+)\)$/ || @value =~ /^(\d+)$/ end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/id3/v1.rb
lib/wahwah/id3/v1.rb
# frozen_string_literal: true module WahWah module ID3 class V1 < Tag TAG_SIZE = 128 TAG_ID = "TAG" DEFAULT_ENCODING = "iso-8859-1" GENRES = [ # Standard Genres "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska", "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "AlternRock", "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave", "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", "Musical", "Rock & Roll", "Hard Rock", # Winamp Extended Genres "Folk", "Folk-Rock", "National Folk", "Swing", "Fast Fusion", "Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock", "Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour", "Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus", "Porn Groove", "Satire", "Slow Jam", "Club", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul", "Freestyle", "Duet", "Punk Rock", "Drum Solo", "A capella", "Euro-House", "Dance Hall", "Goa", "Drum & Bass", "Club-House", "Hardcore Techno", "Terror", "Indie", "BritPop", "Negerpunk", "Polsk Punk", "Beat", "Christian Gangsta Rap", "Heavy Metal", "Black Metal", "Contemporary Christian", "Christian Rock", # Added on WinAmp 1.91 "Merengue", "Salsa", "Thrash Metal", "Anime", "Jpop", "Synthpop", # Added on WinAmp 5.6 "Abstract", "Art Rock", "Baroque", "Bhangra", "Big Beat", "Breakbeat", "Chillout", "Downtempo", "Dub", "EBM", "Eclectic", "Electro", "Electroclash", "Emo", "Experimental", "Garage", "Illbient", "Industro-Goth", "Jam Band", "Krautrock", "Leftfield", "Lounge", "Math Rock", "New Romantic", "Nu-Breakz", "Post-Punk", "Post-Rock", "Psytrance", "Shoegaze", "Space Rock", "Trop Rock", "World Music", "Neoclassical", "Audiobook", "Audio Theatre", "Neue Deutsche Welle", "Podcast", "Indie Rock", "G-Funk", "Dubstep", "Garage Rock", "Psybient" ] def size TAG_SIZE end def version "v1" end def valid? @id == TAG_ID end private # For ID3v1 info, see here https://en.wikipedia.org/wiki/ID3#ID3v1 # # header 3 "TAG" # title 30 30 characters of the title # artist 30 30 characters of the artist name # album 30 30 characters of the album name # year 4 A four-digit year # comment 28 or 30 The comment. # zero-byte 1 If a track number is stored, this byte contains a binary 0. # track 1 The number of the track on the album, or 0. Invalid, if previous byte is not a binary 0. # genre 1 Index in a list of genres, or 255 def parse return unless @file_io.size >= TAG_SIZE @file_io.seek(-TAG_SIZE, IO::SEEK_END) @id = Helper.encode_to_utf8(@file_io.read(3), source_encoding: DEFAULT_ENCODING) return unless valid? @title = Helper.encode_to_utf8(@file_io.read(30), source_encoding: DEFAULT_ENCODING) @artist = Helper.encode_to_utf8(@file_io.read(30), source_encoding: DEFAULT_ENCODING) @album = Helper.encode_to_utf8(@file_io.read(30), source_encoding: DEFAULT_ENCODING) @year = Helper.encode_to_utf8(@file_io.read(4), source_encoding: DEFAULT_ENCODING) comment = @file_io.read(30) if comment.getbyte(-2) == 0 @track = comment.getbyte(-1) comment = comment.byteslice(0..-3) end @comments.push(Helper.encode_to_utf8(comment, source_encoding: DEFAULT_ENCODING)) @genre = GENRES[@file_io.getbyte] || "" end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/id3/image_frame_body.rb
lib/wahwah/id3/image_frame_body.rb
# frozen_string_literal: true module WahWah module ID3 class ImageFrameBody < FrameBody TYPES = %i[ other file_icon other_file_icon cover_front cover_back leaflet media lead_artist artist conductor band composer lyricist recording_location during_recording during_performance movie_screen_capture bright_coloured_fish illustration band_logotype publisher_logotype ] def mime_type mime_type = @mime_type.downcase.yield_self { |type| type == "jpg" ? "jpeg" : type } @version > 2 ? mime_type : "image/#{mime_type}" end # ID3v2.2 image frame structure: # # Text encoding $xx # Image format $xx xx xx # Picture type $xx # Description <text string according to encoding> $00 (00) # Picture data <binary data> # # ID3v2.3 and ID3v2.4 image frame structure: # # Text encoding $xx # MIME type <text string> $00 # Picture type $xx # Description <text string according to encoding> $00 (00) # Picture data <binary data> def parse frame_format = @version > 2 ? "CZ*Ca*" : "Ca3Ca*" encoding_id, @mime_type, type_index, rest_content = @content.unpack(frame_format) encoding = ENCODING_MAPPING[encoding_id] _description, data = Helper.split_with_terminator(rest_content, ENCODING_TERMINATOR_SIZE[encoding]) @value = {data: data, mime_type: mime_type, type: TYPES[type_index]} end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/id3/frame.rb
lib/wahwah/id3/frame.rb
# frozen_string_literal: true module WahWah module ID3 class Frame prepend LazyRead ID_MAPPING = { # ID3v2.2 frame id COM: :comment, TRK: :track, TYE: :year, TAL: :album, TP1: :artist, TT2: :title, TCO: :genre, TPA: :disc, TP2: :albumartist, TCM: :composer, PIC: :image, ULT: :lyrics, # ID3v2.3 and ID3v2.4 frame id COMM: :comment, TRCK: :track, TYER: :year, TALB: :album, TPE1: :artist, TIT2: :title, TCON: :genre, TPOS: :disc, TPE2: :albumartist, TCOM: :composer, APIC: :image, USLT: :lyrics, # ID3v2.4 use TDRC replace TYER TDRC: :year } # ID3v2.3 frame flags field is defined as follows. # # %abc00000 %ijk00000 # # a - Tag alter preservation # b - File alter preservation # c - Read only # i - Compression # j - Encryption # k - Grouping identity V3_HEADER_FLAGS_INDICATIONS = Array.new(16).tap do |array| array[0] = :tag_alter_preservation array[1] = :file_alter_preservation array[2] = :read_only array[8] = :compression array[9] = :encryption array[10] = :grouping_identity end # ID3v2.4 frame flags field is defined as follows. # # %0abc0000 %0h00kmnp # # a - Tag alter preservation # b - File alter preservation # c - Read only # h - Grouping identity # k - Compression # m - Encryption # n - Unsynchronisation # p - Data length indicator V4_HEADER_FLAGS_INDICATIONS = Array.new(16).tap do |array| array[1] = :tag_alter_preservation array[2] = :file_alter_preservation array[3] = :read_only array[9] = :grouping_identity array[12] = :compression array[13] = :encryption array[14] = :unsynchronisation array[15] = :data_length_indicator end attr_reader :name def initialize(version) @version = version parse_frame_header # In ID3v2.3 when frame is compressed using zlib # with 4 bytes for 'decompressed size' appended to the frame header. # # In ID3v2.4 A 'Data Length Indicator' byte MUST be included in the frame # when frame is compressed, and 'Data Length Indicator'represented as a 32 bit # synchsafe integer # # So skip those 4 byte. if compressed? || data_length_indicator? @file_io.seek(4, IO::SEEK_CUR) @size -= 4 end end def valid? @size > 0 && !@name.nil? end def compressed? @flags.include? :compression end def data_length_indicator? @flags.include? :data_length_indicator end def value return unless @size > 0 content = compressed? ? Zlib.inflate(data) : data frame_body = frame_body_class.new(content, @version) frame_body.value end private # ID3v2.2 frame header structure: # # Frame ID $xx xx xx(tree characters) # Size 3 * %xxxxxxxx # # ID3v2.3 frame header structure: # # Frame ID $xx xx xx xx (four characters) # Size 4 * %xxxxxxxx # Flags $xx xx # # ID3v2.4 frame header structure: # # Frame ID $xx xx xx xx (four characters) # Size 4 * %0xxxxxxx # Flags $xx xx def parse_frame_header header_size = @version == 2 ? 6 : 10 header_formate = @version == 2 ? "A3B24" : "A4B32B16" id, size_bits, flags_bits = @file_io.read(header_size).unpack(header_formate) @name = ID_MAPPING[id.to_sym] @size = Helper.id3_size_caculate(size_bits, has_zero_bit: @version == 4) @flags = parse_flags(flags_bits) end def parse_flags(flags_bits) return [] if flags_bits.nil? frame_flags_indications = @version == 4 ? V4_HEADER_FLAGS_INDICATIONS : V3_HEADER_FLAGS_INDICATIONS flags_bits.chars.map.with_index do |flag_bit, index| frame_flags_indications[index] if flag_bit == "1" end.compact end def frame_body_class case @name when :comment CommentFrameBody when :genre GenreFrameBody when :image ImageFrameBody when :lyrics LyricsFrameBody else TextFrameBody end end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/id3/v2_header.rb
lib/wahwah/id3/v2_header.rb
# frozen_string_literal: true module WahWah module ID3 # The ID3v2 tag header, which should be the first information in the file, # is 10 bytes as follows: # ID3v2/file identifier "ID3" # ID3v2 version $03 00 # ID3v2 flags %abc00000 # ID3v2 size 4 * %0xxxxxxx class V2Header TAG_ID = "ID3" HEADER_SIZE = 10 HEADER_FORMAT = "A3CxB8B*" attr_reader :major_version, :size def initialize(file_io) header_content = file_io.read(HEADER_SIZE) || "" @id, @major_version, @flags, size_bits = header_content.unpack(HEADER_FORMAT) if header_content.size >= HEADER_SIZE return unless valid? # Tag size is the size excluding the header size, # so add header size back to get total size. @size = Helper.id3_size_caculate(size_bits) + HEADER_SIZE if has_extended_header? # Extended header structure: # # Extended header size $xx xx xx xx # Extended Flags $xx xx # Size of padding $xx xx xx xx # Skip extended_header extended_header_size = Helper.id3_size_caculate(file_io.read(4).unpack1("B32")) file_io.seek(extended_header_size - 4, IO::SEEK_CUR) end end def valid? @id == TAG_ID end # The second bit in flags byte indicates whether or not the header # is followed by an extended header. def has_extended_header? @flags[1] == "1" end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/id3/frame_body.rb
lib/wahwah/id3/frame_body.rb
# frozen_string_literal: true module WahWah module ID3 class FrameBody # Textual frames are marked with an encoding byte. # # $00 ISO-8859-1 [ISO-8859-1]. Terminated with $00. # $01 UTF-16 [UTF-16] encoded Unicode [UNICODE] with BOM. # $02 UTF-16BE [UTF-16] encoded Unicode [UNICODE] without BOM. # $03 UTF-8 [UTF-8] encoded Unicode [UNICODE]. ENCODING_MAPPING = %w[ISO-8859-1 UTF-16 UTF-16BE UTF-8] ENCODING_TERMINATOR_SIZE = { "ISO-8859-1" => 1, "UTF-16" => 2, "UTF-16BE" => 2, "UTF-8" => 1 } attr_reader :value def initialize(content, version) @content = content @version = version parse end def parse raise WahWahNotImplementedError, "The parse method is not implemented" end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/id3/v2.rb
lib/wahwah/id3/v2.rb
# frozen_string_literal: true module WahWah module ID3 class V2 < Tag extend Forwardable def_delegators :@header, :major_version, :size, :has_extended_header?, :valid? def version "v2.#{major_version}" end private def parse @file_io.rewind @header = V2Header.new(@file_io) return unless valid? until end_of_tag? frame = ID3::Frame.new(@file_io, major_version) unless frame.valid? frame.skip next end update_attribute(frame) end end def update_attribute(frame) name = frame.name case name when :comment # Because there may be more than one comment frame in each tag, # so push it into a array. @comments.push(frame.value) when :image # Because there may be more than one image frame in each tag, # so push it into a array. @images_data.push(frame) frame.skip when :track, :disc # Track and disc value may be extended with a "/" character # and a numeric string containing the total numer. count, total_count = frame.value.split("/", 2) instance_variable_set("@#{name}", count) instance_variable_set("@#{name}_total", total_count) unless total_count.nil? else instance_variable_set("@#{name}", frame.value) end end def end_of_tag? size <= @file_io.pos || file_size <= @file_io.pos end def parse_image_data(image_frame) image_frame.value end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/id3/comment_frame_body.rb
lib/wahwah/id3/comment_frame_body.rb
# frozen_string_literal: true module WahWah module ID3 class CommentFrameBody < FrameBody # Comment frame body structure: # # Text encoding $xx # Language $xx xx xx # Short content description <textstring> $00 (00) # The actual text <textstring> def parse encoding_id, _language, reset_content = @content.unpack("CA3a*") encoding = ENCODING_MAPPING[encoding_id] _description, comment_text = Helper.split_with_terminator(reset_content, ENCODING_TERMINATOR_SIZE[encoding]) @value = Helper.encode_to_utf8(comment_text, source_encoding: encoding) end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/id3/lyrics_frame_body.rb
lib/wahwah/id3/lyrics_frame_body.rb
# frozen_string_literal: true module WahWah module ID3 class LyricsFrameBody < CommentFrameBody end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
aidewoode/wahwah
https://github.com/aidewoode/wahwah/blob/c451fbe9a49d04e1dd8743e904215f1a7cdb9918/lib/wahwah/asf/object.rb
lib/wahwah/asf/object.rb
# frozen_string_literal: true module WahWah module Asf # The base unit of organization for ASF files is called the ASF object. # It consists of a 128-bit GUID for the object, a 64-bit integer object size, and the variable-length object data. # The value of the object size field is the sum of 24 bytes plus the size of the object data in bytes. # The following diagram illustrates the ASF object structure: # # 16 bytes: Object GUID # 8 bytes: Object size # variable-sized: Object data class Object prepend LazyRead HEADER_SIZE = 24 HEADER_FORMAT = "a16Q<" attr_reader :guid def initialize guid_bytes, @size = @file_io.read(HEADER_SIZE)&.unpack(HEADER_FORMAT) return unless valid? @size -= HEADER_SIZE @guid = Helper.byte_string_to_guid(guid_bytes) end def valid? !@size.nil? && @size >= HEADER_SIZE end end end end
ruby
MIT
c451fbe9a49d04e1dd8743e904215f1a7cdb9918
2026-01-04T17:50:26.827863Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/factories.rb
spec/factories.rb
FactoryGirl.define do sequence :name do |n| "Joe's Steam Cleaning #{n}" end sequence :description do |n| "Item #{n}" end sequence :project_name do |n| "Joe's Steam Cleaning Project #{n}" end factory :client, class: Harvest::Client do name details "Steam Cleaning across the country" end factory :invoice, class: Harvest::Invoice do subject "Invoice for Joe's Stream Cleaning" client_id nil issued_at "2011-03-31" due_at "2011-03-31" due_at_human_format "upon receipt" currency "United States Dollars - USD" sequence(:number) notes "Some notes go here" period_end "2011-03-31" period_start "2011-02-26" kind "free_form" state "draft" purchase_order nil tax nil tax2 nil import_hours "no" import_expenses "no" line_items { [FactoryGirl.build(:line_item)] } end factory :line_item, class: Harvest::LineItem do kind "Service" description quantity 200 unit_price "12.00" end factory :invoice_payment, class: Harvest::InvoicePayment do paid_at Time.now amount "0.00" notes "Payment received" end factory :invoice_message, class: Harvest::InvoiceMessage do body "The message body goes here" recipients "john@example.com, jane@example.com" attach_pdf true send_me_a_copy true include_pay_pal_link true end factory :project, class: Harvest::Project do name { generate(:project_name) } end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/spec_helper.rb
spec/spec_helper.rb
require 'harvested' require 'webmock/rspec' require 'vcr' require 'factory_girl' require 'byebug' Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require File.expand_path(f) } VCR.configure do |c| c.cassette_library_dir = '.cassettes' c.hook_into :webmock c.default_cassette_options = { # force cassettes to re_record when we pass VCR_REFRESH=true re_record_interval: ENV['VCR_REFRESH'] == 'true' ? 0 : nil } c.allow_http_connections_when_no_cassette = true end FactoryGirl.find_definitions RSpec.configure do |config| config.include HarvestedHelpers config.before(:suite) do WebMock.allow_net_connect! cassette("clean") do HarvestedHelpers.clean_remote end end config.before(:each) do WebMock.allow_net_connect! end def cassette(*args) if ENV['USE_VCR'] VCR.use_cassette(*args) do yield end else yield end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/support/harvested_helpers.rb
spec/support/harvested_helpers.rb
module HarvestedHelpers def self.credentials raise "You need a credentials file in support/harvest_credentials.yml!!" unless File.exist?("#{File.dirname(__FILE__)}/harvest_credentials.yml") @credentials ||= YAML.load_file("#{File.dirname(__FILE__)}/harvest_credentials.yml") end def credentials; HarvestedHelpers.credentials; end def self.simple_harvest Harvest.client(subdomain: credentials["subdomain"], username: credentials["username"], password: credentials["password"]) end def harvest; @harvest ||= HarvestedHelpers.simple_harvest; end def hardy_harvest Harvest.hardy_client(subdomain: credentials["subdomain"], username: credentials["username"], password: credentials["password"]) end def self.clean_remote harvest = simple_harvest harvest.users.all.each do |u| harvest.reports.expenses_by_user(u, Time.utc(2000, 1, 1), Time.utc(2014, 6, 21)).each do |expense| harvest.expenses.delete(expense, u) end harvest.reports.time_by_user(u, Time.utc(2000, 1, 1), Time.utc(2014, 6, 21)).each do |time| harvest.time.delete(time, u) end harvest.users.delete(u) if u.email != credentials["username"] end # we store expenses on this date in the tests harvest.expenses.all(Time.utc(2009, 12, 28)).each {|e| harvest.expenses.delete(e) } %w(expense_categories time projects invoices contacts clients tasks).each do |collection| harvest.send(collection).all.each {|m| harvest.send(collection).delete(m) } end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/support/json_examples.rb
spec/support/json_examples.rb
shared_examples_for 'a json sanitizer' do |keys| keys.each do |key| it "doesn't include '#{key}' when serializing to json" do instance = described_class.new instance[key] = 10 instance.as_json[instance.class.json_root].keys.should_not include(key) end end end # it_behaves_like 'a json sanitizer', %w(cache_version)
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/user_assignment_spec.rb
spec/harvest/user_assignment_spec.rb
require 'spec_helper' describe Harvest::UserAssignment do describe "#user_as_json" do it "should generate the xml for existing users" do assignment = Harvest::UserAssignment.new(:user => double(:user, :to_i => 3)) assignment.user_as_json.should == {"user" => {"id" => 3}} end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/oauth_credentials_spec.rb
spec/harvest/oauth_credentials_spec.rb
require 'spec_helper' describe Harvest::OAuthCredentials do context '#set_authentication' do it "should set the access token in the query" do credentials = Harvest::OAuthCredentials.new('theaccesstoken') credentials.set_authentication(options = {}) options[:query]['access_token'].should == 'theaccesstoken' end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/trackable_project_spec.rb
spec/harvest/trackable_project_spec.rb
require 'spec_helper' describe Harvest::TrackableProject do it "creates task objects" do projects = Harvest::TrackableProject.parse('[{"tasks":[{"id":123}]}]').first projects.tasks.first.id.should == 123 end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/invoice_message_spec.rb
spec/harvest/invoice_message_spec.rb
require 'spec_helper' describe Harvest::InvoiceMessage do it_behaves_like 'a json sanitizer', %w(cache_version) end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/project_spec.rb
spec/harvest/project_spec.rb
require 'spec_helper' describe Harvest::Project do it_behaves_like 'a json sanitizer', %w(hint_latest_record_at hint_earliest_record_at cache_version) end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/task_assignment_spec.rb
spec/harvest/task_assignment_spec.rb
require 'spec_helper' describe Harvest::TaskAssignment do context "task_as_json" do it "generates the json for existing tasks" do assignment = Harvest::TaskAssignment.new(:task => double(:task, :to_i => 3)) assignment.task_as_json.should == {"task" => {"id" => 3}} end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/expense_category_spec.rb
spec/harvest/expense_category_spec.rb
require 'spec_helper' describe Harvest::ExpenseCategory do it_behaves_like 'a json sanitizer', %w(cache_version) end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/time_entry_spec.rb
spec/harvest/time_entry_spec.rb
require 'spec_helper' describe Harvest::TimeEntry do context '#as_json' do it 'builds a specialized hash' do entry = Harvest::TimeEntry.new(:notes => 'the notes', :project_id => 'the project id', :task_id => 'the task id', :hours => 'the hours', :spent_at => Time.utc(2009, 12, 28)) entry.as_json.should == {"notes" => "the notes", "hours" => "the hours", "project_id" => "the project id", "task_id" => "the task id", "spent_at" => "2009-12-28"} end end context "#spent_at" do it "should parse strings" do date = RUBY_VERSION =~ /1.8/ ? "12/01/2009" : "01/12/2009" entry = Harvest::TimeEntry.new(:spent_at => date) entry.spent_at.should == Date.parse(date) end it "should accept times" do entry = Harvest::TimeEntry.new(:spent_at => Time.utc(2009, 12, 1)) entry.spent_at.should == Date.new(2009, 12, 1) end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/invoice_payment_spec.rb
spec/harvest/invoice_payment_spec.rb
require 'spec_helper' describe Harvest::InvoicePayment do it_behaves_like 'a json sanitizer', %w(cache_version) end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/task_spec.rb
spec/harvest/task_spec.rb
require 'spec_helper' describe Harvest::Task do it_behaves_like 'a json sanitizer', %w(cache_version) end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/base_spec.rb
spec/harvest/base_spec.rb
require 'spec_helper' describe Harvest::Base do describe "username/password errors" do it "should raise error if missing a credential" do lambda { Harvest::Base.new(subdomain: "subdomain", password: "secure") }.should raise_error(/must provide either/i) end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/basic_auth_credentials_spec.rb
spec/harvest/basic_auth_credentials_spec.rb
require 'spec_helper' describe Harvest::BasicAuthCredentials do context '#set_authentication' do it "should set the headers Authorization" do credentials = Harvest::BasicAuthCredentials.new(subdomain: 'some-domain', username: 'username', password: 'password') credentials.set_authentication(options = {}) options[:headers]['Authorization'].should == "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/expense_spec.rb
spec/harvest/expense_spec.rb
require 'spec_helper' describe Harvest::Expense do it_behaves_like 'a json sanitizer', %w(has_receipt receipt_url) describe "#spent_at" do it "should parse strings" do date = RUBY_VERSION =~ /1.8/ ? "12/01/2009" : "01/12/2009" expense = Harvest::Expense.new(:spent_at => date) expense.spent_at.should == Date.parse(date) end it "should accept times" do expense = Harvest::Expense.new(:spent_at => Time.utc(2009, 12, 1)) expense.spent_at.should == Date.new(2009, 12, 1) end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/invoice_spec.rb
spec/harvest/invoice_spec.rb
require 'spec_helper' describe Harvest::Invoice do context 'line_items' do it 'parses csv into objects' do invoice = Harvest::Invoice.new(:line_items => "kind,description,quantity,unit_price,amount,taxed,taxed2,project_id\nService,Abc,200,12.00,2400.0,false,false,100\nService,def,1.00,20.00,20.0,false,false,101\n") invoice.line_items.count.should == 2 line_item = invoice.line_items.first line_item.kind.should == "Service" line_item.project_id.should == "100" end it 'parses csv into objects w/o projects' do invoice = Harvest::Invoice.new(:line_items => "kind,description,quantity,unit_price,amount,taxed,taxed2,project_id\nService,Abc,200,12.00,2400.0,false,false,\nService,def,1.00,20.00,20.0,false,false,\n") invoice.line_items.count.should == 2 line_item = invoice.line_items.first line_item.kind.should == "Service" line_item.description.should == "Abc" end it 'parses empty strings' do invoice = Harvest::Invoice.new(:line_items => "") invoice.line_items.should == [] end it 'accepts rich objects' do Harvest::Invoice.new(:line_items => [Harvest::LineItem.new(:kind => "Service")]).line_items.count.should == 1 Harvest::Invoice.new(:line_items => Harvest::LineItem.new(:kind => "Service")).line_items.count.should == 1 end it 'accepts nil' do Harvest::Invoice.new(:line_items => nil).line_items.should == [] end end context "as_json" do it 'only updates line items remotely if it the invoice is told to' do invoice = Harvest::Invoice.new(:line_items => "kind,description,quantity,unit_price,amount,taxed,taxed2,project_id\nService,Abc,200,12.00,2400.0,false,false,\nService,def,1.00,20.00,20.0,false,false,\n") invoice.line_items.count.should == 2 invoice.line_items.first.kind.should == "Service" invoice.as_json["invoice"].keys.should_not include("csv_line_items") invoice.update_line_items = true invoice.as_json["invoice"]["csv_line_items"].should == "kind,description,quantity,unit_price,amount,taxed,taxed2,project_id\nService,Abc,200,12.00,2400.0,false,false,\nService,def,1.00,20.00,20.0,false,false,\n" end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/harvest/user_spec.rb
spec/harvest/user_spec.rb
require 'spec_helper' describe Harvest::User do it_behaves_like 'a json sanitizer', %w(cache_version) describe "#timezone" do it "should convert friendly timezone setting" do p = Harvest::User.new(:timezone => :cst) p.timezone.should == 'Central Time (US & Canada)' p = Harvest::User.new(:timezone => :est) p.timezone.should == 'Eastern Time (US & Canada)' p = Harvest::User.new(:timezone => :mst) p.timezone.should == 'Mountain Time (US & Canada)' p = Harvest::User.new(:timezone => :pst) p.timezone.should == 'Pacific Time (US & Canada)' p = Harvest::User.new(:timezone => 'pst') p.timezone.should == 'Pacific Time (US & Canada)' end it "should convert standard zones" do p = Harvest::User.new(:timezone => 'america/chicago') p.timezone.should == 'Central Time (US & Canada)' end it "should leave literal zones" do p = Harvest::User.new(:timezone => 'Central Time (US & Canada)') p.timezone.should == 'Central Time (US & Canada)' end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/functional/expenses_spec.rb
spec/functional/expenses_spec.rb
require 'spec_helper' describe 'harvest expenses' do context 'categories' do it 'allows adding, updating and removing categories' do cassette("expense_category1") do category = harvest.expense_categories.create( "name" => "Mileage", "unit_price" => 100, "unit_name" => "mile" ) category.name.should == "Mileage" category.name = "Travel" category = harvest.expense_categories.update(category) category.name.should == "Travel" harvest.expense_categories.delete(category) harvest.expense_categories.all.select{|e| e.name == "Travel" }.should == [] end end end it "allows adding, updating, and removing expenses" do cassette("expenses2") do category = harvest.expense_categories.create( "name" => "Something Deductible", "unit_price" => 100, "unit_name" => "deduction" ) client = harvest.clients.create( "name" => "Tom's Butcher", "details" => "Building API Widgets across the country" ) project = harvest.projects.create( "name" => "Expensing Project", "active" => true, "notes" => "project to test the api", "client_id" => client.id ) expense = harvest.expenses.create( "notes" => "Drive to Chicago", "total_cost" => 75.0, "spent_at" => Time.utc(2009, 12, 28), "expense_category_id" => category.id, "project_id" => project.id ) expense.notes.should == "Drive to Chicago" expense.notes = "Off to Chicago" expense = harvest.expenses.update(expense) expense.notes.should == "Off to Chicago" harvest.expenses.delete(expense) harvest.expenses.all(Time.utc(2009, 12, 28)).select {|e| e.notes == "Off to Chicago"}.should == [] end end end # Copied from feature # @wip # Scenario: Attaching a receipt to an Expense # Given I am using the credentials from "./support/harvest_credentials.yml" # When I create an expense category with the following: # | name | Mileage | # | unit_name | Miles | # | unit_price | 0.485 | # Then there should be an expense category "Mileage" # When I create a client with the following: # | name | Expense Client | # When I create a project for the client "Expense Client" with the following: # | name | Test Project | # When I create an expense for the project "Test Project" with the category "Mileage" with the following: # | notes | Drive to Chicago | # | total_cost | 75.00 | # | spent_at | 12/28/2009 | # Then there should be an expense "Drive to Chicago" on "12/28/2009" # When I attach the receipt "./support/fixtures/receipt.png" to the expense "Drive to Chicago" on "12/28/2009" # Then there should be a receipt "./support/fixtures/receipt.png" attached to the expense "Drive to Chicago" on "12/28/2009"
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/functional/clients_spec.rb
spec/functional/clients_spec.rb
require 'spec_helper' describe 'harvest clients' do it 'allows adding, updating and removing clients' do client_attributes = FactoryGirl.attributes_for(:client) cassette("client") do client = harvest.clients.create(client_attributes) client.name.should == client_attributes[:name] client.name = "Joe and Frank's Steam Cleaning" client = harvest.clients.update(client) client.name.should == "Joe and Frank's Steam Cleaning" harvest.clients.delete(client) harvest.clients.all.select {|p| p.name == "Joe and Frank's Steam Cleaning"}.should == [] end end it 'allows activating and deactivating clients' do cassette("client2") do client = harvest.clients.create(FactoryGirl.attributes_for(:client)) client.should be_active client = harvest.clients.deactivate(client) client.should_not be_active client = harvest.clients.activate(client) client.should be_active end end context "contacts" do it "allows adding, updating, and removing contacts" do cassette("client3") do client = harvest.clients.create(FactoryGirl.attributes_for(:client)) contact = harvest.contacts.create( "client_id" => client.id, "email" => "jane@example.com", "first_name" => "Jane", "last_name" => "Doe" ) contact.client_id.should == client.id contact.email.should == "jane@example.com" harvest.contacts.delete(contact) harvest.contacts.all.select {|e| e.email == "jane@example.com" }.should == [] end end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/functional/project_spec.rb
spec/functional/project_spec.rb
require 'spec_helper' describe 'harvest projects' do it 'allows adding, updating and removing projects' do cassette('project1') do client = harvest.clients.create(FactoryGirl.attributes_for(:client)) project = harvest.projects.create( "name" => "Test Project", "active" => true, "notes" => "project to test the api", "client_id" => client.id ) project.name.should == "Test Project" project.name = "Updated Project" project = harvest.projects.update(project) project.name.should == "Updated Project" harvest.projects.delete(project) harvest.projects.all.select {|p| p.name == "Updated Project"}.should == [] end end it 'allows activating and deactivating clients' do cassette('project2') do client = harvest.clients.create(FactoryGirl.attributes_for(:client)) project = harvest.projects.create( "name" => "Test Project", "active" => true, "notes" => "project to test the api", "client_id" => client.id ) project.should be_active project = harvest.projects.deactivate(project) project.should_not be_active project = harvest.projects.activate(project) project.should be_active end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/functional/invoice_messages_spec.rb
spec/functional/invoice_messages_spec.rb
require 'spec_helper' describe 'harvest invoice messages' do it 'allows adding/removing messages to invoice and retrieving existing invoice messages' do # Make sure Reminder Message is turned off for this test to pass cassette('invoice_message1') do # create a new client and invoice client = harvest.clients.create(FactoryGirl.attributes_for(:client)) invoice = harvest.invoices.create(FactoryGirl.attributes_for(:invoice, :client_id => client.id, :issued_at => Date.today - 2, :due_at_human_format => 'NET 30')) # add a message to the invoice message = Harvest::InvoiceMessage.new(FactoryGirl.attributes_for(:invoice_message, :invoice_id => invoice.id, :body => "A message body")) message_saved = harvest.invoice_messages.create(message) # retrieve the created invoice and compare message_found = harvest.invoice_messages.find(invoice, message_saved) message_found.should == message_saved # add another message to the invoice message2 = Harvest::InvoiceMessage.new(FactoryGirl.attributes_for(:invoice_message, :invoice_id => invoice.id, :body => "Another message body")) message2_saved = harvest.invoice_messages.create(message2) # get all the messages and test if our 2 saved messages are included messages = harvest.invoice_messages.all(invoice) messages.should include(message_saved) messages.should include(message2_saved) # remove a message harvest.invoice_messages.delete(message_saved) messages = harvest.invoice_messages.all(invoice) messages.should_not include(message_saved) messages.should include(message2_saved) # remove another message harvest.invoice_messages.delete(message2_saved) messages = harvest.invoice_messages.all(invoice) messages.should_not include(message_saved) messages.should_not include(message2_saved) harvest.invoice_messages.all(invoice).should be_empty end end it 'allows to change the state of an invoice' do cassette('invoice_message2') do # create a new client and invoice client = harvest.clients.create(FactoryGirl.attributes_for(:client)) invoice = harvest.invoices.create(FactoryGirl.attributes_for(:invoice, :client_id => client.id)) # check the invoice state is 'draft' invoice = harvest.invoices.find(invoice.id) invoice.state.should == 'draft' # -- mark as sent message = Harvest::InvoiceMessage.new(FactoryGirl.attributes_for(:invoice_message, :invoice_id => invoice.id, :body => "sent body message")) harvest.invoice_messages.mark_as_sent(message) # check the invoice state and latest message body invoice = harvest.invoices.find(invoice.id) invoice.state.should == 'open' messages = harvest.invoice_messages.all(invoice) messages.last.body.should == message.body # -- mark_as_closed (write off) message.body = "close body message" harvest.invoice_messages.mark_as_closed(message) # check the invoice state and latest message body invoice = harvest.invoices.find(invoice.id) invoice.state.should == 'closed' # -- re_open message.body = "re-open body message" harvest.invoice_messages.re_open(message) messages = harvest.invoice_messages.all(invoice) # check the invoice state and latest message body invoice = harvest.invoices.find(invoice.id) invoice.state.should == 'open' end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/functional/reporting_spec.rb
spec/functional/reporting_spec.rb
require 'spec_helper' describe 'harvest reporting' do it 'allows project and people entry reporting' do cassette("reports1") do user = harvest.users.create( email: "jane@example.com", first_name: "Jane", last_name: "Doe", password: "secure" ) client = harvest.clients.create(name: "Tim's Dry Cleaning") project1 = harvest.projects.create(name: "Reporting Project1", client_id: client.id) project2 = harvest.projects.create(name: "Reporting Project2", client_id: client.id) task1 = harvest.tasks.create(name: "A billable task", "default_hourly_rate" => 120, "billable_by_default" => true) task2 = harvest.tasks.create(name: "A non billable task", "billable_by_default" => false) harvest.task_assignments.create(project: project1, task: task1) harvest.task_assignments.create(project: project2, task: task2) harvest.user_assignments.create(project: project1, user: user) harvest.user_assignments.create(project: project2, user: user) entry1 = harvest.time.create(notes: "billable entry1", hours: 3, spent_at: "2009/12/28", task_id: task1.id, project_id: project1.id, of_user: user.id) entry2 = harvest.time.create(notes: "non billable entry2", hours: 6, spent_at: "2009/12/28", task_id: task2.id, project_id: project2.id, of_user: user.id) harvest.reports.time_by_project(project1, Time.utc(2009, 12, 20), Time.utc(2009,12,30)).first.should == entry1 harvest.reports.time_by_project(project1, Time.utc(2009, 12, 20), Time.utc(2009,12,30), user: user).first.should == entry1 harvest.reports.time_by_project(project2, Time.utc(2009, 12, 20), Time.utc(2009,12,30), user: user).first.should == entry2 harvest.reports.time_by_project(project2, Time.utc(2009, 12, 20), Time.utc(2009,12,30), billable: true).should == [] harvest.reports.time_by_project(project2, Time.utc(2009, 12, 20), Time.utc(2009,12,30), billable: false).first.should == entry2 sleep 10 harvest.reports.time_by_project(project1, Time.utc(2009, 12, 10), Time.utc(2009,12,30), {updated_since: Time.now.utc}).should == [] harvest.reports.time_by_user(user, Time.utc(2009, 12, 20), Time.utc(2009,12,30)).map(&:id).should == [entry1, entry2].map(&:id) harvest.reports.time_by_user(user, Time.utc(2009, 12, 20), Time.utc(2009,12,30), project: project1).first.should == entry1 harvest.reports.time_by_user(user, Time.utc(2009, 12, 20), Time.utc(2009,12,30), project: project2).first.should == entry2 harvest.reports.time_by_user(user, Time.utc(2009, 12, 20), Time.utc(2009,12,30), billable: true).first.should == entry1 harvest.reports.time_by_user(user, Time.utc(2009, 12, 20), Time.utc(2009,12,30), billable: false).first.should == entry2 entry3_time = Time.now.utc entry3 = harvest.time.create(notes: "test entry for checking updated_since", hours: 5, spent_at: "2009/12/15", task_id: task1.id, project_id: project1.id, of_user: user.id) entries = harvest.reports.time_by_user(user, Time.utc(2009, 12, 10), Time.utc(2009,12,30), {project: project1, updated_since: Time.parse(entry3.updated_at) - 1}) entries.first.should == entry3 entries.size.should == 1 client2 = harvest.clients.create(name: "Phil's Sandwich Shop") harvest.reports.projects_by_client(client).map(&:id).to_set.should == [project1, project2].map(&:id).to_set harvest.reports.projects_by_client(client2).should == [] end end it 'allows expense reporting' do cassette("reports2") do user = harvest.users.create( email: "simon@example.com", first_name: "Simon", last_name: "Stir", password: "secure" ) category = harvest.expense_categories.create(name: "Reporting category", "unit_price" => 100, "unit_name" => "deduction") client = harvest.clients.create(name: "Philip's Butcher") project = harvest.projects.create(name: "Expense Reporting Project", client_id: client.id) harvest.user_assignments.create(project: project, user: user) expense = harvest.expenses.create({ notes: "Drive to Chicago", total_cost: 75.0, spent_at: Time.utc(2009, 12, 28), expense_category_id: category.id, project_id: project.id }, user.id) harvest.reports.expenses_by_project(project, Time.utc(2009, 12, 20), Time.utc(2009,12,30)).first.should == expense harvest.reports.expenses_by_user(user, Time.utc(2009, 12, 20), Time.utc(2009,12,30)).first.should == expense sleep 10 harvest.reports.expenses_by_user(user, Time.utc(2009, 12, 20), Time.utc(2009,12,30), {updated_since: Time.now.utc}).should == [] my_user = harvest.users.all.detect {|u| u.email == credentials["username"]} my_user.should_not be_nil harvest.reports.expenses_by_user(my_user, Time.utc(2009, 12, 20), Time.utc(2009,12,30)).should == [] my_project = harvest.projects.create(name: "Travel Expense Project", client_id: client.id) harvest.reports.expenses_by_project(my_project, Time.utc(2009, 12, 20), Time.utc(2009,12,30)).should == [] end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/functional/tasks_spec.rb
spec/functional/tasks_spec.rb
require 'spec_helper' describe 'harvest tasks' do it 'allows adding, updating and removing tasks' do cassette('tasks') do task = harvest.tasks.create( "name" => "A crud task", "billable_by_default" => true, "default_hourly_rate" => 120 ) task.default_hourly_rate.should == 120.0 task.default_hourly_rate = 140 task = harvest.tasks.update(task) task.default_hourly_rate.should == 140.0 harvest.tasks.delete(task) harvest.tasks.all.select {|t| t.name == "A crud task"}.should == [] end end context "task assignments" do it "allows adding, updating, and removing tasks from projects" do cassette('tasks2') do client = harvest.clients.create(FactoryGirl.attributes_for(:client)) project = harvest.projects.create( "name" => "Test Project2", "active" => true, "notes" => "project to test the api", "client_id" => client.id ) task1 = harvest.tasks.create( "name" => "A task for joe", "billable_by_default" => true, "default_hourly_rate" => 120 ) # need to keep at least one task on the project task2 = harvest.tasks.create( "name" => "A task for joe2", "billable_by_default" => true, "default_hourly_rate" => 100 ) harvest.task_assignments.create("project" => project, "task" => task1) harvest.task_assignments.create("project" => project, "task" => task2) all_assignments = harvest.task_assignments.all(project) assignment1 = all_assignments.detect {|a| a.task_id == task1.id } assignment2 = all_assignments.detect {|a| a.task_id == task2.id } assignment1.hourly_rate = 100 assignment1 = harvest.task_assignments.update(assignment1) assignment1.hourly_rate.should == 100.0 harvest.task_assignments.delete(assignment1) all_assignments = harvest.task_assignments.all(project) all_assignments.size.should == 1 end end it "allows creating and assigning the task at the same time" do cassette('tasks3') do client = harvest.clients.create(FactoryGirl.attributes_for(:client)) project = harvest.projects.create( "name" => "Test Project3", "active" => true, "notes" => "project to test the api", "client_id" => client.id ) project2 = harvest.projects.create_task(project, "A simple task") project2.should == project harvest.task_assignments.all(project).size.should == 1 end end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/functional/users_spec.rb
spec/functional/users_spec.rb
require 'spec_helper' describe 'harvest users' do it "allows adding, updating, and removing users" do cassette("users") do user = harvest.users.create( "first_name" => "Edgar", "last_name" => "Ruth", "email" => "edgar@ruth.com", "timezone" => "cst", "is_admin" => "false", "telephone" => "444-4444" ) user.id.should_not be_nil user.first_name = "Joey" user = harvest.users.update(user) user.first_name.should == "Joey" id = harvest.users.delete(user) harvest.users.all.map(&:id).should_not include(id) end end it "allows activating and deactivating users" do cassette("users2") do user = harvest.users.create( "first_name" => "John", "last_name" => "Ruth", "email" => "john@ruth.com", "timezone" => "cst", "is_admin" => "false", "telephone" => "444-4444" ) user.should be_active user = harvest.users.deactivate(user) user.should_not be_active user = harvest.users.activate(user) user.should be_active harvest.users.delete(user) end end context "assignments" do it "allows adding, updating, and removing users from projects" do cassette('users4') do client = harvest.clients.create( "name" => "Joe's Steam Cleaning w/Users", "details" => "Building API Widgets across the country" ) project = harvest.projects.create( "name" => "Test Project w/User", "active" => true, "notes" => "project to test the api", "client_id" => client.id ) user = harvest.users.create( "first_name" => "Sally", "last_name" => "Ruth", "email" => "sally@ruth.com", "password" => "mypassword", "timezone" => "cst", "is_admin" => "false", "telephone" => "444-4444" ) assignment = harvest.user_assignments.create("project" => project, "user" => user) assignment.hourly_rate = 100 assignment = harvest.user_assignments.update(assignment) assignment.hourly_rate.should == 100.0 harvest.user_assignments.delete(assignment) all_assignments = harvest.user_assignments.all(project) all_assignments.size.should == 1 end end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/functional/hardy_client_spec.rb
spec/functional/hardy_client_spec.rb
require 'spec_helper' describe 'harvest hardy client' do before do WebMock.disable_net_connect! @time = Time.now end it "waits the alloted time out when over rate limit" do stub_request(:get, /\/clients/).to_return({:status => ['503', 'Rate Limited'], :headers => {"Retry-After" => "5"}}, {:body => "[]", :status => 200}) hardy_harvest.clients.all Time.now.should be_within(10).of(@time) end it "waits a default time when over the rate limit" do stub_request(:get, /\/clients/).to_return({:status => ['503', 'Rate Limited']}, {:body => "[]", :status => 200}) hardy_harvest.clients.all Time.now.should be_within(20).of(@time) end it "retries after known errors" do stub_request(:get, /\/rate_limit_status/).to_return({:body => '{"lockout_seconds":2,"last_access_at":"2011-06-18T17:13:22+00:00","max_calls":100,"count":1,"timeframe_limit":15}'}) stub_request(:get, /\/clients/).to_return({:status => ['502', 'Bad Gateway']}).times(2).then.to_return({:body => "[]", :status => 200}) hardy_harvest.clients.all.should == [] stub_request(:get, /\/clients/).to_raise(Net::HTTPError.new("custom error", "")).times(2).then.to_return({:body => "[]", :status => 200}) hardy_harvest.clients.all.should == [] stub_request(:get, /\/clients/).to_return({:status => ['502', 'Bad Gateway']}).times(6).then.to_return({:body => "[]", :status => 200}) expect { hardy_harvest.clients.all }.to raise_error(Harvest::Unavailable) end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/functional/invoice_payments_spec.rb
spec/functional/invoice_payments_spec.rb
require 'spec_helper' describe 'harvest invoice payments' do it 'allows retrieving existing invoice payments' do cassette('invoice_payment1') do client = harvest.clients.create(FactoryGirl.attributes_for(:client)) invoice = harvest.invoices.create(FactoryGirl.attributes_for(:invoice, :client_id => client.id)) payment = Harvest::InvoicePayment.new(FactoryGirl.attributes_for(:invoice_payment, :invoice_id => invoice.id, :amount => invoice.amount)) payment_saved = harvest.invoice_payments.create(payment) payment_found = harvest.invoice_payments.find(invoice, payment_saved) payment_found.should == payment_saved end end it 'allows adding, and removing invoice payments' do cassette('invoice_payment2') do client = harvest.clients.create(FactoryGirl.attributes_for(:client)) invoice = harvest.invoices.create(FactoryGirl.attributes_for(:invoice, :client_id => client.id, update_line_items: true)) half_amount = (invoice.amount.to_f / 2) payment1 = Harvest::InvoicePayment.new(FactoryGirl.attributes_for(:invoice_payment, :invoice_id => invoice.id, :amount => half_amount)) payment1 = harvest.invoice_payments.create(payment1) invoice = harvest.invoices.find(invoice.id) invoice.state.should == 'draft' payment2 = Harvest::InvoicePayment.new(FactoryGirl.attributes_for(:invoice_payment, :invoice_id => invoice.id, :amount => half_amount)) payment2 = harvest.invoice_payments.create(payment2) invoice = harvest.invoices.find(invoice.id) invoice.state.should == 'paid' harvest.invoice_payments.all(invoice).each { |ip| harvest.invoice_payments.delete(ip) } harvest.invoice_payments.all(invoice).should be_empty invoice = harvest.invoices.find(invoice.id) invoice.state.should == 'draft' end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/functional/time_tracking_spec.rb
spec/functional/time_tracking_spec.rb
require 'spec_helper' describe 'harvest time tracking' do it 'allows adding, updating and removing entries' do cassette("time_tracking1") do client = harvest.clients.create("name" => "Jane's Car Shop") project = harvest.projects.create("name" => "Tracking Project", "client_id" => client.id) harvest.projects.create_task(project, "A billable task") task = harvest.tasks.all.detect {|t| t.name == "A billable task"} entry = harvest.time.create("notes" => "Test api support", "hours" => 3, "spent_at" => "2009/12/28", "task_id" => task.id, "project_id" => project.id) entry.notes.should == "Test api support" entry.notes = "Upgraded to JSON" entry = harvest.time.update(entry) entry.notes.should == "Upgraded to JSON" harvest.time.delete(entry) harvest.time.all(Time.utc(2009, 12, 28)).should == [] end end it 'allows you to save entries for a different user' do cassette("time_tracking2") do user = harvest.users.create( "email" => "frank@example.com", "first_name" => "Frank", "last_name" => "Doe", "password" => "secure" ) client = harvest.clients.create("name" => "Kim's Tux Shop") project = harvest.projects.create("name" => "Other User Tracking Project", "client_id" => client.id) harvest.user_assignments.create("project" => project, "user" => user) harvest.projects.create_task(project, "A billable task for tuxes") task = harvest.tasks.all.detect {|t| t.name == "A billable task for tuxes"} entry = harvest.time.create("notes" => "Test api support", "hours" => 3, "spent_at" => "2009/12/28", "task_id" => task.id, "project_id" => project.id, "of_user" => user.id) harvest.time.all(Time.utc(2009, 12, 28), user).should == [entry] entry.notes = "Updating notes" entry = harvest.time.update(entry, user) entry.notes.should == "Updating notes" entry = harvest.time.find(entry, user) entry.notes.should == "Updating notes" harvest.time.delete(entry, user) harvest.time.all(Time.utc(2009, 12, 28), user).should == [] end end it 'allows toggling of timers' do cassette("time_tracking3") do client = harvest.clients.create("name" => "Jane's Used Car Shop") project = harvest.projects.create("name" => "Tracking Project", "client_id" => client.id) harvest.projects.create_task(project, "A billable task") task = harvest.tasks.all.detect {|t| t.name == "A billable task"} entry = harvest.time.create("notes" => "Test api support", "hours" => 3, "spent_at" => "2009/12/28", "task_id" => task.id, "project_id" => project.id) # start existing timer started_entry = harvest.time.toggle(entry.id) started_entry.timer_started_at.should_not be_nil # stop started timer stopped_entry = harvest.time.toggle(started_entry.id) stopped_entry.timer_started_at.should be_nil end end it 'allows retrieving trackable projects and tasks' do cassette("time_tracking4") do client = harvest.clients.create("name" => "Bobby's Coffee Shop") project = harvest.projects.create("name" => "Bobby's Trackable Project", "client_id" => client.id) harvest.projects.create_task(project, "A billable task for Bobby") trackable_projects = harvest.time.trackable_projects trackable_project = trackable_projects.find {|p| p.name == "Bobby's Trackable Project" } trackable_projects.first.client.should == "Bobby's Coffee Shop" trackable_projects.first.tasks.first.name.should == "A billable task for Bobby" end end it 'allows for absence of trackable projects' do cassette("time_tracking5") do user = harvest.users.create( "email" => "gary@example.com", "first_name" => "Gary", "last_name" => "Doe", "password" => "secure" ) trackable_projects = harvest.time.trackable_projects(Time.now, user) trackable_projects.should == [] end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/functional/account_spec.rb
spec/functional/account_spec.rb
require 'spec_helper' describe 'account information' do it 'returns the rate limit when requested' do cassette('account1') do status = harvest.account.rate_limit_status status.max_calls.should == 100 end end it 'returns the result of whoami' do cassette('account2') do user = harvest.account.who_am_i user.email.should == credentials["username"] end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/functional/invoice_spec.rb
spec/functional/invoice_spec.rb
require 'spec_helper' describe 'harvest invoices' do it 'allows adding, updating and removing categories' do cassette('invoice1') do cat = harvest.invoice_categories.create("name" => "New Category") cat.name.should == "New Category" cat.name = "Updated Category" cat = harvest.invoice_categories.update(cat) cat.name.should == "Updated Category" harvest.invoice_categories.delete(cat) harvest.invoice_categories.all.select {|c| c.name == "Updated Category" }.should == [] end end it 'allows adding, updating and removing invoices' do cassette('invoice2') do client = harvest.clients.create(FactoryGirl.attributes_for(:client)) invoice = Harvest::Invoice.new(FactoryGirl.attributes_for(:invoice, :client_id => client.id, update_line_items: true)) invoice = harvest.invoices.create(invoice) invoice.subject.should == "Invoice for Joe's Stream Cleaning" invoice.amount.should == 2400.0 invoice.line_items.size.should == 1 invoice.subject = "Updated Invoice for Joe" invoice.line_items << FactoryGirl.build(:line_item) invoice.update_line_items = true invoice = harvest.invoices.update(invoice) invoice.subject.should == "Updated Invoice for Joe" invoice.amount.should == 4800.0 invoice.line_items.size.should == 2 harvest.invoices.delete(invoice) harvest.invoices.all.select {|p| p.number == "1000"}.should == [] end end it 'allows finding one invoice or all invoices with parameters' do cassette('invoice3') do client = harvest.clients.create(FactoryGirl.attributes_for(:client)) project_attributes = FactoryGirl.attributes_for(:project) project_attributes[:client_id] = client.id project = harvest.projects.create(project_attributes) project.name.should == project_attributes[:name] # Delete any existing invoices. harvest.invoices.all.each {|i| harvest.invoices.delete(i.id)} invoice = Harvest::Invoice.new( "subject" => "Invoice for Frannie's Widgets", "client_id" => client.id, "issued_at" => "2014-01-01", "due_at_human_format" => "NET 10", "currency" => "United States Dollars - USD", "number" => 1000, "notes" => "Some notes go here", "period_end" => "2013-03-31", "period_start" => "2013-02-26", "kind" => "free_form", "state" => "draft", "purchase_order" => nil, "tax" => nil, "tax2" => nil, "kind" => "free_form", "import_hours" => "no", "import_expenses" => "no", "line_items" => [Harvest::LineItem.new("kind" => "Service", "description" => "One item", "quantity" => 200, "unit_price" => "12.00")], "update_line_items" => true ) invoice = harvest.invoices.create(invoice) invoice.subject.should == "Invoice for Frannie's Widgets" invoice.amount.should == 2400.0 invoice.line_items.size.should == 1 invoice = harvest.invoices.find(invoice.id) invoice.subject.should == "Invoice for Frannie's Widgets" invoice.amount.should == 2400.0 invoice.line_items.size.should == 1 invoice.due_at.should == "2014-01-11" invoices = harvest.invoices.all invoices.count.should == 1 invoices = harvest.invoices.all(:status => 'draft') invoices.count.should == 1 invoices = harvest.invoices.all(:status => 'closed') invoices.count.should == 0 invoices = harvest.invoices.all(:status => 'draft', :page => 1) invoices.count.should == 1 invoices = harvest.invoices.all(:timeframe => {:from => '2014-01-01', :to => '2014-01-01'}) invoices.count.should == 1 invoices = harvest.invoices.all(:timeframe => {:from => '19690101', :to => '19690101'}) invoices.count.should == 0 invoices = harvest.invoices.all(:updated_since => Date.today) invoices.count.should == 1 invoices = harvest.invoices.all(:updated_since => '2112-12-31') invoices.count.should == 0 harvest.invoices.delete(invoice) harvest.invoices.all.select {|p| p.number == "1000"}.should == [] end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/spec/functional/errors_spec.rb
spec/functional/errors_spec.rb
require 'spec_helper' describe 'harvest errors' do before { WebMock.disable_net_connect! } it "wraps errors" do stub_request(:get, /\/clients/).to_return({:status => ['400', 'Bad Request']}, {:body => "[]", :status => 200}) expect { harvest.clients.all }.to raise_error(Harvest::BadRequest) stub_request(:get, /\/clients/).to_return({:status => ['404', 'Not Found']}, {:body => "[]", :status => 200}) expect { harvest.clients.all }.to raise_error(Harvest::NotFound) stub_request(:get, /\/clients/).to_return({:status => ['500', 'Server Error']}, {:body => "[]", :status => 200}) expect { harvest.clients.all }.to raise_error(Harvest::ServerError) stub_request(:get, /\/clients/).to_return({:status => ['502', 'Bad Gateway']}, {:body => "[]", :status => 200}) expect { harvest.clients.all }.to raise_error(Harvest::Unavailable) stub_request(:get, /\/clients/).to_return({:status => ['503', 'Rate Limited']}, {:body => "[]", :status => 200}) expect { harvest.clients.all }.to raise_error(Harvest::RateLimited) end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/examples/project_create_script.rb
examples/project_create_script.rb
# File: project_create_script.rb # Date Created: 2012-10-08 # Author(s): Mark Rickert (mjar81@gmail.com) / Skookum Digital Works - http://skookum.com # # Description: This example script takes user input from the command line and # creates a project based the selected options. It then assigns tasks from Harvest # to the project based on an array. After the tasks are added, it addes all the # currently active users to the project. require "harvested" subdomain = 'yoursubdomain' username = 'yourusername' password = 'yourpassword' harvest = Harvest.hardy_client(subdomain: subdomain, username: username, password: password) puts "\nPlease search for a client by typing part of their name:" cname = gets.chomp # Filter out all the clients that don't match the typed string client_search_results = harvest.clients.all.select { |c| c.name.downcase.include?(cname) } case client_search_results.length when 0 puts "No client found. Please try again.\n" abort when 1 # Result is exactly 1. We got the client. client_index = 0 when 1..15 # Have the user select from a list of clients. puts "Please select from the following results:\n" client_search_results.each_with_index do |c, i| puts " #{i+1}. #{c.name}" end client_index = gets.chomp.to_i - 1 else puts "Too many client matches. Please try a more specific search term.\n" abort end client = client_search_results[client_index] puts "\nClient found: #{client.name}\n" puts "Please enter the project name:" project_name = gets.chomp puts "\nIs this project billable? (y/n)" billable = gets.chomp.downcase == "y" puts "\nAny project notes? (hit 'return' for none)" notes = gets.chomp puts "\nWhat sorts of tasks does this project need? Type \"p\" for project tasks or \"s\" for sales tasks.\n" task_types = gets.chomp # Determine what task list to use based on the project type. if task_types.downcase == "p" # These are names of tasks that should already exist in Harvest use_tasks = ["Client Communication", "Planning", "Design", "Development", "Testing/QA", "Documentation", "Deployment"] else use_tasks = ["Sales Calls", "Client Meetings", "Travel", "Estimating"] end # Filter the list of actual tasks we want to add to the project. tasks = harvest.tasks.all.select { |t| use_tasks.include?(t.name) } # Create the project puts "Creating new project: \"#{project_name}\" for client: #{client.name}\n" project = Harvest::Project.new(name: project_name, client_id: client.id, billable: billable, notes: notes) project = harvest.projects.create(project) # Add all the project tasks to the project tasks.each do |t| puts " Adding Task: #{t.name}" task_assignment = Harvest::TaskAssignment.new(task_id: t.id, project_id: project.id) task_assignment = harvest.task_assignments.create(task_assignment) end puts # Add every active user to the project. harvest.users.all.each do |u| next unless u.is_active? puts " Adding User: #{u.first_name} #{u.last_name}" user_assignment = Harvest::UserAssignment.new(user_id: u.id, project_id: project.id) harvest.user_assignments.create(user_assignment) end puts "\nProject successfully created." puts "You can find the project here: http://#{subdomain}.harvestapp.com/projects/#{project.id}/edit\n\n"
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/examples/clear_account.rb
examples/clear_account.rb
# This is commented out because it can be very dangerous if run against a production account # require "harvested" # # subdomain = 'yoursubdomain' # username = 'yourusername' # password = 'yourpassword' # # api = Harvest.hardy_client(subdomain: subdomain, username: username, password: password) # # raise "Are you sure you want to do this? (comment out this exception if so)" # # api.users.all.each do |u| # api.users.delete(u) if u.email != username # end # my_user = api.users.all.first # # api.reports.time_by_user(my_user, Time.parse('01/01/2000'), Time.now).each do |time| # api.time.delete(time) # end # # api.reports.expenses_by_user(my_user, Time.parse('01/01/2000'), Time.now).each do |time| # api.expenses.delete(time) # end # # %w(expenses expense_categories projects contacts clients tasks).each do |collection| # api.send(collection).all.each {|m| api.send(collection).delete(m) } # end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/examples/basics.rb
examples/basics.rb
require "harvested" subdomain = 'yoursubdomain' username = 'yourusername' password = 'yourpassword' harvest = Harvest.hardy_client(subdomain: subdomain, username: username, password: password) # Print out all users, clients, and projects on the account puts "Users:" harvest.users.all.each {|u| p u } puts "Clients:" harvest.clients.all.each {|c| p c } puts "Projects:" harvest.projects.all.each {|project| p project } # Create a Client add a Project to that Client, Add a Task to the Project, track some Time against the Project/Task, and then Run a report against all time I've submitted client = Harvest::Client.new(name: 'SuprCorp') client = harvest.clients.create(client) project = Harvest::Project.new(name: 'SuprGlu', client_id: client.id, notes: 'Some notes about this project') project = harvest.projects.create(project) harvest.projects.create_task(project, 'Bottling Glue') task_assignment = harvest.task_assignments.all(project).first time_entry = Harvest::TimeEntry.new(notes: 'Bottled glue today', hours: 8, spent_at: "04/11/2010", project_id: project.id, task_id: task_assignment.task_id) time_entry = harvest.time.create(time_entry) entries = harvest.reports.time_by_project(project, Time.parse("04/11/2010"), Time.parse("04/12/2010")) puts "Entries:" entries.each {|e| p e}
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/examples/user_assignments.rb
examples/user_assignments.rb
require "harvested" subdomain = 'yoursubdomain' username = 'userusername' password = 'yourpassword' harvest = Harvest.hardy_client(subdomain: subdomain, username: username, password: password) # Create a Client, Project, and a User then assign that User to that Project client = Harvest::Client.new(name: 'SuprCorp') client = harvest.clients.create(client) project = Harvest::Project.new(name: 'SuprGlu', client_id: client.id, notes: 'Some notes about this project') project = harvest.projects.create(project) harvest.projects.create_task(project, 'Bottling Glue') user = Harvest::User.new(first_name: 'Jane', last_name: 'Doe', email: 'jane@doe.com', timezone: :est, password: 'secure') user = harvest.users.create(user) user_assignment = Harvest::UserAssignment.new(user_id: user.id, project_id: project.id) harvest.user_assignments.create(user_assignment) puts 'Assigned Jane Doe to the project "SuprGlu"'
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/examples/task_assignments.rb
examples/task_assignments.rb
require "harvested" subdomain = 'yoursubdomain' username = 'yourusername' password = 'yourpassword' harvest = Harvest.hardy_client(subdomain: subdomain, username: username, password: password) # Create a Client add a Project to that Client client = Harvest::Client.new(name: 'SuprCorp') client = harvest.clients.create(client) project = Harvest::Project.new(name: 'SuprGlu', client_id: client.id, notes: 'Some notes about this project') project = harvest.projects.create(project) # You can create an assign a task in one call harvest.projects.create_task(project, 'Bottling Glue') puts "Assigned the task 'Bottling Glue' to the project 'SuprGlu'" # You can explicitly create the task and then assign it task = Harvest::Task.new(name: 'Packaging Glue', hourly_rate: 30, billable: true) task = harvest.tasks.create(task) task_assignment = Harvest::TaskAssignment.new(task_id: task.id, project_id: project.id) task_assignment = harvest.task_assignments.create(task_assignment) puts "Assigned the task 'Packaging Glue' to the project 'SuprGlu'"
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvested.rb
lib/harvested.rb
require 'httparty' require 'base64' require 'delegate' require 'hashie' require 'json' require 'time' require 'csv' require 'ext/array' require 'ext/hash' require 'ext/date' require 'ext/time' require 'harvest/version' require 'harvest/credentials' require 'harvest/errors' require 'harvest/hardy_client' require 'harvest/timezones' require 'harvest/base' %w(crud activatable).each {|a| require "harvest/behavior/#{a}"} %w(model client contact project task user rate_limit_status task_assignment user_assignment expense_category expense time_entry invoice_category line_item invoice invoice_payment invoice_message trackable_project).each {|a| require "harvest/#{a}"} %w(base account clients contacts projects tasks users task_assignments user_assignments expense_categories expenses time reports invoice_categories invoices invoice_payments invoice_messages).each {|a| require "harvest/api/#{a}"} module Harvest class << self # Creates a standard client that will raise all errors it encounters # # == Options # * Basic Authentication # * +:subdomain+ - Your Harvest subdomain # * +:username+ - Your Harvest username # * +:password+ - Your Harvest password # * OAuth # * +:access_token+ - An OAuth 2.0 access token # # == Examples # Harvest.client(subdomain: 'mysubdomain', username: 'myusername', password: 'mypassword') # Harvest.client(access_token: 'myaccesstoken') # # @return [Harvest::Base] def client(subdomain: nil, username: nil, password: nil, access_token: nil) Harvest::Base.new(subdomain: subdomain, username: username, password: password, access_token: access_token) end # Creates a hardy client that will retry common HTTP errors it encounters and sleep() if it determines it is over your rate limit # # == Options # * Basic Authentication # * +:subdomain+ - Your Harvest subdomain # * +:username+ - Your Harvest username # * +:password+ - Your Harvest password # * OAuth # * +:access_token+ - An OAuth 2.0 access token # # * +:retry+ - How many times the hardy client should retry errors. Set to +5+ by default. # # == Examples # Harvest.hardy_client(subdomain: 'mysubdomain', username: 'myusername', password: 'mypassword', retry: 3) # # Harvest.hardy_client(access_token: 'myaccesstoken', retries: 3) # # == Errors # The hardy client will retry the following errors # * Harvest::Unavailable # * Harvest::InformHarvest # * Net::HTTPError # * Net::HTTPFatalError # * Errno::ECONNRESET # # == Rate Limits # The hardy client will make as many requests as it can until it detects it has gone over the rate limit. Then it will +sleep()+ for the how ever long it takes for the limit to reset. You can find more information about the Rate Limiting at http://www.getharvest.com/api # # @return [Harvest::HardyClient] a Harvest::Base wrapped in a Harvest::HardyClient # @see Harvest::Base def hardy_client(subdomain: nil, username: nil, password: nil, access_token: nil, retries: 5) Harvest::HardyClient.new(client(subdomain: subdomain, username: username, password: password, access_token: access_token), retries) end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/expense_category.rb
lib/harvest/expense_category.rb
module Harvest class ExpenseCategory < Hashie::Mash include Harvest::Model api_path '/expense_categories' def active? !deactivated end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/task.rb
lib/harvest/task.rb
module Harvest # The model that contains information about a task # # == Fields # [+id+] (READONLY) the id of the task # [+name+] (REQUIRED) the name of the task # [+billable+] whether the task is billable by default # [+deactivated+] whether the task is deactivated # [+hourly_rate+] what the default hourly rate for the task is # [+default?+] whether to add this task to new projects by default class Task < Hashie::Mash include Harvest::Model api_path '/tasks' delegate_methods :default? => :is_default def active? !deactivated end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/task_assignment.rb
lib/harvest/task_assignment.rb
module Harvest class TaskAssignment < Hashie::Mash include Harvest::Model def initialize(args = {}, _ = nil) args = args.to_hash.stringify_keys self.task = args.delete("task") if args["task"] self.project = args.delete("project") if args["project"] super end def task=(task) self["task_id"] = task.to_i end def project=(project) self["project_id"] = project.to_i end def active? !deactivated end def task_as_json {"task" => {"id" => task_id}} end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/version.rb
lib/harvest/version.rb
module Harvest VERSION = "4.0.0" end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/project.rb
lib/harvest/project.rb
module Harvest # The model that contains information about a project # # == Fields # [+id+] (READONLY) the id of the project # [+name+] (REQUIRED) the name of the project # [+client_id+] (REQUIRED) the client id of the project # [+code+] the project code # [+notes+] the project notes # [+active?+] true|false whether the project is active # [+billable?+] true|false where the project is billable # [+budget_by+] how the budget is calculated for the project +project|project_cost|task|person|nil+ # [+budget+] what the budget is for the project (based on budget_by) # [+bill_by+] how to bill the project +Tasks|People|Project|nil+ # [+hourly_rate+] what the hourly rate for the project is based on +bill_by+ # [+notify_when_over_budget?+] whether the project will send notifications when it goes over budget # [+over_budget_notification_percentage+] what percentage of the budget the project has to be before it sends a notification. Based on +notify_when_over_budget?+ # [+show_budget_to_all?+] whether the project's budget is shown to employees and contractors # [+basecamp_id+] (READONLY) the id of the basecamp project associated to the project # [+highrise_deal_id+] (READONLY) the id of the highrise deal associated to the project # [+active_task_assignments_count+] (READONLY) the number of active task assignments # [+created_at+] (READONLY) when the project was created # [+updated_at+] (READONLY) when the project was updated class Project < Hashie::Mash include Harvest::Model api_path '/projects' def as_json(args = {}) super(args).tap do |json| json[json_root].delete("hint_earliest_record_at") json[json_root].delete("hint_latest_record_at") end end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/errors.rb
lib/harvest/errors.rb
module Harvest class HTTPError < StandardError attr_reader :response attr_reader :params attr_reader :hint def initialize(response, params = {}, hint = nil) @response = response @params = params @hint = hint super(response) end def to_s "#{self.class.to_s} : #{response.code} #{response.body}" + (hint ? "\n#{hint}" : "") end end class RateLimited < HTTPError; end class NotFound < HTTPError; end class Unavailable < HTTPError; end class InformHarvest < HTTPError; end class BadRequest < HTTPError; end class ServerError < HTTPError; end class AuthenticationFailed < HTTPError ; end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/user_assignment.rb
lib/harvest/user_assignment.rb
module Harvest class UserAssignment < Hashie::Mash include Harvest::Model delegate_methods :project_manager? => :is_project_manager def initialize(args = {}, _ = nil) args = args.to_hash.stringify_keys self.user = args.delete("user") if args["user"] self.project = args.delete("project") if args["project"] super end def user=(user) self["user_id"] = user.to_i end def project=(project) self["project_id"] = project.to_i end def active? !deactivated end def user_as_json {"user" => {"id" => user_id}} end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/timezones.rb
lib/harvest/timezones.rb
module Harvest # shamelessly ripped from Rails: http://github.com/rails/rails/blob/master/activesupport/lib/active_support/values/time_zone.rb module Timezones MAPPING = { "pacific/midway" => "Midway Island", "pacific/pago_pago" => "Samoa", "pacific/honolulu" => "Hawaii", "america/juneau" => "Alaska", "america/los_angeles" => "Pacific Time (US & Canada)", "america/tijuana" => "Tijuana", "america/denver" => "Mountain Time (US & Canada)", "america/phoenix" => "Arizona", "america/chihuahua" => "Chihuahua", "america/mazatlan" => "Mazatlan", "america/chicago" => "Central Time (US & Canada)", "america/regina" => "Saskatchewan", "america/mexico_city" => "Mexico City", "america/monterrey" => "Monterrey", "america/guatemala" => "Central America", "america/new_york" => "Eastern Time (US & Canada)", "america/indiana/indianapolis" => "Indiana (East)", "america/bogota" => "Bogota", "america/lima" => "Lima", "america/halifax" => "Atlantic Time (Canada)", "america/caracas" => "Caracas", "america/la_paz" => "La Paz", "america/santiago" => "Santiago", "america/st_johns" => "Newfoundland", "america/sao_paulo" => "Brasilia", "america/argentina/buenos_aires" => "Buenos Aires", "america/argentina/san_juan" => "Georgetown", "america/godthab" => "Greenland", "atlantic/south_georgia" => "Mid-Atlantic", "atlantic/azores" => "Azores", "atlantic/cape_verde" => "Cape Verde Is.", "europe/dublin" => "Dublin", "europe/lisbon" => "Lisbon", "europe/london" => "London", "africa/casablanca" => "Casablanca", "africa/monrovia" => "Monrovia", "etc/utc" => "UTC", "europe/belgrade" => "Belgrade", "europe/bratislava" => "Bratislava", "europe/budapest" => "Budapest", "europe/ljubljana" => "Ljubljana", "europe/prague" => "Prague", "europe/sarajevo" => "Sarajevo", "europe/skopje" => "Skopje", "europe/warsaw" => "Warsaw", "europe/zagreb" => "Zagreb", "europe/brussels" => "Brussels", "europe/copenhagen" => "Copenhagen", "europe/madrid" => "Madrid", "europe/paris" => "Paris", "europe/amsterdam" => "Amsterdam", "europe/berlin" => "Berlin", "europe/rome" => "Rome", "europe/stockholm" => "Stockholm", "europe/vienna" => "Vienna", "africa/algiers" => "West Central Africa", "europe/bucharest" => "Bucharest", "africa/cairo" => "Cairo", "europe/helsinki" => "Helsinki", "europe/kiev" => "Kyev", "europe/riga" => "Riga", "europe/sofia" => "Sofia", "europe/tallinn" => "Tallinn", "europe/vilnius" => "Vilnius", "europe/athens" => "Athens", "europe/istanbul" => "Istanbul", "europe/minsk" => "Minsk", "asia/jerusalem" => "Jerusalem", "africa/harare" => "Harare", "africa/johannesburg" => "Pretoria", "europe/moscow" => "Moscow", "asia/kuwait" => "Kuwait", "asia/riyadh" => "Riyadh", "africa/nairobi" => "Nairobi", "asia/baghdad" => "Baghdad", "asia/tehran" => "Tehran", "asia/muscat" => "Muscat", "asia/baku" => "Baku", "asia/tbilisi" => "Tbilisi", "asia/yerevan" => "Yerevan", "asia/kabul" => "Kabul", "asia/yekaterinburg" => "Ekaterinburg", "asia/karachi" => "Karachi", "asia/tashkent" => "Tashkent", "asia/kolkata" => "Kolkata", "asia/katmandu" => "Kathmandu", "asia/dhaka" => "Dhaka", "asia/colombo" => "Sri Jayawardenepura", "asia/almaty" => "Almaty", "asia/novosibirsk" => "Novosibirsk", "asia/rangoon" => "Rangoon", "asia/bangkok" => "Bangkok", "asia/jakarta" => "Jakarta", "asia/krasnoyarsk" => "Krasnoyarsk", "asia/shanghai" => "Beijing", "asia/chongqing" => "Chongqing", "asia/hong_kong" => "Hong Kong", "asia/urumqi" => "Urumqi", "asia/kuala_lumpur" => "Kuala Lumpur", "asia/singapore" => "Singapore", "asia/taipei" => "Taipei", "australia/perth" => "Perth", "asia/irkutsk" => "Irkutsk", "asia/ulaanbaatar" => "Ulaan Bataar", "asia/seoul" => "Seoul", "asia/tokyo" => "Tokyo", "asia/yakutsk" => "Yakutsk", "australia/darwin" => "Darwin", "australia/adelaide" => "Adelaide", "australia/melbourne" => "Melbourne", "australia/sydney" => "Sydney", "australia/brisbane" => "Brisbane", "australia/hobart" => "Hobart", "asia/vladivostok" => "Vladivostok", "pacific/guam" => "Guam", "pacific/port_moresby" => "Port Moresby", "asia/magadan" => "Magadan", "pacific/noumea" => "New Caledonia", "pacific/fiji" => "Fiji", "asia/kamchatka" => "Kamchatka", "pacific/majuro" => "Marshall Is.", "pacific/auckland" => "Auckland", "pacific/tongatapu" => "Nuku'alofa" } end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/line_item.rb
lib/harvest/line_item.rb
module Harvest class LineItem < Hashie::Mash end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/trackable_project.rb
lib/harvest/trackable_project.rb
module Harvest # The model for project-tasks combinations that can be added to the timesheet # # == Fields # [+id+] the id of the project # [+name+] the name of the project # [+client+] the name of the client of the project # [+client_id+] the client id of the project # [+tasks+] trackable tasks for the project class TrackableProject < Hashie::Mash include Harvest::Model skip_json_root true def initialize(args = {}, _ = nil) args = args.to_hash.stringify_keys self.tasks = args.delete("tasks") if args["tasks"] super end def tasks=(tasks) self["tasks"] = Task.parse(tasks) end # The model for trackable tasks # # == Fields # [+id+] the id of the task # [+name+] the name of the task # [+billable+] whether the task is billable by default class Task < Hashie::Mash include Harvest::Model skip_json_root true end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/base.rb
lib/harvest/base.rb
module Harvest class Base attr_reader :request, :credentials # @see Harvest.client # @see Harvest.hardy_client def initialize(subdomain: nil, username: nil, password: nil, access_token: nil) @credentials = if subdomain && username && password BasicAuthCredentials.new(subdomain: subdomain, username: username, password: password) elsif access_token OAuthCredentials.new(access_token) else fail 'You must provide either :subdomain, :username, and :password or an oauth :access_token' end end # All API actions surrounding accounts # # == Examples # harvest.account.rate_limit_status # Returns a Harvest::RateLimitStatus # # @return [Harvest::API::Account] def account @account ||= Harvest::API::Account.new(credentials) end # All API Actions surrounding Clients # # == Examples # harvest.clients.all() # Returns all clients in the system # # harvest.clients.find(100) # Returns the client with id = 100 # # client = Harvest::Client.new(:name => 'SuprCorp') # saved_client = harvest.clients.create(client) # returns a saved version of Harvest::Client # # client = harvest.clients.find(205) # client.name = 'SuprCorp LTD.' # updated_client = harvest.clients.update(client) # returns an updated version of Harvest::Client # # client = harvest.clients.find(205) # harvest.clients.delete(client) # returns 205 # # client = harvest.clients.find(301) # deactivated_client = harvest.clients.deactivate(client) # returns an updated deactivated client # activated_client = harvest.clients.activate(client) # returns an updated activated client # # @see Harvest::Behavior::Crud # @see Harvest::Behavior::Activatable # @return [Harvest::API::Clients] def clients @clients ||= Harvest::API::Clients.new(credentials) end # All API Actions surrounding Client Contacts # # == Examples # harvest.contacts.all() # Returns all contacts in the system # harvest.contacts.all(10) # Returns all contacts for the client id=10 in the system # # harvest.contacts.find(100) # Returns the contact with id = 100 # # contact = Harvest::Contact.new(:first_name => 'Jane', :last_name => 'Doe', :client_id => 10) # saved_contact = harvest.contacts.create(contact) # returns a saved version of Harvest::Contact # # contact = harvest.contacts.find(205) # contact.first_name = 'Jilly' # updated_contact = harvest.contacts.update(contact) # returns an updated version of Harvest::Contact # # contact = harvest.contacts.find(205) # harvest.contacts.delete(contact) # returns 205 # # @see Harvest::Behavior::Crud # @return [Harvest::API::Contacts] def contacts @contacts ||= Harvest::API::Contacts.new(credentials) end # All API Actions surrounding Projects # # == Examples # harvest.projects.all() # Returns all projects in the system # # harvest.projects.find(100) # Returns the project with id = 100 # # project = Harvest::Project.new(:name => 'SuprGlu' :client_id => 10) # saved_project = harvest.projects.create(project) # returns a saved version of Harvest::Project # # project = harvest.projects.find(205) # project.name = 'SuprSticky' # updated_project = harvest.projects.update(project) # returns an updated version of Harvest::Project # # project = harvest.project.find(205) # harvest.projects.delete(project) # returns 205 # # project = harvest.projects.find(301) # deactivated_project = harvest.projects.deactivate(project) # returns an updated deactivated project # activated_project = harvest.projects.activate(project) # returns an updated activated project # # project = harvest.projects.find(401) # harvest.projects.create_task(project, 'Bottling Glue') # creates and assigns a task to the project # # @see Harvest::Behavior::Crud # @see Harvest::Behavior::Activatable # @return [Harvest::API::Projects] def projects @projects ||= Harvest::API::Projects.new(credentials) end # All API Actions surrounding Tasks # # == Examples # harvest.tasks.all() # Returns all tasks in the system # # harvest.tasks.find(100) # Returns the task with id = 100 # # task = Harvest::Task.new(:name => 'Server Administration' :default => true) # saved_task = harvest.tasks.create(task) # returns a saved version of Harvest::Task # # task = harvest.tasks.find(205) # task.name = 'Server Administration' # updated_task = harvest.tasks.update(task) # returns an updated version of Harvest::Task # # task = harvest.task.find(205) # harvest.tasks.delete(task) # returns 205 # # @see Harvest::Behavior::Crud # @return [Harvest::API::Tasks] def tasks @tasks ||= Harvest::API::Tasks.new(credentials) end # All API Actions surrounding Users # # == Examples # harvest.users.all() # Returns all users in the system # # harvest.users.find(100) # Returns the user with id = 100 # # user = Harvest::User.new(:first_name => 'Edgar', :last_name => 'Ruth', :email => 'edgar@ruth.com', :password => 'mypassword', :timezone => :cst, :admin => false, :telephone => '444-4444') # saved_user = harvest.users.create(user) # returns a saved version of Harvest::User # # user = harvest.users.find(205) # user.email = 'edgar@ruth.com' # updated_user = harvest.users.update(user) # returns an updated version of Harvest::User # # user = harvest.users.find(205) # harvest.users.delete(user) # returns 205 # # user = harvest.users.find(301) # deactivated_user = harvest.users.deactivate(user) # returns an updated deactivated user # activated_user = harvest.users.activate(user) # returns an updated activated user # # user = harvest.users.find(401) # harvest.users.reset_password(user) # will trigger the reset password feature of harvest and shoot the user an email # # @see Harvest::Behavior::Crud # @see Harvest::Behavior::Activatable # @return [Harvest::API::Users] def users @users ||= Harvest::API::Users.new(credentials) end # All API Actions surrounding assigning tasks to projects # # == Examples # project = harvest.projects.find(101) # harvest.task_assignments.all(project) # returns all tasks assigned to the project (as Harvest::TaskAssignment) # # project = harvest.projects.find(201) # harvest.task_assignments.find(project, 5) # returns the task assignment with ID 5 that is assigned to the project # # project = harvest.projects.find(301) # task = harvest.tasks.find(100) # assignment = Harvest::TaskAssignment.new(:task_id => task.id, :project_id => project.id) # saved_assignment = harvest.task_assignments.create(assignment) # returns a saved version of the task assignment # # project = harvest.projects.find(401) # assignment = harvest.task_assignments.find(project, 15) # assignment.hourly_rate = 150 # updated_assignment = harvest.task_assignments.update(assignment) # returns an updated assignment # # project = harvest.projects.find(501) # assignment = harvest.task_assignments.find(project, 25) # harvest.task_assignments.delete(assignment) # returns 25 # # @return [Harvest::API::TaskAssignments] def task_assignments @task_assignments ||= Harvest::API::TaskAssignments.new(credentials) end # All API Actions surrounding assigning users to projects # # == Examples # project = harvest.projects.find(101) # harvest.user_assignments.all(project) # returns all users assigned to the project (as Harvest::UserAssignment) # # project = harvest.projects.find(201) # harvest.user_assignments.find(project, 5) # returns the user assignment with ID 5 that is assigned to the project # # project = harvest.projects.find(301) # user = harvest.users.find(100) # assignment = Harvest::UserAssignment.new(:user_id => user.id, :project_id => project.id) # saved_assignment = harvest.user_assignments.create(assignment) # returns a saved version of the user assignment # # project = harvest.projects.find(401) # assignment = harvest.user_assignments.find(project, 15) # assignment.project_manager = true # updated_assignment = harvest.user_assignments.update(assignment) # returns an updated assignment # # project = harvest.projects.find(501) # assignment = harvest.user_assignments.find(project, 25) # harvest.user_assignments.delete(assignment) # returns 25 # # @return [Harvest::API::UserAssignments] def user_assignments @user_assignments ||= Harvest::API::UserAssignments.new(credentials) end # All API Actions surrounding managing expense categories # # == Examples # harvest.expense_categories.all() # Returns all expense categories in the system # # harvest.expense_categories.find(100) # Returns the expense category with id = 100 # # category = Harvest::ExpenseCategory.new(:name => 'Mileage', :unit_price => 0.485) # saved_category = harvest.expense_categories.create(category) # returns a saved version of Harvest::ExpenseCategory # # category = harvest.clients.find(205) # category.name = 'Travel' # updated_category = harvest.expense_categories.update(category) # returns an updated version of Harvest::ExpenseCategory # # category = harvest.expense_categories.find(205) # harvest.expense_categories.delete(category) # returns 205 # # @see Harvest::Behavior::Crud # @return [Harvest::API::ExpenseCategories] def expense_categories @expense_categories ||= Harvest::API::ExpenseCategories.new(credentials) end # All API Actions surrounding expenses # # == Examples # harvest.expenses.all() # Returns all expenses for the current week # harvest.expenses.all(Time.parse('11/12/2009')) # returns all expenses for the week of 11/12/2009 # # harvest.expenses.find(100) # Returns the expense with id = 100 def expenses @expenses ||= Harvest::API::Expenses.new(credentials) end def time @time ||= Harvest::API::Time.new(credentials) end def reports @reports ||= Harvest::API::Reports.new(credentials) end def invoice_categories @invoice_categories ||= Harvest::API::InvoiceCategories.new(credentials) end def invoices @invoices ||= Harvest::API::Invoices.new(credentials) end # All API Actions surrounding invoice payments # # == Examples # invoice = harvest.invoices.find(100) # harvest.invoice_payments.all(invoice) # returns all payments for the invoice (as Harvest::InvoicePayment) # # invoice = harvest.invoices.find(100) # harvest.invoice_payments.find(invoice, 5) # returns the payment with ID 5 that is assigned to the invoice # # invoice = harvest.invoices.find(100) # payment = Harvest::InvoicePayment.new(:invoice_id => invoice.id) # saved_payment = harvest.invoice_payments.create(payment) # returns a saved version of the payment # # invoice = harvest.invoices.find(100) # payment = harvest.invoice_payments.find(invoice, 5) # harvest.invoice_payments.delete(payment) # returns 5 # # @return [Harvest::API::InvoicePayments] def invoice_payments @invoice_payments ||= Harvest::API::InvoicePayments.new(credentials) end # All API Actions surrounding invoice messages # # == Examples # # invoice = harvest.invoices.find(100) # harvest.invoice_messages.all(invoice) # returns all messages for the invoice (as Harvest::InvoicePayment) # # invoice = harvest.invoices.find(100) # harvest.invoice_messages.find(invoice, 5) # returns the message with ID 5, assigned to the invoice # # invoice = harvest.invoices.find(100) # message = Harvest::InvoiceMessage.new(:invoice_id => invoice.id) # saved_message = harvest.invoice_messages.create(message) # returns a saved version of the message # # invoice = harvest.invoices.find(100) # message = harvest.invoice_messages.find(invoice, 5) # harvest.invoice_messages.delete(message) # returns 5 # # invoice = harvest.invoices.find(100) # message = Harvest::InvoiceMessage.new(:invoice_id => invoice.id) # harvest.invoice_messages.mark_as_sent(message) # # invoice = harvest.invoices.find(100) # message = Harvest::InvoiceMessage.new(:invoice_id => invoice.id) # harvest.invoice_messages.mark_as_closed(message) # # invoice = harvest.invoices.find(100) # message = Harvest::InvoiceMessage.new(:invoice_id => invoice.id) # harvest.invoice_messages.re_open(message) # # @return [Harvest::API::InvoiceMessages] def invoice_messages @invoice_messages ||= Harvest::API::InvoiceMessages.new(credentials) end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/invoice_category.rb
lib/harvest/invoice_category.rb
module Harvest class InvoiceCategory < Hashie::Mash include Harvest::Model api_path '/invoice_item_categories' def self.json_root; "invoice_item_category"; end class << self def parse(json) parsed = String === json ? JSON.parse(json) : json Array.wrap(parsed).map {|attrs| new(attrs["invoice_category"])} end end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/rate_limit_status.rb
lib/harvest/rate_limit_status.rb
module Harvest # The model that contains the information about the user's rate limit # # == Fields # [+last_access_at+] The last registered request # [+count+] The current number of requests registered # [+timeframe_limit+] The amount of seconds before a rate limit refresh occurs # [+max_calls+] The number of requests you can make within the +timeframe_limit+ # [+lockout_seconds+] If you exceed the rate limit, how long you will be locked out from Harvest class RateLimitStatus < Hashie::Mash include Harvest::Model skip_json_root true # Returns true if the user is over their rate limit # @return [Boolean] # @see http://www.getharvest.com/api def over_limit? count > max_calls end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/credentials.rb
lib/harvest/credentials.rb
module Harvest class BasicAuthCredentials def initialize(subdomain: nil, username: nil, password: nil) @subdomain, @username, @password = subdomain, username, password end def set_authentication(request_options) request_options[:headers] ||= {} request_options[:headers]["Authorization"] = "Basic #{basic_auth}" end def host "https://#{@subdomain}.harvestapp.com" end private def basic_auth Base64.encode64("#{@username}:#{@password}").delete("\r\n") end end class OAuthCredentials def initialize(access_token) @access_token = access_token end def set_authentication(request_options) request_options[:query] ||= {} request_options[:query]["access_token"] = @access_token end def host "https://api.harvestapp.com" end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/expense.rb
lib/harvest/expense.rb
module Harvest class Expense < Hashie::Mash include Harvest::Model api_path '/expenses' delegate_methods(:billed? => :is_billed, :closed? => :is_closed) def initialize(args = {}, _ = nil) args = args.to_hash.stringify_keys self.spent_at = args.delete("spent_at") if args["spent_at"] super end def spent_at=(date) self["spent_at"] = Date.parse(date.to_s) end def as_json(args = {}) super(args).to_hash.stringify_keys.tap do |hash| hash[json_root].update("spent_at" => (spent_at.nil? ? nil : spent_at.xmlschema)) hash[json_root].delete("has_receipt") hash[json_root].delete("receipt_url") end end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/invoice.rb
lib/harvest/invoice.rb
module Harvest # == Fields # [+due_at+] when the invoice is due # [+due_at_human_format+] when the invoice is due in human representation (e.g., due upon receipt) overrides +due_at+ # [+client_id+] (REQUIRED) the client id of the invoice # [+currency+] the invoice currency # [+issued_at+] when the invoice was issued # [+subject+] subject line for the invoice # [+notes+] notes on the invoice # [+number+] invoice number # [+kind+] (REQUIRED) the type of the invoice +free_form|project|task|people|detailed+ # [+projects_to_invoice+] comma separated project ids to gather data from # [+import_hours+] import hours from +project|task|people|detailed+ one of +yes|no+ # [+import_expenses+] import expenses from +project|task|people|detailed+ one of +yes|no+ # [+period_start+] start of the invoice period # [+period_end+] end of the invoice period # [+expense_period_start+] start of the invoice expense period # [+expense_period_end+] end of the invoice expense period # [+csv_line_items+] csv formatted line items for the invoice +kind,description,quantity,unit_price,amount,taxed,taxed2,project_id+ # [+created_at+] (READONLY) when the invoice was created # [+updated_at+] (READONLY) when the invoice was updated # [+id+] (READONLY) the id of the invoice # [+amount+] (READONLY) the amount of the invoice # [+due_amount+] (READONLY) the amount due on the invoice # [+created_by_id+] who created the invoice # [+purchase_order+] purchase order number/text # [+client_key+] unique client key # [+state+] (READONLY) state of the invoice # [+tax+] applied tax percentage # [+tax2+] applied tax 2 percentage # [+tax_amount+] amount to tax # [+tax_amount2+] amount to tax 2 # [+discount_amount+] discount amount to apply to invoice # [+discount_type+] discount type # [+recurring_invoice_id+] the id of the original invoice # [+estimate_id+] id of the related estimate # [+retainer_id+] id of the related retainer class Invoice < Hashie::Mash include Harvest::Model api_path '/invoices' attr_reader :line_items attr_accessor :update_line_items def self.parse(json) parsed = String === json ? JSON.parse(json) : json invoices = Array.wrap(parsed).map {|attrs| new(attrs["invoices"])} invoice = Array.wrap(parsed).map {|attrs| new(attrs["invoice"])} if invoices.first && invoices.first.length > 0 invoices else invoice end end def initialize(args = {}, _ = nil) if args args = args.to_hash.stringify_keys self.line_items = args.delete("csv_line_items") self.line_items = args.delete("line_items") self.line_items = [] if self.line_items.nil? self.update_line_items = args.delete("update_line_items") end super end def line_items=(raw_or_rich) unless raw_or_rich.nil? @line_items = case raw_or_rich when String @line_items = decode_csv(raw_or_rich).map {|row| Harvest::LineItem.new(row) } else raw_or_rich end end end def as_json(*options) json = super(*options) json[json_root]["csv_line_items"] = encode_csv(@line_items) if update_line_items json end private def decode_csv(string) csv = CSV.parse(string) headers = csv.shift csv.map! {|row| headers.zip(row) } csv.map {|row| row.inject({}) {|h, tuple| h.update(tuple[0] => tuple[1]) } } end def encode_csv(line_items) if line_items.empty? "" else header = %w(kind description quantity unit_price amount taxed taxed2 project_id) CSV.generate do |csv| csv << header line_items.each do |item| csv << header.inject([]) {|row, attr| row << item[attr] } end end end end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/invoice_message.rb
lib/harvest/invoice_message.rb
module Harvest class InvoiceMessage < Hashie::Mash include Harvest::Model api_path '/messages' def self.json_root; 'message'; end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/client.rb
lib/harvest/client.rb
module Harvest # The model that contains information about a client # # == Fields # [+id+] (READONLY) the id of the client # [+name+] (REQUIRED) the name of the client # [+details+] the details of the client # [+currency+] what type of currency is associated with the client # [+currency_symbol+] what currency symbol is associated with the client # [+active?+] true|false on whether the client is active # [+highrise_id+] (READONLY) the highrise id associated with this client # [+update_at+] (READONLY) the last modification timestamp class Client < Hashie::Mash include Harvest::Model api_path '/clients' def is_active=(val) self.active = val end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false
zmoazeni/harvested
https://github.com/zmoazeni/harvested/blob/33d26049651fde6adf651d5c8aff8fff97156210/lib/harvest/time_entry.rb
lib/harvest/time_entry.rb
module Harvest class TimeEntry < Hashie::Mash include Harvest::Model skip_json_root true delegate_methods(:closed? => :is_closed, :billed? => :is_billed) def initialize(args = {}, _ = nil) args = args.to_hash.stringify_keys self.spent_at = args.delete("spent_at") if args["spent_at"] super end def spent_at=(date) self["spent_at"] = Date.parse(date.to_s) end def as_json(args = {}) super(args).to_hash.stringify_keys.tap do |hash| hash.update("spent_at" => (spent_at.nil? ? nil : spent_at.xmlschema)) end end end end
ruby
MIT
33d26049651fde6adf651d5c8aff8fff97156210
2026-01-04T17:50:27.559404Z
false