jam-cloud/ruby/lib/jam_ruby/models/latency_tester.rb

69 lines
2.2 KiB
Ruby
Raw Normal View History

2014-05-16 19:39:37 +00:00
module JamRuby
class LatencyTester < ActiveRecord::Base
belongs_to :connection, class_name: 'JamRuby::Connection', foreign_key: :client_id, primary_key: :client_id
# we need to find that latency_tester with the specified connection (and reconnect it)
# or bootstrap a new latency_tester
def self.connect(options)
client_id = options[:client_id]
ip_address = options[:ip_address]
connection_stale_time = options[:connection_stale_time]
connection_expire_time = options[:connection_expire_time]
# first try to find a LatencyTester with that client_id
latency_tester = LatencyTester.find_by_client_id(client_id)
if latency_tester
if latency_tester.connection
connection = latency_tester.connection
else
connection = Connection.new
connection.client_id = client_id
latency_tester.connection = connection
end
else
latency_tester = LatencyTester.new
2014-05-19 13:46:03 +00:00
latency_tester.client_id = client_id
2014-05-16 19:39:37 +00:00
unless latency_tester.save
return latency_tester
end
connection = Connection.new
connection.latency_tester = latency_tester
connection.client_id = client_id
end
if ip_address and !ip_address.eql?(connection.ip_address)
# locidispid stuff
addr = JamIsp.ip_to_num(ip_address)
isp = JamIsp.lookup(addr)
if isp.nil? then ispid = 0 else ispid = isp.coid end
block = GeoIpBlocks.lookup(addr)
if block.nil? then locid = 0 else locid = block.locid end
location = GeoIpLocations.lookup(locid)
if location.nil?
# todo what's a better default location?
locidispid = 0
else
locidispid = locid*1000000+ispid
end
connection.ip_address = ip_address
connection.addr = addr
connection.locidispid = locidispid
end
connection.client_type = 'latency_tester'
connection.aasm_state = Connection::CONNECT_STATE.to_s
connection.stale_time = connection_stale_time
connection.expire_time = connection_expire_time
connection.as_musician = false
unless connection.save
return connection
end
return latency_tester
end
end
end