summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLuke Shumaker <shumakl@purdue.edu>2014-04-25 11:09:09 -0400
committerLuke Shumaker <shumakl@purdue.edu>2014-04-26 23:35:14 -0400
commit40939795096c0b7a1791d71d920b84ff283fb550 (patch)
treecb461881b1a84c337ebc9b3f325561dc8bdef95f
parent4638a832b3b9da87bf076f4370e0d99bdf11ee78 (diff)
Sampling methods WIP
-rw-r--r--app/controllers/users_controller.rb15
-rw-r--r--lib/sampling/README.md28
-rw-r--r--lib/sampling/double_bind.rb7
-rw-r--r--lib/sampling/manual.rb35
-rw-r--r--lib/sampling/riot_api.rb169
-rw-r--r--lib/throttled_api_request.rb25
6 files changed, 265 insertions, 14 deletions
diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb
index 27b3c61..767d992 100644
--- a/app/controllers/users_controller.rb
+++ b/app/controllers/users_controller.rb
@@ -62,20 +62,7 @@ class UsersController < ApplicationController
else
params[:user][:remote_usernames].each do |game_name,user_name|
game = Game.find_by_name(game_name)
- remote_username = HTTParty.get("https://prod.api.pvp.net/api/lol/na/v1.3/summoner/by-name/#{user_name.downcase}?api_key=ad539f86-22fd-474d-9279-79a7a296ac38")
-
- id = "#{remote_username["#{user_name.downcase}"]["id"]}".to_i
- username = "#{remote_username["#{user_name.downcase}"]["name"]}"
-
- hash = {:username => username, :id => id}
-
- remote = @user.remote_usernames.where(:game => game).first
- if remote.nil?
- ok &= @user.remote_usernames.create(game: game, value: hash)
- else
- remote.value = hash
- ok &= remote.save
- end
+ Sampling::RiotApi::set_remote_name(@user, game, user_name)
end
end
respond_to do |format|
diff --git a/lib/sampling/README.md b/lib/sampling/README.md
new file mode 100644
index 0000000..28c603e
--- /dev/null
+++ b/lib/sampling/README.md
@@ -0,0 +1,28 @@
+Files in this directory should be modules implementing the following
+interface:
+
+ - `works_with?(Game) => Boolean`
+ Returns whether or not this sampling method works with the
+ specified game.
+
+ - `uses_remote?() => Boolean`
+ Return whether or not this sampling method requires remote IDs for
+ users.
+ - `set_remote_name(User, Game, String)`
+ Set the remote ID for a user for the specified game. It is safe to
+ assume that this sampling method `works_with?` that game.
+ - `get_remote_name(Object)`
+ When given an object from `RemoteUsername#value`, give back a
+ human-readable/editable name to display.
+
+ - `sampling_start(Match)`
+ Fetch the statistics for a match.
+ - `sampling_done?(Match) => Boolean`
+ Returns whether or not statistics have been completely collected
+ yet.
+
+ - `render_user_interaction(Match, User) => String`
+ Returns HTML to render on a page.
+ - `handle_user_interaction(Match, User, Hash params)`
+ Handles params from the form generated by
+ `#user_interaction_render`.
diff --git a/lib/sampling/double_bind.rb b/lib/sampling/double_bind.rb
new file mode 100644
index 0000000..4a5201c
--- /dev/null
+++ b/lib/sampling/double_bind.rb
@@ -0,0 +1,7 @@
+module Sampling
+ module DoubleBlind
+ def works_with?(game)
+ return true
+ end
+ end
+end
diff --git a/lib/sampling/manual.rb b/lib/sampling/manual.rb
new file mode 100644
index 0000000..17c8104
--- /dev/null
+++ b/lib/sampling/manual.rb
@@ -0,0 +1,35 @@
+module Sampling
+ module HostEntry
+ def self.works_with?(game)
+ return true
+ end
+
+ def self.uses_remote?
+ return false
+ end
+
+ def self.set_remote_name(user, game, value)
+ raise "This sampling method doesn't use remote usernames."
+ end
+
+ def self.get_remote_name(value)
+ raise "This sampling method doesn't use remote usernames."
+ end
+
+ def self.sampling_start(match)
+ # TODO
+ end
+
+ def self.sampling_done?(match)
+ # TODO
+ end
+
+ def self.render_user_interaction(match, user)
+
+ end
+
+ def self.handle_user_interaction(match, user, sampling_params)
+ match.statistics.create(user: nil, name: "blowout",
+ end
+ end
+end
diff --git a/lib/sampling/riot_api.rb b/lib/sampling/riot_api.rb
new file mode 100644
index 0000000..3de4185
--- /dev/null
+++ b/lib/sampling/riot_api.rb
@@ -0,0 +1,169 @@
+module Sampling
+ module RiotApi
+ ##
+ # Return whether or not this sampling method works with the specified game.
+ # Spoiler: It only works with League of Legends (or subclasses of it).
+ public
+ def works_with?(game)
+ if api_key.nil? or region.nil?
+ return false
+ end
+ if game.name == "League of Legends"
+ return true
+ end
+ unless game.parent.nil?
+ return works_with?(game.parent)
+ end
+ end
+
+ ##
+ # This sampling method uses remote IDs
+ public
+ def uses_remote?
+ return true
+ end
+
+ ##
+ # When given a summoner name for a user, figure out the summoner ID.
+ public
+ def set_remote_name(user, game, summoner_name)
+ Delayed::Job.enqueue(UsernameJob.new(user, game, summoner_name), :queue => api_name)
+ end
+ private
+ class UsernameJob < Job
+ def initialize(user, game, summoner_name)
+ @user_id = user.id
+ @game_id = game.id
+ # Escape any funny stuff
+ summoner_names = [summoner_name].map{|name|Sampling::RiotApi::standardize(name.gsub(',',''))}
+ # Generate the request
+ super("v1.3/summoner/by-name/%{summonerNames}", { :summonerNames => summoner_names.join(",") })
+ end
+ def handle(data)
+ user = User.find(@user_id)
+ game = Game.find(@game_id)
+
+ normalized_summoner_name = data.keys.first
+ remote_data = {
+ :id => data[normalized_summoner_name]["id"],
+ :name => data[normalized_summoner_name]["name"],
+ }
+
+ user.set_remote_username(game, remote_data)
+ end
+ end
+
+ ##
+ # When given data from RemoteUsername#value, give back a readable name to display.
+ # Here, this is the summoner name.
+ public
+ def get_remote_name(data)
+ data["name"]
+ end
+
+ ##
+ # Fetch all the statistics for a match.
+ public
+ def sampling_start(match)
+ @match.teams.each do |team|
+ team.users.each do |user|
+ Delayed::Job.enqueue(MatchJob.new(user, match), :queue => api_name)
+ end
+ end
+ end
+ private
+ class FetchStatisticsJob < Job
+ def initialize(user, match)
+ @user_id = user.id
+ @match_id = match.id
+ # Get the summoner id
+ summoner = user.get_remote_username(match.tournament_stage.tournament.game)
+ if summoner.nil?
+ raise "Someone didn't enter their summoner name"
+ end
+ # Generate the request
+ super("v1.3/game/by-summoner/%{summonerId}/recent", { :summonerId => summoner["id"] })
+ end
+ def handle(data)
+ user = User.find(@user_id)
+ match = Match.find(@match_id)
+ Statistic.create(user: user, match: match, value: TODO)
+ end
+ end
+
+ public
+ def sampling_done?(match)
+ # TODO
+ end
+
+ public
+ def render_user_interaction(match, user)
+ return ""
+ end
+
+ public
+ def handle_user_interaction(match, user)
+ end
+
+ ########################################################################
+
+ private
+ def api_name
+ "prod.api.pvp.net/api/lol"
+ end
+
+ private
+ def api_key
+ ENV["RIOT_API_KEY"]
+ end
+
+ private
+ def region
+ ENV["RIOT_API_REGION"]
+ end
+
+ private
+ def url(request, args={})
+ "https://prod.api.pvp.net/api/lol/#{region}/#{request % args.merge(args){|k,v|url_escape(v)}}?#{api_key}"
+ end
+
+ private
+ def url_escape(string)
+ URI::escape(string.to_s, /[^a-zA-Z0-9._~!$&'()*+,;=:@-]/)
+ end
+
+ private
+ def standardize(summoner_name)
+ summoner_name.to_s.downcase.gsub(' ', '')
+ end
+
+ private
+ class Job < ThrottledApiRequest.new(api_name, 10.seconds, 10)
+ def initialize(request, args={})
+ @url = Sampling::RiotApi::url(request, args)
+ end
+
+ def perform
+ response = open(@url)
+ status = response.status
+ data = JSON::parse(response.read)
+
+ # Error codes that RIOT uses:
+ # "400"=>"Bad request"
+ # "401"=>"Unauthorized"
+ # "429"=>"Rate limit exceeded"
+ # "500"=>"Internal server error"
+ # "503"=>"Service unavailable"
+ # "404"=>"Not found"
+ # Should probably handle these better
+ if status[0] != "200"
+ raise "GET #{@url} => #{status.join(" ")}"
+ end
+ self.handle(data)
+ end
+
+ def handle(data)
+ end
+ end
+ end
+end
diff --git a/lib/throttled_api_request.rb b/lib/throttled_api_request.rb
new file mode 100644
index 0000000..3f30c56
--- /dev/null
+++ b/lib/throttled_api_request.rb
@@ -0,0 +1,25 @@
+class ThrottledApiRequest < Struct.new(:api_name, :unit_time, :requests_per)
+ def before(job)
+ loop do
+ sleep_for = -1
+ ActiveRecord::Base.transaction do
+ ApiRequests.create(:api_name => self.api_name)
+ recent_requests = ApiRequets.
+ where(:api_name => self.api_name).
+ where("updated_at > ?", Time.now.utc - self.unit_time).
+ order(:updated_at)
+ if (recent_requests.count > self.requests_per)
+ sleep_for = Time.now.utc - recent_requests[recent_requests.count-self.requests_per].updated_at
+ raise ActiveRecord::Rollback
+ else
+ sleep_for = -1
+ end
+ end
+ if sleep_for != -1
+ sleep(sleep_for)
+ else
+ break
+ end
+ end
+ end
+end