Skip to content

Instantly share code, notes, and snippets.

@jmccartie
Created September 1, 2011 15:25
Show Gist options
  • Save jmccartie/1186410 to your computer and use it in GitHub Desktop.
Save jmccartie/1186410 to your computer and use it in GitHub Desktop.
Device model using Device Atlas
class Device
include HTTParty
attr_accessor :mobile_device, :touch, :device_model,
:device_brand, :ua, :device_os, :bb_info, :properties, :mp4, :h264, :stream
def initialize(ua)
if ua.class == Hash
ua.each do |k, v|
send("#{k}=", v)
end
else
info = self.properties = get_data(ua)
self.ua = ua
self.mobile_device = info.has_key?("mobileDevice") ? !info["mobileDevice"].to_i.zero? : nil
self.touch = info.has_key?("touchScreen")
self.device_model = info.has_key?("model") ? info["model"] : nil
self.device_brand = info.has_key?("vendor") ? info["vendor"] : nil
self.device_os = set_os(info)
self.bb_info = set_bb_info
set_video(info)
end
end
def is_mobile?
self.mobile_device
end
def is_touch?
self.touch
end
def stream?
self.stream
end
private
def get_data(ua)
begin
Timeout.timeout 5 do
response = JSON HTTParty.post('https://mobile-scope.appspot.com/',
:body => {:ua => ua},
:basic_auth => {:username=>ENV['MOBILESCOPE_USER'], :password=> ENV['MOBILESCOPE_PASS']} ).body
response["response"]["data"]["properties"] rescue {}
end
rescue Timeout::Error
return {}
end
end
def set_video(info)
self.mp4 = info.has_key?("mp4.aac.lc") ? !info["mp4.aac.lc"].to_i.zero? : false
self.h264 = info.has_key?("3gp.h264.level10") ? !info["3gp.h264.level10"].to_i.zero? : false
self.stream = info.has_key?("stream.3gp.aac.lc") ? info["stream.3gp.aac.lc"] : false
self.stream = (!bb_info.nil? && bb_info[:version] > 4.3) || self.device_os == "webOS"
end
def set_os(info)
if info["device_brand"] == "Apple"
return "Apple"
elsif info.has_key?("osProprietary") && info["osProprietary"] =~ /Symbian/
return "Symbian OS"
elsif info.has_key?("developerPlatform")
return info["developerPlatform"]
elsif info.has_key?("osProprietary")
return info["osProprietary"]
elsif info.has_key?("model") && info["model"] == "Pixi"
return "webOS"
elsif info.has_key?("osWindows")
return "Windows"
end
nil
end
def set_bb_info
attrs = {:model => nil, :version => nil, :vendor => nil}
if matched = /[Bb]lack[Bb]erry(\d+)\/(\d+\.\d+)/.match(@ua)
attrs[:model] = matched[1].to_i
attrs[:version] = matched[2].to_f
end
if matched = /VendorID\/(\d+)/.match(@ua)
attrs[:vendor] = matched[1]
end
return attrs[:model].nil? ? nil : attrs
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment