pezra-fireeagle 0.9.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/History.txt ADDED
@@ -0,0 +1,41 @@
1
+ == 0.9.0
2
+
3
+ * Support for OAuth 1.0a
4
+
5
+ == 0.8.0.0
6
+
7
+ * Update recent method
8
+
9
+ == 0.7.1.0
10
+
11
+ * Fix OAuth Dependency Issue
12
+
13
+ == 0.6.3
14
+
15
+ * Bugfix for Ruby 1.9
16
+
17
+ == 0.6.2
18
+
19
+ * Offload heavy lifting to OAuth for tokens and signing requests
20
+ * Add time parameter to Client#recent
21
+ * Change lookup params from :cid to :cellid to follow Fire Eagle
22
+ * Cleaned up specs
23
+
24
+ == 0.6.1
25
+
26
+ * Remove 'not implemented' message
27
+ * Remove JSON requirement
28
+
29
+ == 0.6.0
30
+
31
+ * Complete rewrite
32
+
33
+ == 0.0.2
34
+
35
+ * Fix callback_url
36
+ * Add token_url
37
+
38
+ == 0.0.1
39
+
40
+ * Initial version
41
+ * Works
data/License.txt ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2008 Jesse Newland
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Manifest.txt ADDED
@@ -0,0 +1,21 @@
1
+ config/hoe.rb
2
+ config/requirements.rb
3
+ History.txt
4
+ License.txt
5
+ Manifest.txt
6
+ README.txt
7
+ Rakefile
8
+ lib/fireeagle.rb
9
+ lib/fireeagle/client.rb
10
+ lib/fireeagle/location.rb
11
+ lib/fireeagle/response.rb
12
+ lib/fireeagle/user.rb
13
+ lib/fireeagle/version.rb
14
+ setup.rb
15
+ spec/fireeagle_location_spec.rb
16
+ spec/fireeagle_response_spec.rb
17
+ spec/fireeagle_spec.rb
18
+ spec/spec.opts
19
+ spec/spec_helper.rb
20
+ tasks/environment.rake
21
+ tasks/rspec.rake
data/README.txt ADDED
@@ -0,0 +1,52 @@
1
+ FireEagle[http://fireeagle.yahoo.net] (FE) is a system providing centralized
2
+ management of user location information. FE allows 3rd party developers to
3
+ pdate and/or access user's location data.
4
+
5
+ http://fireeagle.yahoo.net/developer/documentation
6
+
7
+ == Installation
8
+
9
+ gem install fireeagle
10
+
11
+ == Usage
12
+
13
+ >> require 'fireeagle'
14
+ >> client = FireEagle::Client.new(
15
+ :consumer_key => "<consumer key>",
16
+ :consumer_secret => "<consumer secret>",
17
+ :access_token => "[access token]",
18
+ :access_token_secret => "[access token secret]")
19
+
20
+ ==== With a User-specific OAuth Access Token
21
+
22
+ # update your location
23
+ >> client.update(:q => "punta del diablo, uruguay") # I wish
24
+ # query your location
25
+ >> user = client.user
26
+ => #<FireEagle::User:0x1ca5e08 ... >
27
+ >> user.locations
28
+ => [#<FireEagle::Location:0x1cdd9e8 ...>, #<FireEagle::Location:0x1cc8ffc ...>, ... ]
29
+ >> user.best_guess
30
+ => #<FireEagle::Location:0x1cdd9e8 ...>
31
+ >> user.best_guess.name
32
+ => "Punta del Diablo, Uruguay"
33
+ # lookup a location
34
+ >> locations = client.lookup(:q => "30022")
35
+ => [#<FireEagle::Location:0x1cdd9e8 ...>, #<FireEagle::Location:0x1cc8ffc ...>, ...]
36
+ >> locations.first.name => "Alpharetta, GA 30022"
37
+ >> locations.first.place_id => "IrhZMHuYA5s1fFi4Qw"
38
+
39
+ == Authorization
40
+
41
+ Authorization is handled by OAuth. For more details about the OAuth
42
+ authorization flow and how it differs based on your application type, please
43
+ see http://fireeagle.yahoo.net/developer/documentation/authorizing
44
+
45
+ == Contributing
46
+
47
+ http://github.com/jnewland/fireeagle/tree/master. You know what to do.
48
+
49
+ Rubyforge Project Page:: http://rubyforge.org/projects/fireeagle
50
+ Author:: Jesse Newland (http://soylentfoo.jnewland.com) (jnewland@gmail.com[mailto:jnewland@gmail.com])
51
+ Copyright:: Copyright (c) 2008 Jesse Newland. Portions[http://pastie.caboo.se/private/oevvkdzl0zrdkf8s7hetg] Copyright (c) 2008 Yahoo!
52
+ License:: Distributed under the same terms as Ruby
data/Rakefile ADDED
@@ -0,0 +1,4 @@
1
+ require 'config/requirements'
2
+ require 'config/hoe' # setup Hoe + all gem configuration
3
+
4
+ Dir['tasks/**/*.rake'].each { |rake| load rake }
data/config/hoe.rb ADDED
@@ -0,0 +1,70 @@
1
+ require 'fireeagle/version'
2
+
3
+ AUTHOR = 'Jesse Newland' # can also be an array of Authors
4
+ EMAIL = "jnewland@gmail.com"
5
+ DESCRIPTION = "Ruby wrapper for Yahoo!'s FireEagle"
6
+ GEM_NAME = 'fireeagle' # what ppl will type to install your gem
7
+ RUBYFORGE_PROJECT = 'fireeagle' # The unix name for your project
8
+ HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org"
9
+ DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}"
10
+
11
+ @config_file = "~/.rubyforge/user-config.yml"
12
+ @config = nil
13
+ RUBYFORGE_USERNAME = "unknown"
14
+ def rubyforge_username
15
+ unless @config
16
+ begin
17
+ @config = YAML.load(File.read(File.expand_path(@config_file)))
18
+ rescue
19
+ puts <<-EOS
20
+ ERROR: No rubyforge config file found: #{@config_file}
21
+ Run 'rubyforge setup' to prepare your env for access to Rubyforge
22
+ - See http://newgem.rubyforge.org/rubyforge.html for more details
23
+ EOS
24
+ exit
25
+ end
26
+ end
27
+ RUBYFORGE_USERNAME.replace @config["username"]
28
+ end
29
+
30
+
31
+ REV = nil
32
+ # UNCOMMENT IF REQUIRED:
33
+ # REV = `svn info`.each {|line| if line =~ /^Revision:/ then k,v = line.split(': '); break v.chomp; else next; end} rescue nil
34
+ VERS = FireEagle::VERSION::STRING + (REV ? ".#{REV}" : "")
35
+ RDOC_OPTS = ['--quiet', '--title', 'fireeagle rdoc',
36
+ "--opname", "index.html",
37
+ "--line-numbers",
38
+ "--main", "README",
39
+ "--inline-source"]
40
+
41
+ class Hoe
42
+ def extra_deps
43
+ @extra_deps.reject! { |x| Array(x).first == 'hoe' }
44
+ @extra_deps
45
+ end
46
+ end
47
+
48
+ # Generate all the Rake tasks
49
+ # Run 'rake -T' to see list of generated tasks (from gem root directory)
50
+ hoe = Hoe.new(GEM_NAME, VERS) do |p|
51
+ p.developer(AUTHOR, EMAIL)
52
+ p.description = DESCRIPTION
53
+ p.summary = DESCRIPTION
54
+ p.url = HOMEPATH
55
+ p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT
56
+ p.test_globs = ["test/**/test_*.rb"]
57
+ p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean.
58
+
59
+ # == Optional
60
+ p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n")
61
+ p.extra_deps = [ ['oauth', '>= 0.2.1'], ['hpricot', '>= 0.6'], ['GeoRuby', '>= 1.3.2'] ] # An array of rubygem dependencies [name, version], e.g. [ ['active_support', '>= 1.3.1'] ]
62
+
63
+ #p.spec_extras = {} # A hash of extra values to set in the gemspec.
64
+
65
+ end
66
+
67
+ CHANGES = hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n")
68
+ PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}"
69
+ hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc')
70
+ hoe.rsync_args = '-av --delete --ignore-errors'
@@ -0,0 +1,18 @@
1
+ require 'fileutils'
2
+ include FileUtils
3
+
4
+ require 'rubygems'
5
+ %w[rake hoe newgem rubigen oauth geo_ruby].each do |req_gem|
6
+ begin
7
+ require req_gem
8
+ rescue LoadError
9
+ req_gem = 'GeoRuby' if req_gem == 'geo_ruby' # gem not the same name
10
+ puts "This Rakefile requires the '#{req_gem}' RubyGem."
11
+ puts "Installation: gem install #{req_gem} -y"
12
+ exit
13
+ end
14
+ end
15
+
16
+ $:.unshift(File.join(File.dirname(__FILE__), %w[.. lib]))
17
+
18
+ require 'fireeagle'
data/lib/fireeagle.rb ADDED
@@ -0,0 +1,66 @@
1
+ require 'time'
2
+ require 'net/https'
3
+ require 'rubygems'
4
+ gem 'oauth', ">= 0.2.4"
5
+ require 'oauth/helper'
6
+ require 'oauth/client/helper'
7
+ require 'oauth/request_proxy/net_http'
8
+ require 'hpricot'
9
+ require 'geo_ruby'
10
+
11
+ class FireEagle
12
+ API_SERVER = "https://fireeagle.yahooapis.com"
13
+ AUTH_SERVER = "https://fireeagle.yahoo.net"
14
+ REQUEST_TOKEN_PATH = "/oauth/request_token"
15
+ ACCESS_TOKEN_PATH = "/oauth/access_token"
16
+ AUTHORIZATION_URL = "#{AUTH_SERVER}/oauth/authorize"
17
+ MOBILE_AUTH_URL = "#{AUTH_SERVER}/oauth/mobile_auth/"
18
+ USER_API_PATH = "/api/0.1/user"
19
+ LOOKUP_API_PATH = "/api/0.1/lookup"
20
+ UPDATE_API_PATH = "/api/0.1/update"
21
+ RECENT_API_PATH = "/api/0.1/recent"
22
+ WITHIN_API_PATH = "/api/0.1/within"
23
+ FORMAT_XML = "xml"
24
+ UPDATE_PARAMS = :lat, :lon, :woeid, :place_id, :address, :mnc, :mcc, :lac, :cellid, :postal, :city, :state, :country, :q, :label
25
+ # not yet supported
26
+ #,:geom, :upcoming_venue_id, :yahoo_local_id, :plazes_id
27
+
28
+ class Error < RuntimeError #:nodoc:
29
+ end
30
+
31
+ class ArgumentError < Error #:nodoc:
32
+ end
33
+
34
+ class FireEagleException < Error #:nodoc:
35
+ end
36
+ end
37
+
38
+ # FireEagle additions to the <code>Hash</code> class
39
+ class Hash
40
+ # Returns <code>true</code> if the ALL or NONE of the given keys are present in <i>my_keys</i>.
41
+ def has_all_or_none_keys?(*my_keys)
42
+ size = my_keys.length
43
+ false_count = 0
44
+ my_keys.each do |k|
45
+ false_count += 1 unless keys.include?(k)
46
+ end
47
+ false_count == 0 or false_count == size
48
+ end
49
+ end
50
+
51
+ # FireEagle addition to the <code>OAuth::Consumer</code> class
52
+ class OAuth::Consumer
53
+ alias_method :create_http_with_verify, :create_http
54
+ # Monkey patch to silence the SSL warnings
55
+ def create_http_without_verify #:nodoc:
56
+ http_object = create_http_with_verify
57
+ http_object.verify_mode = OpenSSL::SSL::VERIFY_NONE if uri.scheme=="https"
58
+ http_object
59
+ end
60
+ alias_method :create_http, :create_http_without_verify
61
+ end
62
+
63
+ require File.dirname(__FILE__) + '/fireeagle/client'
64
+ require File.dirname(__FILE__) + '/fireeagle/location'
65
+ require File.dirname(__FILE__) + '/fireeagle/user'
66
+ require File.dirname(__FILE__) + '/fireeagle/response'
@@ -0,0 +1,320 @@
1
+ class FireEagle
2
+ class Client
3
+ # TODO add access_token=() and request_token=() methods that check whether the tokens are usable
4
+
5
+ attr_reader :access_token, :request_token, :consumer, :format
6
+
7
+ # Initialize a FireEagle Client. Takes an options Hash.
8
+ #
9
+ # == Required keys:
10
+ #
11
+ # [<tt>:consumer_key</tt>] OAuth Consumer key representing your FireEagle Application
12
+ # [<tt>:consumer_secret</tt>] OAuth Consumer secret representing your FireEagle Application
13
+ #
14
+ # == Optional keys:
15
+ #
16
+ # [<tt>:request_token</tt>] OAuth Request Token, for use with convert_to_access_token
17
+ # [<tt>:request_token_secret</tt>] OAuth Request Token Secret, for use with convert_to_access_token
18
+ # [<tt>:access_token</tt>] OAuth Token, either User-specific or General-purpose
19
+ # [<tt>:access_token_secret</tt>] OAuth Token, either User-specific or General-purpose
20
+ # [<tt>:app_id</tt>] Your Mobile Application ID
21
+ # [<tt>:debug</tt>] Boolean
22
+ #
23
+ # User-specific OAuth tokens tie Fire Eagle users to your application. As
24
+ # such, they are intended to be distributed (with keys) to that user's
25
+ # mobile device and/or computer running your desktop or mobile client. For
26
+ # web-based applications User-specific tokens will be retrieved by your
27
+ # web server where they should be treated as private data. Take care to
28
+ # avoid releasing this data to the public, as the corresponding User's
29
+ # location information may be inadvertently exposed. User-specific OAuth
30
+ # tokens should be considered the property of your users.
31
+ #
32
+ # General-purpose OAuth tokens are tied to your application and allow you,
33
+ # as a developer, to make more general (often batch-style) queries against
34
+ # Fire Eagle. As a result, allowing this token/secret combination loose
35
+ # has the potential to reveal a much greater amount of personal data. In
36
+ # an attempt to mitigate this, we will only grant general-purpose tokens
37
+ # to web applications (contact us with details, if you seek an exception).
38
+ # In addition, we require developers to provide a restrictive IP range at
39
+ # registration time in order to further mitigate the risk of
40
+ # general-purpose tokens being used inappropriately.
41
+ #
42
+ # In general, OAuth tokens should be considered sacrosanct in order to
43
+ # help us respect our users' privacy. Please take this responsibility on
44
+ # as your own. If your Application Oauth tokens are compromised, Fire
45
+ # Eagle will turn off your application service until the problem is
46
+ # resolved.
47
+ #
48
+ # If the Client is initialized without an OAuth access token, it's assumed
49
+ # you're operating a non-web based application.
50
+ #
51
+ # == Example web-based authentication flow:
52
+ #
53
+ # Initialize a client with your consumer key and consumer secret.
54
+ #
55
+ # >> c = FireEagle::Client.new(:consumer_key => "key", :consumer_secret => "sekret")
56
+ # => #<FireEagle::Client:0x1ce2e70 ... >
57
+ #
58
+ # Generate a request token with a +callback_url+:
59
+ #
60
+ # >> c.get_request_token("http://example.com/cb")
61
+ # => #<OAuth::Token:0x1cdb5bc @token="request_token", @secret="sekret">
62
+ #
63
+ # Prompt your user to visit your app's authorization url:
64
+ #
65
+ # >> c.authorization_url
66
+ # => "http://fireeagle.yahoo.net/oauth/authorize?oauth_token=request_token"
67
+ #
68
+ # When the user has completed this step, s/he will be redirected back to
69
+ # the callback url you configured when obtaining a request token.
70
+ # +oauth_verifier+ will be present in the callback.
71
+ #
72
+ # >> c.convert_to_access_token(oauth_verifier)
73
+ # => #<OAuth::Token:0x1cd3bf0 @token="access_token", @secret="access_token_secret">
74
+ #
75
+ # == Non web-based applications
76
+ #
77
+ # For non web-based applications, such as a mobile client application, the
78
+ # authentication between the user and the application is slightly
79
+ # different. The request token is displayed to the user by the client
80
+ # application. The user then logs into the FireEagle website (using
81
+ # mobile_authorization_url) and enters this code to authorize the
82
+ # application. When the user finishes the authorization step the client
83
+ # application exchanges the request token for an access token (using
84
+ # +convert_to_access_token+). This is a lightweight method for non-web
85
+ # application users to authenticate an application without entering any
86
+ # identifying information into a potentially insecure application. Request
87
+ # tokens are valid for only 1 hour after being issued.
88
+ #
89
+ # == Example mobile-based authentication flow:
90
+ #
91
+ # Initialize a client with your consumer key, consumer secret, and your mobile application id:
92
+ #
93
+ # >> c = FireEagle::Client.new(:consumer_key => "key", :consumer_secret => "sekret", :app_id => 12345)
94
+ # => #<FireEagle::Client:0x1ce2e70 ... >
95
+ #
96
+ # Generate a request token:
97
+ #
98
+ # >> c.get_request_token
99
+ # => #<OAuth::Token:0x1cdb5bc @token="ENTER_THIS_TOKEN", @secret="sekret">
100
+ #
101
+ # Prompt your user to visit your app's mobile authorization url and enter ENTER_THIS_TOKEN:
102
+ #
103
+ # >> c.mobile_authorization_url
104
+ # => "http://fireeagle.yahoo.net/oauth/mobile_auth/12345"
105
+ #
106
+ # Once the user has indicated to you that they've done this (and provided
107
+ # a verification code), convert their request token to an access token:
108
+ #
109
+ # >> c.convert_to_access_token(oauth_verifier)
110
+ # => #<OAuth::Token:0x1cd3bf0 @token="access_token", @secret="access_token_secret">
111
+ #
112
+ # You're done!
113
+ def initialize(options = {})
114
+ options = {
115
+ :debug => false,
116
+ :format => FireEagle::FORMAT_XML
117
+ }.merge(options)
118
+
119
+ # symbolize keys
120
+ options.map do |k,v|
121
+ options[k.to_sym] = v
122
+ end
123
+ raise FireEagle::ArgumentError, "OAuth Consumer Key and Secret required" if options[:consumer_key].nil? || options[:consumer_secret].nil?
124
+ @consumer = OAuth::Consumer.new(options[:consumer_key], options[:consumer_secret], :site => FireEagle::API_SERVER, :authorize_url => FireEagle::AUTHORIZATION_URL)
125
+ @debug = options[:debug]
126
+ @format = options[:format]
127
+ @app_id = options[:app_id]
128
+ if options[:access_token] && options[:access_token_secret]
129
+ @access_token = OAuth::AccessToken.new(@consumer, options[:access_token], options[:access_token_secret])
130
+ else
131
+ @access_token = nil
132
+ end
133
+ if options[:request_token] && options[:request_token_secret]
134
+ @request_token = OAuth::RequestToken.new(@consumer, options[:request_token], options[:request_token_secret])
135
+ else
136
+ @request_token = nil
137
+ end
138
+ end
139
+
140
+ # Obtain a <strong>new</strong> unauthorized OAuth Request token
141
+ def get_request_token(callback_url = "", force_token_regeneration = false)
142
+ if force_token_regeneration || @request_token.nil?
143
+ @request_token = consumer.get_request_token(:oauth_callback => callback_url)
144
+ end
145
+ @request_token
146
+ end
147
+
148
+ # Return the Fire Eagle authorization URL for your mobile application. At this URL, the User will be prompted for their request_token.
149
+ def mobile_authorization_url
150
+ raise FireEagle::ArgumentError, ":app_id required" if @app_id.nil?
151
+ "#{FireEagle::MOBILE_AUTH_URL}#{@app_id}"
152
+ end
153
+
154
+ # The URL the user must access to authorize this token. get_request_token must be called first. For use by web-based and desktop-based applications.
155
+ def authorization_url
156
+ raise FireEagle::ArgumentError, "call #get_request_token first" if @request_token.nil?
157
+ request_token.authorize_url
158
+ end
159
+
160
+ # Exchange an authorized OAuth Request token for an access token. For use by desktop-based and mobile applications.
161
+ def convert_to_access_token(oauth_verifier)
162
+ raise FireEagle::ArgumentError, "call #get_request_token and have the user authorize the token first" if @request_token.nil?
163
+ @access_token = request_token.get_access_token(:oauth_verifier => oauth_verifier)
164
+ end
165
+
166
+ # Disambiguates potential values for update query. Results from lookup can be passed to
167
+ # update to ensure that FireEagle will understand how to parse the Location Hash.
168
+ #
169
+ # All three Location methods (lookup, update, and within) accept a Location Hash.
170
+ #
171
+ # There is a specific order for looking up locations. For example, if you provide lat, lon, and address,
172
+ # FireEagle will use the the latitude and longitude geo-coordinates and ignore the address.
173
+ #
174
+ # Location Hash keys, in order of priority:
175
+ #
176
+ # [<tt>(:lat, :lon)</tt>] both required, valid values are floats of -180 to 180 for lat and -90 to 90 for lon
177
+ # [<tt>(:woeid)</tt>] Where on Earth ID
178
+ # [<tt>:place_id</tt>] Place ID (via Flickr/Upcomoing); deprecated in favor of WOE IDs when possible
179
+ # [<tt>:address</tt>] street address (may contain a full address, but will be combined with postal, city, state, and country when available)
180
+ # [<tt>(:mnc, :mcc, :lac, :cellid)</tt>] cell tower information, all required (as integers) for a valid tower location
181
+ # [<tt>:postal</tt>] a ZIP or postal code (combined with address, city, state, and country when available)
182
+ # [<tt>:city</tt>] city (combined with address, postal, state, and country when available)
183
+ # [<tt>:state</tt>] state (combined with address, postal, city, and country when available)
184
+ # [<tt>:country</tt>] country (combined with address, postal, city, and state when available)
185
+ # [<tt>:q</tt>] Free-text fallback containing user input. Lat/lon pairs and geometries will be extracted if possible, otherwise this string will be geocoded as-is.
186
+ #
187
+ # Not yet supported:
188
+ #
189
+ # * <tt>upcoming_venue_id</tt>
190
+ # * <tt>yahoo_local_id</tt>
191
+ # * <tt>plazes_id</tt>
192
+ def lookup(params)
193
+ raise FireEagle::ArgumentError, "OAuth Access Token Required" unless @access_token
194
+ response = get(FireEagle::LOOKUP_API_PATH + ".#{format}", :params => params)
195
+ FireEagle::Response.new(response.body).locations
196
+ end
197
+
198
+ # Sets a User's current Location using using a Place ID hash or a set of Location parameters. If the User
199
+ # provides a Location unconfirmed with lookup then FireEagle makes a best guess as to the User's Location.
200
+ #
201
+ # All three Location methods (lookup, update, and within) accept a Location Hash.
202
+ #
203
+ # There is a specific order for looking up locations. For example, if you provide lat, lon, and address,
204
+ # FireEagle will use the the latitude and longitude geo-coordinates and ignore the address.
205
+ #
206
+ # Location Hash keys, in order of priority:
207
+ #
208
+ # [<tt>(:lat, :lon)</tt>] both required, valid values are floats of -180 to 180 for lat and -90 to 90 for lon
209
+ # [<tt>:place_id</tt>] Place ID - valid values decrypts to an integer value
210
+ # [<tt>:address</tt>] street address (may contain a full address, but will be combined with postal, city, state, and country when available)
211
+ # [<tt>(:mnc, :mcc, :lac, :cellid)</tt>] cell tower information, all required (as integers) for a valid tower location
212
+ # [<tt>:postal</tt>] a ZIP or postal code (combined with address, city, state, and country when available)
213
+ # [<tt>:city</tt>] city (combined with address, postal, state, and country when available)
214
+ # [<tt>:state</tt>] state (combined with address, postal, city, and country when available)
215
+ # [<tt>:country</tt>] country (combined with address, postal, city, and state when available)
216
+ # [<tt>:q</tt>] Free-text fallback containing user input. Lat/lon pairs and geometries will be extracted if possible, otherwise this string will be geocoded as-is.
217
+ #
218
+ # Not yet supported:
219
+ #
220
+ # * <tt>upcoming_venue_id</tt>
221
+ # * <tt>yahoo_local_id</tt>
222
+ # * <tt>plazes_id</tt>
223
+ def update(location = {})
224
+ raise FireEagle::ArgumentError, "OAuth Access Token Required" unless @access_token
225
+ location = sanitize_location_hash(location)
226
+ response = post(FireEagle::UPDATE_API_PATH + ".#{format}", :params => location)
227
+ FireEagle::Response.new(response.body)
228
+ end
229
+
230
+ # Returns the Location of a User.
231
+ def user
232
+ raise FireEagle::ArgumentError, "OAuth Access Token Required" unless @access_token
233
+ response = get(FireEagle::USER_API_PATH + ".#{format}")
234
+ FireEagle::Response.new(response.body).users.first
235
+ end
236
+ alias_method :location, :user
237
+
238
+ # Query for Users of an Application who have updated their Location recently. Returns a list of
239
+ # Users for the Application with recently updated locations.
240
+ #
241
+ # == Optional parameters:
242
+ #
243
+ # <tt>time</tt> The time to start looking at recent updates from. Value is flexible, supported forms are 'now', 'yesterday', '12:00', '13:00', '1:00pm' and '2008-03-12 12:34:56'. (default: 'now')
244
+ # <tt>count</tt> Number of users to return per page. (default: 10)
245
+ # <tt>start</tt> The page number at which to start returning the list of users.
246
+ def recent(time = 'now', count = 10, start = 1)
247
+ raise FireEagle::ArgumentError, "OAuth Access Token Required" unless @access_token
248
+ params = { :count => count, :start => start, :time => time }
249
+ response = get(FireEagle::RECENT_API_PATH + ".#{format}", :params => params)
250
+ FireEagle::Response.new(response.body).users
251
+ end
252
+
253
+ # Takes a Place ID or a Location and returns a list of users of your application who are within the bounding box of that Location.
254
+ #
255
+ # Location Hash keys, in order of priority:
256
+ #
257
+ # [<tt>(:lat, :lon)</tt>] both required, valid values are floats of -180 to 180 for lat and -90 to 90 for lon
258
+ # [<tt>:woeid</tt>] Where on Earth ID
259
+ # [<tt>:place_id</tt>] Place ID
260
+ # [<tt>:address</tt>] street address (may contain a full address, but will be combined with postal, city, state, and country when available)
261
+ # [<tt>(:mnc, :mcc, :lac, :cellid)</tt>] cell tower information, all required (as integers) for a valid tower location
262
+ # [<tt>:postal</tt>] a ZIP or postal code (combined with address, city, state, and country when available)
263
+ # [<tt>:city</tt>] city (combined with address, postal, state, and country when available)
264
+ # [<tt>:state</tt>] state (combined with address, postal, city, and country when available)
265
+ # [<tt>:country</tt>] country (combined with address, postal, city, and state when available)
266
+ # [<tt>:q</tt>] Free-text fallback containing user input. Lat/lon pairs and geometries will be extracted if possible, otherwise this string will be geocoded as-is.
267
+ #
268
+ # Not yet supported:
269
+ #
270
+ # * <tt>upcoming_venue_id</tt>
271
+ # * <tt>yahoo_local_id</tt>
272
+ # * <tt>plazes_id</tt>
273
+ def within(location = {}, count = 10, start = 1)
274
+ raise FireEagle::ArgumentError, "OAuth Access Token Required" unless @access_token
275
+ location = sanitize_location_hash(location)
276
+ params = { :count => count, :start => start }.merge(location)
277
+ response = get(FireEagle::WITHIN_API_PATH + ".#{format}", :params => params)
278
+ FireEagle::Response.new(response.body).users
279
+ end
280
+
281
+ protected
282
+
283
+ def sanitize_location_hash(location)
284
+ location.map do |k,v|
285
+ location[k.to_sym] = v
286
+ end
287
+
288
+ location = location.reject { |key, value| !FireEagle::UPDATE_PARAMS.include?(key) }
289
+ raise FireEagle::ArgumentError, "Requires all or none of :lat, :lon" unless location.has_all_or_none_keys?(:lat, :lon)
290
+ raise FireEagle::ArgumentError, "Requires all or none of :mnc, :mcc, :lac, :cellid" unless location.has_all_or_none_keys?(:mnc, :mcc, :lac, :cellid)
291
+ location
292
+ end
293
+
294
+ def get(url, options = {}) #:nodoc:
295
+ request(:get, url, options)
296
+ end
297
+
298
+ def post(url, options = {}) #:nodoc:
299
+ request(:post, url, options)
300
+ end
301
+
302
+ def request(method, url, options) #:nodoc:
303
+ response = case method
304
+ when :post
305
+ access_token.request(:post, url, options[:params])
306
+ when :get
307
+ qs = options[:params].collect { |k,v| "#{CGI.escape(k.to_s)}=#{CGI.escape(v.to_s)}" }.join("&") if options[:params]
308
+ access_token.request(:get, "#{url}?#{qs}")
309
+ else
310
+ raise ArgumentError, "method #{method} not supported"
311
+ end
312
+
313
+ case response.code
314
+ when '500'; then raise FireEagle::FireEagleException, "Internal Server Error"
315
+ when '400'; then raise FireEagle::FireEagleException, "Method Not Implemented Yet"
316
+ else response
317
+ end
318
+ end
319
+ end
320
+ end