* traces - added some routes, replicated data access / pagination, but presentation and pending file control not complete
* edit - setup so that applet can be loaded + token authorisation enabled
* API - tests out ok against applet, but had to change segment-node associations
* misc - gems version required upgraded to 1.2.3 (latest stable rails version), changed some find_first to find(:first... calls
if node_ids.length > 0
node_ids_sql = "(#{node_ids.join(',')})"
# get the referenced segments
- segments = Segment.find_by_sql "select * from current_segments where node_a in #{node_ids_sql} or node_b in #{node_ids_sql}"
+ segments = Segment.find_by_sql "select * from current_segments where visible = 1 and (node_a in #{node_ids_sql} or node_b in #{node_ids_sql})"
end
# see if we have nay missing nodes
segments_nodes = segments.collect {|segment| segment.node_a }
if segment_ids.length > 0
way_segments = WaySegment.find_all_by_segment_id(segment_ids)
way_ids = way_segments.collect {|way_segment| way_segment.id }
-
- ways = Way.find(way_ids)
+ ways = Way.find(way_ids) # NB: doesn't pick up segments, tags from db until accessed via way.way_segments etc.
end
nodes.each do |node|
@user = User.find_by_token(session[:token])
end
- def authorize(realm='Web Password', errormessage="Could't authenticate you")
- username, passwd = get_auth_data
- # check if authorized
- # try to get user
- if @user = User.authenticate(username, passwd)
+ def authorize(realm='Web Password', errormessage="Could't authenticate you") \r
+ username, passwd = get_auth_data # parse from headers\r
+ # authenticate per-scheme
+ if username.nil?\r
+ @user = nil # no authentication provided - perhaps first connect (client should retry after 401)\r
+ elsif username == 'token' \r
+ @user = User.authenticate_token(passwd) # preferred - random token for user from db, passed in basic auth\r
+ else\r
+ @user = User.authenticate(username, passwd) # basic auth\r
+ end\r
+ \r
+ # handle authenticate pass/fail\r
+ if @user
# user exists and password is correct ... horray!
- if @user.methods.include? 'lastlogin'
- # note last login
+ if @user.methods.include? 'lastlogin' # note last login
@session['lastlogin'] = user.lastlogin
@user.last.login = Time.now
@user.save()
@session["User.id"] = @user.id
end
else
- # the user does not exist or the password was wrong
- @response.headers["Status"] = "Unauthorized"
- @response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
- render_text(errormessage, 401)
+ # no auth, the user does not exist or the password was wrong
+ response.headers["Status"] = "Unauthorized"
+ response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
+ render_text(errormessage, 401) # :unauthorized
end
end
return doc
end
+ # extract authorisation credentials from headers, returns user = nil if none\r
private
def get_auth_data
- user, pass = '', ''
- # extract authorisation credentials
- if request.env.has_key? 'X-HTTP_AUTHORIZATION'
- # try to get it where mod_rewrite might have put it
- authdata = @request.env['X-HTTP_AUTHORIZATION'].to_s.split
- elsif request.env.has_key? 'HTTP_AUTHORIZATION'
- # this is the regular location
- authdata = @request.env['HTTP_AUTHORIZATION'].to_s.split
+ if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
+ authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
+ elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
+ authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
end
-
- # at the moment we only support basic authentication
+ # only basic authentication supported
if authdata and authdata[0] == 'Basic'
user, pass = Base64.decode64(authdata[1]).split(':')[0..1]
- end
+ end \r
return [user, pass]
end
before_filter :authorize
after_filter :compress_output
- def create
+ def create\r
response.headers["Content-Type"] = 'application/xml'
if request.put?
node = nil
segment = Segment.from_xml(request.raw_post, true)
if segment
-
segment.user_id = @user.id
segment.from_node = Node.find(segment.node_a.to_i)
class TraceController < ApplicationController
before_filter :authorize_web
layout 'site'
-
- def list
- @page = params[:page].to_i
+
+ # Counts and selects pages of GPX traces for various criteria (by user, tags, public etc.).
+ # target_user - if set, specifies the user to fetch traces for. if not set will fetch all traces
+ # paging_action - the action that will be linked back to from view
+ def list (target_user = nil, paging_action = 'list')
+ @traces_per_page = 4
+ page_index = params[:page] ? params[:page].to_i - 1 : 0 # nice 1-based page -> 0-based page index
+
+ # from display name, pick up user id if one user's traces only
+ display_name = params[:display_name]
+ if target_user.nil? and display_name and display_name != ''
+ target_user = User.find(:first, :conditions => [ "display_name = ?", display_name])
+ end
opt = Hash.new
- opt[:conditions] = ['public = true']
- opt[:order] = 'timestamp DESC'
- opt[:limit] = 20
-
- if @page > 0
- opt[:offset => 20*@page]
+ opt[:include] = [:user, :tags] # load users and tags from db at same time as traces
+
+ # four main cases:
+ # 1 - all traces, logged in = all public traces + all user's (i.e + all mine)
+ # 2 - all traces, not logged in = all public traces
+ # 3 - user's traces, logged in as same user = all user's traces
+ # 4 - user's traces, not logged in as that user = all user's public traces
+ if target_user.nil? # all traces
+ if @user
+ conditions = ["(public = 1 OR user_id = ?)", @user.id] #1
+ else
+ conditions = ["public = 1"] #2
+ end
+ else
+ if @user and @user.id == target_user.id
+ conditions = ["user_id = ?", @user.id] #3 (check vs user id, so no join + can't pick up non-public traces by changing name)
+ else
+ conditions = ["public = 1 AND user_id = ?", target_user.id] #4
+ end
end
-
+ conditions[0] += " AND users.display_name != ''" # users need to set display name before traces will be exposed
+
+ opt[:order] = 'timestamp DESC'
if params[:tag]
-
+ conditions[0] += " AND gpx_file_tags.tag = ?"
+ conditions << params[:tag];
+ end
+
+ opt[:conditions] = conditions
+
+ # count traces using all options except limit
+ @max_trace = Trace.count(opt)
+ @max_page = Integer((@max_trace + 1) / @traces_per_page)
+
+ # last step before fetch - add paging options
+ opt[:limit] = @traces_per_page
+ if page_index > 0
+ opt[:offset] = @traces_per_page * page_index
end
@traces = Trace.find(:all , opt)
+
+ # put together SET of tags across traces, for related links
+ tagset = Hash.new
+ if @traces
+ @traces.each do |trace|
+ trace.tags.reload if params[:tag] # if searched by tag, ActiveRecord won't bring back other tags, so do explicitly here
+ trace.tags.each do |tag|
+ tagset[tag.tag] = tag.tag
+ end
+ end
+ end
+
+ # final helper vars for view
+ @display_name = display_name
+ @all_tags = tagset.values
+ @paging_action = paging_action # the action that paging requests should route back to, e.g. 'list' or 'mine'
+ @page = page_index + 1 # nice 1-based external page numbers
+ end
+
+ def mine
+ if @user
+ list(@user, 'mine') unless @user.nil?
+ else
+ redirect_to :controller => 'user', :action => 'login'
+ end
end
def view
@trace.timestamp = Time.now
if @trace.save
logger.info("id is #{@trace.id}")
- `mv #{filename} /tmp/#{@trace.id}.gpx`
+ File.rename(filename, "/tmp/#{@trace.id}.gpx")
+ # *nix - specific `mv #{filename} /tmp/#{@trace.id}.gpx`
flash[:notice] = "Your GPX file has been uploaded and is awaiting insertion in to the database. This will usually happen within half an hour, and an email will be sent to you on completion."
end
def picture
trace = Trace.find(params[:id])
- send_data(trace.large_picture, :filename => "#{trace.id}.gif", :type => 'image/png', :disposition => 'inline') if trace.public
+ send_data(trace.large_picture, :filename => "#{trace.id}.gif", :type => 'image/gif', :disposition => 'inline') if trace.public
end
def icon
trace = Trace.find(params[:id])
- send_data(trace.icon_picture, :filename => "#{trace.id}.gif", :type => 'image/gif', :disposition => 'inline') if trace.public
+ send_data(trace.icon_picture, :filename => "#{trace.id}_icon.gif", :type => 'image/gif', :disposition => 'inline') if trace.public
end
end
-class WayController < ApplicationController
+class WayController < ApplicationController\r
require 'xml/libxml'
before_filter :authorize
after_filter :compress_output
-
+\r
def create
if request.put?
way = Way.from_xml(request.raw_post, true)
render :nothing => true, :status => 500 # something went very wrong
end
- def rest
+ def rest\r
unless Way.exists?(params[:id])
render :nothing => true, :status => 404
return
way = Way.find(params[:id])
case request.method
- when :get
+ when :get\r
unless way.visible
render :nothing => true, :status => 410
return
class Node < ActiveRecord::Base
require 'xml/libxml'
set_table_name 'current_nodes'
+
validates_numericality_of :latitude
validates_numericality_of :longitude
has_many :old_segments, :foreign_key => :id
belongs_to :user
- has_one :from_node, :class_name => 'Node', :foreign_key => 'id'
- has_one :to_node, :class_name => 'Node', :foreign_key => 'id'
+ # using belongs_to :foreign_key = 'node_*', since if use has_one :foreign_key = 'id', segment preconditions? fails checking for segment id in node table
+ belongs_to :from_node, :class_name => 'Node', :foreign_key => 'node_a'
+ belongs_to :to_node, :class_name => 'Node', :foreign_key => 'node_b'
def self.from_xml(xml, create=false)
p = XML::Parser.new
tt.tag = tag
tt
}
- end
+ end\r
+ \r
+ def large_picture= (data)\r
+ f = File.new(large_picture_name, "wb")\r
+ f.syswrite(data)\r
+ f.close\r
+ end\r
+ \r
+ def icon_picture= (data)\r
+ f = File.new(icon_picture_name, "wb")\r
+ f.syswrite(data)\r
+ f.close\r
+ end\r
+\r
+ def large_picture\r
+ f = File.new(large_picture_name, "rb")\r
+ logger.info "large picture file: '#{f.path}', bytes: #{File.size(f.path)}"\r
+ data = f.sysread(File.size(f.path))\r
+ logger.info "have read data, bytes: '#{data.length}'"\r
+ f.close\r
+ data\r
+ end\r
+ \r
+ def icon_picture\r
+ f = File.new(icon_picture_name, "rb")\r
+ logger.info "icon picture file: '#{f.path}'"\r
+ data = f.sysread(File.size(f.path))\r
+ f.close\r
+ data\r
+ end\r
+ \r
+ # FIXME change to permanent filestore area\r
+ def large_picture_name\r
+ "/tmp/#{id}.gif"\r
+ end\r
+\r
+ # FIXME change to permanent filestore area\r
+ def icon_picture_name\r
+ "/tmp/#{id}_icon.gif"\r
+ end\r
end
write_attribute("pass_crypt_confirm", Digest::MD5.hexdigest(str))
end
- def self.authenticate(email, passwd)
- find_first([ "email = ? AND pass_crypt =?", email, Digest::MD5.hexdigest(passwd) ])
+ def self.authenticate(email, passwd) \r
+ find(:first, :conditions => [ "email = ? AND pass_crypt = ?", email, Digest::MD5.hexdigest(passwd)])\r
end
def self.authenticate_token(token)
- find_first([ "token = ? ", token])
+ find(:first, :conditions => [ "token = ? ", token])
end
def self.make_token(length=30)
el1['visible'] = self.visible.to_s
el1['timestamp'] = self.timestamp.xmlschema
- self.way_segments.each do |seg| # FIXME need to make sure they come back in the right order
- e = XML::Node.new 'seg'
- e['id'] = seg.segment_id.to_s
- el1 << e
- end
+ # make sure segments are output in sequence_id order\r
+ ordered_segments = []\r
+ self.way_segments.each do |seg| \r
+ ordered_segments[seg.sequence_id] = seg.segment_id.to_s
+ end\r
+ ordered_segments.each do |seg_id|\r
+ e = XML::Node.new 'seg'\r
+ e['id'] = seg_id\r
+ el1 << e\r
+ end\r
self.way_tags.each do |tag|
e = XML::Node.new 'tag'
<body>
<div id="content">
-<% if @flash[:notice] %>
- <div id="notice"><%= @flash[:notice] %></div>
+<% if flash[:notice] %>
+ <div id="notice"><%= flash[:notice] %></div>
<% end %>
- <%= @content_for_layout %>
+ <%= yield %>
</div>
</div>
+ <%= yield :optionals %>
+
<div id="cclogo">
<center>
<applet
code="org/openstreetmap/processing/OsmApplet.class"
- archive="OSMApplet.jar, commons-codec-1.3.jar, core.jar, commons-logging.jar, commons-httpclient-3.0-rc3.jar, MinML2.jar, plugin.jar, thinlet.jar"
+ archive="OSMApplet.jar, commons-codec-1.3.jar, core.jar, commons-logging.jar, commons-httpclient-3.0-rc3.jar, MinML2.jar, thinlet.jar"
width="700"
height="500"
MAYSCRIPT="true" >
<param name="user" value="token">
<param name="pass" value="<%= @user.token %>">
<param name="wmsurl" value="http://www.openstreetmap.org/tile/0.2/gpx?;http://www.openstreetmap.org/api/wms/0.2/landsat/?request=GetMap&layers=modis,global_mosaic&styles=&srs=EPSG:4326&FORMAT=image/jpeg">
- <param name="apiurl" value="http://www.openstreetmap.org/api/0.3/">
+ <param name="apiurl" value="<%= SERVER_URL %>/api/<%= API_VERSION %>/">
Your browser needs to support Java to edit maps.<br>
<a href="http://java.com/en/download/index.jsp">Download Java here</a>
</applet>
<td class="<%= cl %>">
<% if trace.inserted %>
<a href="<%= url_for :controller => 'trace', :action => 'view', :id => trace.id, :user_login => trace.user.display_name %>"><img src="<%= url_for :controller => 'trace', :action => 'icon', :id => trace.id, :user_login => trace.user.display_name %>" border="0"></a>
+ <% else %>
+ <span style="color:red">PENDING</span>
<% end %>
</td>
<td class="<%= cl %>"><%= link_to trace.name, {:controller => 'trace', :action => 'view', :display_name => trace.user.display_name, :id => trace.id} %>
<% end %>
... <%= time_ago_in_words( trace.timestamp ) %> ago</span>
<%= link_to 'more', {:controller => 'trace', :action => 'view', :display_name => trace.user.display_name, :id => trace.id} %> /
- <a href="/edit.html?lat=34.1032333&lon=-118.2272333&zoom=14" title="create maps">map</a><br />
+ <a href="/edit.html?lat=<%= trace.latitude %>&lon=<%= trace.longitude %>&zoom=14" title="create maps">map</a><br />
<%= trace.description %>
<br />
by <%= link_to trace.user.display_name, {:controller => 'trace', :action => 'list', :display_name => trace.user.display_name} %>
in
<% if trace.tags %>
<% trace.tags.each do |tag| %>
- <%= link_to tag.tag, :controller => 'trace', :action => 'bytag', :tag => tag.tag %>
+ <%= link_to tag.tag, :controller => 'trace', :action => @paging_action, :tag => tag.tag %>
<% end %>
<% end %>
</td>
--- /dev/null
+<% content_for "optionals" do %>
+ <div class="optionalbox">
+ <h2>Tags</h2>
+ <% if @all_tags %>
+ <% @all_tags.each do |tag| %>
+ <%= link_to tag, :controller => 'trace', :action => @paging_action, :tag => tag %><br />
+ <% end %>
+ <% end %>
+ </div>
+ <div class="optionalbox" >
+ <h2>User</h2>
+ <p>It's an optional box!!</p>
+<% if @user %>
+ <%= "<p><b>...and you're logged in!</b></p>" %>
+<% end %>
+ </div>
+<% end %>
--- /dev/null
+<%\r
+ range_start = ((@page - 1) * @traces_per_page) + 1\r
+ range_end = (@page==@max_page ? @max_trace : (@page * @traces_per_page))\r
+%>\r
+\r
+Showing page \r
+<%= @page %> (<%= range_start %><% \r
+if (@max_trace != range_start) # if more than 1 trace on page \r
+ %>-<%= range_end %><% \r
+end %>\r
+of <%= @max_trace %>)\r
+\r
+<% if @page > 1 %>\r
+ | <%= link_to 'previous page', {:controller => 'trace', :action => @paging_action, :page => @page-1}, {:title => 'previous page'} %>\r
+<% end %>\r
+\r
+<% if @page < @max_page %>\r
+ | <%= link_to 'next page', {:controller => 'trace', :action => @paging_action, :page => @page+1}, {:title => 'next page'} %>\r
+<% end %>\r
<h1>Public GPS Traces</h1>
-<br /><br />
+<br />
-<span class="rsssmall"><a href="<%= url_for :controller => 'trace', :action => 'georss' %>"><img src="http://<%= SERVER_URL %>/images/RSS.gif" border="0"></a></span> |
+<span class="rsssmall"><a href="<%= url_for :controller => 'trace', :action => 'georss' %>"><img src="/images/RSS.gif" border="0"></a></span> |
<% if @user %>
<%= link_to 'See just your traces', {:controller => 'trace', :action => 'mine'} %>
<% else %>
<br /><br />
-Showing page
-<% if @page > 0 %>
- <%= link_to '<<<', {:controller => 'trace', :action => 'list', :page => @page-1}, {:title => 'previous page'} %>
-<% end %>
-
-<%= @page %>
-
-<%= link_to '>>>', {:controller => 'trace', :action => 'list', :page => @page+1}, {:title => 'next page'} %>
-
-(<%= 1+(@page * 20)%>-<%= (1+@page) * 20 %>)
+<%= render (:partial => 'trace_paging_nav') %>
<table id="keyvalue" cellpadding="3">
<tr>
</tr>
<%= render :partial => 'trace', :collection => @traces %>
</table>
+<%= render (:partial => 'trace_paging_nav') %>
+
+<%= render (:partial => 'trace_optionals') %>
<h1>Your GPS Traces</h1>
-<%= link_to 'see all traces', {:controller => 'trace', :action => 'list'} %><br /><br />
+<br />
+
+<%= link_to 'See all traces', {:controller => 'trace', :action => 'list'} %><br /><br />
<% if @user %>
<%= start_form_tag({:action => 'create'}, :multipart => true) %>
<%= end_form_tag %>
+<%= render (:partial => 'trace_paging_nav') %>
<table id="keyvalue" cellpadding="3">
<tr>
<th></th>
<th></th>
</tr>
- <%= render :partial => 'trace', :collection => @traces %>
+ <%= render (:partial => 'trace', :collection => @traces) unless @traces.nil? %>
</table>
+<%= render (:partial => 'trace_paging_nav') %>
<% end %>
-
-
-
+<%= render (:partial => 'trace_optionals') %>
adapter: mysql
database: openstreetmap
username: openstreetmap
- password: openstreetmap
+ password:
host: localhost
# Warning: The database defined as 'test' will be erased and
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
-RAILS_GEM_VERSION = '1.1.6'
+RAILS_GEM_VERSION = '1.2.3'
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
+\r
+# Application constants needed for routes.rb - must go before Initializer call\r
+API_VERSION = ENV['OSM_API_VERSION'] || '0.4'\r
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence those specified here
# end
# Include your application configuration below
-
-API_VERSION = ENV['OSM_API_VERSION'] || '0.4'
SERVER_URL = ENV['OSM_SERVER_URL'] || 'www.openstreetmap.org'
ActionMailer::Base.server_settings = {
ActionController::Routing::Routes.draw do |map|
# API
- API_VERSION = '0.4' # change this in envronment.rb too
map.connect "api/#{API_VERSION}/node/create", :controller => 'node', :action => 'create'
- map.connect "api/#{API_VERSION}/node/:id/history", :controller => 'old_node', :action => 'history', :id => nil
- map.connect "api/#{API_VERSION}/node/:id", :controller => 'node', :action => 'rest', :id => nil
+ map.connect "api/#{API_VERSION}/node/:id/history", :controller => 'old_node', :action => 'history', :id => nil # TODO is this :id => nil correct? looks like it would throw away essential info - if it does check all these id => nils
+ map.connect "api/#{API_VERSION}/node/:id", :controller => 'node', :action => 'rest', :id => nil
map.connect "api/#{API_VERSION}/nodes", :controller => 'node', :action => 'nodes', :id => nil
map.connect "api/#{API_VERSION}/segment/create", :controller => 'segment', :action => 'create'
map.connect '/traces', :controller => 'trace', :action => 'list'
map.connect '/traces/page/:page', :controller => 'trace', :action => 'list'
map.connect '/traces/mine', :controller => 'trace', :action => 'mine'
+ map.connect '/traces/mine/page/:page', :controller => 'trace', :action => 'mine'
+ map.connect '/traces/mine/tag/:tag', :controller => 'trace', :action => 'mine'
+ map.connect '/traces/mine/tag/:tag/page/:page', :controller => 'trace', :action => 'mine'
map.connect '/traces/rss', :controller => 'trace', :action => 'georss'
- map.connect '/traces/user/:display_name/', :controller => 'trace', :action => 'list', :id => nil
+ map.connect '/traces/user/:display_name/', :controller => 'trace', :action => 'list', :id => nil\r
+ map.connect '/traces/user/:display_name/page/:page', :controller => 'trace', :action => 'list', :id => nil\r
map.connect '/traces/user/:display_name/:id', :controller => 'trace', :action => 'view', :id => nil
map.connect '/traces/user/:display_name/:id/picture', :controller => 'trace', :action => 'picture', :id => nil
map.connect '/traces/user/:display_name/:id/icon', :controller => 'trace', :action => 'icon', :id => nil
- map.connect '/traces/tag/:tag/', :controller => 'trace', :action => 'list', :id => nil
+ map.connect '/traces/tag/:tag', :controller => 'trace', :action => 'list', :id => nil
+ map.connect '/traces/tag/:tag/page/:page', :controller => 'trace', :action => 'list', :id => nil\r
# fall through
map.connect ':controller/:action/:id'
alter table gpx_files change private public boolean default 1 not null;
update gpx_files set public = !public;
+create index gpx_files_visible_public_idx on gpx_files(visible, public);
alter table gpx_file_tags change sequence_id sequence_id int(11);
alter table gpx_file_tags drop primary key;
alter table gpx_file_tags add id int(20) auto_increment not null, add primary key(id);
alter table users add preferences text;
+create index users_display_name_idx on users(display_name);
\ No newline at end of file
begin
logger.info("GPX Import importing #{trace.name} from #{trace.user.email}")
-
- gzipped = `file -b /tmp/#{trace.id}.gpx`.chomp =~/^gzip/
+\r
+ # TODO *nix specific, could do to work on windows... would be functionally inferior though - check for '.gz'
+ gzipped = `file -b /tmp/#{trace.id}.gpx`.chomp =~/^gzip/\r
if gzipped
logger.info("gzipped")
-#!/usr/bin/env ruby
-Dir[File.dirname(__FILE__) + "/../lib/daemons/*_ctl"].each {|f| `#{f} #{ARGV.first}`}
\ No newline at end of file
+#!/usr/bin/env ruby\r
+Dir[File.dirname(__FILE__) + "/../lib/daemons/*_ctl"].each {|f| `ruby #{f} #{ARGV.first}`} # TODO remove ruby - hack for windows
\ No newline at end of file