source: subversion/applications/routing/pyroute_webGUI/server.py

Last change on this file was 8131, checked in by ojw, 11 years ago

add filter for localhost browsing only

  • Property svn:executable set to *
File size: 5.2 KB
Line 
1#!/usr/bin/python
2#----------------------------------------------------------------------------
3#
4#----------------------------------------------------------------------------
5# Copyright 2008, Oliver White
6#
7# This program is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program.  If not, see <http://www.gnu.org/licenses/>.
19#---------------------------------------------------------------------------
20from BaseHTTPServer import *
21import re
22import sys
23import math
24import os
25import pickle
26
27from tile_route import TileRoute
28
29sys.path.append("../pyroutelib2")
30import routeAsCSV
31
32class tileServer(BaseHTTPRequestHandler):
33  def __init__(self, request, client_address, server):
34    self.settings = None
35    self.re_tile = re.compile('/tile/(\w+)/(\d+)/(\d+)/(\d+)\.png')
36    self.re_route = re.compile('/route\?start=(.*?)%2C(.*?)&end=(.*?)%2C(.*?)&type=(.*?)')
37    BaseHTTPRequestHandler.__init__(self, request, client_address, server)
38
39  def getNextRoute(self):
40    for id in range(1,10000):
41      filename = "route/%d.txt" % id
42      if(not os.path.exists(filename)):
43        return(filename,id)
44
45  def settingsFilename(self):
46    return("settings.txt")
47 
48  def getSettings(self):
49    """Load self.settings from disk, or return existing copy, or create blank copy"""
50    if(not self.settings):
51      try:
52        self.settings = {}
53        f = open(self.settingsFilename(), "r")
54        self.settings = pickle.load(f)
55        f.close()
56      except IOError:
57        print "Couldn't load settings from disk"
58       
59       
60  def saveSettings(self):
61    """save self.settings to disk"""
62    f = open(self.settingsFilename(), "w")
63    pickle.dump(self.settings, f)
64    f.close()
65   
66  def log_message(self, format, *args):
67    pass  # Kill logging to stderr
68 
69  def return_file(self, filename, contentType='text/HTML'):
70    # Serve a real file from disk (for indexes etc.)
71    f = open(filename, "r")
72    self.send_response(200)
73    self.send_header('Content-type',contentType) # TODO: more headers
74    self.end_headers()
75    self.wfile.write(f.read())
76    f.close()
77  def sendError(self,code,text):
78    self.send_response(code)
79    self.send_header('Content-type','text/HTML')
80    self.end_headers()
81    self.wfile.write("<html><title>Error %d</title></head><body><h1>%d: %s</h1></body></html>" % (code,code,text))
82
83  def do_GET(self):
84    # Filter-out unwanted addresses
85    # (TODO: you should be able to run the server on your phone and connect
86    # to it from your desktop, so we need some other authentication here)
87    (host,port) = self.client_address
88    if(not host in ("127.0.0.1")):
89      print "Ignored connection from %s" % host
90      self.sendError(403, "Access this from the machine running the server")
91      return
92   
93    # Specific files to serve:
94    if(self.path[0:5]=='/map/' or self.path=='/'):
95      self.return_file('slippy.html')
96      return
97
98    # See if a tile was requested
99    match_tile = self.re_tile.search(self.path)
100    match_route = self.re_route.search(self.path)
101   
102    if self.path=='/counter':
103      self.send_response(200)
104      self.send_header('Content-type','text/plain')
105      self.end_headers()
106     
107      self.getSettings()
108      self.settings['test'] = self.settings.get('test',0) + 1
109      self.wfile.write(self.settings['test'])
110      self.saveSettings()
111   
112    elif(match_tile):
113      (layer,z,x,y) = match_tile.groups()
114      z = int(z)
115      x = int(x)
116      y = int(y)
117     
118      # Render the tile
119      print 'Request for %d,%d at zoom %d, layer %s' % (x,y,z,layer)
120
121
122      a = TileRoute("route/latest.csv")
123      pngData = a.RenderTile(z,x,y,None)
124
125      # Return the tile as a PNG
126      self.send_response(200)
127      self.send_header('Content-type','image/PNG')
128      self.end_headers()
129      self.wfile.write(pngData)
130   
131    elif(match_route):
132      (x1,y1,x2,y2,type) = match_route.groups()
133      (x1,y1,x2,y2) = map(float, (x1,y1,x2,y2))
134      dx = x2 - x1
135      dy = y2 - y1
136      dist = math.sqrt(dx * dx + dy * dy)
137      print "Routing from %f,%f to %f,%f = distance %f" % (x1,y1,x2,y2,dist)
138      (filename,id) = self.getNextRoute()
139      if(filename):
140        routeAsCSV.routeToCSVFile(
141          x1,y1,x2,y2,
142          "cycle",
143          filename)
144        self.send_response(200)
145        self.send_header('Content-type','text/HTML')
146        self.end_headers()
147        self.wfile.write("<p>Your route is available on the <a href='/map/?route=%d'>map</a></p>" % id)
148      else:
149        self.sendError(500, "Can't find a good name to call this route")
150    else:
151      print "404: %s" % self.path
152      self.sendError(404, "Unrecognised URL")
153
154try:
155  server = HTTPServer(('',1280), tileServer)
156  server.serve_forever()
157except KeyboardInterrupt:
158  server.socket.close()
159  sys.exit()
160
Note: See TracBrowser for help on using the repository browser.