obsws-ruby/lib/obsws/base.rb

84 lines
1.9 KiB
Ruby
Raw Normal View History

2022-10-22 22:30:40 +01:00
require "digest/sha2"
require "json"
require "waitutil"
require_relative "driver"
2022-10-22 22:30:40 +01:00
require_relative "error"
2023-07-26 14:37:35 +01:00
require_relative "logger"
require_relative "mixin"
2022-10-22 22:30:40 +01:00
module OBSWS
class Base
2023-07-26 14:37:35 +01:00
include Logging
include Driver
2022-10-22 22:30:40 +01:00
include Mixin::OPCodes
attr_reader :closed
attr_writer :updater
2022-10-22 22:30:40 +01:00
def initialize(**kwargs)
host = kwargs[:host] || "localhost"
port = kwargs[:port] || 4455
@password = kwargs[:password] || ""
@subs = kwargs[:subs] || 0
setup_driver(host, port)
start_driver
2022-10-22 22:30:40 +01:00
WaitUtil.wait_for_condition(
"successful identification",
2022-10-22 22:30:40 +01:00
delay_sec: 0.01,
timeout_sec: 3
) { @identified }
2022-10-22 22:30:40 +01:00
end
private
2022-10-22 22:30:40 +01:00
def auth_token(salt:, challenge:)
Digest::SHA256.base64digest(
Digest::SHA256.base64digest(@password + salt) + challenge
)
end
def identify(auth)
payload = {
op: Mixin::OPCodes::IDENTIFY,
d: {
rpcVersion: 1,
eventSubscriptions: @subs
}
}
if auth
if @password.empty?
raise OBSWSError("auth enabled but no password provided")
end
2023-07-26 14:37:35 +01:00
logger.info("initiating authentication")
payload[:d][:authentication] = auth_token(**auth)
end
2022-10-22 22:30:40 +01:00
@driver.text(JSON.generate(payload))
end
def msg_handler(data)
case data[:op]
2022-10-22 22:30:40 +01:00
when Mixin::OPCodes::HELLO
identify(data[:d][:authentication])
2022-10-22 22:30:40 +01:00
when Mixin::OPCodes::IDENTIFIED
@identified = true
2022-10-22 22:30:40 +01:00
when Mixin::OPCodes::EVENT, Mixin::OPCodes::REQUESTRESPONSE
@updater.call(data[:op], data[:d])
2022-10-22 22:30:40 +01:00
end
end
public def req(id, type_, data = nil)
2022-10-22 22:30:40 +01:00
payload = {
op: Mixin::OPCodes::REQUEST,
d: {
requestType: type_,
requestId: id
}
}
payload[:d][:requestData] = data if data
2023-07-26 14:37:35 +01:00
logger.debug("sending request: #{payload}")
2023-07-21 06:04:09 +01:00
@driver.text(JSON.generate(payload))
2022-10-22 22:30:40 +01:00
end
end
end