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
shiroyasha/factory_bot_instruments
https://github.com/shiroyasha/factory_bot_instruments/blob/8306a388288cc13358463f6666ae836c7e1f0218/lib/factory_bot_instruments/version.rb
lib/factory_bot_instruments/version.rb
module FactoryBotInstruments VERSION = "1.2.0" end
ruby
MIT
8306a388288cc13358463f6666ae836c7e1f0218
2026-01-04T17:51:48.615283Z
false
shiroyasha/factory_bot_instruments
https://github.com/shiroyasha/factory_bot_instruments/blob/8306a388288cc13358463f6666ae836c7e1f0218/lib/factory_bot_instruments/benchmarking.rb
lib/factory_bot_instruments/benchmarking.rb
module FactoryBotInstruments module Benchmarking def benchmark_all( except: [], methods: [:create, :build, :build_stubbed], progress: false) factories = FactoryBot.factories.map(&:name) - except report = factories.map do |factory| puts "Processing #{factory}" if progress methods.map do |method| benchmark(factory, :method => method) end end report.flatten.sort_by(&:duration) end def benchmark(factory, method: :create) start = Time.now ActiveRecord::Base.transaction do FactoryBot.public_send(method, factory) raise ActiveRecord::Rollback end Benchmark.new(factory, method, Time.now - start) end end Benchmark = Struct.new(:factory, :method, :duration) do def to_s formated_duration = format("%5.3fs", duration) "#{formated_duration}: FactoryBot.#{method}(:#{factory})" end end end
ruby
MIT
8306a388288cc13358463f6666ae836c7e1f0218
2026-01-04T17:51:48.615283Z
false
shiroyasha/factory_bot_instruments
https://github.com/shiroyasha/factory_bot_instruments/blob/8306a388288cc13358463f6666ae836c7e1f0218/lib/factory_bot_instruments/tracing.rb
lib/factory_bot_instruments/tracing.rb
$FACTORY_BOT_INSTRUMENTS_TRACING = false $FACTORY_BOT_INSTRUMENTS_TRACING_DEPTH = 0 # monkey patch Factory#run module FactoryBot class Factory alias_method :original_run, :run def run(build_strategy, overrides, &block) if $FACTORY_BOT_INSTRUMENTS_TRACING depth = "| " * $FACTORY_BOT_INSTRUMENTS_TRACING_DEPTH signature = "#{build_strategy} \e[32m:#{@name}\e[0m" start = Time.now puts "#{depth}โ”Œ (start) #{signature}" $FACTORY_BOT_INSTRUMENTS_TRACING_DEPTH += 1 end result = original_run(build_strategy, overrides, &block) if $FACTORY_BOT_INSTRUMENTS_TRACING duration = format("%4.3fs", Time.now - start) puts "#{depth}โ”” (finish) #{signature} [#{duration}]" $FACTORY_BOT_INSTRUMENTS_TRACING_DEPTH -= 1 end result end end end module FactoryBotInstruments module TracingHelpers def self.uncolorize(string) string.gsub(/\033\[\d+m/, "") end def self.sql_tracer(active) return yield unless active begin stdout_log = Logger.new($stdout) stdout_log.formatter = proc do |severity, datetime, progname, msg| depth = "| " * ($FACTORY_BOT_INSTRUMENTS_TRACING_DEPTH - 1) msg = FactoryBotInstruments::TracingHelpers.uncolorize(msg) msg = msg.strip msg = msg.gsub(/^SQL /, "") # remove SQL prefix "#{depth}| \e[36m#{msg}\e[0m\n" end standard_logger = ActiveRecord::Base.logger ActiveRecord::Base.logger = stdout_log yield ensure ActiveRecord::Base.logger = standard_logger end end end module Tracing def trace(sql: true) result = nil begin $FACTORY_BOT_INSTRUMENTS_TRACING = true $FACTORY_BOT_INSTRUMENTS_TRACING_DEPTH = 0 FactoryBotInstruments::TracingHelpers.sql_tracer(sql) do result = yield end ensure $FACTORY_BOT_INSTRUMENTS_TRACING = false $FACTORY_BOT_INSTRUMENTS_TRACING_DEPTH = 0 end result end end end
ruby
MIT
8306a388288cc13358463f6666ae836c7e1f0218
2026-01-04T17:51:48.615283Z
false
soveran/cargo
https://github.com/soveran/cargo/blob/5559fd122c8e7629e3bb92984d1f1087e96c4ea8/test/foo-1.0.0.rb
test/foo-1.0.0.rb
class Foo class Bar class Baz def qux "Hello" end end def baz "Hello" end end def bar "Hello" end end export(Foo) if defined?(export)
ruby
MIT
5559fd122c8e7629e3bb92984d1f1087e96c4ea8
2026-01-04T17:51:54.743239Z
false
soveran/cargo
https://github.com/soveran/cargo/blob/5559fd122c8e7629e3bb92984d1f1087e96c4ea8/test/cargo_test.rb
test/cargo_test.rb
# encoding: UTF-8 require File.join(".", "lib", "cargo") setup do unless defined?(Foo1) Foo1 = import("test/foo-1.0.0") end unless defined?(Foo2) Foo2 = import("test/foo-2.0.0") end end test "Foo is not available" do assert nil == defined?(Foo) end test "Foo1 is a class" do assert Class == Foo1.class end test "methods are available" do assert "Hello" == Foo1.new.bar end test "methods on nested classes are available" do assert "Hello" == Foo1::Bar.new.baz assert "Hello" == Foo1::Bar::Baz.new.qux end test "nested classes are not available in the top level" do begin Bar::Baz.new.qux rescue assert NameError == $!.class end end test "Foo2 should be possible" do assert "Hello" == Foo2.new.bar end
ruby
MIT
5559fd122c8e7629e3bb92984d1f1087e96c4ea8
2026-01-04T17:51:54.743239Z
false
soveran/cargo
https://github.com/soveran/cargo/blob/5559fd122c8e7629e3bb92984d1f1087e96c4ea8/test/foo-2.0.0.rb
test/foo-2.0.0.rb
class Foo class Bar class Baz def qux "Hello" end end def baz "Hello" end end def bar "Hello" end end export(Foo) if defined?(export)
ruby
MIT
5559fd122c8e7629e3bb92984d1f1087e96c4ea8
2026-01-04T17:51:54.743239Z
false
soveran/cargo
https://github.com/soveran/cargo/blob/5559fd122c8e7629e3bb92984d1f1087e96c4ea8/lib/cargo.rb
lib/cargo.rb
module Cargo VERSION = "0.0.3" def import(file) unless file.match(/\.rb$/) file = "#{file}.rb" end load(file, true) Thread.current[:cargo].tap do Thread.current[:cargo] = nil end end def export(cargo) Thread.current[:cargo] = cargo end end extend Cargo
ruby
MIT
5559fd122c8e7629e3bb92984d1f1087e96c4ea8
2026-01-04T17:51:54.743239Z
false
ruby-next/freezolite
https://github.com/ruby-next/freezolite/blob/79727191a6790f55220975fd53eb86577f9eb5a0/test/freezolite_test.rb
test/freezolite_test.rb
require "test_helper" class FreezeTheListTest < Minitest::Test if ENV["FREEZOLITE_DISABLED"] == "true" def test_fixtures_default_behaviour load File.join(__dir__, "./fixtures/app/name.rb") result = Name.new + "test" assert result.end_with?("test") load File.join(__dir__, "./fixtures/lib/strings.rb") refute Strings.hello.frozen? load File.join(__dir__, "./fixtures/test/name_test.rb") assert_equal "name 1 2", NameTest.run end def test_constants load File.join(__dir__, "./fixtures/app/constants.rb") refute Constants::ARR.frozen? Constants::ARR << 4 refute Constants::HASH.frozen? Constants::HASH[:d] = 4 refute Constants::SomeClass.frozen? Constants::SomeClass.define_method(:some_method) { "some_method" } end else def test_fixtures_with_freezolite_enabled load File.join(__dir__, "./fixtures/app/name.rb") assert_raises(FrozenError) { Name.new + "test" } load File.join(__dir__, "./fixtures/app/name_unfrozen.rb") result = Name.new + "test" assert result.end_with?("test") load File.join(__dir__, "./fixtures/lib/strings.rb") # This folder is not activated by Freezolite refute Strings.hello.frozen? load File.join(__dir__, "./fixtures/test/name_test.rb") assert_raises(FrozenError) { NameTest.run } end def test_excluded_patterns load File.join(__dir__, "./fixtures/app/vendor/bundle/gem.rb") assert_equal "hot", VendorGem::CONSTANT refute VendorGem::CONSTANT.frozen? end if RUBY_VERSION >= "3.0.0" def test_constants load File.join(__dir__, "./fixtures/app/constants.rb") assert Constants::ARR.frozen? assert Constants::HASH.frozen? refute Constants::SomeClass.frozen? Constants::SomeClass.define_method(:some_method) { "some_method" } end end end end
ruby
MIT
79727191a6790f55220975fd53eb86577f9eb5a0
2026-01-04T17:51:52.275829Z
false
ruby-next/freezolite
https://github.com/ruby-next/freezolite/blob/79727191a6790f55220975fd53eb86577f9eb5a0/test/test_helper.rb
test/test_helper.rb
# frozen_string_literal: true begin require "debug" unless ENV["CI"] rescue LoadError end $LOAD_PATH.unshift File.expand_path("../lib", __dir__) require "freezolite" if ENV["FREEZOLITE_DISABLED"] == "true" $stdout.puts "Freezolite is disabled" else Freezolite.experimental_freeze_constants = true Freezolite.setup( patterns: [ File.join(__dir__, "fixtures", "app", "*.rb"), File.join(__dir__, "fixtures", "test", "*.rb") ], exclude_patterns: [ File.join(__dir__, "fixtures", "app", "vendor", "*") ] ) end Dir["#{__dir__}/support/**/*.rb"].sort.each { |f| require f } require "minitest/autorun"
ruby
MIT
79727191a6790f55220975fd53eb86577f9eb5a0
2026-01-04T17:51:52.275829Z
false
ruby-next/freezolite
https://github.com/ruby-next/freezolite/blob/79727191a6790f55220975fd53eb86577f9eb5a0/test/fixtures/app/name_unfrozen.rb
test/fixtures/app/name_unfrozen.rb
# frozen_string_literal: false # shareable_constant_value: none class Name attr_reader :name NAMES = %w[Alice Bob Charles Diana].freeze def initialize(name = NAMES.sample) @name = name end def +(other) @name << " " << other end end
ruby
MIT
79727191a6790f55220975fd53eb86577f9eb5a0
2026-01-04T17:51:52.275829Z
false
ruby-next/freezolite
https://github.com/ruby-next/freezolite/blob/79727191a6790f55220975fd53eb86577f9eb5a0/test/fixtures/app/constants.rb
test/fixtures/app/constants.rb
module Constants ARR = [1, 2, 3] HASH = {a: 1, b: 2, c: 3} class SomeClass end end
ruby
MIT
79727191a6790f55220975fd53eb86577f9eb5a0
2026-01-04T17:51:52.275829Z
false
ruby-next/freezolite
https://github.com/ruby-next/freezolite/blob/79727191a6790f55220975fd53eb86577f9eb5a0/test/fixtures/app/name.rb
test/fixtures/app/name.rb
class Name attr_reader :name NAMES = %w[Alice Bob Charles Diana] def initialize(name = NAMES.sample) @name = name end def +(other) @name << " " << other end end
ruby
MIT
79727191a6790f55220975fd53eb86577f9eb5a0
2026-01-04T17:51:52.275829Z
false
ruby-next/freezolite
https://github.com/ruby-next/freezolite/blob/79727191a6790f55220975fd53eb86577f9eb5a0/test/fixtures/app/vendor/bundle/gem.rb
test/fixtures/app/vendor/bundle/gem.rb
module VendorGem CONSTANT = "hot" end
ruby
MIT
79727191a6790f55220975fd53eb86577f9eb5a0
2026-01-04T17:51:52.275829Z
false
ruby-next/freezolite
https://github.com/ruby-next/freezolite/blob/79727191a6790f55220975fd53eb86577f9eb5a0/test/fixtures/test/name_test.rb
test/fixtures/test/name_test.rb
class NameTest def self.run x = "name" x << " 1" x << " 2" x end end
ruby
MIT
79727191a6790f55220975fd53eb86577f9eb5a0
2026-01-04T17:51:52.275829Z
false
ruby-next/freezolite
https://github.com/ruby-next/freezolite/blob/79727191a6790f55220975fd53eb86577f9eb5a0/test/fixtures/lib/strings.rb
test/fixtures/lib/strings.rb
module Strings class << self def hello "Hallo" end def goodbye "Auf Wiedersehen" end end end
ruby
MIT
79727191a6790f55220975fd53eb86577f9eb5a0
2026-01-04T17:51:52.275829Z
false
ruby-next/freezolite
https://github.com/ruby-next/freezolite/blob/79727191a6790f55220975fd53eb86577f9eb5a0/lib/freezolite.rb
lib/freezolite.rb
# frozen_string_literal: true require "freezolite/version" module Freezolite class << self attr_reader :experimental_freeze_constants def experimental_freeze_constants=(val) @experimental_freeze_constants = (val == true) ? :literal : val end def setup(patterns:, exclude_patterns: nil) require "require-hooks/setup" ::RequireHooks.around_load(patterns: patterns, exclude_patterns: exclude_patterns) do |path, &block| was_frozen_string_literal = ::RubyVM::InstructionSequence.compile_option[:frozen_string_literal] || false ::RubyVM::InstructionSequence.compile_option = {frozen_string_literal: true} block.call ensure ::RubyVM::InstructionSequence.compile_option = {frozen_string_literal: was_frozen_string_literal} end if experimental_freeze_constants val = experimental_freeze_constants RequireHooks.source_transform(patterns: patterns, exclude_patterns: exclude_patterns) do |path, source| source ||= File.read(path) "# shareable_constant_value: #{val}\n#{source}" end end end end self.experimental_freeze_constants = false end
ruby
MIT
79727191a6790f55220975fd53eb86577f9eb5a0
2026-01-04T17:51:52.275829Z
false
ruby-next/freezolite
https://github.com/ruby-next/freezolite/blob/79727191a6790f55220975fd53eb86577f9eb5a0/lib/freezolite/version.rb
lib/freezolite/version.rb
# frozen_string_literal: true module Freezolite # :nodoc: VERSION = "0.6.0" end
ruby
MIT
79727191a6790f55220975fd53eb86577f9eb5a0
2026-01-04T17:51:52.275829Z
false
ruby-next/freezolite
https://github.com/ruby-next/freezolite/blob/79727191a6790f55220975fd53eb86577f9eb5a0/lib/freezolite/auto.rb
lib/freezolite/auto.rb
require "freezolite" Freezolite.setup( patterns: [File.join(Dir.pwd, "*.rb")], exclude_patterns: [File.join(Dir.pwd, "vendor", "*")] )
ruby
MIT
79727191a6790f55220975fd53eb86577f9eb5a0
2026-01-04T17:51:52.275829Z
false
janlelis/unicode-display_width
https://github.com/janlelis/unicode-display_width/blob/14dd750e454563612622f09f84875b98b1d0cc5a/misc/terminal-emoji-width.rb
misc/terminal-emoji-width.rb
#!/usr/bin/env ruby RULER = "123456789\n" ABC = "abcdefg\n\n" puts "1) TEXT-DEFAULT EMOJI" puts puts RULER + "โ›น" + ABC puts "1B) TEXT-DEFAULT EMOJI + VS16" puts puts RULER + "โ›น๏ธ" + ABC puts "1C) BASE EMOJI CHARACTER + MODIFIER" puts puts RULER + "๐Ÿƒ๐Ÿฝ" + ABC puts "1D) MODIFIER IN ISOLATION" puts puts RULER + "Z๐Ÿฝ" + ABC puts "2) RGI EMOJI SEQ" puts puts RULER + "๐Ÿƒ๐Ÿผโ€โ™€โ€โžก" + ABC puts "2B) RGI EMOJI SEQ (TEXT-DEFAULT FIRST)" puts puts RULER + "โ›น๏ธโ€โ™‚๏ธ" + ABC puts "2C) RGI EMOJI SEQ (TEXT-DEFAULT FIRST + UQE)" puts puts RULER + "โ›นโ€โ™‚๏ธ" + ABC puts "3) NON-RGI VALID EMOJI" puts puts RULER + "๐Ÿค โ€๐Ÿคข" + ABC puts "4) NOT WELL-FORMED EMOJI SEQ" puts puts RULER + "๐Ÿš„๐Ÿพโ€๐Ÿ”†" + ABC
ruby
MIT
14dd750e454563612622f09f84875b98b1d0cc5a
2026-01-04T17:51:48.429695Z
false
janlelis/unicode-display_width
https://github.com/janlelis/unicode-display_width/blob/14dd750e454563612622f09f84875b98b1d0cc5a/spec/display_width_spec.rb
spec/display_width_spec.rb
# frozen_string_literal: true require_relative '../lib/unicode/display_width/string_ext' describe 'Unicode::DisplayWidth.of' do describe '[east asian width]' do it 'returns 2 for F' do expect( '๏ผ'.display_width ).to eq 2 end it 'returns 2 for W' do expect( 'ไธ€'.display_width ).to eq 2 end it 'returns 2 for W (which are currently unassigned)' do expect( "\u{3FFFD}".display_width ).to eq 2 end it 'returns 1 for N' do expect( 'ร€'.display_width ).to eq 1 end it 'returns 1 for Na' do expect( 'A'.display_width ).to eq 1 end it 'returns 1 for H' do expect( '๏ฝก'.display_width ).to eq 1 end it 'returns first argument of display_width for A' do expect( 'ยท'.display_width(1) ).to eq 1 end it 'returns first argument of display_width for A' do expect( 'ยท'.display_width(2) ).to eq 2 end it 'returns 1 for A if no argument given' do expect( 'ยท'.display_width ).to eq 1 end end describe '[zero width]' do it 'returns 0 for Mn chars' do expect( 'ึฟ'.display_width ).to eq 0 end it 'returns 0 for Me chars' do expect( 'าˆ'.display_width ).to eq 0 end it 'returns 0 for Cf chars' do expect( 'โ€‹'.display_width ).to eq 0 end it 'returns 0 for HANGUL JUNGSEONG chars' do expect( 'แ… '.display_width ).to eq 0 expect( 'ํžฐ'.display_width ).to eq 0 end it 'returns 0 for U+2060..U+206F' do expect( "\u{2060}".display_width ).to eq 0 end it 'returns 0 for U+FFF0..U+FFF8' do expect( "\u{FFF0}".display_width ).to eq 0 end it 'returns 0 for U+E0000..U+E0FFF' do expect( "\u{E0000}".display_width ).to eq 0 end end describe '[special characters]' do it 'returns 0 for โ€' do expect( "\0".display_width ).to eq 0 end it 'returns 0 for โ…' do expect( "\x05".display_width ).to eq 0 end it 'returns 0 for โ‡' do expect( "\a".display_width ).to eq 0 end it 'returns -1 for โˆ' do expect( "aaaa\b".display_width ).to eq 3 end it 'returns -1 for โˆ, but at least 0' do expect( "\b".display_width ).to eq 0 end it 'returns 0 for โŠ' do expect( "\n".display_width ).to eq 0 end it 'returns 0 for โ‹' do expect( "\v".display_width ).to eq 0 end it 'returns 0 for โŒ' do expect( "\f".display_width ).to eq 0 end it 'returns 0 for โ' do expect( "\r".display_width ).to eq 0 end it 'returns 0 for โŽ' do expect( "\x0E".display_width ).to eq 0 end it 'returns 0 for โ' do expect( "\x0F".display_width ).to eq 0 end it 'returns 1 for other C0 characters' do expect( "\x01".display_width ).to eq 1 expect( "\x02".display_width ).to eq 1 expect( "\x03".display_width ).to eq 1 expect( "\x04".display_width ).to eq 1 expect( "\x06".display_width ).to eq 1 expect( "\x10".display_width ).to eq 1 expect( "\x11".display_width ).to eq 1 expect( "\x12".display_width ).to eq 1 expect( "\x13".display_width ).to eq 1 expect( "\x14".display_width ).to eq 1 expect( "\x15".display_width ).to eq 1 expect( "\x16".display_width ).to eq 1 expect( "\x17".display_width ).to eq 1 expect( "\x18".display_width ).to eq 1 expect( "\x19".display_width ).to eq 1 expect( "\x1a".display_width ).to eq 1 expect( "\x1b".display_width ).to eq 1 expect( "\x1c".display_width ).to eq 1 expect( "\x1d".display_width ).to eq 1 expect( "\x1e".display_width ).to eq 1 expect( "\x1f".display_width ).to eq 1 expect( "\x7f".display_width ).to eq 1 end it 'returns 0 for LINE SEPARATOR' do expect( "\u{2028}".display_width ).to eq 0 end it 'returns 0 for PARAGRAPH SEPARATOR' do expect( "\u{2029}".display_width ).to eq 0 end it 'returns 1 for SOFT HYPHEN' do expect( "ยญ".display_width ).to eq 1 end it 'returns 2 for THREE-EM DASH' do expect( "โธบ".display_width ).to eq 2 end it 'returns 3 for THREE-EM DASH' do expect( "โธป".display_width ).to eq 3 end it 'returns ambiguous for private-use' do expect( "๓ฐ€€".display_width(1) ).to eq 1 expect( "๓ฐ€€".display_width(2) ).to eq 2 end end describe '[overwrite]' do it 'can be passed a 3rd parameter with overwrites (old format)' do expect( "\t".display_width(1, { 0x09 => 12 }) ).to eq 12 end it 'can be passed as :overwrite option' do expect( "\t".display_width(overwrite: { 0x09 => 12 }) ).to eq 12 end end describe '[encoding]' do it 'works with non-utf8 Unicode encodings' do expect( 'ร€'.encode("UTF-16LE").display_width ).to eq 1 end it 'works with a string that is invalid in its encoding' do s = "\x81\x39".dup.force_encoding(Encoding::SHIFT_JIS) # Would print as ๏ฟฝ9 on the terminal expect( s.display_width ).to eq 2 end it 'works with a binary encoded string that is valid in UTF-8' do expect( 'โ‚ฌ'.b.display_width ).to eq 1 end end describe '[emoji]' do describe '(basic emoji / text emoji)' do it 'counts default-text presentation Emoji according to EAW (example: 1)' do expect( "โฃ".display_width(emoji: :all) ).to eq 1 end it 'counts default-text presentation Emoji according to EAW (example: ambiguous)' do expect( "โ™€".display_width(1, emoji: :all) ).to eq 1 expect( "โ™€".display_width(2, emoji: :all) ).to eq 2 end it 'counts default-text presentation Emoji with Emoji Presentation (VS16) as 2' do expect( "โฃ๏ธ".display_width(emoji: :all) ).to eq 2 end it 'counts default-text presentation Emoji with Emoji Presentation (VS16) as 2 (in a sequence)' do expect( "โฃ๏ธโ€โฃ๏ธ".display_width(emoji: :rgi) ).to eq 4 end it 'counts default-emoji presentation Emoji according to EAW (always 2)' do expect( "๐Ÿ’š".display_width(emoji: :all) ).to eq 2 end end describe '(special emoji / emoji sequences)' do it 'works with flags: width 2' do expect( "๐Ÿ‡ต๐Ÿ‡น".display_width(emoji: :all) ).to eq 2 end it 'works with subdivision flags: width 2' do expect( "๐Ÿด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ".display_width(emoji: :all) ).to eq 2 end it 'works with keycaps: width 2' do expect( "1๏ธโƒฃ".display_width(emoji: :all) ).to eq 2 end end describe '(modifiers and zwj sequences)' do it 'applies simple skin tone modifiers' do expect( "๐Ÿ‘๐Ÿฝ".display_width(emoji: :rgi) ).to eq 2 end it 'counts RGI Emoji ZWJ sequence as width 2' do expect( "๐Ÿคพ๐Ÿฝโ€โ™€๏ธ".display_width(emoji: :rgi) ).to eq 2 end it 'works for emoji involving characters which are east asian ambiguous' do expect( "๐Ÿคพ๐Ÿฝโ€โ™€๏ธ".display_width(2, emoji: :rgi) ).to eq 2 end end describe '(modes)' do describe 'false / :none' do it 'does no Emoji adjustments when emoji suport is disabled' do expect( "๐Ÿคพ๐Ÿฝโ€โ™€๏ธ".display_width(emoji: false) ).to eq 5 expect( "โฃ๏ธ".display_width(emoji: :none) ).to eq 1 expect( "๐Ÿ‘๐Ÿฝ".display_width(emoji: :none) ).to eq 4 end end describe ':vs16' do it 'will ignore shorter width of all Emoji sequences' do # Please note that this is different from emoji: false / emoji: :none # -> Basic Emoji with VS16 still get normalized expect( "๐Ÿคพ๐Ÿฝโ€โ™€๏ธ".display_width(emoji: :vs16) ).to eq 6 end it 'counts default-text presentation Emoji with Emoji Presentation (VS16) as 2' do expect( "โฃ๏ธ".display_width(emoji: :vs16) ).to eq 2 end it 'works with keycaps: width 2' do expect( "1๏ธโƒฃ".display_width(emoji: :vs16) ).to eq 2 end end describe ':rgi' do it 'will ignore shorter width of non-RGI sequences' do expect( "๐Ÿคพ๐Ÿฝโ€โ™€๏ธ".display_width(emoji: :rgi) ).to eq 2 # FQE expect( "๐Ÿคพ๐Ÿฝโ€โ™€".display_width(emoji: :rgi) ).to eq 2 # MQE expect( "โคโ€๐Ÿฉน".display_width(emoji: :rgi) ).to eq 2 # UQE expect( "๐Ÿ‘๐Ÿฝ".display_width(emoji: :rgi) ).to eq 2 # Modifier expect( "J๐Ÿฝ".display_width(emoji: :rgi) ).to eq 3 # Modifier with invalid base expect( "๐Ÿค โ€๐Ÿคข".display_width(emoji: :rgi) ).to eq 4 # Non-RGI/well-formed expect( "๐Ÿš„๐Ÿพโ€โ–ถ๏ธ".display_width(emoji: :rgi) ).to eq 6 # Invalid/non-Emoji sequence end it 'counts default-text presentation Emoji with Emoji Presentation (VS16) as 2' do expect( "โฃ๏ธ".display_width(emoji: :rgi) ).to eq 2 end end describe ':rgi_at' do it 'will assign width based on EAW of first partial Emoji to whole sequence' do expect( "๐Ÿคพ๐Ÿฝโ€โ™€๏ธ".display_width(emoji: :rgi_at) ).to eq 2 expect( "โ›น๏ธโ€โ™€๏ธ".display_width(emoji: :rgi_at) ).to eq 1 expect( "โคโ€๐Ÿฉน".display_width(emoji: :rgi_at) ).to eq 1 end it 'will count partial emoji for non-RGI sequences' do expect( "๐Ÿค โ€๐Ÿคข".display_width(emoji: :rgi_at) ).to eq 4 # Non-RGI/well-formed expect( "๐Ÿš„๐Ÿพโ€โ–ถ๏ธ".display_width(emoji: :rgi_at) ).to eq 5 # Invalid/non-Emoji sequence end it 'uses EAW for default-text presentation Emoji with Emoji Presentation (VS16)' do expect( "โฃ๏ธ".display_width(emoji: :rgi_at) ).to eq 1 end end describe ':possible' do it 'will treat possible/well-formed Emoji sequence as width 2' do expect( "๐Ÿคพ๐Ÿฝโ€โ™€๏ธ".display_width(emoji: :possible) ).to eq 2 # FQE expect( "๐Ÿคพ๐Ÿฝโ€โ™€".display_width(emoji: :possible) ).to eq 2 # MQE expect( "โคโ€๐Ÿฉน".display_width(emoji: :possible) ).to eq 2 # UQE expect( "๐Ÿ‘๐Ÿฝ".display_width(emoji: :possible) ).to eq 2 # Modifier expect( "J๐Ÿฝ".display_width(emoji: :possible) ).to eq 3 # Modifier with invalid base expect( "๐Ÿค โ€๐Ÿคข".display_width(emoji: :possible) ).to eq 2 # Non-RGI/well-formed expect( "๐Ÿš„๐Ÿพโ€โ–ถ๏ธ".display_width(emoji: :possible) ).to eq 6 # Invalid/non-Emoji sequence end it 'counts default-text presentation Emoji with Emoji Presentation (VS16) as 2' do expect( "โฃ๏ธ".display_width(emoji: :possible) ).to eq 2 end end describe ':all' do it 'will treat any ZWJ/modifier/keycap sequences sequence as width 2' do expect( "๐Ÿคพ๐Ÿฝโ€โ™€๏ธ".display_width(emoji: :all) ).to eq 2 # FQE expect( "๐Ÿคพ๐Ÿฝโ€โ™€".display_width(emoji: :all) ).to eq 2 # MQE expect( "โคโ€๐Ÿฉน".display_width(emoji: :all) ).to eq 2 # UQE expect( "๐Ÿ‘๐Ÿฝ".display_width(emoji: :all) ).to eq 2 # Modifier expect( "๐Ÿ‘๐Ÿฝ".display_width(emoji: :all) ).to eq 2 # Modifier expect( "J๐Ÿฝ".display_width(emoji: :all) ).to eq 2 # Modifier with invalid base expect( "๐Ÿค โ€๐Ÿคข".display_width(emoji: :all) ).to eq 2 # Non-RGI/well-formed expect( "๐Ÿš„๐Ÿพโ€โ–ถ๏ธ".display_width(emoji: :all) ).to eq 2 # Invalid/non-Emoji sequence end it 'counts default-text presentation Emoji with Emoji Presentation (VS16) as 2' do expect( "โฃ๏ธ".display_width(emoji: :all) ).to eq 2 end end describe ':all_no_vs16' do it 'will treat any ZWJ/modifier/keycap sequences sequence as width 2' do expect( "๐Ÿคพ๐Ÿฝโ€โ™€๏ธ".display_width(emoji: :all_no_vs16) ).to eq 2 # FQE expect( "๐Ÿคพ๐Ÿฝโ€โ™€".display_width(emoji: :all_no_vs16) ).to eq 2 # MQE expect( "โคโ€๐Ÿฉน".display_width(emoji: :all_no_vs16) ).to eq 2 # UQE expect( "๐Ÿ‘๐Ÿฝ".display_width(emoji: :all_no_vs16) ).to eq 2 # Modifier expect( "J๐Ÿฝ".display_width(emoji: :all_no_vs16) ).to eq 2 # Modifier with wrong base expect( "๐Ÿค โ€๐Ÿคข".display_width(emoji: :all_no_vs16) ).to eq 2 # Non-RGI/well-formed expect( "๐Ÿš„๐Ÿพโ€โ–ถ๏ธ".display_width(emoji: :all_no_vs16) ).to eq 2 # Invalid/non-Emoji sequence end it 'uses EAW for default-text presentation Emoji with Emoji Presentation (VS16)' do expect( "โฃ๏ธ".display_width(emoji: :all_no_vs16) ).to eq 1 end end end end end describe "Config object based API" do let :display_width do Unicode::DisplayWidth.new( # ambiguous: 1, overwrite: { "A".ord => 100 }, emoji: :all, ) end it "will respect given overwrite option" do expect( display_width.of "A" ).to eq 100 end it "will respect given emoji option" do expect( display_width.of "๐Ÿค โ€๐Ÿคข" ).to eq 2 end end
ruby
MIT
14dd750e454563612622f09f84875b98b1d0cc5a
2026-01-04T17:51:48.429695Z
false
janlelis/unicode-display_width
https://github.com/janlelis/unicode-display_width/blob/14dd750e454563612622f09f84875b98b1d0cc5a/lib/unicode/display_width.rb
lib/unicode/display_width.rb
# frozen_string_literal: true require "unicode/emoji" require_relative "display_width/constants" require_relative "display_width/index" require_relative "display_width/emoji_support" module Unicode class DisplayWidth DEFAULT_AMBIGUOUS = 1 INITIAL_DEPTH = 0x10000 ASCII_NON_ZERO_REGEX = /[\0\x05\a\b\n-\x0F]/ ASCII_NON_ZERO_STRING = "\0\x05\a\b\n-\x0F" ASCII_BACKSPACE = "\b" AMBIGUOUS_MAP = { 1 => :WIDTH_ONE, 2 => :WIDTH_TWO, } FIRST_AMBIGUOUS = { WIDTH_ONE: 768, WIDTH_TWO: 161, } NOT_COMMON_NARROW_REGEX = { WIDTH_ONE: /[^\u{10}-\u{2FF}]/m, WIDTH_TWO: /[^\u{10}-\u{A1}]/m, } FIRST_4096 = { WIDTH_ONE: decompress_index(INDEX[:WIDTH_ONE][0][0], 1), WIDTH_TWO: decompress_index(INDEX[:WIDTH_TWO][0][0], 1), } EMOJI_SEQUENCES_REGEX_MAPPING = { rgi: :REGEX_INCLUDE_MQE_UQE, rgi_at: :REGEX_INCLUDE_MQE_UQE, possible: :REGEX_WELL_FORMED, } REGEX_EMOJI_VS16 = Regexp.union( Regexp.compile( Unicode::Emoji::REGEX_TEXT_PRESENTATION.source + "(?<![#*0-9])" + "\u{FE0F}" ), Unicode::Emoji::REGEX_EMOJI_KEYCAP ) # ebase = Unicode::Emoji::REGEX_PROP_MODIFIER_BASE.source REGEX_EMOJI_ALL_SEQUENCES = Regexp.union(/.[\u{1F3FB}-\u{1F3FF}\u{FE0F}]?(\u{200D}.[\u{1F3FB}-\u{1F3FF}\u{FE0F}]?)+|.[\u{1F3FB}-\u{1F3FF}]/, Unicode::Emoji::REGEX_EMOJI_KEYCAP) REGEX_EMOJI_ALL_SEQUENCES_AND_VS16 = Regexp.union(REGEX_EMOJI_ALL_SEQUENCES, REGEX_EMOJI_VS16) # Returns monospace display width of string def self.of(string, ambiguous = nil, overwrite = nil, old_options = {}, **options) # Binary strings don't make much sense when calculating display width. # Assume it's valid UTF-8 if string.encoding == Encoding::BINARY && !string.force_encoding(Encoding::UTF_8).valid_encoding? # Didn't work out, go back to binary string.force_encoding(Encoding::BINARY) end string = string.encode(Encoding::UTF_8, invalid: :replace, undef: :replace) unless string.encoding == Encoding::UTF_8 options = normalize_options(string, ambiguous, overwrite, old_options, **options) width = 0 unless options[:overwrite].empty? width, string = width_custom(string, options[:overwrite]) end if string.ascii_only? return width + width_ascii(string) end ambiguous_index_name = AMBIGUOUS_MAP[options[:ambiguous]] unless string.match?(NOT_COMMON_NARROW_REGEX[ambiguous_index_name]) return width + string.size end # Retrieve Emoji width if options[:emoji] != :none e_width, string = emoji_width( string, options[:emoji], options[:ambiguous], ) width += e_width unless string.match?(NOT_COMMON_NARROW_REGEX[ambiguous_index_name]) return width + string.size end end index_full = INDEX[ambiguous_index_name] index_low = FIRST_4096[ambiguous_index_name] first_ambiguous = FIRST_AMBIGUOUS[ambiguous_index_name] string.each_codepoint{ |codepoint| if codepoint > 15 && codepoint < first_ambiguous width += 1 elsif codepoint < 0x1001 width += index_low[codepoint] || 1 else d = INITIAL_DEPTH w = index_full[codepoint / d] while w.instance_of? Array w = w[(codepoint %= d) / (d /= 16)] end width += w || 1 end } # Return result + prevent negative lengths width < 0 ? 0 : width end # Returns width of custom overwrites and remaining string def self.width_custom(string, overwrite) width = 0 string = string.each_codepoint.select{ |codepoint| if overwrite[codepoint] width += overwrite[codepoint] nil else codepoint end }.pack("U*") [width, string] end # Returns width for ASCII-only strings. Will consider zero-width control symbols. def self.width_ascii(string) if string.match?(ASCII_NON_ZERO_REGEX) res = string.delete(ASCII_NON_ZERO_STRING).bytesize - string.count(ASCII_BACKSPACE) return res < 0 ? 0 : res end string.bytesize end # Returns width of all considered Emoji and remaining string def self.emoji_width(string, mode = :all, ambiguous = DEFAULT_AMBIGUOUS) res = 0 if emoji_set_regex = EMOJI_SEQUENCES_REGEX_MAPPING[mode] emoji_width_via_possible( string, Unicode::Emoji.const_get(emoji_set_regex), mode == :rgi_at, ambiguous, ) elsif mode == :all_no_vs16 no_emoji_string = string.gsub(REGEX_EMOJI_ALL_SEQUENCES){ res += 2; "" } [res, no_emoji_string] elsif mode == :vs16 no_emoji_string = string.gsub(REGEX_EMOJI_VS16){ res += 2; "" } [res, no_emoji_string] elsif mode == :all no_emoji_string = string.gsub(REGEX_EMOJI_ALL_SEQUENCES_AND_VS16){ res += 2; "" } [res, no_emoji_string] else [0, string] end end # Match possible Emoji first, then refine def self.emoji_width_via_possible(string, emoji_set_regex, strict_eaw = false, ambiguous = DEFAULT_AMBIGUOUS) res = 0 # For each string possibly an emoji no_emoji_string = string.gsub(REGEX_EMOJI_ALL_SEQUENCES_AND_VS16){ |emoji_candidate| # Check if we have a combined Emoji with width 2 (or EAW an Apple Terminal) if emoji_candidate == emoji_candidate[emoji_set_regex] if strict_eaw res += self.of(emoji_candidate[0], ambiguous, emoji: false) else res += 2 end "" # We are dealing with a default text presentation emoji or a well-formed sequence not matching the above Emoji set else if !strict_eaw # Ensure all explicit VS16 sequences have width 2 emoji_candidate.gsub!(REGEX_EMOJI_VS16){ res += 2; "" } end emoji_candidate end } [res, no_emoji_string] end def self.normalize_options(string, ambiguous = nil, overwrite = nil, old_options = {}, **options) unless old_options.empty? warn "Unicode::DisplayWidth: Please migrate to keyword arguments - #{old_options.inspect}" options.merge! old_options end options[:ambiguous] = ambiguous if ambiguous options[:ambiguous] ||= DEFAULT_AMBIGUOUS if options[:ambiguous] != 1 && options[:ambiguous] != 2 raise ArgumentError, "Unicode::DisplayWidth: Ambiguous width must be 1 or 2" end if overwrite && !overwrite.empty? warn "Unicode::DisplayWidth: Please migrate to keyword arguments - overwrite: #{overwrite.inspect}" options[:overwrite] = overwrite end options[:overwrite] ||= {} if [nil, true, :auto].include?(options[:emoji]) options[:emoji] = EmojiSupport.recommended elsif options[:emoji] == false options[:emoji] = :none end options end def initialize(ambiguous: DEFAULT_AMBIGUOUS, overwrite: {}, emoji: true) @ambiguous = ambiguous @overwrite = overwrite @emoji = emoji end def get_config(**kwargs) { ambiguous: kwargs[:ambiguous] || @ambiguous, overwrite: kwargs[:overwrite] || @overwrite, emoji: kwargs[:emoji] || @emoji, } end def of(string, **kwargs) self.class.of(string, **get_config(**kwargs)) end end end
ruby
MIT
14dd750e454563612622f09f84875b98b1d0cc5a
2026-01-04T17:51:48.429695Z
false
janlelis/unicode-display_width
https://github.com/janlelis/unicode-display_width/blob/14dd750e454563612622f09f84875b98b1d0cc5a/lib/unicode/display_width/no_string_ext.rb
lib/unicode/display_width/no_string_ext.rb
# frozen_string_literal: true warn "You are loading 'unicode-display_width/no_string_ext'\n" \ "Beginning with version 2.0, this is not necessary anymore\n"\ "You can just require 'unicode-display_width' now and no\n"\ "string extension will be loaded" require_relative "../display_width"
ruby
MIT
14dd750e454563612622f09f84875b98b1d0cc5a
2026-01-04T17:51:48.429695Z
false
janlelis/unicode-display_width
https://github.com/janlelis/unicode-display_width/blob/14dd750e454563612622f09f84875b98b1d0cc5a/lib/unicode/display_width/reline_ext.rb
lib/unicode/display_width/reline_ext.rb
# Experimental # Patches Reline's get_mbchar_width to use Unicode::DisplayWidth require "reline" require "reline/unicode" require_relative "../display_width" class Reline::Unicode def self.get_mbchar_width(mbchar) Unicode::DisplayWidth.of(mbchar, Reline.ambiguous_width) end end
ruby
MIT
14dd750e454563612622f09f84875b98b1d0cc5a
2026-01-04T17:51:48.429695Z
false
janlelis/unicode-display_width
https://github.com/janlelis/unicode-display_width/blob/14dd750e454563612622f09f84875b98b1d0cc5a/lib/unicode/display_width/index.rb
lib/unicode/display_width/index.rb
# frozen_string_literal: true require "zlib" require_relative "constants" module Unicode class DisplayWidth File.open(INDEX_FILENAME, "rb") do |file| serialized_data = Zlib::GzipReader.new(file).read serialized_data.force_encoding Encoding::BINARY INDEX = Marshal.load(serialized_data) end def self.decompress_index(index, level) index.flat_map{ |value| if level > 0 if value.instance_of?(Array) value[15] ||= nil decompress_index(value, level - 1) else decompress_index([value] * 16, level - 1) end else if value.instance_of?(Array) value[15] ||= nil value else [value] * 16 end end } end end end
ruby
MIT
14dd750e454563612622f09f84875b98b1d0cc5a
2026-01-04T17:51:48.429695Z
false
janlelis/unicode-display_width
https://github.com/janlelis/unicode-display_width/blob/14dd750e454563612622f09f84875b98b1d0cc5a/lib/unicode/display_width/string_ext.rb
lib/unicode/display_width/string_ext.rb
# frozen_string_literal: true require_relative "../display_width" class String def display_width(ambiguous = nil, overwrite = nil, old_options = {}, **options) Unicode::DisplayWidth.of(self, ambiguous, overwrite, old_options = {}, **options) end end
ruby
MIT
14dd750e454563612622f09f84875b98b1d0cc5a
2026-01-04T17:51:48.429695Z
false
janlelis/unicode-display_width
https://github.com/janlelis/unicode-display_width/blob/14dd750e454563612622f09f84875b98b1d0cc5a/lib/unicode/display_width/constants.rb
lib/unicode/display_width/constants.rb
# frozen_string_literal: true module Unicode class DisplayWidth VERSION = "3.2.0" UNICODE_VERSION = "17.0.0" DATA_DIRECTORY = File.expand_path(File.dirname(__FILE__) + "/../../../data/") INDEX_FILENAME = DATA_DIRECTORY + "/display_width.marshal.gz" end end
ruby
MIT
14dd750e454563612622f09f84875b98b1d0cc5a
2026-01-04T17:51:48.429695Z
false
janlelis/unicode-display_width
https://github.com/janlelis/unicode-display_width/blob/14dd750e454563612622f09f84875b98b1d0cc5a/lib/unicode/display_width/emoji_support.rb
lib/unicode/display_width/emoji_support.rb
# frozen_string_literal: true module Unicode class DisplayWidth module EmojiSupport # Tries to find out which terminal emulator is used to # set emoji: config to best suiting value # # Please also see section in README.md and # misc/terminal-emoji-width.rb # # Please note: Many terminals do not set any ENV vars, # maybe CSI queries can help? def self.recommended @recommended ||= _recommended end def self._recommended if ENV["CI"] return :rqi end case ENV["TERM_PROGRAM"] when "iTerm.app" return :all when "Apple_Terminal" return :rgi_at when "WezTerm" return :all_no_vs16 end case ENV["TERM"] when "contour","foot" # konsole: all, how to detect? return :all when /kitty/ return :vs16 end if ENV["WT_SESSION"] # Windows Terminal return :vs16 end # As of last time checked: gnome-terminal, vscode, alacritty :none end # Maybe: Implement something like https://github.com/jquast/ucs-detect # which uses the terminal cursor to check for best support level # at runtime # def self.detect! # end end end end
ruby
MIT
14dd750e454563612622f09f84875b98b1d0cc5a
2026-01-04T17:51:48.429695Z
false
logstash-plugins/logstash-filter-grok
https://github.com/logstash-plugins/logstash-filter-grok/blob/973a647eb915cb6cb41dc3dca07eeaa02b71dcaf/spec/spec_helper.rb
spec/spec_helper.rb
# encoding: utf-8 require "logstash/devutils/rspec/spec_helper" require "stud/temporary" module LogStash::Environment # running the grok code outside a logstash package means # LOGSTASH_HOME will not be defined, so let's set it here # before requiring the grok filter unless self.const_defined?(:LOGSTASH_HOME) LOGSTASH_HOME = File.expand_path("../../../", __FILE__) end # also :pattern_path method must exist so we define it too unless self.method_defined?(:pattern_path) def pattern_path(path) ::File.join(LOGSTASH_HOME, "patterns", path) end end end
ruby
Apache-2.0
973a647eb915cb6cb41dc3dca07eeaa02b71dcaf
2026-01-04T17:51:55.085667Z
false
logstash-plugins/logstash-filter-grok
https://github.com/logstash-plugins/logstash-filter-grok/blob/973a647eb915cb6cb41dc3dca07eeaa02b71dcaf/spec/filters/grok_performance_spec.rb
spec/filters/grok_performance_spec.rb
# encoding: utf-8 require_relative "../spec_helper" begin require "rspec-benchmark" rescue LoadError # due testing against LS 5.x end RSpec.configure do |config| config.include RSpec::Benchmark::Matchers if defined? RSpec::Benchmark::Matchers end require "logstash/filters/grok" describe LogStash::Filters::Grok do subject do described_class.new(config).tap { |filter| filter.register } end EVENT_COUNT = 300_000 describe "base-line performance", :performance => true do EXPECTED_MIN_RATE = 30_000 # per second - based on Travis CI (docker) numbers let(:config) do { 'match' => { "message" => "%{SYSLOGLINE}" }, 'overwrite' => [ "message" ] } end it "matches at least #{EXPECTED_MIN_RATE} events/second" do max_duration = EVENT_COUNT / EXPECTED_MIN_RATE message = "Mar 16 00:01:25 evita postfix/smtpd[1713]: connect from camomile.cloud9.net[168.100.1.3]" expect do duration = measure do EVENT_COUNT.times { subject.filter(LogStash::Event.new("message" => message)) } end puts "filters/grok parse rate: #{"%02.0f/sec" % (EVENT_COUNT / duration)}, elapsed: #{duration}s" end.to perform_under(max_duration).warmup(1).sample(2).times end end describe "timeout", :performance => true do ACCEPTED_TIMEOUT_DEGRADATION = 100 # in % (compared to timeout-less run) # TODO: with more real-world (pipeline) setup this usually gets bellow 10% on average MATCH_PATTERNS = { "message" => [ "foo0: %{NUMBER:bar}", "foo1: %{NUMBER:bar}", "foo2: %{NUMBER:bar}", "foo3: %{NUMBER:bar}", "foo4: %{NUMBER:bar}", "foo5: %{NUMBER:bar}", "foo6: %{NUMBER:bar}", "foo7: %{NUMBER:bar}", "foo8: %{NUMBER:bar}", "foo9: %{NUMBER:bar}", "%{SYSLOGLINE}" ] } SAMPLE_MESSAGE = "Mar 16 00:01:25 evita postfix/smtpd[1713]: connect from aaaaaaaa.aaaaaa.net[111.111.11.1]".freeze TIMEOUT_MILLIS = 5_000 let(:config_wout_timeout) do { 'match' => MATCH_PATTERNS, 'timeout_scope' => "event", 'timeout_millis' => 0 # 0 - disabled timeout } end let(:config_with_timeout) do { 'match' => MATCH_PATTERNS, 'timeout_scope' => "event", 'timeout_millis' => TIMEOUT_MILLIS } end SAMPLE_COUNT = 2 it "has less than #{ACCEPTED_TIMEOUT_DEGRADATION}% overhead" do filter_wout_timeout = LogStash::Filters::Grok.new(config_wout_timeout).tap(&:register) wout_timeout_duration = do_sample_filter(filter_wout_timeout) # warmup puts "filters/grok(timeout => 0) warmed up in #{wout_timeout_duration}" before_sample! no_timeout_durations = Array.new(SAMPLE_COUNT).map do do_sample_filter(filter_wout_timeout) end puts "filters/grok(timeout => 0) took #{no_timeout_durations}" expected_duration = avg(no_timeout_durations) expected_duration += (expected_duration / 100) * ACCEPTED_TIMEOUT_DEGRADATION puts "expected_duration #{expected_duration}" filter_with_timeout = LogStash::Filters::Grok.new(config_with_timeout).tap(&:register) with_timeout_duration = do_sample_filter(filter_with_timeout) # warmup puts "filters/grok(timeout_scope => event) warmed up in #{with_timeout_duration}" try(3) do before_sample! durations = [] begin expect do do_sample_filter(filter_with_timeout).tap { |duration| durations << duration } end.to perform_under(expected_duration).sample(SAMPLE_COUNT).times ensure puts "filters/grok(timeout_scope => event) took #{durations}" end end end @private def do_sample_filter(filter) sample_event = { "message" => SAMPLE_MESSAGE } measure do for _ in (1..EVENT_COUNT) do # EVENT_COUNT.times without the block cost filter.filter(LogStash::Event.new(sample_event)) end end end end @private def measure start = Time.now yield Time.now - start end def avg(ary) ary.inject(0) { |m, i| m + i } / ary.size.to_f end def before_sample! 2.times { JRuby.gc } sleep TIMEOUT_MILLIS / 1000 end def sleep(seconds) puts "sleeping for #{seconds} seconds (redundant - potential timeout propagation)" Kernel.sleep(seconds) end end
ruby
Apache-2.0
973a647eb915cb6cb41dc3dca07eeaa02b71dcaf
2026-01-04T17:51:55.085667Z
false
logstash-plugins/logstash-filter-grok
https://github.com/logstash-plugins/logstash-filter-grok/blob/973a647eb915cb6cb41dc3dca07eeaa02b71dcaf/spec/filters/grok_spec.rb
spec/filters/grok_spec.rb
# encoding: utf-8 require_relative "../spec_helper" require 'logstash/plugin_mixins/ecs_compatibility_support/spec_helper' require "logstash/filters/grok" describe LogStash::Filters::Grok do subject { described_class.new(config) } let(:config) { {} } let(:event) { LogStash::Event.new(data) } let(:data) { { "message" => message } } def self.sample(message, &block) # mod = RSpec::Core::MemoizedHelpers.module_for(self) # mod.attr_reader :message # # mod.__send__(:define_method, :message) { message } # it("matches: #{message}") { @message = message; block.call } describe message do let(:message) { message } it("groks", &block) end end describe "in ecs mode", :ecs_compatibility_support, :aggregate_failures do ecs_compatibility_matrix(:disabled, :v1, :v8 => :v1) do |ecs_select| before(:each) do allow_any_instance_of(described_class).to receive(:ecs_compatibility).and_return(ecs_compatibility) subject.register subject.filter(event) end describe "simple syslog line" do let(:message) { 'Mar 16 00:01:25 evita postfix/smtpd[1713]: connect from camomile.cloud9.net[168.100.1.3]' } context 'with overwrite' do let(:config) { { "match" => { "message" => "%{SYSLOGLINE}" }, "overwrite" => [ "message" ] } } it "matches pattern" do expect( event.get("tags") ).to be nil expect( event.get ecs_select[disabled: "[logsource]", v1: "[host][hostname]"] ).to eq "evita" expect( event.get("timestamp") ).to eq "Mar 16 00:01:25" expect( event.get("message") ).to eql "connect from camomile.cloud9.net[168.100.1.3]" expect( event.get ecs_select[disabled: "[program]", v1: "[process][name]"] ).to eq "postfix/smtpd" expect( event.get(ecs_select[disabled: "[pid]", v1: "[process][pid]"]).to_s ).to eq "1713" end end context 'with target' do let(:config) { { "match" => { "message" => "%{SYSLOGLINE}" }, "target" => "grok" } } it "matches pattern" do expect( event.get("message") ).to eql message expect( event.get("tags") ).to be nil expect( event.get("grok") ).to_not be nil expect( event.get("[grok][timestamp]") ).to eql "Mar 16 00:01:25" expect( event.get("[grok][message]") ).to eql "connect from camomile.cloud9.net[168.100.1.3]" expect( event.get(ecs_select[disabled: "[grok][pid]", v1: "[grok][process][pid]"]).to_s ).to eq "1713" end end context 'with [deep] target' do let(:config) { { "match" => { "message" => "%{SYSLOGLINE}" }, "target" => "[@metadata][grok]" } } it "matches pattern" do expect( event.get("message") ).to eql message expect( event.get("tags") ).to be nil expect( event.get("grok") ).to be nil expect( event.get ecs_select[disabled: "[@metadata][grok][logsource]", v1: "[@metadata][grok][host][hostname]"] ).to eq "evita" expect( event.get("[@metadata][grok][message]") ).to eql "connect from camomile.cloud9.net[168.100.1.3]" expect( event.get(ecs_select[disabled: "[@metadata][grok][pid]", v1: "[@metadata][grok][process][pid]"]).to_s ).to eq "1713" end end end describe "ietf 5424 syslog line" do let(:config) { { "match" => { "message" => "%{SYSLOG5424LINE}" } } } sample "<191>1 2009-06-30T18:30:00+02:00 paxton.local grokdebug 4123 - [id1 foo=\"bar\"][id2 baz=\"something\"] Hello, syslog." do expect( event.get("tags") ).to be nil expect( event.get(ecs_select[disabled: "[syslog5424_pri]", v1: "[log][syslog][priority]"]).to_s ).to eq "191" expect( event.get ecs_select[disabled: "[syslog5424_ver]", v1: "[system][syslog][version]"] ).to eq "1" expect( event.get ecs_select[disabled: "[syslog5424_ts]", v1: "[timestamp]"] ).to eq "2009-06-30T18:30:00+02:00" expect( event.get ecs_select[disabled: "[syslog5424_host]", v1: "[host][hostname]"] ).to eq "paxton.local" expect( event.get ecs_select[disabled: "[syslog5424_app]", v1: "[process][name]"] ).to eq "grokdebug" expect( event.get(ecs_select[disabled: "[syslog5424_proc]", v1: "[process][pid]"] ).to_s ).to eq "4123" expect( event.get ecs_select[disabled: "[syslog5424_msgid]", v1: "[log][syslog][msgid]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_sd]", v1: "[system][syslog][structured_data]"] ).to eq "[id1 foo=\"bar\"][id2 baz=\"something\"]" expect( event.get ecs_select[disabled: "[syslog5424_msg]", v1: "[message][1]"] ).to eq "Hello, syslog." end sample "<191>1 2009-06-30T18:30:00+02:00 paxton.local grokdebug - - [id1 foo=\"bar\"] No process ID." do expect( event.get("tags") ).to be nil expect( event.get(ecs_select[disabled: "[syslog5424_pri]", v1: "[log][syslog][priority]"]).to_s ).to eq "191" expect( event.get ecs_select[disabled: "[syslog5424_ver]", v1: "[system][syslog][version]"] ).to eq "1" expect( event.get ecs_select[disabled: "[syslog5424_ts]", v1: "[timestamp]"] ).to eq "2009-06-30T18:30:00+02:00" expect( event.get ecs_select[disabled: "[syslog5424_host]", v1: "[host][hostname]"] ).to eq "paxton.local" expect( event.get ecs_select[disabled: "[syslog5424_app]", v1: "[process][name]"] ).to eq "grokdebug" expect( event.get(ecs_select[disabled: "[syslog5424_proc]", v1: "[process][pid]"] ) ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_msgid]", v1: "[log][syslog][msgid]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_sd]", v1: "[system][syslog][structured_data]"] ).to eq "[id1 foo=\"bar\"]" expect( event.get ecs_select[disabled: "[syslog5424_msg]", v1: "[message][1]"] ).to eq "No process ID." end sample "<191>1 2009-06-30T18:30:00+02:00 paxton.local grokdebug 4123 - - No structured data." do expect( event.get("tags") ).to be nil expect( event.get(ecs_select[disabled: "[syslog5424_pri]", v1: "[log][syslog][priority]"]).to_s ).to eq "191" expect( event.get ecs_select[disabled: "[syslog5424_ver]", v1: "[system][syslog][version]"] ).to eq "1" expect( event.get ecs_select[disabled: "[syslog5424_ts]", v1: "[timestamp]"] ).to eq "2009-06-30T18:30:00+02:00" expect( event.get ecs_select[disabled: "[syslog5424_host]", v1: "[host][hostname]"] ).to eq "paxton.local" expect( event.get ecs_select[disabled: "[syslog5424_app]", v1: "[process][name]"] ).to eq "grokdebug" expect( event.get(ecs_select[disabled: "[syslog5424_proc]", v1: "[process][pid]"] ).to_s ).to eq '4123' expect( event.get ecs_select[disabled: "[syslog5424_msgid]", v1: "[log][syslog][msgid]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_sd]", v1: "[system][syslog][structured_data]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_msg]", v1: "[message][1]"] ).to eq "No structured data." end sample "<191>1 2009-06-30T18:30:00+02:00 paxton.local grokdebug - - - No PID or SD." do expect( event.get("tags") ).to be nil expect( event.get(ecs_select[disabled: "[syslog5424_pri]", v1: "[log][syslog][priority]"]).to_s ).to eq "191" expect( event.get ecs_select[disabled: "[syslog5424_ver]", v1: "[system][syslog][version]"] ).to eq "1" expect( event.get ecs_select[disabled: "[syslog5424_ts]", v1: "[timestamp]"] ).to eq "2009-06-30T18:30:00+02:00" expect( event.get ecs_select[disabled: "[syslog5424_host]", v1: "[host][hostname]"] ).to eq "paxton.local" expect( event.get ecs_select[disabled: "[syslog5424_app]", v1: "[process][name]"] ).to eq "grokdebug" expect( event.get(ecs_select[disabled: "[syslog5424_proc]", v1: "[process][pid]"] ) ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_msgid]", v1: "[log][syslog][msgid]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_sd]", v1: "[system][syslog][structured_data]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_msg]", v1: "[message][1]"] ).to eq "No PID or SD." end sample "<191>1 2009-06-30T18:30:00+02:00 paxton.local grokdebug 4123 - Missing structured data." do expect( event.get("tags") ).to be nil expect( event.get(ecs_select[disabled: "[syslog5424_proc]", v1: "[process][pid]"] ).to_s ).to eq '4123' expect( event.get ecs_select[disabled: "[syslog5424_msgid]", v1: "[log][syslog][msgid]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_sd]", v1: "[system][syslog][structured_data]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_msg]", v1: "[message][1]"] ).to eq "Missing structured data." end sample "<191>1 2009-06-30T18:30:00+02:00 paxton.local grokdebug 4123 - - Additional spaces." do expect( event.get("tags") ).to be nil expect( event.get ecs_select[disabled: "[syslog5424_app]", v1: "[process][name]"] ).to eq "grokdebug" expect( event.get(ecs_select[disabled: "[syslog5424_proc]", v1: "[process][pid]"] ).to_s ).to eq '4123' expect( event.get ecs_select[disabled: "[syslog5424_msgid]", v1: "[log][syslog][msgid]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_sd]", v1: "[system][syslog][structured_data]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_msg]", v1: "[message][1]"] ).to eq "Additional spaces." end sample "<191>1 2009-06-30T18:30:00+02:00 paxton.local grokdebug 4123 - Additional spaces and missing SD." do expect( event.get("tags") ).to be nil expect( event.get ecs_select[disabled: "[syslog5424_app]", v1: "[process][name]"] ).to eq "grokdebug" expect( event.get(ecs_select[disabled: "[syslog5424_proc]", v1: "[process][pid]"] ).to_s ).to eq "4123" expect( event.get ecs_select[disabled: "[syslog5424_msgid]", v1: "[log][syslog][msgid]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_sd]", v1: "[system][syslog][structured_data]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_msg]", v1: "[message][1]"] ).to eq "Additional spaces and missing SD." end sample "<30>1 2014-04-04T16:44:07+02:00 osctrl01 dnsmasq-dhcp 8048 - - Appname contains a dash" do expect( event.get("tags") ).to be nil expect( event.get(ecs_select[disabled: "[syslog5424_pri]", v1: "[log][syslog][priority]"]).to_s ).to eq "30" expect( event.get ecs_select[disabled: "[syslog5424_ver]", v1: "[system][syslog][version]"] ).to eq "1" expect( event.get ecs_select[disabled: "[syslog5424_ts]", v1: "[timestamp]"] ).to eq "2014-04-04T16:44:07+02:00" expect( event.get ecs_select[disabled: "[syslog5424_host]", v1: "[host][hostname]"] ).to eq "osctrl01" expect( event.get ecs_select[disabled: "[syslog5424_app]", v1: "[process][name]"] ).to eq "dnsmasq-dhcp" expect( event.get(ecs_select[disabled: "[syslog5424_proc]", v1: "[process][pid]"] ).to_s ).to eq "8048" expect( event.get ecs_select[disabled: "[syslog5424_msgid]", v1: "[log][syslog][msgid]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_sd]", v1: "[system][syslog][structured_data]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_msg]", v1: "[message][1]"] ).to eq "Appname contains a dash" end sample "<30>1 2014-04-04T16:44:07+02:00 osctrl01 - 8048 - - Appname is nil" do expect( event.get("tags") ).to be nil expect( event.get(ecs_select[disabled: "[syslog5424_pri]", v1: "[log][syslog][priority]"]).to_s ).to eq "30" expect( event.get ecs_select[disabled: "[syslog5424_ver]", v1: "[system][syslog][version]"] ).to eq "1" expect( event.get ecs_select[disabled: "[syslog5424_ts]", v1: "[timestamp]"] ).to eq "2014-04-04T16:44:07+02:00" expect( event.get ecs_select[disabled: "[syslog5424_host]", v1: "[host][hostname]"] ).to eq "osctrl01" expect( event.get ecs_select[disabled: "[syslog5424_app]", v1: "[process][name]"] ).to eq nil expect( event.get(ecs_select[disabled: "[syslog5424_proc]", v1: "[process][pid]"] ).to_s ).to eq "8048" expect( event.get ecs_select[disabled: "[syslog5424_msgid]", v1: "[log][syslog][msgid]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_sd]", v1: "[system][syslog][structured_data]"] ).to eq nil expect( event.get ecs_select[disabled: "[syslog5424_msg]", v1: "[message][1]"] ).to eq "Appname is nil" end end end end describe "non ecs" do before(:each) do subject.register subject.filter(event) end describe "parsing an event with multiple messages (array of strings)" do let(:config) { { "match" => { "message" => "(?:hello|world) %{NUMBER:num}" } } } let(:message) { [ "hello 12345", "world 23456" ] } it "matches them all" do expect( event.get("num") ).to eql [ "12345", "23456" ] end end describe "coercing matched values" do let(:config) { { "match" => { "message" => "%{NUMBER:foo:int} %{NUMBER:bar:float}" } } } let(:message) { '400 454.33' } it "coerces matched values" do expect( event.get("foo") ).to be_a Integer expect( event.get("foo") ).to eql 400 expect( event.get("bar") ).to be_a Float expect( event.get("bar") ).to eql 454.33 end end describe "in-line pattern definitions" do let(:config) { { "match" => { "message" => "%{FIZZLE=\\d+}" }, "named_captures_only" => false } } sample "hello 1234" do expect( event.get("FIZZLE") ).to eql '1234' end end describe "processing selected fields" do let(:config) { { 'match' => { "message" => "%{WORD:word}", "examplefield" => "%{NUMBER:num}" }, 'break_on_match' => false } } let(:data) { { "message" => "hello world", "examplefield" => "12345" } } it "processes declared matches" do expect( event.get("word") ).to eql 'hello' expect( event.get("num") ).to eql '12345' end end describe "adding fields on match" do let(:config) { { 'match' => { "message" => "matchme %{NUMBER:fancy}" }, 'add_field' => [ "new_field", "%{fancy}" ] } } sample "matchme 1234" do expect( event.get("tags") ).to be nil expect( event.get("new_field") ).to eql "1234" end sample "this will not be matched" do expect( event.get("tags") ).to include("_grokparsefailure") expect( event ).not_to include 'new_field' end end context "empty fields" do describe "drop by default" do let(:config) { { 'match' => { "message" => "1=%{WORD:foo1} *(2=%{WORD:foo2})?" } } } sample "1=test" do expect( event.get("tags") ).to be nil expect( event ).to include 'foo1' # Since 'foo2' was not captured, it must not be present in the event. expect( event ).not_to include 'foo2' end end describe "keep if keep_empty_captures is true" do let(:config) { { 'match' => { "message" => "1=%{WORD:foo1} *(2=%{WORD:foo2})?" }, 'keep_empty_captures' => true } } sample "1=test" do expect( event.get("tags") ).to be nil # use .to_hash for this test, for now, because right now # the Event.include? returns false for missing fields as well # as for fields with nil values. expect( event.to_hash ).to include 'foo1' expect( event.to_hash ).to include 'foo2' end end end describe "when named_captures_only == false" do let(:config) { { 'match' => { "message" => "Hello %{WORD}. %{WORD:foo}" }, 'named_captures_only' => false } } sample "Hello World, yo!" do expect( event ).to include 'WORD' expect( event.get("WORD") ).to eql "World" expect( event ).to include 'foo' expect( event.get("foo") ).to eql "yo" end end describe "using oniguruma named captures (?<name>regex)" do context "plain regexp" do let(:config) { { 'match' => { "message" => "(?<foo>\\w+)" } } } sample "hello world" do expect( event.get("tags") ).to be nil expect( event.get("foo") ).to eql "hello" end end context "grok patterns" do let(:config) { { 'match' => { "message" => "(?<timestamp>%{DATE_EU} %{TIME})" } } } sample "fancy 12-12-12 12:12:12" do expect( event.get("tags") ).to be nil expect( event.get("timestamp") ).to eql "12-12-12 12:12:12" end end end describe "grok on integer types" do let(:config) { { 'match' => { "status" => "^403$" }, 'add_tag' => "four_oh_three" } } let(:data) { Hash({ "status" => 403 }) } it "parses" do expect( event.get("tags") ).not_to include "_grokparsefailure" expect( event.get("tags") ).to include "four_oh_three" end end describe "grok on float types" do let(:config) { { 'match' => { "version" => "^1.0$" }, 'add_tag' => "one_point_oh" } } let(:data) { Hash({ "version" => 1.0 }) } it "parses" do expect( event.get("tags") ).not_to include "_grokparsefailure" expect( event.get("tags") ).to include "one_point_oh" end end describe "grok on %{LOGLEVEL}" do let(:config) { { 'match' => { "message" => "%{LOGLEVEL:level}: error!" } } } log_level_names = %w( trace Trace TRACE debug Debug DEBUG notice Notice Notice info Info INFO warn warning Warn Warning WARN WARNING err error Err Error ERR ERROR crit critical Crit Critical CRIT CRITICAL fatal Fatal FATAL severe Severe SEVERE emerg emergency Emerg Emergency EMERG EMERGENCY ) log_level_names.each do |level_name| sample "#{level_name}: error!" do expect( event.get("level") ).to eql level_name end end end describe "timeout on failure" do let(:config) { { 'match' => { "message" => "(.*a){30}" }, 'timeout_millis' => 100 } } sample "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" do expect( event.get("tags") ).to include("_groktimeout") expect( event.get("tags") ).not_to include("_grokparsefailure") end end describe "no timeout on failure with multiple patterns (when timeout not grouped)" do let(:config) { { 'match' => { "message" => [ "(.*f){20}", "(.*e){20}", "(.*d){20}", "(.*c){20}", "(.*b){20}", "(.*a){25}", "(.*a){24}", "(.*a){23}", "(.*a){22}", "(.*a){21}", "(.*a){25}", "(.*a){24}", "(.*a){23}", "(.*a){22}", "(.*a){21}", "(.*a){25}", "(.*a){24}", "(.*a){23}", "(.*a){22}", "(.*a){21}", "(.*a){20}" ] }, 'timeout_millis' => 750, 'timeout_scope' => 'pattern' } } sample( 'b' * 15 + 'c' * 15 + 'd' * 15 + 'e' * 15 + ' ' + 'a' * 20 ) do expect( event.get("tags") ).to be nil end end describe "timeout on grouped (multi-pattern) failure" do let(:config) { { 'match' => { "message" => [ "(.*f){20}", "(.*e){20}", "(.*d){20}", "(.*c){20}", "(.*b){20}", "(.*a){25}", "(.*a){24}", "(.*a){23}", "(.*a){22}", "(.*a){21}", "(.*a){25}", "(.*a){24}", "(.*a){23}", "(.*a){22}", "(.*a){21}", "(.*a){25}", "(.*a){24}", "(.*a){23}", "(.*a){22}", "(.*a){21}", "(.*a){20}" ] }, 'timeout_millis' => 750, 'timeout_scope' => 'event' } } sample( 'b' * 15 + 'c' * 15 + 'd' * 15 + 'e' * 15 + ' ' + 'a' * 20 ) do expect( event.get("tags") ).to include("_groktimeout") expect( event.get("tags") ).not_to include("_grokparsefailure") end end describe "tagging on failure" do let(:config) { { 'match' => { "message" => "matchme %{NUMBER:fancy}" }, 'tag_on_failure' => 'not_a_match' } } sample "matchme 1234" do expect( event.get("tags") ).to be nil end sample "this will not be matched" do expect( event.get("tags") ).to include("not_a_match") end end describe "captures named fields even if the whole text matches" do let(:config) { { 'match' => { "message" => "%{DATE_EU:stimestamp}" } } } sample "11/01/01" do expect( event.get("stimestamp") ).to eql "11/01/01" end end describe "allow dashes in capture names" do let(:config) { { 'match' => { "message" => "%{WORD:foo-bar}" } } } sample "hello world" do expect( event.get("foo-bar") ).to eql "hello" end end describe "single value match with duplicate-named fields in pattern" do let(:config) { { 'match' => { "message" => "%{INT:foo}|%{WORD:foo}" } } } sample "hello world" do expect( event.get("foo") ).to be_a(String) end sample "123 world" do expect( event.get("foo") ).to be_a(String) end end describe "break_on_match default should be true" do let(:config) { { 'match' => { "message" => "%{INT:foo}", "somefield" => "%{INT:bar}" } } } let(:data) { Hash("message" => "hello world 123", "somefield" => "testme abc 999") } it 'exits filter after first match' do expect( event.get("foo") ).to eql '123' expect( event.get("bar") ).to be nil end end describe "break_on_match when set to false" do let(:config) { { 'match' => { "message" => "%{INT:foo}", "somefield" => "%{INT:bar}" }, 'break_on_match' => false } } let(:data) { Hash("message" => "hello world 123", "somefield" => "testme abc 999") } it 'should try all patterns' do expect( event.get("foo") ).to eql '123' expect( event.get("bar") ).to eql '999' end end context "break_on_match default for array input with single grok pattern" do let(:config) { { 'match' => { "message" => "%{INT:foo}" }, 'break_on_match' => false } } describe 'fully matching input' do let(:data) { Hash("message" => ["hello world 123", "line 23"]) } # array input -- it 'matches' do expect( event.get("foo") ).to eql ["123", "23"] expect( event.get("tags") ).to be nil end end describe 'partially matching input' do let(:data) { Hash("message" => ["hello world 123", "abc"]) } # array input, one of them matches it 'matches' do expect( event.get("foo") ).to eql "123" expect( event.get("tags") ).to be nil end end end describe "break_on_match = true (default) for array input with multiple grok pattern" do let(:config) { { 'match' => { "message" => ["%{INT:foo}", "%{WORD:bar}"] } } } describe 'matching input' do let(:data) { Hash("message" => ["hello world 123", "line 23"]) } # array input -- it 'matches' do expect( event.get("foo") ).to eql ["123", "23"] expect( event.get("bar") ).to be nil expect( event.get("tags") ).to be nil end end describe 'partially matching input' do let(:data) { Hash("message" => ["hello world", "line 23"]) } # array input, one of them matches it 'matches' do expect( event.get("bar") ).to eql 'hello' expect( event.get("foo") ).to eql "23" expect( event.get("tags") ).to be nil end end end describe "break_on_match = false for array input with multiple grok pattern" do let(:config) { { 'match' => { "message" => ["%{INT:foo}", "%{WORD:bar}"] }, 'break_on_match' => false } } describe 'fully matching input' do let(:data) { Hash("message" => ["hello world 123", "line 23"]) } # array input -- it 'matches' do expect( event.get("foo") ).to eql ["123", "23"] expect( event.get("bar") ).to eql ["hello", "line"] expect( event.get("tags") ).to be nil end end describe 'partially matching input' do let(:data) { Hash("message" => ["hello world", "line 23"]) } # array input, one of them matches it 'matches' do expect( event.get("bar") ).to eql ["hello", "line"] expect( event.get("foo") ).to eql "23" expect( event.get("tags") ).to be nil end end end describe "grok with unicode" do let(:config) { { #'match' => { "message" => "<%{POSINT:syslog_pri}>%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:syslog_hostname} %{PROG:syslog_program}(?:\[%{POSINT:syslog_pid}\])?: %{GREEDYDATA:syslog_message}" } 'match' => { "message" => "<%{POSINT:syslog_pri}>%{SPACE}%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:syslog_hostname} %{PROG:syslog_program}(:?)(?:\\[%{GREEDYDATA:syslog_pid}\\])?(:?) %{GREEDYDATA:syslog_message}" } } } sample "<22>Jan 4 07:50:46 mailmaster postfix/policy-spf[9454]: : SPF permerror (Junk encountered in record 'v=spf1 mx a:mail.domain.no ip4:192.168.0.4 ๏ฟฝall'): Envelope-from: email@domain.no" do expect( event.get("tags") ).to be nil expect( event.get("syslog_pri") ).to eql "22" expect( event.get("syslog_program") ).to eql "postfix/policy-spf" end end describe "grok with nil coerced value" do let(:config) { { 'match' => { "message" => "test (N/A|%{BASE10NUM:duration:float}ms)" } } } sample "test 28.4ms" do expect( event.get("duration") ).to eql 28.4 expect( event.get("tags") ).to be nil end sample "test N/A" do expect( event.to_hash ).not_to include("duration") expect( event.get("tags") ).to be nil end sample "test abc" do expect( event.get("duration") ).to be nil expect( event.get("tags") ).to eql ["_grokparsefailure"] end end describe "grok with nil coerced value and keep_empty_captures" do let(:config) { { 'match' => { "message" => "test (N/A|%{BASE10NUM:duration:float}ms)" }, 'keep_empty_captures' => true } } sample "test N/A" do expect( event.to_hash ).to include("duration") expect( event.get("tags") ).to be nil end end describe "grok with no coercion" do let(:config) { { 'match' => { "message" => "test (N/A|%{BASE10NUM:duration}ms)" }, } } sample "test 28.4ms" do expect( event.get("duration") ).to eql '28.4' expect( event.get("tags") ).to be nil end sample "test N/A" do expect( event.get("duration") ).to be nil expect( event.get("tags") ).to be nil end end describe "opening/closing" do let(:config) { { "match" => {"message" => "A"} } } let(:message) { 'AAA' } it "should close cleanly" do expect { subject.do_close }.not_to raise_error end end describe "after grok when the event is JSON serialised the field values are unchanged" do let(:config) { { 'match' => ["message", "Failed password for (invalid user |)%{USERNAME:username} from %{IP:src_ip} port %{BASE10NUM:port}"], 'remove_field' => ["message","severity"], 'add_tag' => ["ssh_failure"] } } sample('{"facility":"auth","message":"Failed password for testuser from 1.1.1.1 port 22"}') do expect( event.get("username") ).to eql "testuser" expect( event.get("port") ).to eql "22" expect( event.get("src_ip") ).to eql "1.1.1.1" expect( LogStash::Json.dump(event.get('username')) ).to eql "\"testuser\"" expect( event.to_json ).to match %r|"src_ip":"1.1.1.1"| expect( event.to_json ).to match %r|"@timestamp":"#{Regexp.escape(event.get('@timestamp').to_s)}"| expect( event.to_json ).to match %r|"port":"22"| expect( event.to_json ).to match %r|"@version":"1"| expect( event.to_json ).to match %r|"username"|i expect( event.to_json ).to match %r|"testuser"| expect( event.to_json ).to match %r|"tags":\["ssh_failure"\]| end end describe "grok with inline pattern definition successfully extracts fields" do let(:config) { { 'match' => { "message" => "%{APACHE_TIME:timestamp} %{LOGLEVEL:level} %{MY_PATTERN:hindsight}" }, 'pattern_definitions' => { "APACHE_TIME" => "%{DAY} %{MONTH} %{MONTHDAY} %{TIME} %{YEAR}", "MY_PATTERN" => "%{YEAR}" } } } sample "Mon Dec 26 16:22:08 2016 error 2020" do expect( event.get("timestamp") ).to eql "Mon Dec 26 16:22:08 2016" expect( event.get("level") ).to eql "error" expect( event.get("hindsight") ).to eql "2020" end end describe "grok with inline pattern definition overwrites existing pattern definition" do let(:config) { { 'match' => { "message" => "%{APACHE_TIME:timestamp} %{LOGLEVEL:level}" }, # loglevel was previously ([Aa]lert|ALERT|[Tt]... 'pattern_definitions' => { "APACHE_TIME" => "%{DAY} %{MONTH} %{MONTHDAY} %{TIME} %{YEAR}", "LOGLEVEL" => "%{NUMBER}" } } } sample "Mon Dec 26 16:22:08 2016 9999" do expect( event.get("timestamp") ).to eql "Mon Dec 26 16:22:08 2016" expect( event.get("level") ).to eql "9999" end end context 'when timeouts are explicitly disabled' do let(:config) do { "timeout_millis" => 0 } end context 'when given a pathological input', slow: true do let(:message) { "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"} let(:config) { super().merge("match" => { "message" => "(.*a){30}" }) } it 'blocks for at least 3 seconds' do blocking_exception_class = Class.new(::Exception) # avoid RuntimeError expect do Timeout.timeout(3, blocking_exception_class) do subject.filter(event) end end.to raise_exception(blocking_exception_class) end end end end end describe LogStash::Filters::Grok do subject(:grok_filter) { described_class.new(config) } let(:config) { {} } context 'when initialized with `ecs_compatibility => v8`' do let(:config) { super().merge("ecs_compatibility" => "v8", "match" => ["message", "%{SYSLOGLINE}"]) } context '#register' do let(:logger_stub) { double('Logger').as_null_object } before(:each) { allow_any_instance_of(described_class).to receive(:logger).and_return(logger_stub)} it 'logs a helpful warning about the unreleased v8' do grok_filter.register expect(logger_stub).to have_received(:warn).with(a_string_including "preview of the unreleased ECS v8") end end end end describe LogStash::Filters::Grok do describe "(LEGACY)" do describe "patterns in the 'patterns/' dir override core patterns" do let(:pattern_dir) { File.join(LogStash::Environment::LOGSTASH_HOME, "patterns") } let(:has_pattern_dir?) { Dir.exist?(pattern_dir) } before do FileUtils.mkdir(pattern_dir) unless has_pattern_dir? @file = File.new(File.join(pattern_dir, 'grok.pattern'), 'w+') @file.write('WORD \b[2-5]\b')
ruby
Apache-2.0
973a647eb915cb6cb41dc3dca07eeaa02b71dcaf
2026-01-04T17:51:55.085667Z
true
logstash-plugins/logstash-filter-grok
https://github.com/logstash-plugins/logstash-filter-grok/blob/973a647eb915cb6cb41dc3dca07eeaa02b71dcaf/lib/logstash/filters/grok.rb
lib/logstash/filters/grok.rb
# encoding: utf-8 require "logstash/filters/base" require "logstash/namespace" require "logstash/environment" require "logstash/patterns/core" require 'logstash/plugin_mixins/ecs_compatibility_support' require "grok-pure" # rubygem 'jls-grok' require "timeout" # Parse arbitrary text and structure it. # # Grok is currently the best way in Logstash to parse unstructured log # data into something structured and queryable. # # This tool is perfect for syslog logs, apache and other webserver logs, mysql # logs, and in general, any log format that is generally written for humans # and not computer consumption. # # Logstash ships with about 120 patterns by default. You can find them here: # <https://github.com/logstash-plugins/logstash-patterns-core/tree/master/patterns>. You can add # your own trivially. (See the `patterns_dir` setting) # # If you need help building patterns to match your logs, you will find the # <http://grokdebug.herokuapp.com> and <http://grokconstructor.appspot.com/> applications quite useful! # # ==== Grok Basics # # Grok works by combining text patterns into something that matches your # logs. # # The syntax for a grok pattern is `%{SYNTAX:SEMANTIC}` # # The `SYNTAX` is the name of the pattern that will match your text. For # example, `3.44` will be matched by the `NUMBER` pattern and `55.3.244.1` will # be matched by the `IP` pattern. The syntax is how you match. # # The `SEMANTIC` is the identifier you give to the piece of text being matched. # For example, `3.44` could be the duration of an event, so you could call it # simply `duration`. Further, a string `55.3.244.1` might identify the `client` # making a request. # # For the above example, your grok filter would look something like this: # [source,ruby] # %{NUMBER:duration} %{IP:client} # # Optionally you can add a data type conversion to your grok pattern. By default # all semantics are saved as strings. If you wish to convert a semantic's data type, # for example change a string to an integer then suffix it with the target data type. # For example `%{NUMBER:num:int}` which converts the `num` semantic from a string to an # integer. Currently the only supported conversions are `int` and `float`. # # .Examples: # # With that idea of a syntax and semantic, we can pull out useful fields from a # sample log like this fictional http request log: # [source,ruby] # 55.3.244.1 GET /index.html 15824 0.043 # # The pattern for this could be: # [source,ruby] # %{IP:client} %{WORD:method} %{URIPATHPARAM:request} %{NUMBER:bytes} %{NUMBER:duration} # # A more realistic example, let's read these logs from a file: # [source,ruby] # input { # file { # path => "/var/log/http.log" # } # } # filter { # grok { # match => { "message" => "%{IP:client} %{WORD:method} %{URIPATHPARAM:request} %{NUMBER:bytes} %{NUMBER:duration}" } # } # } # # After the grok filter, the event will have a few extra fields in it: # # * `client: 55.3.244.1` # * `method: GET` # * `request: /index.html` # * `bytes: 15824` # * `duration: 0.043` # # ==== Regular Expressions # # Grok sits on top of regular expressions, so any regular expressions are valid # in grok as well. The regular expression library is Oniguruma, and you can see # the full supported regexp syntax https://github.com/kkos/oniguruma/blob/master/doc/RE[on the Oniguruma # site]. # # ==== Custom Patterns # # Sometimes logstash doesn't have a pattern you need. For this, you have # a few options. # # First, you can use the Oniguruma syntax for named capture which will # let you match a piece of text and save it as a field: # [source,ruby] # (?<field_name>the pattern here) # # For example, postfix logs have a `queue id` that is an 10 or 11-character # hexadecimal value. I can capture that easily like this: # [source,ruby] # (?<queue_id>[0-9A-F]{10,11}) # # Alternately, you can create a custom patterns file. # # * Create a directory called `patterns` with a file in it called `extra` # (the file name doesn't matter, but name it meaningfully for yourself) # * In that file, write the pattern you need as the pattern name, a space, then # the regexp for that pattern. # # For example, doing the postfix queue id example as above: # [source,ruby] # # contents of ./patterns/postfix: # POSTFIX_QUEUEID [0-9A-F]{10,11} # # Then use the `patterns_dir` setting in this plugin to tell logstash where # your custom patterns directory is. Here's a full example with a sample log: # [source,ruby] # Jan 1 06:25:43 mailserver14 postfix/cleanup[21403]: BEF25A72965: message-id=<20130101142543.5828399CCAF@mailserver14.example.com> # [source,ruby] # filter { # grok { # patterns_dir => ["./patterns"] # match => { "message" => "%{SYSLOGBASE} %{POSTFIX_QUEUEID:queue_id}: %{GREEDYDATA:syslog_message}" } # } # } # # The above will match and result in the following fields: # # * `timestamp: Jan 1 06:25:43` # * `logsource: mailserver14` # * `program: postfix/cleanup` # * `pid: 21403` # * `queue_id: BEF25A72965` # * `syslog_message: message-id=<20130101142543.5828399CCAF@mailserver14.example.com>` # # The `timestamp`, `logsource`, `program`, and `pid` fields come from the # `SYSLOGBASE` pattern which itself is defined by other patterns. # # Another option is to define patterns _inline_ in the filter using `pattern_definitions`. # This is mostly for convenience and allows user to define a pattern which can be used just in that # filter. This newly defined patterns in `pattern_definitions` will not be available outside of that particular `grok` filter. # class LogStash::Filters::Grok < LogStash::Filters::Base include LogStash::PluginMixins::ECSCompatibilitySupport config_name "grok" # A hash of matches of field => value # # For example: # [source,ruby] # filter { # grok { match => { "message" => "Duration: %{NUMBER:duration}" } } # } # # If you need to match multiple patterns against a single field, the value can be an array of patterns # [source,ruby] # filter { # grok { match => { "message" => [ "Duration: %{NUMBER:duration}", "Speed: %{NUMBER:speed}" ] } } # } # config :match, :validate => :hash, :default => {} # # Logstash ships by default with a bunch of patterns, so you don't # necessarily need to define this yourself unless you are adding additional # patterns. You can point to multiple pattern directories using this setting. # Note that Grok will read all files in the directory matching the patterns_files_glob # and assume it's a pattern file (including any tilde backup files). # [source,ruby] # patterns_dir => ["/opt/logstash/patterns", "/opt/logstash/extra_patterns"] # # Pattern files are plain text with format: # [source,ruby] # NAME PATTERN # # For example: # [source,ruby] # NUMBER \d+ # # The patterns are loaded when the pipeline is created. config :patterns_dir, :validate => :array, :default => [] # A hash of pattern-name and pattern tuples defining custom patterns to be used by # the current filter. Patterns matching existing names will override the pre-existing # definition. Think of this as inline patterns available just for this definition of # grok config :pattern_definitions, :validate => :hash, :default => {} # Glob pattern, used to select the pattern files in the directories # specified by patterns_dir config :patterns_files_glob, :validate => :string, :default => "*" # Break on first match. The first successful match by grok will result in the # filter being finished. If you want grok to try all patterns (maybe you are # parsing different things), then set this to false. config :break_on_match, :validate => :boolean, :default => true # If `true`, only store named captures from grok. config :named_captures_only, :validate => :boolean, :default => true # If `true`, keep empty captures as event fields. config :keep_empty_captures, :validate => :boolean, :default => false # Define the target field for placing the matched captures. # If this setting is omitted, data gets stored at the root (top level) of the event. config :target, :validate => :string # Append values to the `tags` field when there has been no # successful match config :tag_on_failure, :validate => :array, :default => ["_grokparsefailure"] # Attempt to terminate regexps after this amount of time. # This applies per pattern if multiple patterns are applied # This will never timeout early, but may take a little longer to timeout. # Actual timeout is approximate based on a 250ms quantization. # Set to 0 to disable timeouts config :timeout_millis, :validate => :number, :default => 30000 # When multiple patterns are provided to `match`, # the timeout has historically applied to _each_ pattern, incurring overhead # for each and every pattern that is attempted; when the grok filter is # configured with `timeout_scope => 'event'`, the plugin instead enforces # a single timeout across all attempted matches on the event, so it can # achieve similar safeguard against runaway matchers with significantly # less overhead. # It's usually better to scope the timeout for the whole event. config :timeout_scope, :validate => %w(pattern event), :default => "pattern" # Tag to apply if a grok regexp times out. config :tag_on_timeout, :validate => :string, :default => '_groktimeout' # The fields to overwrite. # # This allows you to overwrite a value in a field that already exists. # # For example, if you have a syslog line in the `message` field, you can # overwrite the `message` field with part of the match like so: # [source,ruby] # filter { # grok { # match => { "message" => "%{SYSLOGBASE} %{DATA:message}" } # overwrite => [ "message" ] # } # } # # In this case, a line like `May 29 16:37:11 sadness logger: hello world` # will be parsed and `hello world` will overwrite the original message. config :overwrite, :validate => :array, :default => [] def register # a cache of capture name handler methods. @handlers = {} @patternfiles = [] # Have (default) patterns_path show first. Last-in pattern definitions wins # this will let folks redefine built-in patterns at runtime @patternfiles += patterns_files_from_paths(patterns_path, "*") @patternfiles += patterns_files_from_paths(@patterns_dir, @patterns_files_glob) @patterns = Hash.new { |h,k| h[k] = [] } @logger.debug("Match data", :match => @match) @metric_match_fields = metric.namespace(:patterns_per_field) @match.each do |field, patterns| patterns = [patterns] if patterns.is_a?(String) @metric_match_fields.gauge(field, patterns.length) @logger.trace? && @logger.trace("Grok compile", :field => field, :patterns => patterns) patterns.each do |pattern| @logger.debug? && @logger.debug("regexp: #{@type}/#{field}", :pattern => pattern) grok = Grok.new grok.logger = @logger add_patterns_from_files(@patternfiles, grok) add_patterns_from_inline_definition(@pattern_definitions, grok) grok.compile(pattern, @named_captures_only) @patterns[field] << grok end end # @match.each @match_counter = metric.counter(:matches) @failure_counter = metric.counter(:failures) @target = "[#{@target.strip}]" if @target && @target !~ /\[.*?\]/ @timeout = @timeout_millis > 0.0 ? RubyTimeout.new(@timeout_millis) : NoopTimeout::INSTANCE @matcher = ( @timeout_scope.eql?('event') ? EventTimeoutMatcher : PatternTimeoutMatcher ).new(self) end # def register def filter(event) matched = false @logger.debug? && @logger.debug("Running grok filter", :event => event.to_hash) @patterns.each do |field, groks| if match(groks, field, event) matched = true break if @break_on_match end end if matched @match_counter.increment(1) filter_matched(event) else @failure_counter.increment(1) @tag_on_failure.each {|tag| event.tag(tag)} end @logger.debug? && @logger.debug("Event now: ", :event => event.to_hash) rescue GrokTimeoutException => e @logger.warn(e.message) metric.increment(:timeouts) event.tag(@tag_on_timeout) end # def filter def close end private # The default pattern paths, depending on environment. def patterns_path patterns_path = [] case ecs_compatibility when :disabled patterns_path << LogStash::Patterns::Core.path # :legacy when :v1 patterns_path << LogStash::Patterns::Core.path('ecs-v1') when :v8 @logger.warn("ECS v8 support is a preview of the unreleased ECS v8, and uses the v1 patterns. When Version 8 of the Elastic Common Schema becomes available, this plugin will need to be updated") patterns_path << LogStash::Patterns::Core.path('ecs-v1') else fail(NotImplementedError, "ECS #{ecs_compatibility} is not supported by this plugin.") end # allow plugin to be instantiated outside the LS environment (in tests) if defined? LogStash::Environment.pattern_path patterns_path << LogStash::Environment.pattern_path("*") end patterns_path end def match(groks, field, event) input = event.get(field) if input.is_a?(Array) success = false input.each do |input| success |= match_against_groks(groks, field, input, event) end return success else match_against_groks(groks, field, input, event) end rescue StandardError => e @logger.warn("Grok regexp threw exception", :message => e.message, :exception => e.class, :backtrace => e.backtrace) return false end def match_against_groks(groks, field, input, event) # Convert anything else to string (number, hash, etc) context = GrokContext.new(field, input.to_s) @matcher.match(context, groks, event, @break_on_match) end # Internal (base) helper to handle the global timeout switch. # @private class Matcher def initialize(filter) @filter = filter end def match(context, groks, event, break_on_match) matched = false groks.each do |grok| context.set_grok(grok) matched = execute(context, grok) if matched grok.capture(matched) { |field, value| @filter.handle(field, value, event) } break if break_on_match end end matched end protected def execute(context, grok) grok.execute(context.input) end end # @private class EventTimeoutMatcher < Matcher # @override def match(context, groks, event, break_on_match) @filter.with_timeout(context) { super } end end # @private class PatternTimeoutMatcher < Matcher # @override def execute(context, grok) @filter.with_timeout(context) { super } end end def handle(field, value, event) return if (value.nil? || (value.is_a?(String) && value.empty?)) unless @keep_empty_captures target_field = @target ? "#{@target}[#{field}]" : field if @overwrite.include?(field) event.set(target_field, value) else v = event.get(target_field) if v.nil? event.set(target_field, value) elsif v.is_a?(Array) # do not replace the code below with: # event[field] << value # this assumes implementation specific feature of returning a mutable object # from a field ref which should not be assumed and will change in the future. v << value event.set(target_field, v) elsif v.is_a?(String) # Promote to array since we aren't overwriting. event.set(target_field, [v, value]) else @logger.debug("Not adding matched value - found existing (#{v.class})", :field => target_field, :value => value) end end end public :handle def patterns_files_from_paths(paths, glob) patternfiles = [] @logger.debug("Grok patterns path", :paths => paths) paths.each do |path| if File.directory?(path) path = File.join(path, glob) end Dir.glob(path).each do |file| @logger.trace("Grok loading patterns from file", :path => file) if File.directory?(file) @logger.debug("Skipping path because it is a directory", :path => file) else patternfiles << file end end end patternfiles end # def patterns_files_from_paths def add_patterns_from_files(paths, grok) paths.each do |path| if !File.exists?(path) raise "Grok pattern file does not exist: #{path}" end grok.add_patterns_from_file(path) end end # def add_patterns_from_files def add_patterns_from_inline_definition(pattern_definitions, grok) pattern_definitions.each do |name, pattern| next if pattern.nil? grok.add_pattern(name, pattern.chomp) end end class TimeoutError < RuntimeError; end class GrokTimeoutException < Exception attr_reader :grok, :field, :value def initialize(grok, field, value) @grok = grok @field = field @value = value end def message "Timeout executing grok '#{@grok.pattern}' against field '#{field}' with value '#{trunc_value}'!" end def trunc_value if value.size <= 255 # If no more than 255 chars value else "Value too large to output (#{value.bytesize} bytes)! First 255 chars are: #{value[0..255]}" end end end def with_timeout(context, &block) @timeout.exec(&block) rescue TimeoutError => error handle_timeout(context, error) end public :with_timeout def handle_timeout(context, error) raise GrokTimeoutException.new(context.grok, context.field, context.input) end # @private class GrokContext attr_reader :grok, :field, :input def initialize(field, input) @field = field @input = input end def set_grok(grok) @grok = grok end end # @private class NoopTimeout INSTANCE = new def exec yield end end # @private class RubyTimeout def initialize(timeout_millis) # divide by float to allow fractional seconds, the Timeout class timeout value is in seconds but the underlying # executor resolution is in microseconds so fractional second parameter down to microseconds is possible. # see https://github.com/jruby/jruby/blob/9.2.7.0/core/src/main/java/org/jruby/ext/timeout/Timeout.java#L125 @timeout_seconds = timeout_millis / 1000.0 end def exec(&block) Timeout.timeout(@timeout_seconds, TimeoutError, &block) end end end # class LogStash::Filters::Grok
ruby
Apache-2.0
973a647eb915cb6cb41dc3dca07eeaa02b71dcaf
2026-01-04T17:51:55.085667Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/test/test_ssdp_search.rb
test/test_ssdp_search.rb
require 'test/unit' require 'test/utilities' require 'ssdp' class TestSSDPSearch < SSDP::TestCase def test_self_parse_search search = SSDP::Search.parse util_search assert_equal Time, search.date.class assert_equal 'upnp:rootdevice', search.target assert_equal 2, search.wait_time end def test_inspect search = SSDP::Search.parse util_search id = search.object_id.to_s 16 expected = "#<SSDP::Search:0x#{id} upnp:rootdevice>" assert_equal expected, search.inspect end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/test/test_ssdp.rb
test/test_ssdp.rb
require 'test/unit' require_relative 'utilities' require 'ssdp' require 'upnp_savon/test_utilities' class TestSSDP < SSDP::TestCase def setup super @ssdp = SSDP.new @ssdp.timeout = 0 end def teardown @ssdp.listener.kill if @ssdp.listener end def test_discover socket = UPnPSavon::FakeSocket.new util_notify @ssdp.socket = socket notifications = @ssdp.discover assert_equal [], socket.sent assert_equal 1, notifications.length assert_equal 'upnp:rootdevice', notifications.first.type end def test_listen @ssdp.socket = UPnPSavon::FakeSocket.new util_notify @ssdp.listen notification = @ssdp.queue.pop assert_equal 'upnp:rootdevice', notification.type end def test_new_socket SSDP.send :const_set, :UDPSocket, UPnPSavon::FakeSocket socket = @ssdp.new_socket ttl = [@ssdp.ttl].pack 'i' expected = [ [Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, "\357\377\377\372\000\000\000\000"], [Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, "\000"], [Socket::IPPROTO_IP, Socket::IP_MULTICAST_TTL, ttl], [Socket::IPPROTO_IP, Socket::IP_TTL, ttl], ] assert_equal expected, socket.socket_options ensure SSDP.send :remove_const, :UDPSocket end def test_parse_bad assert_raise SSDP::Error do @ssdp.parse '' end end def test_parse_notification notification = @ssdp.parse util_notify assert_equal 'upnp:rootdevice', notification.type end def test_parse_notification_byebye notification = @ssdp.parse util_notify assert_equal 'upnp:rootdevice', notification.type end def test_parse_search response = @ssdp.parse util_search assert_equal 'upnp:rootdevice', response.target end def test_parse_search_response response = @ssdp.parse util_search_response assert_equal 'upnp:rootdevice', response.target end def test_search socket = UPnPSavon::FakeSocket.new util_search_response @ssdp.socket = socket responses = @ssdp.search m_search = <<-M_SEARCH M-SEARCH * HTTP/1.1\r HOST: 239.255.255.250:1900\r MAN: \"ssdp:discover\"\r MX: 0\r ST: ssdp:all\r \r M_SEARCH assert_equal [[m_search, 0, @ssdp.broadcast, @ssdp.port]], socket.sent assert_equal 1, responses.length assert_equal 'upnp:rootdevice', responses.first.target end def test_search_device socket = UPnPSavon::FakeSocket.new util_search_response @ssdp.socket = socket responses = @ssdp.search [:device, 'MyDevice.1'] m_search = <<-M_SEARCH M-SEARCH * HTTP/1.1\r HOST: 239.255.255.250:1900\r MAN: \"ssdp:discover\"\r MX: 0\r ST: urn:schemas-upnp-org:device:MyDevice.1\r \r M_SEARCH assert_equal [[m_search, 0, @ssdp.broadcast, @ssdp.port]], socket.sent end def test_search_root socket = UPnPSavon::FakeSocket.new util_search_response @ssdp.socket = socket responses = @ssdp.search :root m_search = <<-M_SEARCH M-SEARCH * HTTP/1.1\r HOST: 239.255.255.250:1900\r MAN: \"ssdp:discover\"\r MX: 0\r ST: upnp:rootdevice\r \r M_SEARCH assert_equal [[m_search, 0, @ssdp.broadcast, @ssdp.port]], socket.sent end def test_search_service socket = UPnPSavon::FakeSocket.new util_search_response @ssdp.socket = socket responses = @ssdp.search [:service, 'MyService.1'] m_search = <<-M_SEARCH M-SEARCH * HTTP/1.1\r HOST: 239.255.255.250:1900\r MAN: \"ssdp:discover\"\r MX: 0\r ST: urn:schemas-upnp-org:service:MyService.1\r \r M_SEARCH assert_equal [[m_search, 0, @ssdp.broadcast, @ssdp.port]], socket.sent end def test_search_ssdp socket = UPnPSavon::FakeSocket.new util_search_response @ssdp.socket = socket responses = @ssdp.search 'ssdp:foo' m_search = <<-M_SEARCH M-SEARCH * HTTP/1.1\r HOST: 239.255.255.250:1900\r MAN: \"ssdp:discover\"\r MX: 0\r ST: ssdp:foo\r \r M_SEARCH assert_equal [[m_search, 0, @ssdp.broadcast, @ssdp.port]], socket.sent end def test_search_urn socket = UPnPSavon::FakeSocket.new util_search_response @ssdp.socket = socket responses = @ssdp.search 'urn:foo' m_search = <<-M_SEARCH M-SEARCH * HTTP/1.1\r HOST: 239.255.255.250:1900\r MAN: \"ssdp:discover\"\r MX: 0\r ST: urn:foo\r \r M_SEARCH assert_equal [[m_search, 0, @ssdp.broadcast, @ssdp.port]], socket.sent end def test_search_uuid socket = UPnPSavon::FakeSocket.new util_search_response @ssdp.socket = socket responses = @ssdp.search 'uuid:foo' m_search = <<-M_SEARCH M-SEARCH * HTTP/1.1\r HOST: 239.255.255.250:1900\r MAN: \"ssdp:discover\"\r MX: 0\r ST: uuid:foo\r \r M_SEARCH assert_equal [[m_search, 0, @ssdp.broadcast, @ssdp.port]], socket.sent end def test_send_notify socket = UPnPSavon::FakeSocket.new @ssdp.socket = socket uri = 'http://127.255.255.255:65536/description' device = UPnPSavon::Device.new 'TestDevice', 'test device' @ssdp.send_notify uri, 'upnp:rootdevice', device search = <<-SEARCH NOTIFY * HTTP/1.1\r HOST: 239.255.255.250:1900\r CACHE-CONTROL: max-age=120\r LOCATION: #{uri}\r NT: upnp:rootdevice\r NTS: ssdp:alive\r SERVER: Ruby SSDP/#{SSDP::VERSION} UPnP/1.0 #{util_device_version}\r USN: #{device.name}::upnp:rootdevice\r \r SEARCH assert_equal [[search, 0, @ssdp.broadcast, @ssdp.port]], socket.sent end def test_send_response socket = UPnPSavon::FakeSocket.new @ssdp.socket = socket uri = 'http://127.255.255.255:65536/description' device = UPnPSavon::Device.new 'TestDevice', 'test device' @ssdp.send_response uri, 'upnp:rootdevice', device.name, device search = <<-SEARCH HTTP/1.1 200 OK\r CACHE-CONTROL: max-age=120\r EXT:\r LOCATION: #{uri}\r SERVER: Ruby SSDP/#{SSDP::VERSION} UPnP/1.0 #{util_device_version}\r ST: upnp:rootdevice\r NTS: ssdp:alive\r USN: #{device.name}\r Content-Length: 0\r \r SEARCH assert_equal [[search, 0, @ssdp.broadcast, @ssdp.port]], socket.sent end def test_send_search socket = UPnPSavon::FakeSocket.new @ssdp.socket = socket @ssdp.send_search 'bunnies' search = <<-SEARCH M-SEARCH * HTTP/1.1\r HOST: 239.255.255.250:1900\r MAN: \"ssdp:discover\"\r MX: 0\r ST: bunnies\r \r SEARCH assert_equal [[search, 0, @ssdp.broadcast, @ssdp.port]], socket.sent end def test_stop_listening thread = Thread.new do sleep end @ssdp.listener = thread @ssdp.stop_listening assert_equal false, thread.alive? assert_equal nil, @ssdp.listener end def util_device_version "UPnPSavon::Device::TestDevice/#{UPnPSavon::Device::TestDevice::VERSION}" end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/test/test_ssdp_response.rb
test/test_ssdp_response.rb
require 'test/unit' require 'test/utilities' require 'SSDP' class TestSSDPResponse < SSDP::TestCase def setup super @response = SSDP::Response.parse util_search_response end def test_self_parse_notify assert_equal Time, @response.date.class assert_equal true, @response.ext assert_equal URI.parse('http://example.com/root_device.xml'), @response.location assert_equal 10, @response.max_age assert_equal 'uuid:BOGUS::upnp:rootdevice', @response.name assert_equal 'OS/5 UPnP/1.0 product/7', @response.server assert_equal 'upnp:rootdevice', @response.target end def test_inspect id = @response.object_id.to_s 16 expected = "#<SSDP::Response:0x#{id} upnp:rootdevice http://example.com/root_device.xml>" assert_equal expected, @response.inspect end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/test/test_ssdp_notification.rb
test/test_ssdp_notification.rb
require 'test/unit' require 'test/utilities' require 'ssdp' class TestSSDPNotification < SSDP::TestCase def test_self_parse_notify notification = SSDP::Notification.parse util_notify assert_equal Time, notification.date.class assert_equal '239.255.255.250', notification.host assert_equal '1900', notification.port assert_equal URI.parse('http://example.com/root_device.xml'), notification.location assert_equal 10, notification.max_age assert_equal 'uuid:BOGUS::upnp:rootdevice', notification.name assert_equal 'upnp:rootdevice', notification.type assert_equal 'OS/5 SSDP/1.0 product/7', notification.server assert_equal 'ssdp:alive', notification.sub_type end def test_self_parse_notify_byebye notification = SSDP::Notification.parse util_notify_byebye assert_equal Time, notification.date.class assert_equal '239.255.255.250', notification.host assert_equal '1900', notification.port assert_equal nil, notification.location assert_equal nil, notification.max_age assert_equal 'uuid:BOGUS::upnp:rootdevice', notification.name assert_equal 'upnp:rootdevice', notification.type assert_equal 'ssdp:byebye', notification.sub_type end def test_alive_eh notification = SSDP::Notification.parse util_notify assert notification.alive? notification = SSDP::Notification.parse util_notify_byebye assert !notification.alive? end def test_byebye_eh notification = SSDP::Notification.parse util_notify_byebye assert notification.byebye? notification = SSDP::Notification.parse util_notify assert !notification.byebye? end def test_inspect notification = SSDP::Notification.parse util_notify id = notification.object_id.to_s 16 expected = "#<SSDP::Notification:0x#{id} upnp:rootdevice ssdp:alive http://example.com/root_device.xml>" assert_equal expected, notification.inspect end def test_inspect_byebye notification = SSDP::Notification.parse util_notify_byebye id = notification.object_id.to_s 16 expected = "#<SSDP::Notification:0x#{id} upnp:rootdevice ssdp:byebye>" assert_equal expected, notification.inspect end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/features/support/common.rb
features/support/common.rb
Given /^I have a non-local IP address$/ do @local_ip, @port = local_ip_and_port @local_ip.should_not be_nil @local_ip.should_not match /^127.0.0/ end Given /^a UDP port on that IP is free$/ do @port.should_not be_nil end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/features/support/fake_upnp_device_collection.rb
features/support/fake_upnp_device_collection.rb
require 'singleton' require 'socket' require 'ipaddr' require_relative '../../lib/playful/ssdp/network_constants' class FakeUPnPDeviceCollection include Singleton include Playful::SSDP::NetworkConstants attr_accessor :respond_with def initialize @response = '' @ssdp_listen_thread = nil @serve_description = false @local_ip, @local_port = local_ip_and_port end def expect_discovery(type) case type when :m_search end end def stop_ssdp_listening puts "<#{self.class}> Stopping..." @ssdp_listen_thread.kill if @ssdp_listen_thread && @ssdp_listen_thread.alive? puts "<#{self.class}> Stopped." end # @return [Thread] The thread that's doing the listening. def start_ssdp_listening multicast_socket = setup_multicast_socket multicast_socket.bind(MULTICAST_IP, MULTICAST_PORT) ttl = [4].pack 'i' unicast_socket = UDPSocket.open unicast_socket.setsockopt(Socket::IPPROTO_IP, Socket::IP_MULTICAST_TTL, ttl) @ssdp_listen_thread = Thread.new do loop do text, sender = multicast_socket.recvfrom(1024) #puts "<#{self.class}> received text:\n#{text} from #{sender}" #if text =~ /ST: upnp:rootdevice/ #if text =~ /#{@response}/m if text =~ /M-SEARCH.*#{@local_ip}/m puts "<#{self.class}> received text:\n#{text} from #{sender}" return_port, return_ip = sender[1], sender[2] puts "<#{self.class}> sending response\n#{@response}\n back to: #{return_ip}:#{return_port}" unicast_socket.send(@response, 0, return_ip, return_port) #multicast_socket.close end end end end def start_serving_description =begin tcp_server = TCPServer.new('0.0.0.0', 4567) @serve_description = true while @serve_description @description_serve_thread = Thread.start(tcp_server.accept) do |s| print(s, " is accepted\n") s.write(Time.now) print(s, " is gone\n") s.close end end =end require 'webrick' @description_server = WEBrick::HTTPServer.new(Port: 4567) trap('INT') { @description_server.shutdown } @description_server.mount_proc '/' do |req, res| res.body = "<start>\n</start>" end @description_server.start end def stop_serving_description =begin @serve_description = false if @description_serve_thread && @description_serve_thread.alive? @description_serve_thread.join end =end @description_server.stop end def setup_multicast_socket membership = IPAddr.new(MULTICAST_IP).hton + IPAddr.new('0.0.0.0').hton ttl = [4].pack 'i' socket = UDPSocket.new socket.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, membership) socket.setsockopt(Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, "\000") socket.setsockopt(Socket::IPPROTO_IP, Socket::IP_MULTICAST_TTL, ttl) socket.setsockopt(Socket::IPPROTO_IP, Socket::IP_TTL, ttl) socket end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/features/support/env.rb
features/support/env.rb
require 'socket' require 'log_buddy' require_relative '../../lib/playful/control_point' def local_ip_and_port orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true UDPSocket.open do |s| s.connect '64.233.187.99', 1 s.addr.last [s.addr.last, s.addr[1]] end ensure Socket.do_not_reverse_lookup = orig end ENV['RUBY_UPNP_ENV'] = 'testing'
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/features/support/world_extensions.rb
features/support/world_extensions.rb
module HelperStuff def control_point @control_point ||= Playful::ControlPoint.new end def fake_device_collection @fake_device_collection ||= FakeUPnPDeviceCollection.instance end def local_ip @local_ip ||= local_ip_and_port.first end end World(HelperStuff)
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/features/step_definitions/device_steps.rb
features/step_definitions/device_steps.rb
When /^I start my device on that IP address and port$/ do @device = Playful::Device.new(@local_ip, @port) @device.start.should be_true end Then /^the device multicasts a discovery message$/ do pending # express the regexp above with the code you wish you had end Given /^I don't have an IP address$/ do pending # express the regexp above with the code you wish you had end When /^I start the device$/ do pending # express the regexp above with the code you wish you had end Then /^I get an error message saying I don't have an IP address$/ do pending # express the regexp above with the code you wish you had end Given /^I have a local\-link IP address$/ do pending # express the regexp above with the code you wish you had end Then /^the device starts running normally$/ do pending # express the regexp above with the code you wish you had end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/features/step_definitions/control_point_steps.rb
features/step_definitions/control_point_steps.rb
When /^I create my control point$/ do @control_point = Playful::ControlPoint.new end When /^tell it to find all root devices$/ do @control_point.find_devices(:root, 5) end When /^tell it to find all services$/ do @control_point.find_services end Then /^it gets a list of root devices$/ do @control_point.device_list.should_not be_empty end Then /^it gets a list of services$/ do @control_point.services.should_not be_empty end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/features/step_definitions/device_discovery_steps.rb
features/step_definitions/device_discovery_steps.rb
require_relative '../support/fake_upnp_device_collection' require 'cucumber/rspec/doubles' Thread.abort_on_exception = true Playful::SSDP.log = false Given /^there's at least (\d+) root device in my network$/ do |device_count| fake_device_collection.respond_with = <<-ROOT_DEVICE HTTP/1.1 200 OK\r CACHE-CONTROL: max-age=1200\r DATE: Mon, 26 Sep 2011 06:40:19 GMT\r LOCATION: http://#{local_ip}:4567\r SERVER: Linux-i386-2.6.38-10-generic-pae, UPnP/1.0, PMS/1.25.1\r ST: upnp:rootdevice\r EXT:\r USN: uuid:3c202906-992d-3f0f-b94c-90e1902a136d::upnp:rootdevice\r Content-Length: 0\r ROOT_DEVICE Thread.start { fake_device_collection.start_ssdp_listening } Thread.start { fake_device_collection.start_serving_description } sleep 0.2 end When /^I come online$/ do control_point.should be_a Playful::ControlPoint end Then /^I should discover at least (\d+) root device$/ do |device_count| control_point.find_devices(:root) fake_device_collection.stop_ssdp_listening fake_device_collection.stop_serving_description control_point.device_list.should have_at_least(device_count.to_i).items end Then /^the location of that device should match my fake device's location$/ do locations = control_point.device_list.map { |device| device[:location] } locations.should include "http://#{local_ip}:4567" end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/spec/spec_helper.rb
spec/spec_helper.rb
require 'simplecov' SimpleCov.start require 'coveralls' Coveralls.wear! $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |file| require file } ENV['RUBY_UPNP_ENV'] = 'testing' RSpec.configure do |config| #config.raise_errors_for_deprecations! end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/spec/support/search_responses.rb
spec/support/search_responses.rb
SSDP_SEARCH_RESPONSES_PARSED = { root_device1: { cache_control: 'max-age=1200', date: 'Mon, 26 Sep 2011 06:40:19 GMT', location: 'http://192.168.10.3:5001/description/fetch', server: 'Linux-i386-2.6.38-10-generic-pae, UPnP/1.0, PMS/1.25.1', st: 'upnp:rootdevice', ext: nil, usn: 'uuid:3c202906-992d-3f0f-b94c-90e1902a136d::upnp:rootdevice', content_length: 0 }, root_device2: { cache_control: 'max-age=1200', date: 'Mon, 26 Sep 2011 06:40:20 GMT', location: 'http://192.168.10.4:5001/description/fetch', server: 'Linux-i386-2.6.38-10-generic-pae, UPnP/1.0, PMS/1.25.1', st: 'upnp:rootdevice', ext: nil, usn: 'uuid:3c202906-992d-3f0f-b94c-90e1902a136e::upnp:rootdevice', content_length: 0 }, media_server: { cache_control: 'max-age=1200', date: 'Mon, 26 Sep 2011 06:40:21 GMT', location: 'http://192.168.10.3:5001/description/fetch', server: 'Linux-i386-2.6.38-10-generic-pae, UPnP/1.0, PMS/1.25.1', st: 'urn:schemas-upnp-org:device:MediaServer:1', ext: nil, usn: 'uuid:3c202906-992d-3f0f-b94c-90e1902a136d::urn:schemas-upnp-org:device:MediaServer:1', content_length: 0 } } SSDP_DESCRIPTIONS = { root_device1: { 'root' => { 'specVersion' => { 'major' => '1', 'minor' => '0' }, 'URLBase' => 'http://192.168.10.3:5001/', 'device' => { 'dlna:X_DLNADOC' => %w[DMS-1.50 M-DMS-1.50], 'deviceType' => 'urn:schemas-upnp-org:device:MediaServer:1', 'friendlyName' => 'PS3 Media Server [gutenberg]', 'manufacturer' => 'PMS', 'manufacturerURL' => 'http://ps3mediaserver.blogspot.com', 'modelDescription' => 'UPnP/AV 1.0 Compliant Media Server', 'modelName' => 'PMS', 'modelNumber' => '01', 'modelURL' => 'http://ps3mediaserver.blogspot.com', 'serialNumber' => nil, 'UPC' => nil, 'UDN' => 'uuid:3c202906-992d-3f0f-b94c-90e1902a136d', 'iconList' => { 'icon' => { 'mimetype' => 'image/jpeg', 'width' => '120', 'height' => '120', 'depth' => '24', 'url' => '/images/icon-256.png' } }, 'presentationURL' => 'http://192.168.10.3:5001/console/index.html', 'serviceList' => { 'service' => [ { 'serviceType' => 'urn:schemas-upnp-org:service:ContentDirectory:1', 'serviceId' => 'urn:upnp-org:serviceId:ContentDirectory', 'SCPDURL' => '/UPnP_AV_ContentDirectory_1.0.xml', 'controlURL' => '/upnp/control/content_directory', 'eventSubURL' => '/upnp/event/content_directory' }, { 'serviceType' => 'urn:schemas-upnp-org:service:ConnectionManager:1', 'serviceId' => 'urn:upnp-org:serviceId:ConnectionManager', 'SCPDURL' => '/UPnP_AV_ConnectionManager_1.0.xml', 'controlURL' => '/upnp/control/connection_manager', 'eventSubURL' => '/upnp/event/connection_manager' } ] } }, '@xmlns:dlna' => 'urn:schemas-dlna-org:device-1-0', '@xmlns' => 'urn:schemas-upnp-org:device-1-0' } } } ROOT_DEVICE1 = <<-RD HTTP/1.1 200 OK CACHE-CONTROL: max-age=1200 DATE: Mon, 26 Sep 2011 06:40:19 GMT LOCATION: http://1.2.3.4:5678/description/fetch SERVER: Linux-i386-2.6.38-10-generic-pae, UPnP/1.0, PMS/1.25.1 ST: upnp:rootdevice EXT: USN: uuid:3c202906-992d-3f0f-b94c-90e1902a136d::upnp:rootdevice Content-Length: 0 RD ROOT_DEVICE2 = <<-RD HTTP/1.1 200 OK CACHE-CONTROL: max-age=1200 DATE: Mon, 26 Sep 2011 06:40:20 GMT LOCATION: http://1.2.3.4:5678/description/fetch SERVER: Linux-i386-2.6.38-10-generic-pae, UPnP/1.0, PMS/1.25.1 ST: upnp:rootdevice EXT: USN: uuid:3c202906-992d-3f0f-b94c-90e1902a136e::upnp:rootdevice Content-Length: 0 RD MEDIA_SERVER = <<-MD HTTP/1.1 200 OK CACHE-CONTROL: max-age=1200 DATE: Mon, 26 Sep 2011 06:40:21 GMT LOCATION: http://1.2.3.4:5678/description/fetch SERVER: Linux-i386-2.6.38-10-generic-pae, UPnP/1.0, PMS/1.25.1 ST: urn:schemas-upnp-org:device:MediaServer:1 EXT: USN: uuid:3c202906-992d-3f0f-b94c-90e1902a136d::urn:schemas-upnp-org:device:MediaServer: Content-Length: 0 MD RESPONSES = { root_device1: ROOT_DEVICE1, root_device2: ROOT_DEVICE2, media_server: MEDIA_SERVER }
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/spec/unit/core_ext/to_upnp_s_spec.rb
spec/unit/core_ext/to_upnp_s_spec.rb
require 'spec_helper' require 'core_ext/to_upnp_s' describe Hash do describe '#to_upnp_s' do context ':uuid as key' do it "returns a String like 'uuid:[Hash value]'" do expect({ uuid: '12345' }.to_upnp_s).to eq 'uuid:12345' end it "doesn't check if the Hash value is legit" do expect({ uuid: '' }.to_upnp_s).to eq 'uuid:' end end context ':device_type as key' do context 'domain name not given' do it "returns a String like 'urn:schemas-upnp-org:device:[device type]'" do expect({ device_type: '12345' }.to_upnp_s). to eq 'urn:schemas-upnp-org:device:12345' end it "doesn't check if the Hash value is legit" do expect({ device_type: '' }.to_upnp_s).to eq 'urn:schemas-upnp-org:device:' end end context 'domain name given' do it "returns a String like 'urn:[domain name]:device:[device type]'" do expect({ device_type: '12345', domain_name: 'my-domain' }.to_upnp_s). to eq 'urn:my-domain:device:12345' end it "doesn't check if the Hash value is legit" do expect({ device_type: '', domain_name: 'stuff' }.to_upnp_s). to eq 'urn:stuff:device:' end end end context ':service_type as key' do context 'domain name not given' do it "returns a String like 'urn:schemas-upnp-org:service:[service type]'" do expect({ service_type: '12345' }.to_upnp_s). to eq 'urn:schemas-upnp-org:service:12345' end it "doesn't check if the Hash value is legit" do expect({ service_type: '' }.to_upnp_s).to eq 'urn:schemas-upnp-org:service:' end end context 'domain name given' do it "returns a String like 'urn:[domain name]:service:[service type]'" do expect({ service_type: '12345', domain_name: 'my-domain' }.to_upnp_s). to eq 'urn:my-domain:service:12345' end it "doesn't check if the Hash value is legit" do expect({ service_type: '', domain_name: 'my-domain' }.to_upnp_s). to eq 'urn:my-domain:service:' end end end context 'some other Hash key' do context 'domain name not given' do it 'returns self.to_s' do expect({ firestorm: 12345 }.to_upnp_s).to eq '{:firestorm=>12345}' end end end end end describe Symbol do context ':all' do describe '#to_upnp_s' do it "returns 'ssdp:all'" do expect(:all.to_upnp_s).to eq 'ssdp:all' end end end context ':root' do describe '#to_upnp_s' do it "returns 'upnp:rootdevice'" do expect(:root.to_upnp_s).to eq 'upnp:rootdevice' end end end it "returns itself if one of the defined shortcuts wasn't given" do expect(:firestorm.to_upnp_s).to eq :firestorm end end describe String do it 'returns itself' do expect('Stuff and things'.to_upnp_s).to eq 'Stuff and things' end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/spec/unit/playful/control_point_spec.rb
spec/unit/playful/control_point_spec.rb
require 'spec_helper' require 'playful/control_point' describe Playful::ControlPoint do subject do Playful::ControlPoint.new(1) end describe '#ssdp_search_and_listen' do let(:notification) do double 'notification' end let(:searcher) do s = double 'Playful::SSDP::Searcher' s.stub_chain(:discovery_responses, :subscribe).and_yield notification s end before do expect(Playful::SSDP).to receive(:search).with('ssdp:all', {}).and_return searcher EM.stub(:add_periodic_timer) end after do EM.unstub(:add_periodic_timer) end it 'creates a ControlPoint::Device for every discovery response' do EM.stub(:add_timer) subject.should_receive(:create_device).with(notification) subject.ssdp_search_and_listen('ssdp:all') end it 'shuts down the searcher and starts the listener after the given response wait time' do EM.stub(:add_timer).and_yield subject.stub(:create_device) searcher.should_receive(:close_connection) subject.should_receive(:listen) subject.ssdp_search_and_listen('ssdp:all') end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/spec/unit/playful/ssdp_spec.rb
spec/unit/playful/ssdp_spec.rb
require 'spec_helper' require 'playful/ssdp' describe Playful::SSDP do subject { Playful::SSDP } describe '.listen' do let(:listener) do searcher = double 'Playful::SSDP::Listener' searcher.stub_chain(:alive_notifications, :pop).and_yield(%w[one two]) searcher.stub_chain(:byebye_notifications, :pop).and_yield(%w[three four]) searcher end before do allow(EM).to receive(:run).and_yield allow(EM).to receive(:add_timer) allow(EM).to receive(:open_datagram_socket).and_return listener end context 'reactor is already running' do it 'returns a Playful::SSDP::Listener' do allow(EM).to receive(:reactor_running?).and_return true expect(subject.listen).to eq listener end end context 'reactor is not already running' do it 'returns a Hash of available and byebye responses' do allow(EM).to receive(:add_shutdown_hook).and_yield expect(subject.listen).to eq({ alive_notifications: %w[one two], byebye_notifications: %w[three four] }) end it 'opens a UDP socket on 239.255.255.250, port 1900' do allow(EM).to receive(:add_shutdown_hook) expect(EM).to receive(:open_datagram_socket).with('239.255.255.250', 1900, Playful::SSDP::Listener, 4) subject.listen end end end describe '.search' do let(:multicast_searcher) do searcher = double 'Playful::SSDP::Searcher' searcher.stub_chain(:discovery_responses, :subscribe).and_yield(%w[one two]) searcher end let(:broadcast_searcher) do searcher = double 'Playful::SSDP::BroadcastSearcher' searcher.stub_chain(:discovery_responses, :subscribe).and_yield(%w[three four]) searcher end before do allow(EM).to receive(:run).and_yield allow(EM).to receive(:add_timer) allow(EM).to receive(:open_datagram_socket).and_return multicast_searcher end context 'when search_target is not a String' do it 'calls #to_upnp_s on search_target' do search_target = double('search_target') expect(search_target).to receive(:to_upnp_s) subject.search(search_target) end end context 'when search_target is a String' do it 'calls #to_upnp_s on search_target but does not alter it' do search_target = "I'm a string" expect(search_target).to receive(:to_upnp_s).and_call_original expect(EM).to receive(:open_datagram_socket).with('0.0.0.0', 0, Playful::SSDP::Searcher, "I'm a string", {}) subject.search(search_target) end end context 'reactor is already running' do it 'returns a Playful::SSDP::Searcher' do allow(EM).to receive(:reactor_running?).and_return true expect(subject.search).to eq multicast_searcher end end context 'reactor is not already running' do context 'options hash includes do_broadcast_search' do before do allow(EM).to receive(:open_datagram_socket). and_return(multicast_searcher, broadcast_searcher) end it 'returns an Array of responses' do allow(EM).to receive(:add_shutdown_hook).and_yield expect(subject.search(:all, do_broadcast_search: true)).to eq %w[one two three four] end it 'opens 2 UDP sockets on 0.0.0.0, port 0' do allow(EM).to receive(:add_shutdown_hook) expect(EM).to receive(:open_datagram_socket).with('0.0.0.0', 0, Playful::SSDP::Searcher, 'ssdp:all', {}) expect(EM).to receive(:open_datagram_socket).with('0.0.0.0', 0, Playful::SSDP::BroadcastSearcher, 'ssdp:all', 5, 4) subject.search(:all, do_broadcast_search: true) end end context 'options hash does not include do_broadcast_search' do it 'returns an Array of responses' do allow(EM).to receive(:add_shutdown_hook).and_yield expect(subject.search).to eq %w[one two] end it 'opens a UDP socket on 0.0.0.0, port 0' do allow(EM).to receive(:add_shutdown_hook) expect(EM).to receive(:open_datagram_socket).with('0.0.0.0', 0, Playful::SSDP::Searcher, 'ssdp:all', {}) subject.search end end end end describe '.notify' do pending 'Implementation of UPnP Devices' end describe '.send_notification' do pending 'Implementation of UPnP Devices' end =begin context 'by default' do it "searches for 'ssdp:all'" do pending end it 'waits for 5 seconds for responses' do before = Time.now SSDP.search after = Time.now (after - before).should < 5.1 (after - before).should > 5.0 end end context "finds 'upnp:rootdevice's" do it "by using the spec's string 'upnp:rootdevice'" do SSDP.search('upnp:rootdevice').should == [ { :cache_control=>'max-age=1200', :date=>'Mon, 26 Sep 2011 06:40:19 GMT', :location=>'http://192.168.10.3:5001/description/fetch', :server=>'Linux-i386-2.6.38-10-generic-pae, UPnP/1.0, PMS/1.25.1', :st=>'upnp:rootdevice', :ext=>'', :usn=>'uuid:3c202906-992d-3f0f-b94c-90e1902a136d::upnp:rootdevice', :content_length=>'0' } ] end it 'by using :root' do pending end end it 'can wait for user-defined seconds for responses' do before = Time.now SSDP.search(:all, 1) after = Time.now (after - before).should < 1.1 (after - before).should > 1.0 end it 'finds a device by its URN' do pending end it 'finds a device by its UUID' do pending end it 'finds a device by its UPnP device type' do pending end it 'finds a device by its UPnP device type using a non-standard domain name' do pending end it 'finds a service by its UPnP service type' do pending end it 'find a service by its UPnP service type using a non-standard domain name' do pending end =end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/spec/unit/playful/control_point/device_spec.rb
spec/unit/playful/control_point/device_spec.rb
require 'spec_helper' require 'playful/control_point/device' describe Playful::ControlPoint::Device do pending end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/spec/unit/playful/ssdp/searcher_spec.rb
spec/unit/playful/ssdp/searcher_spec.rb
require 'spec_helper' require 'playful/ssdp/searcher' describe Playful::SSDP::Searcher do around(:each) do |example| EM.synchrony do example.run EM.stop end end before do Playful.log = false allow_any_instance_of(Playful::SSDP::MulticastConnection).to receive(:setup_multicast_socket) end subject do Playful::SSDP::Searcher.new(1, 'ssdp:all', {}) end it 'lets you read its responses' do responses = double 'responses' subject.instance_variable_set(:@discovery_responses, responses) expect(subject.discovery_responses).to eq responses end describe '#initialize' do it 'does an #m_search' do expect_any_instance_of(Playful::SSDP::Searcher).to receive(:m_search).and_return(<<-MSEARCH M-SEARCH * HTTP/1.1\r HOST: 239.255.255.250:1900\r MAN: "ssdp:discover"\r MX: 5\r ST: ssdp:all\r \r MSEARCH ) subject end end describe '#receive_data' do let(:parsed_response) do parsed_response = double 'parsed response' expect(parsed_response).to receive(:has_key?).with(:nts).and_return false expect(parsed_response).to receive(:[]).and_return false parsed_response end it 'takes a response and adds it to the list of responses' do response = double 'response' allow(subject).to receive(:peer_info).and_return(['0.0.0.0', 4567]) expect(subject).to receive(:parse).with(response).exactly(1).times. and_return(parsed_response) expect(subject.instance_variable_get(:@discovery_responses)).to receive(:<<). with(parsed_response) subject.receive_data(response) end end describe '#post_init' do before { allow_any_instance_of(Playful::SSDP::Searcher).to receive(:m_search).and_return('hi') } it 'sends an M-SEARCH as a datagram over 239.255.255.250:1900' do m_search_count_times = subject.instance_variable_get(:@m_search_count) expect(subject).to receive(:send_datagram). with('hi', '239.255.255.250', 1900). exactly(m_search_count_times).times. and_return 0 subject.post_init end end describe '#m_search' do it 'builds the MSEARCH string using the given parameters' do expect(subject.m_search('ssdp:all', 10)).to eq <<-MSEARCH M-SEARCH * HTTP/1.1\r HOST: 239.255.255.250:1900\r MAN: "ssdp:discover"\r MX: 10\r ST: ssdp:all\r \r MSEARCH end it 'uses 239.255.255.250 as the HOST IP' do expect(subject.m_search('ssdp:all', 10)).to match(/HOST: 239.255.255.250/m) end it 'uses 1900 as the HOST port' do expect(subject.m_search('ssdp:all', 10)).to match(/HOST:.*1900/m) end it 'lets you search for undefined search target types' do expect(subject.m_search('spaceship', 10)).to eq <<-MSEARCH M-SEARCH * HTTP/1.1\r HOST: 239.255.255.250:1900\r MAN: "ssdp:discover"\r MX: 10\r ST: spaceship\r \r MSEARCH end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/spec/unit/playful/ssdp/listener_spec.rb
spec/unit/playful/ssdp/listener_spec.rb
require 'spec_helper' require 'playful/ssdp/listener' describe Playful::SSDP::Listener do around(:each) do |example| EM.synchrony do example.run EM.stop end end before do allow_any_instance_of(Playful::SSDP::Listener).to receive(:setup_multicast_socket) end subject { Playful::SSDP::Listener.new(1) } describe '#receive_data' do it 'logs the IP and port from which the request came from' do expect(subject).to receive(:peer_info).and_return %w[ip port] expect(subject).to receive(:log). with("Response from ip:port:\nmessage\n") allow(subject).to receive(:parse).and_return({}) subject.receive_data('message') end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/spec/unit/playful/ssdp/notifier_spec.rb
spec/unit/playful/ssdp/notifier_spec.rb
require 'spec_helper' require 'playful/ssdp/notifier' describe Playful::SSDP::Notifier do around(:each) do |example| EM.synchrony do example.run EM.stop end end let(:nt) { 'en tee' } let(:usn) { 'you ess en' } let(:ddf_url) { 'ddf url' } let(:duration) { 567 } subject do Playful::SSDP::Notifier.new(1, nt, usn, ddf_url, duration) end describe '#initialize' do it 'creates a notification' do expect_any_instance_of(Playful::SSDP::Notifier).to receive(:notification). with(nt, usn, ddf_url, duration) subject end end describe '#post_init' do context 'send_datagram returns positive value' do before do expect(subject).to receive(:send_datagram).and_return 1 end it 'logs what was sent' do expect(subject).to receive(:log).with /Sent notification/ subject.post_init end end context 'send_datagram returns 0' do before do expect(subject).to receive(:send_datagram).and_return 0 end it 'does not log what was sent' do expect(subject).to_not receive(:log) subject.post_init end end end describe '#notification' do before do subject.instance_variable_set(:@os, 'my OS') end it 'builds the notification message' do expect(subject.notification(nt, usn, ddf_url, duration)).to eq <<-NOTE NOTIFY * HTTP/1.1\r HOST: 239.255.255.250:1900\r CACHE-CONTROL: max-age=567\r LOCATION: ddf url\r NT: en tee\r NTS: ssdp:alive\r SERVER: my OS UPnP/1.0 Playful/#{Playful::VERSION}\r USN: you ess en\r \r NOTE end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/spec/unit/playful/ssdp/multicast_connection_spec.rb
spec/unit/playful/ssdp/multicast_connection_spec.rb
require 'spec_helper' require 'playful/ssdp/multicast_connection' describe Playful::SSDP::MulticastConnection do around(:each) do |example| EM.synchrony do example.run EM.stop end end subject { Playful::SSDP::MulticastConnection.new(1) } before do Playful.log = false end describe '#peer_info' do before do allow_any_instance_of(Playful::SSDP::MulticastConnection).to receive(:setup_multicast_socket) subject.stub_chain(:get_peername, :[], :unpack). and_return(%w[1234 1 2 3 4]) end it 'returns an Array with IP and port' do expect(subject.peer_info).to eq ['1.2.3.4', 1234] end it 'returns IP as a String' do expect(subject.peer_info.first).to be_a String end it 'returns port as a Fixnum' do expect(subject.peer_info.last).to be_a Fixnum end end describe '#parse' do before do allow_any_instance_of(Playful::SSDP::MulticastConnection).to receive(:setup_multicast_socket) end it 'turns headers into Hash keys' do result = subject.parse ROOT_DEVICE1 expect(result).to have_key :cache_control expect(result).to have_key :date expect(result).to have_key :location expect(result).to have_key :server expect(result).to have_key :st expect(result).to have_key :ext expect(result).to have_key :usn expect(result).to have_key :content_length end it 'turns header values into Hash values' do result = subject.parse ROOT_DEVICE1 expect(result[:cache_control]).to eq 'max-age=1200' expect(result[:date]).to eq 'Mon, 26 Sep 2011 06:40:19 GMT' expect(result[:location]).to eq 'http://1.2.3.4:5678/description/fetch' expect(result[:server]).to eq 'Linux-i386-2.6.38-10-generic-pae, UPnP/1.0, PMS/1.25.1' expect(result[:st]).to eq 'upnp:rootdevice' expect(result[:ext]).to be_empty expect(result[:usn]).to eq 'uuid:3c202906-992d-3f0f-b94c-90e1902a136d::upnp:rootdevice' expect(result[:content_length]).to eq '0' end context 'single line String as response data' do before { @data = ROOT_DEVICE1.gsub("\n", ' ') } it 'returns an empty Hash' do expect(subject.parse(@data)).to eq({ }) end it "logs the 'bad' response" do subject.should_receive(:log).twice subject.parse @data end end end describe '#setup_multicast_socket' do before do allow_any_instance_of(Playful::SSDP::MulticastConnection).to receive(:set_membership) allow_any_instance_of(Playful::SSDP::MulticastConnection).to receive(:switch_multicast_loop) allow_any_instance_of(Playful::SSDP::MulticastConnection).to receive(:set_multicast_ttl) allow_any_instance_of(Playful::SSDP::MulticastConnection).to receive(:set_ttl) end it 'adds 0.0.0.0 and 239.255.255.250 to the membership group' do expect(subject).to receive(:set_membership).with( IPAddr.new('239.255.255.250').hton + IPAddr.new('0.0.0.0').hton ) subject.setup_multicast_socket end it 'sets multicast TTL to 4' do expect(subject).to receive(:set_multicast_ttl).with(4) subject.setup_multicast_socket end it 'sets TTL to 4' do expect(subject).to receive(:set_ttl).with(4) subject.setup_multicast_socket end context "ENV['RUBY_UPNP_ENV'] != testing" do after { ENV['RUBY_UPNP_ENV'] = 'testing' } it 'turns multicast loop off' do ENV['RUBY_UPNP_ENV'] = 'development' expect(subject).to receive(:switch_multicast_loop).with(:off) subject.setup_multicast_socket end end end describe '#switch_multicast_loop' do before do allow_any_instance_of(Playful::SSDP::MulticastConnection).to receive(:setup_multicast_socket) end it "passes '\\001' to the socket option call when param == :on" do expect(subject).to receive(:set_sock_opt).with( Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, "\001" ) subject.switch_multicast_loop :on end it "passes '\\001' to the socket option call when param == '\\001'" do expect(subject).to receive(:set_sock_opt).with( Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, "\001" ) subject.switch_multicast_loop "\001" end it "passes '\\000' to the socket option call when param == :off" do expect(subject).to receive(:set_sock_opt).with( Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, "\000" ) subject.switch_multicast_loop :off end it "passes '\\000' to the socket option call when param == '\\000'" do expect(subject).to receive(:set_sock_opt).with( Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, "\000" ) subject.switch_multicast_loop "\000" end it "raises when not :on, :off, '\\000', or '\\001'" do expect { subject.switch_multicast_loop 12312312 }. to raise_error(Playful::SSDP::Error) end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful.rb
lib/playful.rb
require_relative 'playful/version' module Playful end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/rack/upnp_control_point.rb
lib/rack/upnp_control_point.rb
require 'rack' require_relative '../playful/control_point' module Rack # Middleware that allows your Rack app to keep tabs on devices that the # {Playful::ControlPoint} has found. UPnP devices that match the +search_type+ # are discovered and added to the list, then removed as those devices send out # +ssdp:byebye+ notifications. All of this depends on +EventMachine::Channel+s, # and thus requires that an EventMachine reactor is running. If you don't # have one running, the {Playful::ControlPoint} will start one for you. # # @example Control all root devices # # Thin::Server.start('0.0.0.0', 3000) do # use Rack::UPnPControlPoint, search_type: :root # # map "/devices" do # run lambda { |env| # devices = env['upnp.devices'] # friendly_names = devices.map(&:friendly_name).join("\n") # [200, {'Content-Type' => 'text/plain'}, [friendly_names]] # } # end # end # class UPnPControlPoint # @param [Rack::Builder] app Your Rack application. # @param [Hash] options Options to pass to the Playful::SSDP::Searcher. # @see Playful::SSDP::Searcher def initialize(app, options = {}) @app = app @devices = [] options[:search_type] ||= :root EM.next_tick { start_control_point(options[:search_type], options) } end # Creates and starts the {Playful::ControlPoint}, then manages the list of # devices using the +EventMachine::Channel+ objects yielded in. # # @param [Symbol,String] search_type The device(s) you want to search for # and control. # @param [Hash] options Options to pass to the Playful::SSDP::Searcher. # @see Playful::SSDP::Searcher def start_control_point(search_type, options) @cp = ::Playful::ControlPoint.new(search_type, options) @cp.start do |new_device_channel, old_device_channel| new_device_channel.subscribe do |notification| @devices << notification end old_device_channel.subscribe do |old_device| @devices.reject! { |d| d.usn == old_device[:usn] } end end end # Adds the whole list of devices to <tt>env['upnp.devices']</tt> so that # that list can be accessed from within your app. # # @param [Hash] env The Rack environment. def call(env) env['upnp.devices'] = @devices @app.call(env) end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/core_ext/hash_patch.rb
lib/core_ext/hash_patch.rb
class Hash def symbolize_keys! self.inject({}) { |result, (k, v)| result[k.to_sym] = v; result } end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/core_ext/to_upnp_s.rb
lib/core_ext/to_upnp_s.rb
class Hash # Converts Hash search targets to SSDP search target String. Conversions are # as follows: # uuid: "someUUID" # => "uuid:someUUID" # device_type: "someDeviceType:1" # => "urn:schemas-upnp-org:device:someDeviceType:1" # service_type: "someServiceType:2" # => "urn:schemas-upnp-org:service:someServiceType:2" # # You can use custom UPnP domain names too: # { device_type: "someDeviceType:3", # domain_name: "mydomain-com" } # => "urn:my-domain:device:someDeviceType:3" # { service_type: "someServiceType:4", # domain_name: "mydomain-com" } # => "urn:my-domain:service:someDeviceType:4" # # @return [String] The converted String, according to the UPnP spec. def to_upnp_s if self.has_key? :uuid return "uuid:#{self[:uuid]}" elsif self.has_key? :device_type if self.has_key? :domain_name return "urn:#{self[:domain_name]}:device:#{self[:device_type]}" else return "urn:schemas-upnp-org:device:#{self[:device_type]}" end elsif self.has_key? :service_type if self.has_key? :domain_name return "urn:#{self[:domain_name]}:service:#{self[:service_type]}" else return "urn:schemas-upnp-org:service:#{self[:service_type]}" end else self.to_s end end end class Symbol # Converts Symbol search targets to SSDP search target String. Conversions are # as follows: # :all # => "ssdp:all" # :root # => "upnp:rootdevice" # "root" # => "upnp:rootdevice" # # @return [String] The converted String, according to the UPnP spec. def to_upnp_s if self == :all 'ssdp:all' elsif self == :root 'upnp:rootdevice' else self end end end class String # This doesn't do anything to the string; just allows users to call the # method without having to check type first. def to_upnp_s self end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/core_ext/socket_patch.rb
lib/core_ext/socket_patch.rb
require 'socket' # Workaround for missing constants on Windows module Socket::Constants IP_ADD_MEMBERSHIP = 12 unless defined? IP_ADD_MEMBERSHIP IP_MULTICAST_LOOP = 11 unless defined? IP_MULTICAST_LOOP IP_MULTICAST_TTL = 10 unless defined? IP_MULTICAST_TTL IP_TTL = 4 unless defined? IP_TTL end class Socket IP_ADD_MEMBERSHIP = 12 unless defined? IP_ADD_MEMBERSHIP IP_MULTICAST_LOOP = 11 unless defined? IP_MULTICAST_LOOP IP_MULTICAST_TTL = 10 unless defined? IP_MULTICAST_TTL IP_TTL = 4 unless defined? IP_TTL end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/version.rb
lib/playful/version.rb
module Playful VERSION = '0.1.0.alpha.1' end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/logger.rb
lib/playful/logger.rb
require 'log_switch' module Playful extend LogSwitch end Playful.log_class_name = true
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/ssdp.rb
lib/playful/ssdp.rb
require_relative '../core_ext/socket_patch' require 'eventmachine' require 'em-synchrony' require_relative '../core_ext/to_upnp_s' require_relative 'logger' require_relative 'ssdp/error' require_relative 'ssdp/network_constants' require_relative 'ssdp/listener' require_relative 'ssdp/searcher' require_relative 'ssdp/notifier' require_relative 'ssdp/broadcast_searcher' module Playful # This is the main class for doing SSDP stuff. You can have a look at child # classes, but you'll probably want to just use these methods here. # # SSDP is "Simple Service Discovery Protocol", which lets you find and learn # about UPnP devices on your network. Of the six "steps" of UPnP (given in # the UPnP spec--that's counting step 0), SSDP is what provides step 1, or the # "discovery" step. # # Before you can do anything with any of the UPnP devices on your network, you # need to +search+ your network to see what devices are available. Once you've # found what's available, you can then decide device(s) you'd like to control # (that's where Control Points come in; take a look at Playful::ControlPoint). # After searching, you should then +listen+ to the activity on your network. # New devices on your network may come online (via +ssdp:alive+) and devices # that you care about may go offline (via +ssdp:byebye+), in which case you # probably shouldn't try to talk to them anymore. # # @todo Add docs for Playful::Device perspective. class SSDP include LogSwitch::Mixin include NetworkConstants # Opens a multicast UDP socket on 239.255.255.250:1900 and listens for # alive and byebye notifications from devices. # # @param [Fixnum] ttl The TTL to use on the UDP socket. # # @return [Hash<Array>,Playful::SSDP::Listener] If the EventMachine reactor is # _not_ running, it returns two key/value pairs--one for # alive_notifications, one for byebye_notifications. If the reactor _is_ # running, it returns a Playful::SSDP::Listener so that that object can be # used however desired. The latter method is used in Playful::ControlPoints # so that an object of that type can keep track of devices it cares about. def self.listen(ttl=TTL) alive_notifications = Set.new byebye_notifications = Set.new listener = proc do l = EM.open_datagram_socket(MULTICAST_IP, MULTICAST_PORT, Playful::SSDP::Listener, ttl) i = 0 EM.add_periodic_timer(5) { i += 5; Playful.log "Listening for #{i}\n" } l end if EM.reactor_running? return listener.call else EM.synchrony do l = listener.call alive_getter = Proc.new do |notification| alive_notifications << notification EM.next_tick { l.alive_notifications.pop(&live_getter) } end l.alive_notifications.pop(&alive_getter) byebye_getter = Proc.new do |notification| byebye_notifications << notification EM.next_tick { l.byebye_notifications.pop(&byebye_getter) } end l.byebye_notifications.pop(&byebye_getter) trap_signals end end { alive_notifications: alive_notifications.to_a.flatten, byebye_notifications: byebye_notifications.to_a.flatten } end # Opens a UDP socket on 0.0.0.0, on an ephemeral port, has Playful::SSDP::Searcher # build and send the search request, then receives the responses. The search # will stop after +response_wait_time+. # # @param [String] search_target # # @param [Hash] options # # @option options [Fixnum] response_wait_time # @option options [Fixnum] ttl # @option options [Fixnum] m_search_count # @option options [Boolean] do_broadcast_search Tells the search call to also send # a M-SEARCH over 255.255.255.255. This is *NOT* part of the UPnP spec; # it's merely a hack for working with some types of devices that don't # properly implement the UPnP spec. # # @return [Array<Hash>,Playful::SSDP::Searcher] Returns a Hash that represents # the headers from the M-SEARCH response. Each one of these can be passed # in to Playful::ControlPoint::Device.new to download the device's # description file, parse it, and interact with the device's devices # and/or services. If the reactor is already running this will return a # a Playful::SSDP::Searcher which will make its accessors available so you # can get responses in real time. def self.search(search_target=:all, options = {}) response_wait_time = options[:response_wait_time] || 5 ttl = options[:ttl] || TTL do_broadcast_search = options[:do_broadcast_search] searcher_options = options searcher_options.delete :do_broadcast_search responses = [] search_target = search_target.to_upnp_s multicast_searcher = proc do EM.open_datagram_socket('0.0.0.0', 0, Playful::SSDP::Searcher, search_target, searcher_options) end broadcast_searcher = proc do EM.open_datagram_socket('0.0.0.0', 0, Playful::SSDP::BroadcastSearcher, search_target, response_wait_time, ttl) end if EM.reactor_running? return multicast_searcher.call else EM.synchrony do ms = multicast_searcher.call ms.discovery_responses.subscribe do |notification| responses << notification end if do_broadcast_search bs = broadcast_searcher.call bs.discovery_responses.subscribe do |notification| responses << notification end end EM.add_timer(response_wait_time) { EM.stop } trap_signals end end responses.flatten end # @todo This is for Playful::Devices, which aren't implemented yet, and thus # this may not be working. def self.notify(notification_type, usn, ddf_url, valid_for_duration=1800) responses = [] notification_type = notification_type.to_upnp_s EM.synchrony do s = send_notification(notification_type, usn, ddf_url, valid_for_duration) EM.add_shutdown_hook { responses = s.discovery_responses } EM.add_periodic_timer(valid_for_duration) do s = send_notification(notification_type, usn, ddf_url, valid_for_duration) end trap_signals end responses end # @todo This is for Playful::Devices, which aren't implemented yet, and thus # this may not be working. def self.send_notification(notification_type, usn, ddf_url, valid_for_duration) EM.open_datagram_socket('0.0.0.0', 0, Playful::SSDP::Notifier, notification_type, usn, ddf_url, valid_for_duration) end private # Traps INT, TERM, and HUP signals and stops the reactor. def self.trap_signals trap('INT') { EM.stop } trap('TERM') { EM.stop } trap('HUP') { EM.stop } if RUBY_PLATFORM !~ /mswin|mingw/ end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/device.rb
lib/playful/device.rb
require 'thin' require 'em-synchrony' require 'rack' require 'rack/lobster' module Playful class Device # Multicasts discovery messages to advertise its root device, any embedded # devices, and any services. def start EM.synchrony do web_server = Thin::Server.start('0.0.0.0', 3000) do use Rack::CommonLogger use Rack::ShowExceptions map '/presentation' do use Rack::Lint run Rack::Lobster.new end end # Do advertisement # Listen for subscribers end end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/control_point.rb
lib/playful/control_point.rb
require 'open-uri' require 'nori' require 'em-synchrony' require_relative 'logger' require_relative 'ssdp' require_relative 'control_point/service' require_relative 'control_point/device' require_relative 'control_point/error' module Playful # Allows for controlling a UPnP device as defined in the UPnP spec for control # points. # # It uses +Nori+ for parsing the description XML files, which will use +Nokogiri+ # if you have it installed. class ControlPoint include LogSwitch::Mixin def self.config yield self end class << self attr_accessor :raise_on_remote_error end @@raise_on_remote_error ||= true attr_reader :devices # @param [String] search_target The device(s) to control. # @param [Hash] search_options Options to pass on to SSDP search and listen calls. # @option options [Fixnum] response_wait_time # @option options [Fixnum] m_search_count # @option options [Fixnum] ttl def initialize(search_target, search_options = {}) @search_target = search_target @search_options = search_options @search_options[:ttl] ||= 4 @devices = [] @new_device_channel = EventMachine::Channel.new @old_device_channel = EventMachine::Channel.new end # Starts the ControlPoint. If an EventMachine reactor is running already, # it'll join that reactor, otherwise it'll start the reactor. # # @yieldparam [EventMachine::Channel] new_device_channel The means through # which clients can get notified when a new device has been discovered # either through SSDP searching or from an +ssdp:alive+ notification. # @yieldparam [EventMachine::Channel] old_device_channel The means through # which clients can get notified when a device has gone offline (have sent # out a +ssdp:byebye+ notification). def start(&blk) @stopping = false starter = -> do ssdp_search_and_listen(@search_target, @search_options) blk.call(@new_device_channel, @old_device_channel) @running = true end if EM.reactor_running? log 'Joining reactor...' starter.call else log 'Starting reactor...' EM.synchrony(&starter) end end def listen(ttl) EM.defer do listener = SSDP.listen(ttl) listener.alive_notifications.subscribe do |advertisement| log "Got alive #{advertisement}" if @devices.any? { |d| d.usn == advertisement[:usn] } log "Device with USN #{advertisement[:usn]} already exists." else log "Device with USN #{advertisement[:usn]} not found. Creating..." create_device(advertisement) end end listener.byebye_notifications.subscribe do |advertisement| log "Got bye-bye from #{advertisement}" @devices.reject! do |device| device.usn == advertisement[:usn] end @old_device_channel << advertisement end end end def ssdp_search_and_listen(search_for, options = {}) searcher = SSDP.search(search_for, options) searcher.discovery_responses.subscribe do |notification| create_device(notification) end # Do I need to do this? EM.add_timer(options[:response_wait_time]) do searcher.close_connection listen(options[:ttl]) end EM.add_periodic_timer(5) do log "Time since last timer: #{Time.now - @timer_time}" if @timer_time log "Connections: #{EM.connection_count}" @timer_time = Time.now puts "<#{self.class}> Device count: #{@devices.size}" puts "<#{self.class}> Device unique: #{@devices.uniq.size}" end trap_signals end def create_device(notification) deferred_device = Device.new(ssdp_notification: notification) deferred_device.errback do |partially_built_device, message| log message #add_device(partially_built_device) if self.class.raise_on_remote_error raise ControlPoint::Error, message end end deferred_device.callback do |built_device| log "Device created from #{notification}" add_device(built_device) end deferred_device.fetch end def add_device(built_device) if (@devices.any? { |d| d.usn == built_device.usn }) || (@devices.any? { |d| d.udn == built_device.udn }) log 'Newly created device already exists in internal list. Not adding.' #if @devices.any? { |d| d.usn == built_device.usn } # log "Newly created device (#{built_device.usn}) already exists in internal list. Not adding." else log 'Adding newly created device to internal list..' @new_device_channel << built_device @devices << built_device end end def stop @running = false @stopping = false EM.stop if EM.reactor_running? end def running? @running end def trap_signals trap('INT') { stop } trap('TERM') { stop } trap('HUP') { stop } if RUBY_PLATFORM !~ /mswin|mingw/ end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/control_point/base.rb
lib/playful/control_point/base.rb
require 'nori' require 'em-http-request' require_relative 'error' require_relative '../logger' require_relative '../../playful' module Playful class ControlPoint class Base include LogSwitch::Mixin protected def get_description(location, description_getter) log "Getting description with getter ID #{description_getter.object_id} for: #{location}" http = EM::HttpRequest.new(location).aget t = EM::Timer.new(30) do http.fail(:timeout) end http.errback do |error| if error == :timeout log 'Timed out getting description. Retrying...' http = EM::HttpRequest.new(location).get else log "Unable to retrieve DDF from #{location}", :error log "Request error: #{http.error}" log "Response status: #{http.response_header.status}" description_getter.set_deferred_status(:failed) if ControlPoint.raise_on_remote_error raise ControlPoint::Error, "Unable to retrieve DDF from #{location}" end end end http.callback { log "HTTP callback called for #{description_getter.object_id}" if http.response_header.status != 200 log "Response status: #{http.response_header.status}" description_getter.set_deferred_status(:failed) else response = xml_parser.parse(http.response) description_getter.set_deferred_status(:succeeded, response) end } end def build_url(url_base, rest_of_url) if url_base.end_with?('/') && rest_of_url.start_with?('/') rest_of_url.sub!('/', '') end url_base + rest_of_url end # @return [Nori::Parser] def xml_parser @xml_parser if @xml_parser options = { convert_tags_to: lambda { |tag| tag.to_sym } } begin require 'nokogiri' options.merge! parser: :nokogiri rescue LoadError warn "Tried loading nokogiri for XML couldn't. This is OK, just letting you know." end @xml_parser = Nori.new(options) end end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/control_point/service.rb
lib/playful/control_point/service.rb
require 'savon' require_relative 'base' require_relative 'error' require_relative '../../core_ext/hash_patch' require 'em-http' HTTPI.adapter = :em_http module Playful class ControlPoint # An object of this type functions as somewhat of a proxy to a UPnP device's # service. The object sort of defines itself when you call #fetch; it # gets the description file from the device, parses it, populates its # attributes (as accessors) and defines singleton methods from the list of # actions that the service defines. # # After the fetch is done, you can call Ruby methods on the service and # expect a Ruby Hash back as a return value. The methods will look just # the SOAP actions and will always return a Hash, where key/value pairs are # converted from the SOAP response; values are converted to the according # Ruby type based on <dataType> in the <serviceStateTable>. # # Types map like: # * Integer # * ui1 # * ui2 # * ui4 # * i1 # * i2 # * i4 # * int # * Float # * r4 # * r8 # * number # * fixed.14.4 # * float # * String # * char # * string # * uuid # * TrueClass # * 1 # * true # * yes # * FalseClass # * 0 # * false # * no # # @example No "in" params # my_service.GetSystemUpdateID # => { "Id" => 1 } # class Service < Base include EventMachine::Deferrable include LogSwitch::Mixin #vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv # Passed in by +service_list_info+ # # @return [String] UPnP service type, including URN. attr_reader :service_type # @return [String] Service identifier, unique within this service's devices. attr_reader :service_id # @return [URI::HTTP] Service description URL. attr_reader :scpd_url # @return [URI::HTTP] Control URL. attr_reader :control_url # @return [URI::HTTP] Eventing URL. attr_reader :event_sub_url # # DONE +service_list_info+ #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv # Determined by service description file # # @return [String] attr_reader :xmlns # @return [String] attr_reader :spec_version # @return [Array<Hash>] attr_reader :action_list # Probably don't need to keep this long-term; just adding for testing. attr_reader :service_state_table # # DONE description #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # @return [Hash] The whole description... just in case. attr_reader :description # @param [String] device_base_url URL given (or otherwise determined) by # <URLBase> from the device that owns the service. # @param [Hash] service_list_info Info given in the <serviceList> section # of the device description. def initialize(device_base_url, service_list_info) @service_list_info = service_list_info @action_list = [] @xmlns = '' extract_service_list_info(device_base_url) configure_savon end # Fetches the service description file, parses it, extracts attributes # into accessors, and defines Ruby methods from SOAP actions. Since this # is a long-ish process, this is done using EventMachine Deferrable # behavior. def fetch if @scpd_url.empty? log 'NO SCPDURL to get the service description from. Returning.' set_deferred_success self return end description_getter = EventMachine::DefaultDeferrable.new log "Fetching service description with #{description_getter.object_id}" get_description(@scpd_url, description_getter) description_getter.errback do msg = 'Failed getting service description.' log "#{msg}", :error # @todo Should this return self? or should it succeed? set_deferred_status(:failed, msg) if ControlPoint.raise_on_remote_error raise ControlPoint::Error, msg end end description_getter.callback do |description| log "Service description received for #{description_getter.object_id}." @description = description @xmlns = @description[:scpd][:@xmlns] extract_spec_version extract_service_state_table if @description[:scpd][:actionList] log "Defining methods from action_list using [#{description_getter.object_id}]" define_methods_from_actions(@description[:scpd][:actionList][:action]) end set_deferred_status(:succeeded, self) end end private # Extracts all of the basic service information from the information # handed over from the device description about the service. The actual # service description info gathering is *not* done here. # # @param [String] device_base_url The URLBase from the device. Used to # build absolute URLs for the service. def extract_service_list_info(device_base_url) @control_url = if @service_list_info[:controlURL] build_url(device_base_url, @service_list_info[:controlURL]) else log 'Required controlURL attribute is blank.' '' end @event_sub_url = if @service_list_info[:eventSubURL] build_url(device_base_url, @service_list_info[:eventSubURL]) else log 'Required eventSubURL attribute is blank.' '' end @service_type = @service_list_info[:serviceType] @service_id = @service_list_info[:serviceId] @scpd_url = if @service_list_info[:SCPDURL] build_url(device_base_url, @service_list_info[:SCPDURL]) else log 'Required SCPDURL attribute is blank.' '' end end def extract_spec_version "#{@description[:scpd][:specVersion][:major]}.#{@description[:scpd][:specVersion][:minor]}" end def extract_service_state_table @service_state_table = if @description[:scpd][:serviceStateTable].is_a? Hash @description[:scpd][:serviceStateTable][:stateVariable] elsif @description[:scpd][:serviceStateTable].is_a? Array @description[:scpd][:serviceStateTable].map do |state| state[:stateVariable] end end end # Determines if <actionList> from the service description contains a # single action or multiple actions and delegates to create Ruby methods # accordingly. # # @param [Hash,Array] action_list The value from <scpd><actionList><action> # from the service description. def define_methods_from_actions(action_list) log "Defining methods; action list: #{action_list}" if action_list.is_a? Hash @action_list << action_list define_method_from_action(action_list[:name].to_sym, action_list[:argumentList][:argument]) elsif action_list.is_a? Array action_list.each do |action| =begin in_args_count = action[:argumentList][:argument].find_all do |arg| arg[:direction] == 'in' end.size =end @action_list << action args = action[:argumentList] ? action[:argumentList][:argument] : {} define_method_from_action(action[:name].to_sym, args) end else log "Got actionList that's not an Array or Hash." end end # Defines a Ruby method from the SOAP action. # # All resulting methods will either take no arguments or a single Hash as # an argument, whatever the SOAP action describes as its "in" arguments. # If the action describes "in" arguments, then you must provide a Hash # where keys are argument names and values are the values for those # arguments. # # For example, the GetCurrentConnectionInfo action from the # "ConnectionManager:1" service describes an "in" argument named # "ConnectionID" whose dataType is "i4". To call this action via the # Ruby method, it'd look like: # # connection_manager.GetCurrentConnectionInfo({ "ConnectionID" => 42 }) # # There is currently no type checking for these "in" arguments. # # Calling that Ruby method will, in turn, call the SOAP action by the same # name, with the body set to: # # <connectionID>42</connectionID> # # The UPnP device providing the service will reply with a SOAP # response--either a fault or with good data--and that will get converted # to a Hash. This Hash will contain key/value pairs defined by the "out" # argument names and values. Each value is converted to an associated # Ruby type, determined from the serviceStateTable. If no return data # is relevant for the request you made, some devices may return an empty # body. # # @param [Symbol] action_name The extracted value from <actionList> # <action><name> from the spec. # @param [Hash,Array] argument_info The extracted values from # <actionList><action><argumentList><argument> from the spec. def define_method_from_action(action_name, argument_info) # Do this here because, for some reason, @service_type is out of scope # in the #request block below. st = @service_type define_singleton_method(action_name) do |params| begin response = @soap_client.call(action_name.to_s) do |locals| locals.message_tags 'xmlns:u' => @service_type locals.soap_action "#{st}##{action_name}" #soap.namespaces["s:encodingStyle"] = "http://schemas.xmlsoap.org/soap/encoding/" unless params.nil? raise ArgumentError, 'Method only accepts Hashes' unless params.is_a? Hash soap.body = params.symbolize_keys! end end rescue Savon::SOAPFault, Savon::HTTPError => ex hash = xml_parser.parse(ex.http.body) msg = <<-MSG SOAP request failure! HTTP response code: #{ex.http.code} HTTP headers: #{ex.http.headers} HTTP body: #{ex.http.body} HTTP body as Hash: #{hash} MSG log "#{msg}" raise(ActionError, msg) if ControlPoint.raise_on_remote_error if hash.empty? return ex.http.body else return hash[:Envelope][:Body] end end return_value = if argument_info.is_a?(Hash) && argument_info[:direction] == 'out' return_ruby_from_soap(action_name, response, argument_info) elsif argument_info.is_a? Array argument_info.map do |arg| if arg[:direction] == 'out' return_ruby_from_soap(action_name, response, arg) end end else log "No args with direction 'out'" {} end return_value end log "Defined method: #{action_name}" end # Uses the serviceStateTable to look up the output from the SOAP response # for the given action, then converts it to the according Ruby data type. # # @param [String] action_name The name of the SOAP action that was called # for which this will get the response from. # @param [Savon::SOAP::Response] soap_response The response from making # the SOAP call. # @param [Hash] out_argument The Hash that tells out the "out" argument # which tells what data type to return. # @return [Hash] Key will be the "out" argument name as a Symbol and the # key will be the value as its converted Ruby type. def return_ruby_from_soap(action_name, soap_response, out_argument) out_arg_name = out_argument[:name] #puts "out arg name: #{out_arg_name}" related_state_variable = out_argument[:relatedStateVariable] #puts "related state var: #{related_state_variable}" state_variable = @service_state_table.find do |state_var_hash| state_var_hash[:name] == related_state_variable end #puts "state var: #{state_variable}" int_types = %w[ui1 ui2 ui4 i1 i2 i4 int] float_types = %w[r4 r8 number fixed.14.4 float] string_types = %w[char string uuid] true_types = %w[1 true yes] false_types = %w[0 false no] if soap_response.success? && soap_response.to_xml.empty? log 'Got successful but empty soap response!' return {} end if int_types.include? state_variable[:dataType] { out_arg_name.to_sym => soap_response. hash[:Envelope][:Body]["#{action_name}Response".to_sym][out_arg_name.to_sym].to_i } elsif string_types.include? state_variable[:dataType] { out_arg_name.to_sym => soap_response. hash[:Envelope][:Body]["#{action_name}Response".to_sym][out_arg_name.to_sym].to_s } elsif float_types.include? state_variable[:dataType] { out_arg_name.to_sym => soap_response. hash[:Envelope][:Body]["#{action_name}Response".to_sym][out_arg_name.to_sym].to_f } elsif true_types.include? state_variable[:dataType] { out_arg_name.to_sym => true } elsif false_types.include? state_variable[:dataType] { out_arg_name.to_sym => false } else log "Got SOAP response that I dunno what to do with: #{soap_response.hash}" end end def configure_savon @soap_client = Savon.client do |globals| globals.endpoint @control_url globals.namespace @service_type globals.convert_request_keys_to :camelcase globals.namespace_identifier :u globals.env_namespace :s globals.log true end end end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/control_point/device.rb
lib/playful/control_point/device.rb
require_relative 'base' require_relative 'service' require_relative 'error' require 'uri' require 'eventmachine' require 'time' module Playful class ControlPoint class Device < Base include EM::Deferrable include LogSwitch::Mixin attr_reader :ssdp_notification #vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv # Passed in as part of +device_info+; given by the SSDP search response. # attr_reader :cache_control attr_reader :date attr_reader :ext attr_reader :location attr_reader :server attr_reader :st attr_reader :usn # # DONE +device_info+ #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # @return [Hash] The whole parsed description... just in case. attr_reader :description attr_reader :expiration #vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv # Determined by device description file. # #------- <root> elements ------- # @return [String] The xmlns attribute of the device from the description file. attr_reader :xmlns # @return [Hash] :major and :minor revisions of the UPnP spec this device adheres to. attr_reader :spec_version # @return [String] URLBase from the device's description file. attr_reader :url_base #------- <root><device> elements ------- # @return [String] The type of UPnP device (URN) from the description file. attr_reader :device_type # @return [String] Short device description for the end user. attr_reader :friendly_name # @return [String] Manufacturer's name. attr_reader :manufacturer # @return [String] Manufacturer's web site. attr_reader :manufacturer_url # @return [String] Long model description for the end user, from the description file. attr_reader :model_description # @return [String] Model name of this device from the description file. attr_reader :model_name # @return [String] Model number of this device from the description file. attr_reader :model_number # @return [String] Web site for model of this device. attr_reader :model_url # @return [String] The serial number from the description file. attr_reader :serial_number # @return [String] The UDN for the device, from the description file. attr_reader :udn # @return [String] The UPC of the device from the description file. attr_reader :upc # @return [Array<Hash>] An Array where each element is a Hash that describes an icon. attr_reader :icon_list # Services provided directly by this device. attr_reader :service_list # Devices embedded directly into this device. attr_reader :device_list # @return [String] URL for device control via a browser. attr_reader :presentation_url # # DONE description file #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # @param [Hash] device_info # @option device_info [Hash] ssdp_notification # @option device_info [Hash] device_description # @option device_info [Hash] parent_base_url def initialize(device_info) super() @device_info = device_info log "Got device info: #{@device_info}" @device_list = [] @service_list = [] @icon_list = [] @xmlns = '' @done_creating_devices = false @done_creating_services = false end def fetch description_getter = EventMachine::DefaultDeferrable.new description_getter.errback do msg = 'Failed getting description.' log msg, :error @done_creating_devices = true @done_creating_services = true set_deferred_status(:failed, msg) if ControlPoint.raise_on_remote_error raise ControlPoint::Error, msg end end if @device_info.has_key? :ssdp_notification extract_from_ssdp_notification(description_getter) elsif @device_info.has_key? :device_description log 'Creating device from device description file info.' description_getter.set_deferred_success @device_info[:device_description] else log "Not sure what to extract from this device's info." description_getter.set_deferred_failure end description_getter.callback do |description| log "Description received from #{description_getter.object_id}" @description = description if @description.nil? log 'Description is empty.', :error set_deferred_status(:failed, 'Got back an empty description...') return end extract_spec_version @url_base = extract_url_base log "Set url_base to #{@url_base}" if @device_info[:ssdp_notification] @xmlns = @description[:root][:@xmlns] log "Extracting description for root device #{description_getter.object_id}" extract_description(@description[:root][:device]) elsif @device_info.has_key? :device_description log "Extracting description for non-root device #{description_getter.object_id}" extract_description(@description) end end tickloop = EM.tick_loop do if @done_creating_devices && @done_creating_services log 'All done creating stuff' :stop end end tickloop.on_stop { set_deferred_status :succeeded, self } end def extract_from_ssdp_notification(callback) log 'Creating device from SSDP Notification info.' @ssdp_notification = @device_info[:ssdp_notification] @cache_control = @ssdp_notification[:cache_control] @location = ssdp_notification[:location] @server = ssdp_notification[:server] @st = ssdp_notification[:st] || ssdp_notification[:nt] @ext = ssdp_notification.has_key?(:ext) ? true : false @usn = ssdp_notification[:usn] @date = ssdp_notification[:date] || '' @expiration = if @date.empty? Time.now + @cache_control.match(/\d+/)[0].to_i else Time.at(Time.parse(@date).to_i + @cache_control.match(/\d+/)[0].to_i) end if @location get_description(@location, callback) else message = 'M-SEARCH response is either missing the Location header or has an empty value.' message << "Response: #{@ssdp_notification}" if ControlPoint.raise_on_remote_error raise ControlPoint::Error, message end end end def extract_url_base if @description[:root] && @description[:root][:URLBase] @description[:root][:URLBase] elsif @device_info[:parent_base_url] @device_info[:parent_base_url] else tmp_uri = URI(@location) "#{tmp_uri.scheme}://#{tmp_uri.host}:#{tmp_uri.port}/" end end # True if the device hasn't received an alive notification since it last # told its max age. def expired? Time.now > @expiration if @expiration end def has_devices? !@device_list.empty? end def has_services? !@service_list.empty? end def extract_description(ddf) log 'Extracting basic attributes from description...' @device_type = ddf[:deviceType] || '' @friendly_name = ddf[:friendlyName] || '' @manufacturer = ddf[:manufacturer] || '' @manufacturer_url = ddf[:manufacturerURL] || '' @model_description = ddf[:modelDescription] || '' @model_name = ddf[:modelName] || '' @model_number = ddf[:modelNumber] || '' @model_url = ddf[:modelURL] || '' @serial_number = ddf[:serialNumber] || '' @udn = ddf[:UDN] || '' @upc = ddf[:UPC] || '' @icon_list = extract_icons(ddf[:iconList]) @presentation_url = ddf[:presentationURL] || '' log 'Basic attributes extracted.' start_device_extraction start_service_extraction end def extract_spec_version if @description[:root] "#{@description[:root][:specVersion][:major]}.#{@description[:root][:specVersion][:minor]}" end end def start_service_extraction services_extractor = EventMachine::DefaultDeferrable.new if @description[:serviceList] log 'Extracting services from non-root device.' extract_services(@description[:serviceList], services_extractor) elsif @description[:root][:device][:serviceList] log 'Extracting services from root device.' extract_services(@description[:root][:device][:serviceList], services_extractor) end services_extractor.errback do msg = 'Failed extracting services.' log msg, :error @done_creating_services = true if ControlPoint.raise_on_remote_error raise ControlPoint::Error, msg end end services_extractor.callback do |services| log 'Done extracting services.' @service_list = services log "New service count: #{@service_list.size}." @done_creating_services = true end end def start_device_extraction device_extractor = EventMachine::DefaultDeferrable.new extract_devices(device_extractor) device_extractor.errback do msg = 'Failed extracting device.' log msg, :error @done_creating_devices = true if ControlPoint.raise_on_remote_error raise ControlPoint::Error, msg end end device_extractor.callback do |device| if device log "Device extracted from #{device_extractor.object_id}." @device_list << device else log "Device extraction done from #{device_extractor.object_id} but none were extracted." end log "Child device size is now: #{@device_list.size}" @done_creating_devices = true end end # @return [Array<Hash>] def extract_icons(ddf_icon_list) return [] unless ddf_icon_list log "Icon list: #{ddf_icon_list}" if ddf_icon_list[:icon].is_a? Array ddf_icon_list[:icon].map do |values| values[:url] = build_url(@url_base, values[:url]) values end else [{ mimetype: ddf_icon_list[:icon][:mimetype], width: ddf_icon_list[:icon][:width], height: ddf_icon_list[:icon][:height], depth: ddf_icon_list[:icon][:depth], url: build_url(@url_base, ddf_icon_list[:icon][:url]) }] end end def extract_devices(group_device_extractor) log "Extracting child devices for #{self.object_id} using #{group_device_extractor.object_id}" device_list_hash = if @description.has_key? :root log 'Description has a :root key...' if @description[:root][:device][:deviceList] @description[:root][:device][:deviceList][:device] else log 'No child devices to extract.' group_device_extractor.set_deferred_status(:succeeded) end elsif @description[:deviceList] log 'Description does not have a :root key...' @description[:deviceList][:device] else log 'No child devices to extract.' group_device_extractor.set_deferred_status(:succeeded) end if device_list_hash.nil? || device_list_hash.empty? group_device_extractor.set_deferred_status(:succeeded) return end log "device list: #{device_list_hash}" if device_list_hash.is_a? Array EM::Iterator.new(device_list_hash, device_list_hash.count).map( proc do |device, iter| single_device_extractor = EventMachine::DefaultDeferrable.new single_device_extractor.errback do msg = 'Failed extracting device.' log msg, :error if ControlPoint.raise_on_remote_error raise ControlPoint::Error, msg end end single_device_extractor.callback do |d| iter.return(d) end extract_device(device, single_device_extractor) end, proc do |found_devices| group_device_extractor.set_deferred_status(:succeeded, found_devices) end ) else single_device_extractor = EventMachine::DefaultDeferrable.new single_device_extractor.errback do msg = 'Failed extracting device.' log msg, :error group_device_extractor.set_deferred_status(:failed, msg) if ControlPoint.raise_on_remote_error raise ControlPoint::Error, msg end end single_device_extractor.callback do |device| group_device_extractor.set_deferred_status(:succeeded, [device]) end log 'Extracting single device...' extract_device(device_list_hash, group_device_extractor) end end def extract_device(device, device_extractor) deferred_device = Device.new(device_description: device, parent_base_url: @url_base) deferred_device.errback do msg = "Couldn't build device!" log msg, :error device_extractor.set_deferred_status(:failed, msg) if ControlPoint.raise_on_remote_error raise ControlPoint::Error, msg end end deferred_device.callback do |built_device| log "Device created: #{built_device.device_type}" device_extractor.set_deferred_status(:succeeded, built_device) end deferred_device.fetch end def extract_services(service_list, group_service_extractor) log 'Extracting services...' log "service list: #{service_list}" return if service_list.nil? service_list.each_value do |service| if service.is_a? Array EM::Iterator.new(service, service.count).map( proc do |s, iter| single_service_extractor = EventMachine::DefaultDeferrable.new single_service_extractor.errback do msg = 'Failed to create service.' log msg, :error if ControlPoint.raise_on_remote_error raise ControlPoint::Error, msg end end single_service_extractor.callback do |s| iter.return(s) end extract_service(s, single_service_extractor) end, proc do |found_services| group_service_extractor.set_deferred_status(:succeeded, found_services) end ) else single_service_extractor = EventMachine::DefaultDeferrable.new single_service_extractor.errback do msg = 'Failed to create service.' log msg, :error group_service_extractor.set_deferred_status :failed, msg if ControlPoint.raise_on_remote_error raise ControlPoint::Error, msg end end single_service_extractor.callback do |s| group_service_extractor.set_deferred_status :succeeded, [s] end log 'Extracting single service...' extract_service(service, single_service_extractor) end end end def extract_service(service, single_service_extractor) service_getter = Service.new(@url_base, service) log "Extracting service with #{service_getter.object_id}" service_getter.errback do |message| msg = "Couldn't build service with info: #{service}" log msg, :error single_service_extractor.set_deferred_status(:failed, msg) if ControlPoint.raise_on_remote_error raise ControlPoint::Error, message end end service_getter.callback do |built_service| log "Service created: #{built_service.service_type}" single_service_extractor.set_deferred_status(:succeeded, built_service) end service_getter.fetch end end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/control_point/error.rb
lib/playful/control_point/error.rb
module Playful class ControlPoint class Error < StandardError # end # Indicates an error occurred when performing a UPnP action while controlling # a device. See section 3.2 of the UPnP spec. class ActionError < StandardError # end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/ssdp/searcher.rb
lib/playful/ssdp/searcher.rb
require_relative '../logger' require_relative 'multicast_connection' module Playful # A subclass of an EventMachine::Connection, this handles doing M-SEARCHes. # # Search types: # ssdp:all # upnp:rootdevice # uuid:[device-uuid] # urn:schemas-upnp-org:device:[deviceType-version] # urn:schemas-upnp-org:service:[serviceType-version] # urn:[custom-schema]:device:[deviceType-version] # urn:[custom-schema]:service:[serviceType-version] class SSDP::Searcher < SSDP::MulticastConnection include LogSwitch::Mixin DEFAULT_RESPONSE_WAIT_TIME = 5 DEFAULT_M_SEARCH_COUNT = 2 # @return [EventMachine::Channel] Provides subscribers with responses from # their search request. attr_reader :discovery_responses # @param [String] search_target # @param [Hash] options # @option options [Fixnum] response_wait_time # @option options [Fixnum] ttl # @option options [Fixnum] m_search_count The number of times to send the # M-SEARCH. UPnP 1.0 suggests to send the request more than once. def initialize(search_target, options = {}) options[:ttl] ||= TTL options[:response_wait_time] ||= DEFAULT_RESPONSE_WAIT_TIME @m_search_count = options[:m_search_count] ||= DEFAULT_M_SEARCH_COUNT @search = m_search(search_target, options[:response_wait_time]) super options[:ttl] end # This is the callback called by EventMachine when it receives data on the # socket that's been opened for this connection. In this case, the method # parses the SSDP responses/notifications into Hashes and adds them to the # appropriate EventMachine::Channel (provided as accessor methods). This # effectively means that in each Channel, you get a Hash that represents # the headers for each response/notification that comes in on the socket. # # @param [String] response The data received on this connection's socket. def receive_data(response) ip, port = peer_info log "Response from #{ip}:#{port}:\n#{response}\n" parsed_response = parse(response) return if parsed_response.has_key? :nts return if parsed_response[:man] && parsed_response[:man] =~ /ssdp:discover/ @discovery_responses << parsed_response end # Sends the M-SEARCH that was built during init. Logs what was sent if the # send was successful. def post_init @m_search_count.times do if send_datagram(@search, MULTICAST_IP, MULTICAST_PORT) > 0 log "Sent datagram search:\n#{@search}" end end end # Builds the M-SEARCH request string. # # @param [String] search_target # @param [Fixnum] response_wait_time def m_search(search_target, response_wait_time) <<-MSEARCH M-SEARCH * HTTP/1.1\r HOST: #{MULTICAST_IP}:#{MULTICAST_PORT}\r MAN: "ssdp:discover"\r MX: #{response_wait_time}\r ST: #{search_target}\r \r MSEARCH end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/ssdp/multicast_connection.rb
lib/playful/ssdp/multicast_connection.rb
require_relative '../../core_ext/socket_patch' require_relative 'network_constants' require_relative '../logger' require_relative 'error' require 'ipaddr' require 'socket' require 'eventmachine' require 'em-synchrony' module Playful class SSDP class MulticastConnection < EventMachine::Connection include Playful::SSDP::NetworkConstants include LogSwitch::Mixin # @param [Fixnum] ttl The TTL value to use when opening the UDP socket # required for SSDP actions. def initialize(ttl=TTL) @ttl = ttl @discovery_responses = EM::Channel.new @alive_notifications = EM::Channel.new @byebye_notifications = EM::Channel.new setup_multicast_socket end # Gets the IP and port from the peer that just sent data. # # @return [Array<String,Fixnum>] The IP and port. def peer_info peer_bytes = get_peername[2, 6].unpack('nC4') port = peer_bytes.first.to_i ip = peer_bytes[1, 4].join('.') [ip, port] end # Converts the headers to a set of key-value pairs. # # @param [String] data The data to convert. # @return [Hash] The converted data. Returns an empty Hash if it didn't # know how to parse. def parse(data) new_data = {} unless data =~ /\n/ log 'Received response as a single-line String. Discarding.' log "Bad response looked like:\n#{data}" return new_data end data.each_line do |line| line =~ /(\S+):(.*)/ unless $1.nil? key = $1 value = $2 key = key.gsub('-', '_').downcase.to_sym new_data[key] = value.strip end end new_data end # Sets Socket options to allow for multicasting. If ENV["RUBY_UPNP_ENV"] is # equal to "testing", then it doesn't turn off multicast looping. def setup_multicast_socket set_membership(IPAddr.new(MULTICAST_IP).hton + IPAddr.new('0.0.0.0').hton) set_multicast_ttl(@ttl) set_ttl(@ttl) unless ENV['RUBY_UPNP_ENV'] == 'testing' switch_multicast_loop :off end end # @param [String] membership The network byte ordered String that represents # the IP(s) that should join the membership group. def set_membership(membership) set_sock_opt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, membership) end # @param [Fixnum] ttl TTL to set IP_MULTICAST_TTL to. def set_multicast_ttl(ttl) set_sock_opt(Socket::IPPROTO_IP, Socket::IP_MULTICAST_TTL, [ttl].pack('i')) end # @param [Fixnum] ttl TTL to set IP_TTL to. def set_ttl(ttl) set_sock_opt(Socket::IPPROTO_IP, Socket::IP_TTL, [ttl].pack('i')) end # @param [Symbol] on_off Turn on/off multicast looping. Supply :on or :off. def switch_multicast_loop(on_off) hex_value = case on_off when :on then "\001" when "\001" then "\001" when :off then "\000" when "\000" then "\000" else raise SSDP::Error, "Can't switch IP_MULTICAST_LOOP to '#{on_off}'" end set_sock_opt(Socket::IPPROTO_IP, Socket::IP_MULTICAST_LOOP, hex_value) end end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/ssdp/notifier.rb
lib/playful/ssdp/notifier.rb
require_relative '../logger' require_relative 'multicast_connection' class Playful::SSDP::Notifier < Playful::SSDP::MulticastConnection include LogSwitch::Mixin def initialize(nt, usn, ddf_url, valid_for_duration) @os = RbConfig::CONFIG['host_vendor'].capitalize + '/' + RbConfig::CONFIG['host_os'] @upnp_version = '1.0' @notification = notification(nt, usn, ddf_url, valid_for_duration) end def post_init if send_datagram(@notification, MULTICAST_IP, MULTICAST_PORT) > 0 log "Sent notification:\n#{@notification}" end end # @param [String] nt "Notification Type"; a potential search target. Used in # +NT+ header. # @param [String] usn "Unique Service Name"; a composite identifier for the # advertisement. Used in +USN+ header. # @param [String] ddf_url Device Description File URL for the root device. # @param [Fixnum] valid_for_duration Duration in seconds for which the # advertisement is valid. Used in +CACHE-CONTROL+ header. def notification(nt, usn, ddf_url, valid_for_duration) <<-NOTIFICATION NOTIFY * HTTP/1.1\r HOST: #{MULTICAST_IP}:#{MULTICAST_PORT}\r CACHE-CONTROL: max-age=#{valid_for_duration}\r LOCATION: #{ddf_url}\r NT: #{nt}\r NTS: ssdp:alive\r SERVER: #{@os} UPnP/#{@upnp_version} Playful/#{Playful::VERSION}\r USN: #{usn}\r \r NOTIFICATION end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/ssdp/broadcast_searcher.rb
lib/playful/ssdp/broadcast_searcher.rb
require_relative '../../core_ext/socket_patch' require_relative '../logger' require_relative 'network_constants' require 'ipaddr' require 'socket' require 'eventmachine' # TODO: DRY this up!! (it's mostly the same as Playful::SSDP::MulticastConnection) module Playful class SSDP class BroadcastSearcher < EventMachine::Connection include LogSwitch::Mixin include EventMachine::Deferrable include Playful::SSDP::NetworkConstants # @return [Array] The list of responses from the current discovery request. attr_reader :discovery_responses attr_reader :available_responses attr_reader :byebye_responses def initialize(search_target, response_wait_time, ttl=TTL) @ttl = ttl @discovery_responses = [] @alive_notifications = [] @byebye_notifications = [] setup_broadcast_socket @search = m_search(search_target, response_wait_time) end def post_init if send_datagram(@search, BROADCAST_IP, MULTICAST_PORT) > 0 log "Sent broadcast datagram search:\n#{@search}" end end def m_search(search_target, response_wait_time) <<-MSEARCH M-SEARCH * HTTP/1.1\r HOST: #{MULTICAST_IP}:#{MULTICAST_PORT}\r MAN: "ssdp:discover"\r MX: #{response_wait_time}\r ST: #{search_target}\r \r MSEARCH end # Gets the IP and port from the peer that just sent data. # # @return [Array<String,Fixnum>] The IP and port. def peer_info peer_bytes = get_peername[2, 6].unpack('nC4') port = peer_bytes.first.to_i ip = peer_bytes[1, 4].join('.') [ip, port] end def receive_data(response) ip, port = peer_info log "Response from #{ip}:#{port}:\n#{response}\n" parsed_response = parse(response) if parsed_response.has_key? :nts if parsed_response[:nts] == 'ssdp:alive' @alive_notifications << parsed_response elsif parsed_response[:nts] == 'ssdp:bye-bye' @byebye_notifications << parsed_response else raise "Unknown NTS value: #{parsed_response[:nts]}" end else @discovery_responses << parsed_response end end # Converts the headers to a set of key-value pairs. # # @param [String] data The data to convert. # @return [Hash] The converted data. Returns an empty Hash if it didn't # know how to parse. def parse(data) new_data = {} unless data =~ /\n/ log 'Received response as a single-line String. Discarding.' log "Bad response looked like:\n#{data}" return new_data end data.each_line do |line| line =~ /(\S*):(.*)/ unless $1.nil? key = $1 value = $2 key = key.gsub('-', '_').downcase.to_sym new_data[key] = value.strip end end new_data end # Sets Socket options to allow for brodcasting. def setup_broadcast_socket set_sock_opt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true) end end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/ssdp/network_constants.rb
lib/playful/ssdp/network_constants.rb
module Playful class SSDP module NetworkConstants BROADCAST_IP = '255.255.255.255' # Default multicast IP address MULTICAST_IP = '239.255.255.250' # Default multicast port MULTICAST_PORT = 1900 # Default TTL TTL = 4 end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/ssdp/error.rb
lib/playful/ssdp/error.rb
module Playful class SSDP class Error < StandardError end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
turboladen/playful
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/ssdp/listener.rb
lib/playful/ssdp/listener.rb
require_relative 'multicast_connection' class Playful::SSDP::Listener < Playful::SSDP::MulticastConnection include LogSwitch::Mixin # @return [EventMachine::Channel] Provides subscribers with notifications # from devices that have come online (sent +ssdp:alive+ notifications). attr_reader :alive_notifications # @return [EventMachine::Channel] Provides subscribers with notifications # from devices that have gone offline (sent +ssd:byebye+ notifications). attr_reader :byebye_notifications # This is the callback called by EventMachine when it receives data on the # socket that's been opened for this connection. In this case, the method # parses the SSDP notifications into Hashes and adds them to the # appropriate EventMachine::Channel (provided as accessor methods). This # effectively means that in each Channel, you get a Hash that represents # the headers for each notification that comes in on the socket. # # @param [String] response The data received on this connection's socket. def receive_data(response) ip, port = peer_info log "Response from #{ip}:#{port}:\n#{response}\n" parsed_response = parse(response) return unless parsed_response.has_key? :nts if parsed_response[:nts] == 'ssdp:alive' @alive_notifications << parsed_response elsif parsed_response[:nts] == 'ssdp:byebye' @byebye_notifications << parsed_response else raise "Unknown NTS value: #{parsed_response[:nts]}" end end end
ruby
MIT
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
2026-01-04T17:51:58.974526Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/simple_recommender_test.rb
test/simple_recommender_test.rb
require 'test_helper' class SimpleRecommenderTest < ActiveSupport::TestCase test "module exists" do assert_kind_of Module, SimpleRecommender end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/test_helper.rb
test/test_helper.rb
# Configure Rails Environment ENV["RAILS_ENV"] = "test" require File.expand_path("../../test/dummy/config/environment.rb", __FILE__) ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)] require "rails/test_help" require "minitest/spec" # Filter out Minitest backtrace while allowing backtrace from other libraries # to be shown. Minitest.backtrace_filter = Minitest::BacktraceFilter.new # Load support files Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } # Load fixtures from the engine if ActiveSupport::TestCase.respond_to?(:fixture_path=) ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__) ActiveSupport::TestCase.fixtures :all end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/app/helpers/application_helper.rb
test/dummy/app/helpers/application_helper.rb
module ApplicationHelper end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/app/controllers/application_controller.rb
test/dummy/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/app/models/tag.rb
test/dummy/app/models/tag.rb
class Tag < ActiveRecord::Base end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/app/models/book.rb
test/dummy/app/models/book.rb
class Book < ActiveRecord::Base include SimpleRecommender::Recommendable has_and_belongs_to_many :tags has_many :likes has_many :users, through: :likes belongs_to :author, class_name: "User" similar_by :users end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/app/models/like.rb
test/dummy/app/models/like.rb
class Like < ActiveRecord::Base belongs_to :user belongs_to :book end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/app/models/user.rb
test/dummy/app/models/user.rb
class User < ActiveRecord::Base has_and_belongs_to_many :books end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/db/schema.rb
test/dummy/db/schema.rb
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20170125034341) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" enable_extension "intarray" create_table "books", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "author_id" end add_index "books", ["author_id"], name: "index_books_on_author_id", using: :btree create_table "books_tags", force: :cascade do |t| t.integer "book_id" t.integer "tag_id" end add_index "books_tags", ["book_id"], name: "index_books_tags_on_book_id", using: :btree add_index "books_tags", ["tag_id"], name: "index_books_tags_on_tag_id", using: :btree create_table "likes", force: :cascade do |t| t.integer "user_id" t.integer "book_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "likes", ["book_id"], name: "index_likes_on_book_id", using: :btree add_index "likes", ["user_id"], name: "index_likes_on_user_id", using: :btree create_table "tags", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "users", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_foreign_key "books_tags", "books" add_foreign_key "books_tags", "tags" add_foreign_key "likes", "books" add_foreign_key "likes", "users" end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/db/migrate/20170123001909_create_books_users.rb
test/dummy/db/migrate/20170123001909_create_books_users.rb
class CreateBooksUsers < ActiveRecord::Migration def change create_table :books_users do |t| t.references :book t.references :user end add_index :books_users, [:book_id, :user_id], unique: true add_index :books_users, :user_id end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/db/migrate/20170125034331_create_books_tags.rb
test/dummy/db/migrate/20170125034331_create_books_tags.rb
class CreateBooksTags < ActiveRecord::Migration def change create_table :books_tags do |t| t.references :book, index: true, foreign_key: true t.references :tag, index: true, foreign_key: true end end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/db/migrate/20170125034341_remove_books_users.rb
test/dummy/db/migrate/20170125034341_remove_books_users.rb
class RemoveBooksUsers < ActiveRecord::Migration def change drop_table :books_users end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/db/migrate/20170125030446_create_likes.rb
test/dummy/db/migrate/20170125030446_create_likes.rb
class CreateLikes < ActiveRecord::Migration def change create_table :likes do |t| t.references :user, index: true, foreign_key: true t.references :book, index: true, foreign_key: true t.timestamps null: false end end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/db/migrate/20170125032813_add_author_to_books.rb
test/dummy/db/migrate/20170125032813_add_author_to_books.rb
class AddAuthorToBooks < ActiveRecord::Migration def change add_reference :books, :author, index: true end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/db/migrate/20170125030342_create_tags.rb
test/dummy/db/migrate/20170125030342_create_tags.rb
class CreateTags < ActiveRecord::Migration def change create_table :tags do |t| t.string :name t.timestamps null: false end end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/db/migrate/20170123010745_enable_int_array_extension.rb
test/dummy/db/migrate/20170123010745_enable_int_array_extension.rb
class EnableIntArrayExtension < ActiveRecord::Migration def change enable_extension "intarray" end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/db/migrate/20170123001813_create_books.rb
test/dummy/db/migrate/20170123001813_create_books.rb
class CreateBooks < ActiveRecord::Migration def change create_table :books do |t| t.string :name t.timestamps null: false end end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/db/migrate/20170123001819_create_users.rb
test/dummy/db/migrate/20170123001819_create_users.rb
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :name t.timestamps null: false end end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/test/models/tag_test.rb
test/dummy/test/models/tag_test.rb
require 'test_helper' class TagTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/test/models/user_test.rb
test/dummy/test/models/user_test.rb
require 'test_helper' class UserTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/test/models/like_test.rb
test/dummy/test/models/like_test.rb
require 'test_helper' class LikeTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/test/models/book_test.rb
test/dummy/test/models/book_test.rb
require 'test_helper' class BookTest < ActiveSupport::TestCase describe BookTest do let(:python_book) { Book.find_by(name: "Learning Python") } let(:ruby_book) { Book.find_by(name: "Learning Ruby") } let(:cpp_book) { Book.find_by(name: "Learning C++") } let(:violin_book) { Book.find_by(name: "Playing Violin") } describe "#similar_items" do let(:n_results) { 3 } subject { python_book.similar_items(n_results: n_results) } it "returns similar books" do assert_equal [ruby_book, cpp_book, violin_book], subject end it "returns similarity scores" do expected_similarities = [1.0, (1.0/3), (1.0/3)] expected_similarities.zip(subject.map(&:similarity)).each do |expected, actual| assert_in_delta expected, actual, 0.01 end end end end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/application.rb
test/dummy/config/application.rb
require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" # require "sprockets/railtie" require "rails/test_unit/railtie" Bundler.require(*Rails.groups) require "simple_recommender" module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/environment.rb
test/dummy/config/environment.rb
# Load the Rails application. require File.expand_path('../application', __FILE__) # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/routes.rb
test/dummy/config/routes.rb
Rails.application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/boot.rb
test/dummy/config/boot.rb
# Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) $LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__)
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/initializers/filter_parameter_logging.rb
test/dummy/config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [:password]
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false