mirror of
https://github.com/onyx-and-iris/obsws-ruby.git
synced 2026-04-09 09:53:29 +00:00
Compare commits
76 Commits
main
...
662f14282f
| Author | SHA1 | Date | |
|---|---|---|---|
| 662f14282f | |||
| 2e0e584d3a | |||
| a8425cf7cd | |||
| 7e580dc91a | |||
| 92174219a7 | |||
| 0c71eb2398 | |||
| 3ea21cd371 | |||
| 70b60b3cac | |||
| c97d14abe2 | |||
| 123b9c55ca | |||
| 299351cac0 | |||
| 3ef4396885 | |||
| c6bb8d07ff | |||
| 48b94a2682 | |||
| 210d13ba1e | |||
| 59bcf2a338 | |||
| dc8ac155ec | |||
| 23d64ef9d8 | |||
| 9be9dc80a2 | |||
| a40ab77be9 | |||
| b440ace20c | |||
| f5a817ab4e | |||
| 13f57f79f6 | |||
| 976c8f19a8 | |||
| 515fa565d4 | |||
| 46bfb53db8 | |||
| f669498c69 | |||
| aeec0635ca | |||
| 86b84aeef9 | |||
| e4f4961c56 | |||
| 4fdebc8178 | |||
| 155cbe019a | |||
| 6293ae7b8c | |||
| 57fca646b5 | |||
| d12a1a5954 | |||
| 438f3b1659 | |||
| d15418a660 | |||
| 2883fd42cc | |||
| 88b2eabc0c | |||
| e15e17cc9f | |||
| 72e09d5278 | |||
| 11d991b039 | |||
| 3d3d8f3020 | |||
| 82c6ced760 | |||
| 72ee539b96 | |||
| bbfaf486c3 | |||
| 8534c59fa2 | |||
| 9940fbbf9f | |||
| 18d291c6eb | |||
| 6dc21314e8 | |||
| 15585c90e9 | |||
| 15c4baf5d7 | |||
| 15dcaeedda | |||
| 856b7b5a5b | |||
| af85d8b9ab | |||
| 5f08b97759 | |||
| 73ae24eb4b | |||
| 153f35e742 | |||
| 17dcaa18d8 | |||
| 955b00571a | |||
| d9b054b108 | |||
| 799ae52b02 | |||
| bc93654297 | |||
| aafcd185d0 | |||
| 43ecfb37f5 | |||
| 2e70c63ae7 | |||
| c67ce47026 | |||
|
|
0bac7eaf3a | ||
|
|
5b0ce79e46 | ||
|
|
a0f5d8e57b | ||
|
|
f1a1c970e0 | ||
|
|
449684c405 | ||
|
|
da5ef76c81 | ||
|
|
8752132012 | ||
|
|
fb162ca195 | ||
|
|
b33fe94cee |
7
.gitignore
vendored
7
.gitignore
vendored
@@ -46,7 +46,8 @@ build-iPhoneSimulator/
|
||||
# for a library or gem, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# Gemfile.lock
|
||||
# .ruby-version
|
||||
.ruby-version
|
||||
.ruby_version
|
||||
# .ruby-gemset
|
||||
|
||||
# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
|
||||
@@ -56,6 +57,8 @@ build-iPhoneSimulator/
|
||||
# .rubocop-https?--*
|
||||
|
||||
# config
|
||||
obs.toml
|
||||
obs.yml
|
||||
# quick test
|
||||
quick.rb
|
||||
|
||||
.vscode/
|
||||
50
Gemfile.lock
50
Gemfile.lock
@@ -1,20 +1,58 @@
|
||||
PATH
|
||||
remote: .
|
||||
specs:
|
||||
obsws (0.0.3)
|
||||
observer (~> 0.1.1)
|
||||
obsws (0.5.8)
|
||||
waitutil (~> 0.2.1)
|
||||
websocket-driver (~> 0.7.5)
|
||||
|
||||
GEM
|
||||
remote: https://rubygems.org/
|
||||
specs:
|
||||
ast (2.4.2)
|
||||
json (2.6.3)
|
||||
language_server-protocol (3.17.0.3)
|
||||
lint_roller (1.1.0)
|
||||
minitest (5.16.3)
|
||||
observer (0.1.1)
|
||||
perfect_toml (0.9.0)
|
||||
parallel (1.23.0)
|
||||
parser (3.2.2.3)
|
||||
ast (~> 2.4.1)
|
||||
racc
|
||||
racc (1.7.1)
|
||||
rainbow (3.1.1)
|
||||
rake (11.3.0)
|
||||
regexp_parser (2.8.1)
|
||||
rexml (3.2.5)
|
||||
rubocop (1.52.1)
|
||||
json (~> 2.3)
|
||||
parallel (~> 1.10)
|
||||
parser (>= 3.2.2.3)
|
||||
rainbow (>= 2.2.2, < 4.0)
|
||||
regexp_parser (>= 1.8, < 3.0)
|
||||
rexml (>= 3.2.5, < 4.0)
|
||||
rubocop-ast (>= 1.28.0, < 2.0)
|
||||
ruby-progressbar (~> 1.7)
|
||||
unicode-display_width (>= 2.4.0, < 3.0)
|
||||
rubocop-ast (1.29.0)
|
||||
parser (>= 3.2.1.0)
|
||||
rubocop-performance (1.18.0)
|
||||
rubocop (>= 1.7.0, < 2.0)
|
||||
rubocop-ast (>= 0.4.0)
|
||||
ruby-progressbar (1.13.0)
|
||||
standard (1.30.1)
|
||||
language_server-protocol (~> 3.17.0.2)
|
||||
lint_roller (~> 1.0)
|
||||
rubocop (~> 1.52.0)
|
||||
standard-custom (~> 1.0.0)
|
||||
standard-performance (~> 1.1.0)
|
||||
standard-custom (1.0.2)
|
||||
lint_roller (~> 1.0)
|
||||
rubocop (~> 1.50)
|
||||
standard-performance (1.1.2)
|
||||
lint_roller (~> 1.1)
|
||||
rubocop-performance (~> 1.18.0)
|
||||
unicode-display_width (2.4.2)
|
||||
waitutil (0.2.1)
|
||||
websocket-driver (0.7.5)
|
||||
websocket-driver (0.7.6)
|
||||
websocket-extensions (>= 0.1.0)
|
||||
websocket-extensions (0.1.5)
|
||||
|
||||
@@ -24,8 +62,8 @@ PLATFORMS
|
||||
DEPENDENCIES
|
||||
minitest (~> 5.16, >= 5.16.3)
|
||||
obsws!
|
||||
perfect_toml (~> 0.9.0)
|
||||
rake (~> 11.2, >= 11.2.2)
|
||||
standard (~> 1.30)
|
||||
|
||||
BUNDLED WITH
|
||||
2.3.22
|
||||
|
||||
86
README.md
86
README.md
@@ -1,8 +1,8 @@
|
||||
[](https://badge.fury.io/rb/obsws)
|
||||
[](https://github.com/onyx-and-iris/obsws-ruby/blob/dev/LICENSE)
|
||||
[](https://github.com/prettier/plugin-ruby)
|
||||
[](https://github.com/standardrb/standard)
|
||||
|
||||
# A Ruby wrapper around OBS Studio WebSocket v5.0
|
||||
# Ruby Clients for OBS Studio WebSocket v5.0
|
||||
|
||||
## Requirements
|
||||
|
||||
@@ -16,77 +16,79 @@
|
||||
### Bundler
|
||||
|
||||
```
|
||||
bundle add 'obsws'
|
||||
bundle add obsws
|
||||
bundle install
|
||||
```
|
||||
|
||||
### Gem
|
||||
|
||||
`gem install 'obsws'`
|
||||
|
||||
## `Use`
|
||||
|
||||
#### Example `main.rb`
|
||||
|
||||
pass `host`, `port` and `password` as keyword arguments.
|
||||
Pass `host`, `port` and `password` as keyword arguments.
|
||||
|
||||
```ruby
|
||||
require "obsws"
|
||||
|
||||
def main
|
||||
r_client =
|
||||
OBSWS::Requests::Client.new(
|
||||
host: "localhost",
|
||||
port: 4455,
|
||||
password: "strongpassword"
|
||||
)
|
||||
class Main
|
||||
INPUT = "Mic/Aux"
|
||||
|
||||
r_client.run do
|
||||
# Toggle the mute state of your Mic input
|
||||
r_client.toggle_input_mute("Mic/Aux")
|
||||
def run
|
||||
OBSWS::Requests::Client
|
||||
.new(host: "localhost", port: 4455, password: "strongpassword")
|
||||
.run do |client|
|
||||
# Toggle the mute state of your Mic input and print its new mute state
|
||||
client.toggle_input_mute(INPUT)
|
||||
resp = client.get_input_mute(INPUT)
|
||||
puts "Input '#{INPUT}' was set to #{resp.input_muted}"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
main if $0 == __FILE__
|
||||
Main.new.run if $PROGRAM_NAME == __FILE__
|
||||
```
|
||||
|
||||
Passing OBSWS::Requests::Client.run a block closes the socket once the block returns.
|
||||
|
||||
### Requests
|
||||
|
||||
Method names for requests match the API calls but snake cased. `run` accepts a block that closes the socket once you are done.
|
||||
Method names for requests match the API calls but snake cased.
|
||||
|
||||
example:
|
||||
|
||||
```ruby
|
||||
r_client.run do
|
||||
# GetVersion
|
||||
resp = r_client.get_version
|
||||
# GetVersion
|
||||
resp = r_client.get_version
|
||||
|
||||
# SetCurrentProgramScene
|
||||
r_client.set_current_program_scene("BRB")
|
||||
end
|
||||
# SetCurrentProgramScene
|
||||
r_client.set_current_program_scene("BRB")
|
||||
```
|
||||
|
||||
For a full list of requests refer to [Requests](https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#requests)
|
||||
|
||||
### Events
|
||||
|
||||
Register an observer class and define `on_` methods for events. Method names should match the api event but snake cased.
|
||||
Register `on_` callback methods. Method names should match the api event but snake cased.
|
||||
|
||||
example:
|
||||
|
||||
```ruby
|
||||
class Observer
|
||||
def initialize
|
||||
@e_client = OBSWS::Events::Client.new(**kwargs)
|
||||
# register class with the event client
|
||||
@e_client.add_observer(self)
|
||||
@e_client = OBSWS::Events::Client.new(host: "localhost", port: 4455, password: "strongpassword")
|
||||
# register callback methods with the Event client
|
||||
@e_client.register(
|
||||
[
|
||||
method(:on_current_program_scene_changed),
|
||||
method(:on_input_mute_state_changed)
|
||||
]
|
||||
)
|
||||
end
|
||||
|
||||
# define "on_" event methods.
|
||||
def on_current_program_scene_changed
|
||||
def on_current_program_scene_changed(data)
|
||||
...
|
||||
end
|
||||
def on_input_mute_state_changed
|
||||
def on_input_mute_state_changed(data)
|
||||
...
|
||||
end
|
||||
...
|
||||
@@ -111,10 +113,28 @@ def on_scene_created(data):
|
||||
|
||||
### Errors
|
||||
|
||||
If a request fails an `OBSWSError` will be raised with a status code.
|
||||
If a general error occurs an `OBSWSError` will be raised.
|
||||
|
||||
If a connection attempt fails or times out an `OBSWSConnectionError` will be raised.
|
||||
|
||||
If a request fails an `OBSWSRequestError` will be raised with a status code.
|
||||
|
||||
- The request name and code are retrievable through the following attributes:
|
||||
- `req_name`
|
||||
- `code`
|
||||
|
||||
For a full list of status codes refer to [Codes](https://github.com/obsproject/obs-websocket/blob/master/docs/generated/protocol.md#requeststatus)
|
||||
|
||||
### Logging
|
||||
|
||||
To enable logs set an environmental variable `OBSWS_LOG_LEVEL` to the appropriate level.
|
||||
|
||||
example in powershell:
|
||||
|
||||
```powershell
|
||||
$env:OBSWS_LOG_LEVEL="DEBUG"
|
||||
```
|
||||
|
||||
### Tests
|
||||
|
||||
To run all tests:
|
||||
|
||||
22
Rakefile
22
Rakefile
@@ -1,9 +1,29 @@
|
||||
require "minitest/test_task"
|
||||
|
||||
HERE = __dir__
|
||||
|
||||
Minitest::TestTask.create(:test) do |t|
|
||||
t.libs << "test"
|
||||
t.warning = false
|
||||
t.test_globs = ["test/**/*_test.rb"]
|
||||
t.test_globs = ["test/**/test_*.rb"]
|
||||
end
|
||||
|
||||
task default: :test
|
||||
|
||||
namespace :e do
|
||||
desc "Runs the events example"
|
||||
task :events do
|
||||
filepath = File.join(HERE, "examples", "events", "main.rb")
|
||||
ruby filepath
|
||||
end
|
||||
desc "Runs the levels example"
|
||||
task :levels do
|
||||
filepath = File.join(HERE, "examples", "levels", "main.rb")
|
||||
ruby filepath
|
||||
end
|
||||
desc "Runs the scene_rotate example"
|
||||
task :scene_rotate do
|
||||
filepath = File.join(HERE, "examples", "scene_rotate", "main.rb")
|
||||
ruby filepath
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
source "https://rubygems.org"
|
||||
|
||||
# gem "rails"
|
||||
|
||||
gem "perfect_toml", "~> 0.9.0"
|
||||
|
||||
gem "obsws", path: "../.."
|
||||
@@ -1,27 +0,0 @@
|
||||
PATH
|
||||
remote: ../..
|
||||
specs:
|
||||
obsws (0.0.2)
|
||||
observer (~> 0.1.1)
|
||||
waitutil (~> 0.2.1)
|
||||
websocket-driver (~> 0.7.5)
|
||||
|
||||
GEM
|
||||
remote: https://rubygems.org/
|
||||
specs:
|
||||
observer (0.1.1)
|
||||
perfect_toml (0.9.0)
|
||||
waitutil (0.2.1)
|
||||
websocket-driver (0.7.5)
|
||||
websocket-extensions (>= 0.1.0)
|
||||
websocket-extensions (0.1.5)
|
||||
|
||||
PLATFORMS
|
||||
x64-mingw-ucrt
|
||||
|
||||
DEPENDENCIES
|
||||
obsws!
|
||||
perfect_toml (~> 0.9.0)
|
||||
|
||||
BUNDLED WITH
|
||||
2.3.24
|
||||
@@ -1,28 +1,27 @@
|
||||
require "obsws"
|
||||
require "perfect_toml"
|
||||
require_relative "../../lib/obsws"
|
||||
require "yaml"
|
||||
|
||||
OBSWS::LOGGER.debug!
|
||||
|
||||
class Observer
|
||||
attr_reader :running
|
||||
|
||||
class Main
|
||||
def initialize(**kwargs)
|
||||
@r_client = OBSWS::Requests::Client.new(**kwargs)
|
||||
@e_client = OBSWS::Events::Client.new(**kwargs)
|
||||
@e_client.add_observer(self)
|
||||
|
||||
puts info.join("\n")
|
||||
puts infostring
|
||||
@running = true
|
||||
end
|
||||
|
||||
def info
|
||||
def run
|
||||
sleep(0.1) while @running
|
||||
end
|
||||
|
||||
def infostring
|
||||
resp = @r_client.get_version
|
||||
[
|
||||
"Using obs version:",
|
||||
resp.obs_version,
|
||||
"With websocket version:",
|
||||
resp.obs_web_socket_version
|
||||
]
|
||||
"Using obs version: #{resp.obs_version}.",
|
||||
"With websocket version: #{resp.obs_web_socket_version}"
|
||||
].join(" ")
|
||||
end
|
||||
|
||||
def on_current_program_scene_changed(data)
|
||||
@@ -45,14 +44,8 @@ class Observer
|
||||
end
|
||||
end
|
||||
|
||||
def conn_from_toml
|
||||
PerfectTOML.load_file("obs.toml", symbolize_names: true)[:connection]
|
||||
def conn_from_yaml
|
||||
YAML.load_file("obs.yml", symbolize_names: true)[:connection]
|
||||
end
|
||||
|
||||
def main
|
||||
o = Observer.new(**conn_from_toml)
|
||||
|
||||
sleep(0.1) while o.running
|
||||
end
|
||||
|
||||
main if $0 == __FILE__
|
||||
Main.new(**conn_from_yaml).run if $PROGRAM_NAME == __FILE__
|
||||
|
||||
52
examples/levels/main.rb
Normal file
52
examples/levels/main.rb
Normal file
@@ -0,0 +1,52 @@
|
||||
require_relative "../../lib/obsws"
|
||||
require "yaml"
|
||||
|
||||
module LevelTypes
|
||||
VU = 0
|
||||
POSTFADER = 1
|
||||
PREFADER = 2
|
||||
end
|
||||
|
||||
class Main
|
||||
DEVICE = "Desktop Audio"
|
||||
|
||||
def initialize(**kwargs)
|
||||
subs = OBSWS::Events::SUBS::LOW_VOLUME | OBSWS::Events::SUBS::INPUTVOLUMEMETERS
|
||||
@e_client = OBSWS::Events::Client.new(subs:, **kwargs)
|
||||
@e_client.register(
|
||||
[
|
||||
method(:on_input_mute_state_changed),
|
||||
method(:on_input_volume_meters)
|
||||
]
|
||||
)
|
||||
end
|
||||
|
||||
def run
|
||||
puts "press <Enter> to quit"
|
||||
loop { break if gets.chomp.empty? }
|
||||
end
|
||||
|
||||
def on_input_mute_state_changed(data)
|
||||
if data.input_name == DEVICE
|
||||
puts "#{DEVICE} mute toggled"
|
||||
end
|
||||
end
|
||||
|
||||
def on_input_volume_meters(data)
|
||||
fget = ->(x) { (x > 0) ? (20 * Math.log(x, 10)).round(1) : -200.0 }
|
||||
|
||||
data.inputs.each do |d|
|
||||
name = d[:inputName]
|
||||
if name == DEVICE && !d[:inputLevelsMul].empty?
|
||||
left, right = d[:inputLevelsMul]
|
||||
puts "#{name} [L: #{fget.call(left[LevelTypes::POSTFADER])}, R: #{fget.call(right[LevelTypes::POSTFADER])}]"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def conn_from_yaml
|
||||
YAML.load_file("obs.yml", symbolize_names: true)[:connection]
|
||||
end
|
||||
|
||||
Main.new(**conn_from_yaml).run if $PROGRAM_NAME == __FILE__
|
||||
23
examples/scene_rotate/main.rb
Normal file
23
examples/scene_rotate/main.rb
Normal file
@@ -0,0 +1,23 @@
|
||||
require_relative "../../lib/obsws"
|
||||
require "yaml"
|
||||
|
||||
|
||||
class Main
|
||||
def conn_from_yaml
|
||||
YAML.load_file("obs.yml", symbolize_names: true)[:connection]
|
||||
end
|
||||
|
||||
def run
|
||||
OBSWS::Requests::Client.new(**conn_from_yaml).run do |client|
|
||||
resp = client.get_scene_list
|
||||
resp.scenes.reverse_each do |scene|
|
||||
puts "Switching to scene #{scene[:sceneName]}"
|
||||
client.set_current_program_scene(scene[:sceneName])
|
||||
sleep(0.5)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
Main.new.run if $PROGRAM_NAME == __FILE__
|
||||
33
lib/obsws.rb
33
lib/obsws.rb
@@ -1,11 +1,36 @@
|
||||
require "digest/sha2"
|
||||
require "json"
|
||||
require "logger"
|
||||
require "securerandom"
|
||||
require "socket"
|
||||
require "waitutil"
|
||||
require "websocket/driver"
|
||||
|
||||
require_relative "obsws/logger"
|
||||
require_relative "obsws/driver"
|
||||
require_relative "obsws/util"
|
||||
require_relative "obsws/mixin"
|
||||
require_relative "obsws/base"
|
||||
|
||||
require_relative "obsws/req"
|
||||
require_relative "obsws/event"
|
||||
|
||||
module OBSWS
|
||||
include Logger::Severity
|
||||
require_relative "obsws/version"
|
||||
|
||||
LOGGER = Logger.new(STDOUT)
|
||||
LOGGER.level = WARN
|
||||
module OBSWS
|
||||
class OBSWSError < StandardError; end
|
||||
|
||||
class OBSWSConnectionError < OBSWSError; end
|
||||
|
||||
class OBSWSRequestError < OBSWSError
|
||||
attr_reader :req_name, :code
|
||||
|
||||
def initialize(req_name, code, comment)
|
||||
@req_name = req_name
|
||||
@code = code
|
||||
message = "Request #{@req_name} returned code #{@code}."
|
||||
message << " With message: #{comment}" if comment
|
||||
super(message)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,72 +1,44 @@
|
||||
require "socket"
|
||||
require "websocket/driver"
|
||||
require "digest/sha2"
|
||||
require "json"
|
||||
require "observer"
|
||||
require "waitutil"
|
||||
|
||||
require_relative "mixin"
|
||||
require_relative "error"
|
||||
|
||||
module OBSWS
|
||||
class Socket
|
||||
attr_reader :url
|
||||
class Identified
|
||||
attr_accessor :state
|
||||
|
||||
def initialize(url, socket)
|
||||
@url = url
|
||||
@socket = socket
|
||||
def initialize
|
||||
@state = :pending
|
||||
end
|
||||
|
||||
def write(s)
|
||||
@socket.write(s)
|
||||
def error_message
|
||||
case @state
|
||||
when :passwordless
|
||||
"auth enabled but no password provided"
|
||||
else
|
||||
"failed to identify client with the websocket server"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
class Base
|
||||
include Observable
|
||||
include Logging
|
||||
include Driver::Director
|
||||
include Mixin::OPCodes
|
||||
|
||||
attr_reader :id, :driver, :closed
|
||||
attr_reader :closed, :identified
|
||||
attr_writer :updater
|
||||
|
||||
def initialize(**kwargs)
|
||||
host = kwargs[:host] || "localhost"
|
||||
port = kwargs[:port] || 4455
|
||||
@password = kwargs[:password] || ""
|
||||
@subs = kwargs[:subs] || 0
|
||||
|
||||
@socket = TCPSocket.new(host, port)
|
||||
@driver =
|
||||
WebSocket::Driver.client(Socket.new("ws://#{host}:#{port}", @socket))
|
||||
@driver.on :open do |msg|
|
||||
LOGGER.debug("driver socket open")
|
||||
end
|
||||
@driver.on :close do |msg|
|
||||
LOGGER.debug("driver socket closed")
|
||||
@closed = true
|
||||
end
|
||||
@driver.on :message do |msg|
|
||||
LOGGER.debug("received [#{msg}] passing to handler")
|
||||
msg_handler(JSON.parse(msg.data, symbolize_names: true))
|
||||
end
|
||||
start_driver
|
||||
@identified = Identified.new
|
||||
setup_driver(host, port) and start_driver
|
||||
WaitUtil.wait_for_condition(
|
||||
"waiting successful identification",
|
||||
"successful identification",
|
||||
delay_sec: 0.01,
|
||||
timeout_sec: 3
|
||||
) { @identified }
|
||||
timeout_sec: kwargs[:connect_timeout] || 3
|
||||
) { @identified.state != :pending }
|
||||
end
|
||||
|
||||
def start_driver
|
||||
Thread.new do
|
||||
@driver.start
|
||||
|
||||
loop do
|
||||
@driver.parse(@socket.readpartial(4096))
|
||||
rescue EOFError
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
private
|
||||
|
||||
def auth_token(salt:, challenge:)
|
||||
Digest::SHA256.base64digest(
|
||||
@@ -74,7 +46,7 @@ module OBSWS
|
||||
)
|
||||
end
|
||||
|
||||
def authenticate(auth = nil)
|
||||
def identify(auth)
|
||||
payload = {
|
||||
op: Mixin::OPCodes::IDENTIFY,
|
||||
d: {
|
||||
@@ -82,29 +54,29 @@ module OBSWS
|
||||
eventSubscriptions: @subs
|
||||
}
|
||||
}
|
||||
payload[:d][:authentication] = auth_token(**auth) if auth
|
||||
if auth
|
||||
if @password.empty?
|
||||
@identified.state = :passwordless
|
||||
return
|
||||
end
|
||||
logger.info("initiating authentication")
|
||||
payload[:d][:authentication] = auth_token(**auth)
|
||||
end
|
||||
@driver.text(JSON.generate(payload))
|
||||
end
|
||||
|
||||
def msg_handler(data)
|
||||
case data[:op]
|
||||
when Mixin::OPCodes::HELLO
|
||||
if data[:d].key? :authentication
|
||||
LOGGER.debug("initiating authentication")
|
||||
else
|
||||
LOGGER.debug("authentication disabled... skipping.")
|
||||
end
|
||||
authenticate(data[:d][:authentication])
|
||||
identify(data[:d][:authentication])
|
||||
when Mixin::OPCodes::IDENTIFIED
|
||||
LOGGER.debug("client succesfully identified with server")
|
||||
@identified = true
|
||||
@identified.state = :identified
|
||||
when Mixin::OPCodes::EVENT, Mixin::OPCodes::REQUESTRESPONSE
|
||||
changed
|
||||
notify_observers(data[:op], data[:d])
|
||||
@updater.call(data[:op], data[:d])
|
||||
end
|
||||
end
|
||||
|
||||
def req(id, type_, data = nil)
|
||||
public def req(id, type_, data = nil)
|
||||
payload = {
|
||||
op: Mixin::OPCodes::REQUEST,
|
||||
d: {
|
||||
@@ -113,8 +85,8 @@ module OBSWS
|
||||
}
|
||||
}
|
||||
payload[:d][:requestData] = data if data
|
||||
queued = @driver.text(JSON.generate(payload))
|
||||
LOGGER.debug("request with id #{id} queued? #{queued}")
|
||||
logger.debug("sending request: #{payload}")
|
||||
@driver.text(JSON.generate(payload))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
50
lib/obsws/driver.rb
Normal file
50
lib/obsws/driver.rb
Normal file
@@ -0,0 +1,50 @@
|
||||
module OBSWS
|
||||
module Driver
|
||||
class Socket
|
||||
attr_reader :url
|
||||
|
||||
def initialize(url, socket)
|
||||
@url = url
|
||||
@socket = socket
|
||||
end
|
||||
|
||||
def write(s)
|
||||
@socket.write(s)
|
||||
end
|
||||
end
|
||||
|
||||
module Director
|
||||
def setup_driver(host, port)
|
||||
@socket = TCPSocket.new(host, port)
|
||||
@driver =
|
||||
WebSocket::Driver.client(Socket.new("ws://#{host}:#{port}", @socket))
|
||||
@driver.on :open do |msg|
|
||||
logger.debug("driver socket open")
|
||||
end
|
||||
@driver.on :close do |msg|
|
||||
logger.debug("driver socket closed")
|
||||
@closed = true
|
||||
end
|
||||
@driver.on :message do |msg|
|
||||
msg_handler(JSON.parse(msg.data, symbolize_names: true))
|
||||
end
|
||||
end
|
||||
|
||||
private def start_driver
|
||||
Thread.new do
|
||||
@driver.start
|
||||
|
||||
loop do
|
||||
@driver.parse(@socket.readpartial(4096))
|
||||
rescue EOFError
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
public def stop_driver
|
||||
@driver.close
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,6 +0,0 @@
|
||||
module OBSWS
|
||||
module Error
|
||||
class OBSWSError < StandardError
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,91 +1,99 @@
|
||||
require "json"
|
||||
|
||||
require_relative "util"
|
||||
require_relative "mixin"
|
||||
|
||||
module OBSWS
|
||||
module Events
|
||||
module SUBS
|
||||
NONE = 0
|
||||
GENERAL = (1 << 0)
|
||||
CONFIG = (1 << 1)
|
||||
SCENES = (1 << 2)
|
||||
INPUTS = (1 << 3)
|
||||
TRANSITIONS = (1 << 4)
|
||||
FILTERS = (1 << 5)
|
||||
OUTPUTS = (1 << 6)
|
||||
SCENEITEMS = (1 << 7)
|
||||
MEDIAINPUTS = (1 << 8)
|
||||
VENDORS = (1 << 9)
|
||||
UI = (1 << 10)
|
||||
GENERAL = 1 << 0
|
||||
CONFIG = 1 << 1
|
||||
SCENES = 1 << 2
|
||||
INPUTS = 1 << 3
|
||||
TRANSITIONS = 1 << 4
|
||||
FILTERS = 1 << 5
|
||||
OUTPUTS = 1 << 6
|
||||
SCENEITEMS = 1 << 7
|
||||
MEDIAINPUTS = 1 << 8
|
||||
VENDORS = 1 << 9
|
||||
UI = 1 << 10
|
||||
|
||||
def low_volume
|
||||
GENERAL | CONFIG | SCENES | INPUTS | TRANSITIONS | FILTERS | OUTPUTS |
|
||||
LOW_VOLUME = GENERAL | CONFIG | SCENES | INPUTS | TRANSITIONS | FILTERS | OUTPUTS |
|
||||
SCENEITEMS | MEDIAINPUTS | VENDORS | UI
|
||||
end
|
||||
|
||||
INPUTVOLUMEMETERS = (1 << 16)
|
||||
INPUTACTIVESTATECHANGED = (1 << 17)
|
||||
INPUTSHOWSTATECHANGED = (1 << 18)
|
||||
SCENEITEMTRANSFORMCHANGED = (1 << 19)
|
||||
INPUTVOLUMEMETERS = 1 << 16
|
||||
INPUTACTIVESTATECHANGED = 1 << 17
|
||||
INPUTSHOWSTATECHANGED = 1 << 18
|
||||
SCENEITEMTRANSFORMCHANGED = 1 << 19
|
||||
|
||||
def high_volume
|
||||
INPUTVOLUMEMETERS | INPUTACTIVESTATECHANGED | INPUTSHOWSTATECHANGED |
|
||||
HIGH_VOLUME = INPUTVOLUMEMETERS | INPUTACTIVESTATECHANGED | INPUTSHOWSTATECHANGED |
|
||||
SCENEITEMTRANSFORMCHANGED
|
||||
end
|
||||
|
||||
def all
|
||||
low_volume | high_volume
|
||||
end
|
||||
|
||||
module_function :low_volume, :high_volume, :all
|
||||
ALL = LOW_VOLUME | HIGH_VOLUME
|
||||
end
|
||||
|
||||
module Callbacks
|
||||
include Util
|
||||
include Util::String
|
||||
|
||||
def observers
|
||||
@observers ||= []
|
||||
end
|
||||
|
||||
def add_observer(observer)
|
||||
@observers = [] unless defined?(@observers)
|
||||
observer = [observer] if !observer.respond_to? :each
|
||||
observer.each { |o| @observers.append(o) }
|
||||
observer = [observer] unless observer.respond_to? :each
|
||||
observer.each { |o| observers << o unless observers.include? o }
|
||||
end
|
||||
|
||||
def remove_observer(observer)
|
||||
@observers.delete(observer)
|
||||
observer = [observer] unless observer.respond_to? :each
|
||||
observers.reject! { |o| observer.include? o }
|
||||
end
|
||||
|
||||
def notify_observers(event, data)
|
||||
if defined?(@observers)
|
||||
@observers.each do |o|
|
||||
if o.respond_to? "on_#{event.to_snake}"
|
||||
if data.empty?
|
||||
o.send("on_#{event.to_snake}")
|
||||
else
|
||||
o.send("on_#{event.to_snake}", data)
|
||||
end
|
||||
end
|
||||
private def notify_observers(event, data)
|
||||
observers.each do |o|
|
||||
if o.is_a? Method
|
||||
if o.name.to_s == "on_#{snakecase(event)}"
|
||||
data.empty? ? o.call : o.call(data)
|
||||
end
|
||||
elsif o.respond_to? "on_#{snakecase(event)}"
|
||||
data.empty? ? o.send("on_#{snakecase(event)}") : o.send("on_#{snakecase(event)}", data)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
alias_method :callbacks, :observers
|
||||
alias_method :register, :add_observer
|
||||
alias_method :deregister, :remove_observer
|
||||
end
|
||||
|
||||
class Client
|
||||
include Logging
|
||||
include Callbacks
|
||||
include Mixin::TearDown
|
||||
include Mixin::OPCodes
|
||||
|
||||
def initialize(**kwargs)
|
||||
kwargs[:subs] = SUBS.low_volume
|
||||
kwargs[:subs] ||= SUBS::LOW_VOLUME
|
||||
@base_client = Base.new(**kwargs)
|
||||
@base_client.add_observer(self)
|
||||
unless @base_client.identified.state == :identified
|
||||
err_msg = @base_client.identified.error_message
|
||||
logger.error(err_msg)
|
||||
raise OBSWSConnectionError.new(err_msg)
|
||||
end
|
||||
|
||||
def update(op_code, data)
|
||||
logger.info("#{self} successfully identified with server")
|
||||
rescue Errno::ECONNREFUSED, WaitUtil::TimeoutError => e
|
||||
msg = "#{e.class.name}: #{e.message}"
|
||||
logger.error(msg)
|
||||
raise OBSWSConnectionError.new(msg)
|
||||
else
|
||||
@base_client.updater = ->(op_code, data) {
|
||||
if op_code == Mixin::OPCodes::EVENT
|
||||
logger.debug("received: #{data}")
|
||||
event = data[:eventType]
|
||||
data = data.key?(:eventData) ? data[:eventData] : {}
|
||||
data = data.fetch(:eventData, {})
|
||||
notify_observers(event, Mixin::Data.new(data, data.keys))
|
||||
end
|
||||
}
|
||||
end
|
||||
|
||||
def to_s
|
||||
self.class.name.split("::").last(2).join("::")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
9
lib/obsws/logger.rb
Normal file
9
lib/obsws/logger.rb
Normal file
@@ -0,0 +1,9 @@
|
||||
module OBSWS
|
||||
module Logging
|
||||
def logger
|
||||
@logger ||= Logger.new($stdout, level: ENV.fetch("OBSWS_LOG_LEVEL", "WARN"))
|
||||
@logger.progname = instance_of?(::Module) ? name : self.class.name
|
||||
@logger
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,13 +1,11 @@
|
||||
require_relative "util"
|
||||
|
||||
module OBSWS
|
||||
module Mixin
|
||||
module Meta
|
||||
include Util
|
||||
include Util::String
|
||||
|
||||
def make_field_methods(*params)
|
||||
params.each do |param|
|
||||
define_singleton_method(param.to_s.to_snake) { @resp[param] }
|
||||
define_singleton_method(snakecase(param.to_s)) { @resp[param] }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -18,24 +16,26 @@ module OBSWS
|
||||
def initialize(resp, fields)
|
||||
@resp = resp
|
||||
@fields = fields
|
||||
self.make_field_methods *fields
|
||||
make_field_methods(*fields)
|
||||
end
|
||||
|
||||
def empty? = @fields.empty?
|
||||
|
||||
def attrs = @fields.map { |f| f.to_s.to_snake }
|
||||
def attrs = @fields.map { |f| snakecase(f.to_s) }
|
||||
end
|
||||
|
||||
class Response < MetaObject
|
||||
end
|
||||
class Response < MetaObject; end
|
||||
# Represents a request response object
|
||||
|
||||
class Data < MetaObject
|
||||
end
|
||||
class Data < MetaObject; end
|
||||
# Represents an event data object
|
||||
|
||||
module TearDown
|
||||
def close
|
||||
@base_client.driver.close
|
||||
def stop_driver
|
||||
@base_client.stop_driver
|
||||
end
|
||||
|
||||
alias_method :close, :stop_driver
|
||||
end
|
||||
|
||||
module OPCodes
|
||||
|
||||
484
lib/obsws/req.rb
484
lib/obsws/req.rb
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,12 @@
|
||||
module OBSWS
|
||||
module Util
|
||||
class ::String
|
||||
def to_camel
|
||||
self.split(/_/).map(&:capitalize).join
|
||||
module String
|
||||
def camelcase(s)
|
||||
s.split("_").map(&:capitalize).join
|
||||
end
|
||||
|
||||
def to_snake
|
||||
self
|
||||
def snakecase(s)
|
||||
s
|
||||
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
|
||||
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
|
||||
.downcase
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
module OBSWS
|
||||
module Version
|
||||
module VERSION
|
||||
module_function
|
||||
|
||||
def major
|
||||
@@ -7,11 +7,11 @@ module OBSWS
|
||||
end
|
||||
|
||||
def minor
|
||||
0
|
||||
5
|
||||
end
|
||||
|
||||
def patch
|
||||
3
|
||||
8
|
||||
end
|
||||
|
||||
def to_a
|
||||
|
||||
25
main.rb
25
main.rb
@@ -1,17 +1,18 @@
|
||||
require_relative "lib/obsws"
|
||||
require "obsws"
|
||||
|
||||
def main
|
||||
r_client =
|
||||
OBSWS::Requests::Client.new(
|
||||
host: "localhost",
|
||||
port: 4455,
|
||||
password: "strongpassword"
|
||||
)
|
||||
class Main
|
||||
INPUT = "Mic/Aux"
|
||||
|
||||
r_client.run do
|
||||
# Toggle the mute state of your Mic input
|
||||
r_client.toggle_input_mute("Mic/Aux")
|
||||
def run
|
||||
OBSWS::Requests::Client
|
||||
.new(host: "localhost", port: 4455, password: "strongpassword")
|
||||
.run do |client|
|
||||
# Toggle the mute state of your Mic input and print its new mute state
|
||||
client.toggle_input_mute(INPUT)
|
||||
resp = client.get_input_mute(INPUT)
|
||||
puts "Input '#{INPUT}' was set to #{resp.input_muted}"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
main if $0 == __FILE__
|
||||
Main.new.run if $PROGRAM_NAME == __FILE__
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require File.expand_path("lib/obsws/version", __dir__)
|
||||
lib = File.expand_path("./lib")
|
||||
|
||||
Gem::Specification.new do |spec|
|
||||
spec.name = "obsws"
|
||||
spec.version = OBSWS::Version
|
||||
spec.version = OBSWS::VERSION
|
||||
spec.summary = "OBS Websocket v5 wrapper"
|
||||
spec.description = "A Ruby wrapper around OBS Websocket v5"
|
||||
spec.authors = ["onyx_online"]
|
||||
@@ -13,14 +13,13 @@ Gem::Specification.new do |spec|
|
||||
spec.extra_rdoc_files = Dir["README.md", "CHANGELOG.md", "LICENSE"]
|
||||
spec.homepage = "https://rubygems.org/gems/obsws"
|
||||
spec.license = "MIT"
|
||||
spec.add_runtime_dependency "observer", "~> 0.1.1"
|
||||
spec.add_runtime_dependency "websocket-driver", "~> 0.7.5"
|
||||
spec.add_runtime_dependency "waitutil", "~> 0.2.1"
|
||||
spec.add_development_dependency "perfect_toml", "~> 0.9.0"
|
||||
spec.add_development_dependency "standard", "~> 1.30"
|
||||
spec.add_development_dependency "minitest", "~> 5.16", ">= 5.16.3"
|
||||
spec.add_development_dependency "rake", "~> 11.2", ">= 11.2.2"
|
||||
spec.required_ruby_version = ">= 3.0"
|
||||
spec.metadata = {
|
||||
"source_code_uri" => "https://github.com/onyx-and-iris/obsws.git"
|
||||
"source_code_uri" => "https://github.com/onyx-and-iris/obsws-ruby"
|
||||
}
|
||||
end
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
require "minitest"
|
||||
require "minitest/autorun"
|
||||
require "perfect_toml"
|
||||
require "yaml"
|
||||
|
||||
require_relative "../lib/obsws"
|
||||
|
||||
class OBSWSTest < Minitest::Test
|
||||
def self.before_run
|
||||
conn = PerfectTOML.load_file("obs.toml", symbolize_names: true)[:connection]
|
||||
@@r_client = OBSWS::Requests::Client.new(**conn)
|
||||
class << self
|
||||
attr_reader :r_client
|
||||
end
|
||||
|
||||
@@r_client.create_scene("START_TEST")
|
||||
@@r_client.create_scene("BRB_TEST")
|
||||
@@r_client.create_scene("END_TEST")
|
||||
def self.before_run
|
||||
conn = YAML.load_file("obs.yml", symbolize_names: true)[:connection]
|
||||
@r_client = OBSWS::Requests::Client.new(**conn)
|
||||
|
||||
r_client.create_scene("START_TEST")
|
||||
r_client.create_scene("BRB_TEST")
|
||||
r_client.create_scene("END_TEST")
|
||||
end
|
||||
|
||||
before_run
|
||||
@@ -23,9 +27,9 @@ class OBSWSTest < Minitest::Test
|
||||
end
|
||||
|
||||
Minitest.after_run do
|
||||
@@r_client.remove_scene("START_TEST")
|
||||
@@r_client.remove_scene("BRB_TEST")
|
||||
@@r_client.remove_scene("END_TEST")
|
||||
@@r_client.close
|
||||
r_client.remove_scene("START_TEST")
|
||||
r_client.remove_scene("BRB_TEST")
|
||||
r_client.remove_scene("END_TEST")
|
||||
r_client.close
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
require_relative "../minitest_helper"
|
||||
|
||||
class AttrsTest < OBSWSTest
|
||||
def test_get_version_attrs
|
||||
resp = @@r_client.get_version
|
||||
assert resp.attrs ==
|
||||
%w[
|
||||
available_requests
|
||||
obs_version
|
||||
obs_web_socket_version
|
||||
platform
|
||||
platform_description
|
||||
rpc_version
|
||||
supported_image_formats
|
||||
]
|
||||
end
|
||||
end
|
||||
17
test/obsws/test_attrs.rb
Normal file
17
test/obsws/test_attrs.rb
Normal file
@@ -0,0 +1,17 @@
|
||||
require_relative "../minitest_helper"
|
||||
|
||||
class AttrsTest < Minitest::Test
|
||||
def test_get_version_attrs
|
||||
resp = OBSWSTest.r_client.get_version
|
||||
assert resp.attrs ==
|
||||
%w[
|
||||
available_requests
|
||||
obs_version
|
||||
obs_web_socket_version
|
||||
platform
|
||||
platform_description
|
||||
rpc_version
|
||||
supported_image_formats
|
||||
]
|
||||
end
|
||||
end
|
||||
36
test/obsws/test_error.rb
Normal file
36
test/obsws/test_error.rb
Normal file
@@ -0,0 +1,36 @@
|
||||
require_relative "../minitest_helper"
|
||||
|
||||
class OBSWSConnectionErrorTest < Minitest::Test
|
||||
def test_it_raises_an_obsws_connection_error_on_wrong_password
|
||||
e = assert_raises(OBSWS::OBSWSConnectionError) do
|
||||
OBSWS::Requests::Client
|
||||
.new(host: "localhost", port: 4455, password: "wrongpassword", connect_timeout: 0.1)
|
||||
end
|
||||
assert_equal("Timed out waiting for successful identification (0.1 seconds elapsed)", e.message)
|
||||
end
|
||||
|
||||
def test_it_raises_an_obsws_connection_error_on_auth_enabled_but_no_password_provided_for_request_client
|
||||
e = assert_raises(OBSWS::OBSWSConnectionError) do
|
||||
OBSWS::Requests::Client
|
||||
.new(host: "localhost", port: 4455, password: "")
|
||||
end
|
||||
assert_equal("auth enabled but no password provided", e.message)
|
||||
end
|
||||
|
||||
def test_it_raises_an_obsws_connection_error_on_auth_enabled_but_no_password_provided_for_event_client
|
||||
e = assert_raises(OBSWS::OBSWSConnectionError) do
|
||||
OBSWS::Events::Client
|
||||
.new(host: "localhost", port: 4455, password: "")
|
||||
end
|
||||
assert_equal("auth enabled but no password provided", e.message)
|
||||
end
|
||||
end
|
||||
|
||||
class OBSWSRequestErrorTest < Minitest::Test
|
||||
def test_it_raises_an_obsws_request_error_on_invalid_request
|
||||
e = assert_raises(OBSWS::OBSWSRequestError) { OBSWSTest.r_client.toggle_input_mute("unknown") }
|
||||
assert_equal("ToggleInputMute", e.req_name)
|
||||
assert_equal(600, e.code)
|
||||
assert_equal("Request ToggleInputMute returned code 600. With message: No source was found by the name of `unknown`.", e.message)
|
||||
end
|
||||
end
|
||||
@@ -1,22 +1,22 @@
|
||||
require_relative "../minitest_helper"
|
||||
|
||||
class RequestTest < OBSWSTest
|
||||
class RequestTest < Minitest::Test
|
||||
def test_it_checks_obs_major_version
|
||||
resp = @@r_client.get_version
|
||||
resp = OBSWSTest.r_client.get_version
|
||||
ver = resp.obs_version.split(".").map(&:to_i)
|
||||
assert ver[0] >= 28
|
||||
end
|
||||
|
||||
def test_it_checks_ws_major_version
|
||||
resp = @@r_client.get_version
|
||||
resp = OBSWSTest.r_client.get_version
|
||||
ver = resp.obs_web_socket_version.split(".").map(&:to_i)
|
||||
assert ver[0] >= 5
|
||||
end
|
||||
|
||||
def test_it_sets_and_gets_current_program_scene
|
||||
%w[START_TEST BRB_TEST END_TEST].each do |s|
|
||||
@@r_client.set_current_program_scene(s)
|
||||
resp = @@r_client.get_current_program_scene
|
||||
OBSWSTest.r_client.set_current_program_scene(s)
|
||||
resp = OBSWSTest.r_client.get_current_program_scene
|
||||
assert resp.current_program_scene_name == s
|
||||
end
|
||||
end
|
||||
@@ -26,8 +26,8 @@ class RequestTest < OBSWSTest
|
||||
server: "rtmp://addressofrtmpserver",
|
||||
key: "live_myvery_secretkey"
|
||||
}
|
||||
@@r_client.set_stream_service_settings("rtmp_common", settings)
|
||||
resp = @@r_client.get_stream_service_settings
|
||||
OBSWSTest.r_client.set_stream_service_settings("rtmp_common", settings)
|
||||
resp = OBSWSTest.r_client.get_stream_service_settings
|
||||
assert resp.stream_service_type == "rtmp_common"
|
||||
assert resp.stream_service_settings ==
|
||||
{
|
||||
Reference in New Issue
Block a user