Class: Turntabler::Client
- Inherits:
-
Object
- Object
- Turntabler::Client
- Includes:
- Assertions, DigestHelpers, Loggable
- Defined in:
- lib/turntabler/client.rb
Overview
Provides access to the Turntable API
Instance Attribute Summary collapse
-
#clock_delta ⇒ Fixnum
The difference of time (in seconds) between this client and Turntable servers.
-
#id ⇒ String
readonly
The unique id representing this client.
-
#room(room_id = nil) ⇒ Turntabler::Room
Gets the current room the authorized user is in or builds a new room bound to the given room id.
-
#rooms ⇒ Turntabler::RoomDirectory
readonly
The directory for looking up / creating rooms.
-
#timeout ⇒ Fixnum
readonly
The response timeout configured for the connection.
Instance Method Summary collapse
-
#api(command, params = {}) ⇒ Hash
private
Runs the given API command.
-
#avatars ⇒ Array<Turntabler::Avatar>
Get all avatars availble on Turntable.
-
#close(allow_reconnect = false) ⇒ true
Closes the current connection to Turntable if one was previously opened.
-
#connect(url = room(digest(rand)).url) ⇒ true
private
Initiates a connection with the given url.
-
#initialize(email, password, options = {}) { ... } ⇒ Client
constructor
Creates a new client for communicating with Turntable.fm with the given email / password.
-
#on(event, options = {}, &block) ⇒ true
Registers a handler to invoke when an event occurs in Turntable.
-
#reset_keepalive(interval = 10) ⇒ Object
private
Resets the keepalive timer to run at the given interval.
-
#search_song(query, options = {}) ⇒ Array<Turntabler::Song>
Finds songs that match the given query.
-
#song(song_id) ⇒ Turntabler::Song
Builds a new song bound to the given song id.
-
#stickers ⇒ Array<Turntabler::Sticker>
Get all stickers available on Turntable.
-
#trigger(command, *args) ⇒ true
Triggers callback handlers for the given Turntable command.
-
#url ⇒ String
private
Gets the chat server url currently connected to.
-
#user(user_id = nil) ⇒ Turntabler::User
Gets the current authorized user or builds a new user bound to the given user id.
-
#user_by_name(name) ⇒ Turntabler::User
Gets the user with the given DJ name.
Methods included from DigestHelpers
Methods included from Assertions
#assert_valid_keys, #assert_valid_values
Constructor Details
#initialize(email, password, options = {}) { ... } ⇒ Client
Creates a new client for communicating with Turntable.fm with the given email / password.
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
# File 'lib/turntabler/client.rb', line 58 def initialize(email, password, = {}, &block) = { :id => "#{Time.now.to_i}-#{rand}", :timeout => 10, :reconnect => false, :reconnect_wait => 5 }.merge() assert_valid_keys(, :id, :room, :url, :user_id, :auth, :timeout, :reconnect, :reconnect_wait) @id = [:id] @user = AuthorizedUser.new(self, :email => email, :password => password, :_id => [:user_id], :userauth => [:auth]) @rooms = RoomDirectory.new(self) @event_handlers = {} @timeout = [:timeout] @reconnect = [:reconnect] @reconnect_wait = [:reconnect_wait] @clock_delta = 0 # Setup default event handlers on(:heartbeat) { on_heartbeat } on(:session_missing) { on_session_missing } on(:session_ended) { on_session_ended } # Connect to an initial room / server reconnect_from(ConnectionError, APIError) do if room_name = [:room] room(room_name).enter elsif url = [:url] connect(url) else connect end end instance_eval(&block) if block_given? end |
Instance Attribute Details
#clock_delta ⇒ Fixnum
The difference of time (in seconds) between this client and Turntable servers
41 42 43 |
# File 'lib/turntabler/client.rb', line 41 def clock_delta @clock_delta end |
#id ⇒ String (readonly)
The unique id representing this client
24 25 26 |
# File 'lib/turntabler/client.rb', line 24 def id @id end |
#room(room_id = nil) ⇒ Turntabler::Room
Gets the current room the authorized user is in or builds a new room bound to the given room id.
409 410 411 |
# File 'lib/turntabler/client.rb', line 409 def room(room_id = nil) room_id ? Room.new(self, :_id => room_id) : @room end |
#rooms ⇒ Turntabler::RoomDirectory (readonly)
The directory for looking up / creating rooms
33 34 35 |
# File 'lib/turntabler/client.rb', line 33 def rooms @rooms end |
#timeout ⇒ Fixnum (readonly)
The response timeout configured for the connection
37 38 39 |
# File 'lib/turntabler/client.rb', line 37 def timeout @timeout end |
Instance Method Details
#api(command, params = {}) ⇒ Hash
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Runs the given API command.
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
# File 'lib/turntabler/client.rb', line 161 def api(command, params = {}) raise(ConnectionError, 'Connection is not open') unless @connection && @connection.connected? = @connection.publish(params.merge(:api => command)) # Wait until we get a response for the given message data = wait do |&resume| on(:response_received, :once => true, :if => {'msgid' => }) {|data| resume.call(data)} end if data['success'] data else error = data['error'] || data['err'] raise APIError, "Command \"#{command}\" failed with message: \"#{error}\"" end end |
#avatars ⇒ Array<Turntabler::Avatar>
Get all avatars availble on Turntable.
446 447 448 449 450 451 452 453 454 455 |
# File 'lib/turntabler/client.rb', line 446 def avatars data = api('user.available_avatars') avatars = [] data['avatars'].each do |avatar_group| avatar_group['avatarids'].each do |avatar_id| avatars << Avatar.new(self, :_id => avatar_id, :min => avatar_group['min'], :acl => avatar_group['acl']) end end avatars end |
#close(allow_reconnect = false) ⇒ true
Closes the current connection to Turntable if one was previously opened.
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
# File 'lib/turntabler/client.rb', line 125 def close(allow_reconnect = false) if @connection # Disable reconnects if specified reconnect = @reconnect @reconnect = reconnect && allow_reconnect # Clean up timers / connections @keepalive_timer.cancel if @keepalive_timer @keepalive_timer = nil @connection.close # Revert change to reconnect config once the final signal is received wait do |&resume| on(:session_ended, :once => true) { resume.call } end @reconnect = reconnect end true end |
#connect(url = room(digest(rand)).url) ⇒ true
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
This will only open a new connection if the client isn’t already connected to the given url
Initiates a connection with the given url. Once a connection is started, this will also attempt to authenticate the user.
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
# File 'lib/turntabler/client.rb', line 103 def connect(url = room(digest(rand)).url) if !@connection || !@connection.connected? || @connection.url != url # Close any existing connection close # Create a new connection to the given url @connection = Connection.new(url, :timeout => timeout, :params => {:clientid => id, :userid => user.id, :userauth => user.auth}) @connection.handler = lambda {|data| trigger(data.delete('command'), data)} @connection.start # Wait until the connection is authenticated wait do |&resume| on(:session_missing, :once => true) { resume.call } end end true end |
#on(event, options = {}, &block) ⇒ true
Registers a handler to invoke when an event occurs in Turntable.
Client Events
-
:reconnected- The client reconnected (and re-entered any room that the user was previously in)
Room Events
-
:room_updated- Information about the room was updated -
:room_description_updated- The room’s description was updated
User Events
-
:user_entered- A user entered the room -
:user_left- A user left the room -
:user_booted- A user has been booted from the room -
:user_updated- A user’s profile was updated -
:user_name_updated- A user’s name was updated -
:user_avatar_updated- A user’s avatar was updated -
:user_spoke- A user spoke in the chat room
DJ Events
-
:fan_added- A new fan was added by a user in the room -
:fan_removed- A fan was removed from a user in the room
DJ Events
-
:dj_added- A new DJ was added to the stage -
:dj_removed- A DJ was removed from the stage -
:dj_escorted_off- A DJ was escorted off the stage by a moderator -
:dj_booed_off- A DJ was booed off the stage
Moderator Events
-
:moderator_added- A new moderator was added to the room -
:moderator_removed- A moderator was removed from the room
Song Events
-
:song_unavailable- Indicates that there are no more songs to play in the room -
:song_started- A new song has started playing -
:song_ended- The current song has ended. This is typically followed by a:song_startedor:song_unavailableevent. -
:song_voted- One or more votes were cast for the song -
:song_snagged- A user in the room has queued the current song onto their playlist -
:song_skipped- A song was skipped due to either the dj skipping it or too many downvotes -
:song_moderated- A song was forcefully skipped by a moderator -
:song_blocked- A song was prevented from playing due to a copyright claim
Messaging Events
-
:message_received- A private message was received from another user in the room
394 395 396 397 398 399 |
# File 'lib/turntabler/client.rb', line 394 def on(event, = {}, &block) event = event.to_sym @event_handlers[event] ||= [] @event_handlers[event] << Handler.new(event, , &block) true end |
#reset_keepalive(interval = 10) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Resets the keepalive timer to run at the given interval.
568 569 570 571 572 573 574 575 576 577 578 |
# File 'lib/turntabler/client.rb', line 568 def reset_keepalive(interval = 10) if !@keepalive_timer || @keepalive_interval != interval @keepalive_interval = interval # Periodically update the user's status to remain available @keepalive_timer.cancel if @keepalive_timer @keepalive_timer = EM::Synchrony.add_periodic_timer(interval) do Turntabler.run { user.update(:status => user.status) } end end end |
#search_song(query, options = {}) ⇒ Array<Turntabler::Song>
The user must be entered in a room to search for songs
Finds songs that match the given query.
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 |
# File 'lib/turntabler/client.rb', line 495 def search_song(query, = {}) assert_valid_keys(, :artist, :duration, :page) = {:page => 1}.merge() raise(APIError, 'User must be in a room to search for songs') unless room if artist = [:artist] query = "title: #{query}" query << " artist: #{artist}" end query << " duration: #{[:duration]}" if [:duration] api('file.search', :query => query, :page => [:page]) # Wait for the async callback songs = wait do |&resume| on(:search_completed, :once => true, :if => {'query' => query}) {|songs| resume.call(songs)} on(:search_failed, :once => true, :if => {'query' => query}) { resume.call } end songs || raise(APIError, 'Search failed to complete') end |
#song(song_id) ⇒ Turntabler::Song
Builds a new song bound to the given song id.
474 475 476 |
# File 'lib/turntabler/client.rb', line 474 def song(song_id) Song.new(self, :_id => song_id) end |
#stickers ⇒ Array<Turntabler::Sticker>
Get all stickers available on Turntable.
463 464 465 466 |
# File 'lib/turntabler/client.rb', line 463 def stickers data = api('sticker.get') data['stickers'].map {|attrs| Sticker.new(self, attrs)} end |
#trigger(command, *args) ⇒ true
If the command is unknown, it will simply get skipped and not raise an exception
Triggers callback handlers for the given Turntable command. This should either be invoked when responses are received for Turntable or when triggering custom events.
Triggering custom events
After defining custom events, ‘trigger` can be used to invoke any handler that’s been registered for that event. The argument list passed into ‘trigger` will be passed, exactly as specified, to the registered handlers.
549 550 551 552 553 554 555 556 557 558 559 560 561 562 |
# File 'lib/turntabler/client.rb', line 549 def trigger(command, *args) command = command.to_sym if command if Event.command?(command) event = Event.new(self, command, args) handlers = @event_handlers[event.name] || [] handlers.each do |handler| success = handler.run(event) handlers.delete(handler) if success && handler.once end end true end |
#url ⇒ String
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Gets the chat server url currently connected to
150 151 152 |
# File 'lib/turntabler/client.rb', line 150 def url @connection && @connection.url end |
#user(user_id = nil) ⇒ Turntabler::User
Gets the current authorized user or builds a new user bound to the given user id.
421 422 423 |
# File 'lib/turntabler/client.rb', line 421 def user(user_id = nil) user_id ? User.new(self, :_id => user_id) : @user end |
#user_by_name(name) ⇒ Turntabler::User
Gets the user with the given DJ name. This should only be used if the id of the user is unknown.
433 434 435 436 437 438 |
# File 'lib/turntabler/client.rb', line 433 def user_by_name(name) data = api('user.get_id', :name => name) user = self.user(data['userid']) user.attributes = {'name' => name} user end |