Exemplo n.º 1
0
 def get(self, type = 'html'):
     
     recent = Attraction.all()
     recent.filter("next =", None)
     recent.order("-datetime")
     
     popular = Attraction.all()
     popular.filter("next =", None)
     popular.order("-rating")
     
     users = User.all()
     users.order("-activity")
     
     template_values = {
         'recent': recent.fetch(10),
         'popular': popular.fetch(5),
         'users': users.fetch(5),
         'service': '/home.atom',
         'opensearch': '/home.search'
     }
     
     for attraction in template_values['recent']:
         attraction.thumbnail = self.convertFlickrUrl(attraction.picture, 's')
     
     for attraction in template_values['popular']:
         attraction.thumbnail = self.convertFlickrUrl(attraction.picture, 's')
     
     self.output('home', type, template_values)
Exemplo n.º 2
0
    def post(self):
        n = int(self.request.get("n"))
        l = 50
        f = self.request.get("f")

        import csv

        csvReader = csv.reader(open("attractions" + f + ".csv"))

        count = 1
        for row in csvReader:

            if count >= n and count < n + l:

                q = Attraction.all()
                q.filter("id =", row[0])
                attraction = q.get()

                if attraction:

                    attraction.geobox = (
                        str(round(float(attraction.location.lat), 1))
                        + ","
                        + str(round(float(attraction.location.lon), 1))
                    )
                    attraction.put()

            elif count >= n:

                taskqueue.add(url="/creategeo", params={"n": n + l, "f": f})
                break

            count = count + 1
Exemplo n.º 3
0
 def get(self, attractionId = None):
     
     template_values = {}
     template_values['lat'] = 0
     template_values['lon'] = 0
     
     if attractionId:
         query = Attraction.all()
         query.filter("id =", attractionId)
         attraction = query.get()
         
         if attraction:
             attraction.picture = self.convertFlickrUrl(attraction.picture, 'm')
             template_values['attraction'] = attraction
             
         else:
             self.output('404', 'html')
             return
     
     else:
         try:
             coords = self.request.get('c').split(',')
             template_values['lat'] = "%.2f" % float(coords[0])
             template_values['lon'] = "%.2f" % float(coords[1])
         except:
             pass
     
     self.output('edit', 'html', template_values)
def select(id):
    attraction = None
    sql = "SELECT * FROM attractions WHERE id = %s"
    values = [id]
    result = run_sql(sql, values)[0]

    if result is not None:
        city = city_repository.select(result['city_id'])
        attraction = Attraction(result['name'], result['cost'], city, result['id'])
    return attraction
Exemplo n.º 5
0
def select_all():
    attractions = []

    sql = "SELECT * FROM attractions"
    results = run_sql(sql)

    for row in results:
        land = land_repository.select(row['land_id'])
        attraction = Attraction(row['name'], land, row['visited'], row['notes'], row['id'])
        attractions.append(attraction)
    return attractions
def select_all():
    attractions = []
# I WANT TO ORDER THE ATTRACTIONS BY CITY
    sql = "SELECT * FROM attractions" 
    # ORDER BY city.id"
    results = run_sql(sql)

    for row in results:
        city = city_repository.select(row['city_id'])
        attraction = Attraction(row['name'], row['cost'], city, row['id'])
        attractions.append(attraction)
    return attractions
Exemplo n.º 7
0
 def post(self, attractionId):
     
     if self.request.get('comment'):
         
         next = attractionId
         while next: # walk to newest version of this attraction
             query = Attraction.all()
             query.filter("id =", next)
             latestAttraction = query.get()
             next = latestAttraction.next
         
         from google.appengine.api import users
         user = users.get_current_user()
         if user:
             username = user.nickname();
         else:
             username = self.request.remote_addr
         
         data = {}
         data['name'] = latestAttraction.name
         data['region'] = latestAttraction.region
         data['description'] = latestAttraction.description + "\r\n\r\n--" + username + "\r\n\r\n" + self.request.get('comment')
         data['location'] = {}
         data['location']['lat'] = latestAttraction.location.lat
         data['location']['lon'] = latestAttraction.location.lon
         data['href'] = latestAttraction.href
         data['picture'] = latestAttraction.picture
         data['tags'] = latestAttraction.tags
         data['free'] = latestAttraction.free
         data['rating'] = latestAttraction.rating
         
         newAttraction = db.run_in_transaction(self.createAttraction, latestAttraction.key(), data)
         
         user = self.getUserObject() # create user object if it doesn't exist
         newBadges = None
         
         if user: # update stats
             self.addStat(user, 6)
             
             newBadges = self.updateBadges(user)
             user.put()
         
         if newBadges:
             self.redirect('/badges/%s.html' % newBadges.pop(0))
         else:
             self.redirect('/attractions/' + newAttraction.id + '.html')
         return
Exemplo n.º 8
0
 def post(self, attractionId):
     
     from google.appengine.api import users
     user = users.get_current_user()
     
     if user:
         
         attractions = Attraction.all()
         attractions.filter("id =", attractionId)
         attraction = attractions.get()
         
         if attraction:
             
             userObject = self.getUserObject(user)
             
             if attraction.root in userObject.recommended:
                 userObject.recommended.remove(attraction.root)
                 if attraction.rating > 0:
                     attraction.rating = attraction.rating - 1
             else:
                 userObject.recommended.append(attraction.root)
                 if type(attraction.rating) == long:
                     attraction.rating = attraction.rating + 1
                 else:
                     attraction.rating = 1
             
             attraction.put()
             userObject.put()
             
             if attraction.userid != userObject.id:
                 query = User.all()
                 query.filter("id =", attraction.userid)
                 user = query.get()
                 
                 if user:
                     # update stats
                     self.addStat(user, 3) # recommended
                     
                     newBadges = self.updateBadges(user)
                     user.put()
                 
     self.redirect('/attractions/' + attractionId + '.html')
     return
Exemplo n.º 9
0
    def post(self, attractionId):

        from google.appengine.api import users
        user = users.get_current_user()

        if user:

            attractions = Attraction.all()
            attractions.filter("id =", attractionId)
            attraction = attractions.get()

            if attraction:

                userObject = self.getUserObject(user)

                if attraction.root in userObject.recommended:
                    userObject.recommended.remove(attraction.root)
                    if attraction.rating > 0:
                        attraction.rating = attraction.rating - 1
                else:
                    userObject.recommended.append(attraction.root)
                    if type(attraction.rating) == long:
                        attraction.rating = attraction.rating + 1
                    else:
                        attraction.rating = 1

                attraction.put()
                userObject.put()

                if attraction.userid != userObject.id:
                    query = User.all()
                    query.filter("id =", attraction.userid)
                    user = query.get()

                    if user:
                        # update stats
                        self.addStat(user, 3)  # recommended

                        newBadges = self.updateBadges(user)
                        user.put()

        self.redirect('/attractions/' + attractionId + '.html')
        return
Exemplo n.º 10
0
 def get(self, attractionId, type):
     
     attractions = Attraction.all()
     attractions.filter("id =", attractionId)
     attraction = attractions.get()
     
     if attraction:
         attraction.picture = self.convertFlickrUrl(attraction.picture, 'm')
         
         result = re.split('\r\n\r\n--', attraction.description)
         if result:
             attraction.description = result[0]
             comments = result[1:]
             attraction.comments = []
             for comment in comments:
                 exploded = re.split('\r\n\r\n', comment)
                 attraction.comments.append({
                     "user": exploded[0],
                     "userid": self.getUserId(exploded[0]),
                     "comment": "\r\n\r\n".join(exploded[1:])
                 })
         
         template_values = {
             'attraction': attraction,
             'gpx': self.request.url.replace('.html', '.gpx')
         }
         
         from google.appengine.api import users
         user = users.get_current_user()
         if user:
             userObject = self.getUserObject(user)
             
             if attraction.root in userObject.recommended:
                 template_values['recommended'] = True
             
             if attraction.root in userObject.itinerary:
                 template_values['itinerary'] = True
         
         self.output('attraction', type, template_values)
     else:
         self.output('404', 'html')
Exemplo n.º 11
0
 def post(self):
     n = int(self.request.get('n'))
     l = 50
     f = self.request.get('f')
     
     import csv
     
     csvReader = csv.reader(open('attractions' + f + '.csv'))
     
     count = 1
     for row in csvReader:
         
         if count >= n and count < n + l:
             
             query = Attraction.all()
             query.filter("id =", row[0])
             attraction = query.get()
             
             if attraction:
                 if row[9] != '' and row[9] != 'unknown' and row[9] not in attraction.tags:
                     attraction.tags.append(row[9])
                 for key in self.tags.keys():
                     if ' ' + key + ' ' in ' ' + row[3].lower() + ' ' and self.tags[key] not in attraction.tags:
                         attraction.tags.append(self.tags[key])
                 if 'unknown' in attraction.tags:
                     attraction.tags.remove('unknown')
                 attraction.put()
             
         elif count >= n:
             
             taskqueue.add(
                 url = '/autotag',
                 params = {
                     'n': n + l,
                     'f': f
                 }
             )
             break
         
         count = count  + 1
Exemplo n.º 12
0
 def post(self):
     n = int(self.request.get('n'))
     l = 50
     
     import csv
     
     csvReader = csv.reader(open('attractions4.csv'))
     
     count = 1
     for row in csvReader:
         
         if count >= n and count < n + l:
             
             attractions = Attraction.all()
             attractions.filter("id =", row[0])
             attraction = attractions.get()
             
             if attraction:
                 attraction.datetime = datetime.datetime(
                     year = int(row[8][0:4]),
                     month = int(row[8][5:7]),
                     day = int(row[8][8:10]),
                     hour = int(row[8][11:13]),
                     minute = int(row[8][14:16]),
                     second = int(row[8][17:19])
                 )
                 attraction.put()
             
         elif count >= n:
             
             taskqueue.add(
                 url = '/fixdate',
                 params = {
                     'n': n + l,
                 }
             )
             break
         
         count = count  + 1
Exemplo n.º 13
0
    def post(self, attractionId):

        from google.appengine.api import users
        user = users.get_current_user()

        if user:

            attractions = Attraction.all()
            attractions.filter("id =", attractionId)
            attraction = attractions.get()

            if attraction:

                userObject = self.getUserObject(user)

                if attraction.root in userObject.itinerary:
                    userObject.itinerary.remove(attraction.root)
                else:
                    userObject.itinerary.append(attraction.root)

                userObject.put()

        self.redirect('/attractions/' + attractionId + '.html')
        return
Exemplo n.º 14
0
 def post(self, attractionId):
     
     from google.appengine.api import users
     user = users.get_current_user()
     
     if user:
         
         attractions = Attraction.all()
         attractions.filter("id =", attractionId)
         attraction = attractions.get()
         
         if attraction:
             
             userObject = self.getUserObject(user)
             
             if attraction.root in userObject.itinerary:
                 userObject.itinerary.remove(attraction.root)
             else:
                 userObject.itinerary.append(attraction.root)
             
             userObject.put()
             
     self.redirect('/attractions/' + attractionId + '.html')
     return
Exemplo n.º 15
0
    def post(self, attractionId=None):

        template_values = {}
        template_values['lat'] = 0
        template_values['lon'] = 0

        attraction = {}
        attraction['id'] = attractionId
        attraction['name'] = self.request.get('name')
        attraction['description'] = self.request.get('description')
        attraction['location'] = {}
        attraction['location']['lat'] = self.request.get('lat')
        attraction['location']['lon'] = self.request.get('lon')
        attraction['href'] = self.request.get('href')
        attraction['picture'] = self.request.get('picture')
        attraction['tags'] = self.request.get('tags').split(' ')

        if self.request.get('location.x') and self.request.get('location.y'):
            attraction['location']['lat'] = float(
                attraction['location']['lat']) - (
                    (float(self.request.get('location.y')) - 75) /
                    18000) + 0.001
            attraction['location']['lon'] = float(
                attraction['location']['lon']) + (
                    (float(self.request.get('location.x')) - 150) / 12000)

        errors = {}

        if self.request.get('title') != 'don\'t spam me bro!':
            try:
                self.redirect('/attractions/' + attractionId + '.html')
            except:
                self.redirect('/')
            return

        if len(attraction['name']) == 0:
            errors['name'] = True
            errors['name_empty'] = True
        if len(attraction['name']) > 100:
            errors['name'] = True
            errors['name_long'] = True

        if len(attraction['description']) > 5000:
            errors['description'] = True

        if not attraction['location']['lat'] or float(
                attraction['location']['lat']) < -90 or float(
                    attraction['location']['lat']) > 90:
            errors['location'] = True

        if not attraction['location']['lon'] or float(
                attraction['location']['lon']) < -180 or float(
                    attraction['location']['lon']) > 180:
            errors['location'] = True

        if not len(attraction['href']) == 0 and not re.match(
                r"^https?://.+$", attraction['href']):
            errors['href'] = True

        if not len(attraction['picture']) == 0 and not re.match(
                r"^https?://.+$", attraction['picture']):
            errors['picture'] = True

        for key, tag in enumerate(attraction['tags']):
            if tag == '':
                del attraction['tags'][key]
            elif not re.match(r"^[a-z0-9]+$", tag):
                errors['tags'] = True

        if errors or (self.request.get('location.x')
                      and self.request.get('location.y')):

            attraction['picture'] = self.convertFlickrUrl(
                attraction['picture'], 'm')

            template_values['attraction'] = attraction,
            template_values['errors'] = errors

            self.output('edit', 'html', template_values)

        else:

            if attractionId:  # editing
                next = attractionId
                while next:  # walk to newest version of this attraction
                    query = Attraction.all()
                    query.filter("id =", next)
                    latestAttraction = query.get()
                    next = latestAttraction.next

            else:  # creating

                latestAttraction = None

            try:
                user = self.getUserObject(
                )  # create user object if it doesn't exist
                if user:

                    if latestAttraction:
                        newAttraction = db.run_in_transaction(
                            self.createAttraction, latestAttraction.key(),
                            attraction)
                        sameEditor = (user.id == latestAttraction.userid)
                    else:
                        newAttraction = db.run_in_transaction(
                            self.createAttraction, None, attraction)
                        sameEditor = False

                    # update stats
                    if not sameEditor:
                        self.addStat(user, 1)  # new edit
                        if newAttraction.region != 'Unknown location':
                            parts = newAttraction.region.split(",")
                            region = ",".join(parts[-2:]).strip(" ")
                            self.addStat(user, 2, region)  # edit location
                    if latestAttraction and newAttraction.picture != '' and latestAttraction.picture == '':
                        self.addStat(user, 4)  # new picture
                    if latestAttraction and 'dupe' in newAttraction.tags and 'dupe' not in latestAttraction.tags:
                        self.addStat(user, 5)  # new dupe tag added
                    if latestAttraction and 'delete' in newAttraction.tags and 'delete' not in latestAttraction.tags:
                        self.addStat(user, 12)  # new delete tag added
                    if latestAttraction \
                        and newAttraction.name == latestAttraction.name \
                        and newAttraction.description == latestAttraction.description \
                        and newAttraction.href == latestAttraction.href \
                        and newAttraction.picture == latestAttraction.picture \
                        and newAttraction.tags == latestAttraction.tags:
                        self.addStat(user, 8)  # no change idiot

                    # type edit
                    if not sameEditor:
                        for badge in self.badges.items():
                            try:
                                if badge[1]['tag'] in newAttraction.tags:
                                    self.addStat(user, 11, badge[0])
                            except KeyError:
                                pass

                        if newAttraction.region != 'Unknown location':
                            for badge in self.badges.items():
                                try:
                                    if str(
                                            badge[1]
                                        ['location']) in newAttraction.region:
                                        self.addStat(user, 10, badge[0])
                                except:
                                    pass

                    newBadges = self.updateBadges(user)
                    user.put()

                    if newBadges:
                        self.redirect('/badges/%s.html' % newBadges.pop(0))
                        return

                try:
                    self.redirect('/attractions/' + newAttraction.id + '.html')
                except:
                    self.redirect('/')
                return

            except db.TransactionFailedError:

                template_values['attraction'] = attraction
                template_values['errors'] = {'save': True}

                self.output('edit', 'html', template_values)
Exemplo n.º 16
0
    def createAttraction(self, key, attractionData):

        from google.appengine.api import users
        from django.utils import simplejson
        import urllib, md5

        user = users.get_current_user()
        if type(user) == users.User:
            attractionData['userid'] = self.getUserId(user.email())
            attractionData['username'] = user.nickname()
        else:
            attractionData['userid'] = None
            attractionData['username'] = self.request.remote_addr

        region = 'Unknown location'

        url = "http://maps.google.com/maps/geo?q=%.2f,%.2f&sensor=false" % (
            float(attractionData['location']['lat']),
            float(attractionData['location']['lon']))
        jsonString = urllib.urlopen(url).read()
        if jsonString:
            data = simplejson.loads(jsonString)
            for placemark in data['Placemark']:
                region = ", ".join(self.getLocationName(placemark))
                if region:
                    break

        if key:
            oldAttraction = db.get(key)
            attractionData['root'] = oldAttraction.root
            attractionData['previous'] = oldAttraction.id
            attractionData['free'] = oldAttraction.free
            attractionData['rating'] = oldAttraction.rating
            attractionData['free'] = oldAttraction.free
        else:
            oldAttraction = None
            attractionData['root'] = None
            attractionData['previous'] = None
            attractionData['free'] = True
            attractionData['rating'] = 0
            attractionData['free'] = True

        if not attractionData['free']:
            import difflib
            s = difflib.SequenceMatcher(None, oldAttraction.description,
                                        attractionData['description'])
            if s.ratio() < 0.5:
                attractionData['free'] = True

        newAttraction = Attraction(
            parent=oldAttraction,
            root=attractionData['root'],
            previous=attractionData['previous'],
            name=attractionData['name'],
            region=region,
            description=attractionData['description'],
            location=db.GeoPt(lat=attractionData['location']['lat'],
                              lon=attractionData['location']['lon']),
            geobox=str(round(float(attractionData['location']['lat']), 1)) +
            ',' + str(round(float(attractionData['location']['lon']), 1)),
            href=attractionData['href'],
            picture=attractionData['picture'],
            tags=attractionData['tags'],
            free=attractionData['free'],
            rating=attractionData['rating'],
            userid=attractionData['userid'],
            username=attractionData['username'])

        newAttraction.id = md5.new(unicode(newAttraction)).hexdigest()
        if not newAttraction.root:
            newAttraction.root = newAttraction.id
        newAttraction.put()

        if oldAttraction:
            oldAttraction.next = newAttraction.id
            oldAttraction.put()

        return newAttraction
Exemplo n.º 17
0
 def post(self):
     n = int(self.request.get('n'))
     l = 50
     f = self.request.get('f')
     
     import csv
     
     csvReader = csv.reader(open('attractions' + f + '.csv'))
     
     count = 1
     for row in csvReader:
         
         if count >= n and count < n + l:
             
             q = Attraction.all()
             q.filter("id =", row[0])
             
             if q.count() > 1:
                 attractions = q.fetch(100)
                 for attraction in attractions:
                     attraction.delete()
                 attraction = None
             else:
                 attraction = q.get()
             
             if not attraction:
                 
                 location = row[1].split(',')
                 
                 if row[7] == 'y':
                     freeVal = True
                 else:
                     freeVal = False
                 
                 name = row[2].decode('utf-8').replace("\n", ' ')
                 if name == '':
                     name = 'No name'
                 
                 try:
                     newAttraction = Attraction(
                         id = row[0],
                         root = row[0],
                         name = name,
                         region = row[6].decode('utf-8').replace("\n", ' '),
                         description = row[3].decode('utf-8'),
                         location = db.GeoPt(
                             lat = location[0],
                             lon = location[1]
                         ),
                         geobox = str(round(float(location[0]), 1)) + ',' + str(round(float(location[1]), 1)),
                         href = row[4].decode('utf-8'),
                         picture = row[5].decode('utf-8'),
                         free = freeVal,
                         datetime = datetime.datetime(
                             year = int(row[8][0:4]),
                             month = int(row[8][5:7]),
                             day = int(row[8][8:10]),
                             hour = int(row[8][11:13]),
                             minute = int(row[8][14:16]),
                             second = int(row[8][17:19])
                         )
                     )
                     
                     newAttraction.put()
                     
                 except db.BadValueError:
                     pass
             
         elif count >= n:
             
             taskqueue.add(
                 url = '/import',
                 params = {
                     'n': n + l,
                     'f': f
                 }
             )
             break
         
         count = count  + 1
     
     if f < 4:
         taskqueue.add(
             url = '/import',
             params = {
                 'n': n + l,
                 'f': f + 1
             }
         )
Exemplo n.º 18
0
    def post(self):
        n = int(self.request.get('n'))
        l = 50
        f = self.request.get('f')

        import csv

        csvReader = csv.reader(open('attractions' + f + '.csv'))

        count = 1
        for row in csvReader:

            if count >= n and count < n + l:

                q = Attraction.all()
                q.filter("id =", row[0])

                if q.count() > 1:
                    attractions = q.fetch(100)
                    for attraction in attractions:
                        attraction.delete()
                    attraction = None
                else:
                    attraction = q.get()

                if not attraction:

                    location = row[1].split(',')

                    if row[7] == 'y':
                        freeVal = True
                    else:
                        freeVal = False

                    name = row[2].decode('utf-8').replace("\n", ' ')
                    if name == '':
                        name = 'No name'

                    try:
                        newAttraction = Attraction(
                            id=row[0],
                            root=row[0],
                            name=name,
                            region=row[6].decode('utf-8').replace("\n", ' '),
                            description=row[3].decode('utf-8'),
                            location=db.GeoPt(lat=location[0],
                                              lon=location[1]),
                            geobox=str(round(float(location[0]), 1)) + ',' +
                            str(round(float(location[1]), 1)),
                            href=row[4].decode('utf-8'),
                            picture=row[5].decode('utf-8'),
                            free=freeVal,
                            datetime=datetime.datetime(
                                year=int(row[8][0:4]),
                                month=int(row[8][5:7]),
                                day=int(row[8][8:10]),
                                hour=int(row[8][11:13]),
                                minute=int(row[8][14:16]),
                                second=int(row[8][17:19])))

                        newAttraction.put()

                    except db.BadValueError:
                        pass

            elif count >= n:

                taskqueue.add(url='/import', params={'n': n + l, 'f': f})
                break

            count = count + 1

        if f < 4:
            taskqueue.add(url='/import', params={'n': n + l, 'f': f + 1})
Exemplo n.º 19
0
country_repository.save(america)
peru = Country("Peru", "South America")
country_repository.save(peru)

paris = City("Paris", france)
city_repository.save(paris)
rome = City("Rome", italy)
city_repository.save(rome)
venice = City("Venice", italy)
city_repository.save(venice)
new_york_city = City("New York City", america)
city_repository.save(new_york_city)
lima = City("Lima", peru)
city_repository.save(lima)

eiffel_tower = Attraction("Eiffel Tower", 25.90, paris)
attraction_repository.save(eiffel_tower)
the_louvre = Attraction("The Louvre", 17, paris)
attraction_repository.save(the_louvre)
the_colosseum = Attraction("The colosseum", 12, rome)
attraction_repository.save(the_colosseum)
st_marks_basilica = Attraction("Saint Mark's Basilica", 3, venice)
attraction_repository.save(st_marks_basilica)
central_park = Attraction("Central Park", 0, new_york_city)
attraction_repository.save(central_park)
natural_history_mueseum = Attraction("Natural History Museum", 23,
                                     new_york_city)
attraction_repository.save(natural_history_mueseum)
huaca_pucllana = Attraction("Huaca Pucllana", 15, peru)
attraction_repository.save(huaca_pucllana)
Exemplo n.º 20
0
    def post(self):
        n = int(self.request.get('n'))
        l = 50
        f = self.request.get('f')

        import csv

        csvReader = csv.reader(open('attractions' + f + '.csv'))

        count = 1
        for row in csvReader:

            if count >= n and count < n + l:

                q = Attraction.all()
                q.filter("id =", row[0])
                attraction = q.get()

                if attraction:

                    location = row[1].split(',')

                    url = "http://maps.google.com/maps/geo?q=%.2f,%.2f&sensor=false" % (
                        float(location[0]), float(location[1]))
                    jsonString = urllib.urlopen(url).read()
                    if jsonString:
                        data = simplejson.loads(jsonString)
                        if 'Placemark' in data:
                            for placemark in data['Placemark']:
                                try:
                                    if placemark['AddressDetails']['Country'][
                                            'AdministrativeArea']['SubAdministrativeArea'][
                                                'SubAdministrativeAreaName'] == placemark[
                                                    'AddressDetails']['Country'][
                                                        'AdministrativeArea'][
                                                            'AdministrativeAreaName']:
                                        raise KeyError
                                    attraction.region = "%s, %s, %s" % (
                                        placemark['AddressDetails']['Country']
                                        ['AdministrativeArea']
                                        ['SubAdministrativeArea']
                                        ['SubAdministrativeAreaName'],
                                        placemark['AddressDetails']['Country']
                                        ['AdministrativeArea']
                                        ['AdministrativeAreaName'],
                                        placemark['AddressDetails']['Country']
                                        ['CountryName'])
                                    break
                                except KeyError:
                                    try:
                                        if placemark['AddressDetails']['Country'][
                                                'AdministrativeArea']['Locality'][
                                                    'LocalityName'] == placemark[
                                                        'AddressDetails']['Country'][
                                                            'AdministrativeArea'][
                                                                'AdministrativeAreaName']:
                                            raise KeyError
                                        attraction.region = "%s, %s, %s" % (
                                            placemark['AddressDetails']
                                            ['Country']['AdministrativeArea']
                                            ['Locality']['LocalityName'],
                                            placemark['AddressDetails']
                                            ['Country']['AdministrativeArea']
                                            ['AdministrativeAreaName'],
                                            placemark['AddressDetails']
                                            ['Country']['CountryName'])
                                        break
                                    except KeyError:
                                        try:
                                            attraction.region = "%s, %s" % (
                                                placemark['AddressDetails']
                                                ['Country']
                                                ['AdministrativeArea']
                                                ['AdministrativeAreaName'],
                                                placemark['AddressDetails']
                                                ['Country']['CountryName'])
                                            break
                                        except KeyError:
                                            try:
                                                attraction.region = "%s, %s" % (
                                                    placemark['AddressDetails']
                                                    ['Country']
                                                    ['SubAdministrativeArea']
                                                    ['SubAdministrativeAreaName'],
                                                    placemark['AddressDetails']
                                                    ['Country']['CountryName'])
                                                break
                                            except KeyError:
                                                attraction.region = 'Unknown location'
                        else:
                            attraction.region = 'Unknown location'
                    else:
                        attraction.region = 'Unknown location'

                    attraction.put()

            elif count >= n:

                taskqueue.add(url='/fixregion', params={'n': n + l, 'f': f})
                break

            count = count + 1
Exemplo n.º 21
0
 def get(self, attractionId, type):
     
     attractions = []
     
     query = Attraction.all()
     query.filter("id =", attractionId)
     attraction = query.get()
     
     if attraction:
         
         while attraction.next != None:
             query = Attraction.all()
             query.filter("id =", attraction.next)
             attraction = query.get()
             attractions.insert(0, attraction)
         
         while attractionId:
             query = Attraction.all()
             query.filter("id =", attractionId)
             attraction = query.get()
             attractions.append(attraction)
             attractionId = attraction.previous if attraction.previous else False
         
         for index in range(0, len(attractions) - 1):
             oldAttr = attractions[index + 1]
             newAttr = attractions[index]
             attractions[index].diff = []
             
             diffString = "Name: %s\nRegion: %s\nMore info: %s\nTags: %s\n\n%s\n"
             
             old = diffString % (
                 oldAttr.name,
                 oldAttr.region,
                 oldAttr.href,
                 " ".join(oldAttr.tags),
                 oldAttr.description
             )
             new = diffString % (
                 newAttr.name,
                 newAttr.region,
                 newAttr.href,
                 " ".join(newAttr.tags),
                 newAttr.description
             )
             
             diff = difflib.unified_diff(old.splitlines(1), new.splitlines(1), n = 3)
             for line in diff:
                 if line[0:3] != '---' and line[0:3] != '+++' and line[0:2] != '@@':
                     if line[0:1] == '+':
                         attractions[index].diff.append(('add', line.strip(" \n+")))
                     elif line[0:1] == '-':
                         attractions[index].diff.append(('take', line.strip(" \n-")))
                     else:
                         attractions[index].diff.append(('', line.strip()))
             
             oldPic = self.convertFlickrUrl(oldAttr.picture, 's')
             newPic = self.convertFlickrUrl(newAttr.picture, 's')
             if oldPic != newPic:
                 attractions[index].diff.append(('pic', oldPic, newPic))
             
             if oldAttr.location.lat != newAttr.location.lat and oldAttr.location.lon != newAttr.location.lon:
                 attractions[index].diff.append(('loc', oldAttr.location, newAttr.location))
             
         
         template_values = {
             'name': attraction.name,
             'attractions': attractions,
             'atom': self.request.url.replace('.html', '.atom'),
             'atomtag': 'history:' + attraction.root,
             'url': self.request.url
         }
         
         self.output('history', type, template_values)
         
     else:
         
         self.output('404', 'html')
Exemplo n.º 22
0
 def post(self):
     n = int(self.request.get('n'))
     l = 50
     f = self.request.get('f')
     
     import csv
     
     csvReader = csv.reader(open('attractions' + f + '.csv'))
     
     count = 1
     for row in csvReader:
         
         if count >= n and count < n + l:
             
             q = Attraction.all()
             q.filter("id =", row[0])
             attraction = q.get()
             
             if attraction:
                 
                 location = row[1].split(',')
                 
                 url = "http://maps.google.com/maps/geo?q=%.2f,%.2f&sensor=false" % (float(location[0]), float(location[1]))
                 jsonString = urllib.urlopen(url).read()
                 if jsonString:
                     data = simplejson.loads(jsonString)
                     if 'Placemark' in data:
                         for placemark in data['Placemark']:
                             try:
                                 if placemark['AddressDetails']['Country']['AdministrativeArea']['SubAdministrativeArea']['SubAdministrativeAreaName'] == placemark['AddressDetails']['Country']['AdministrativeArea']['AdministrativeAreaName']:
                                     raise KeyError
                                 attraction.region = "%s, %s, %s" % (
                                     placemark['AddressDetails']['Country']['AdministrativeArea']['SubAdministrativeArea']['SubAdministrativeAreaName'],
                                     placemark['AddressDetails']['Country']['AdministrativeArea']['AdministrativeAreaName'],
                                     placemark['AddressDetails']['Country']['CountryName']
                                 )
                                 break;
                             except KeyError:
                                 try:
                                     if placemark['AddressDetails']['Country']['AdministrativeArea']['Locality']['LocalityName'] == placemark['AddressDetails']['Country']['AdministrativeArea']['AdministrativeAreaName']:
                                         raise KeyError
                                     attraction.region = "%s, %s, %s" % (
                                         placemark['AddressDetails']['Country']['AdministrativeArea']['Locality']['LocalityName'],
                                         placemark['AddressDetails']['Country']['AdministrativeArea']['AdministrativeAreaName'],
                                         placemark['AddressDetails']['Country']['CountryName']
                                     )
                                     break;
                                 except KeyError:
                                     try:
                                         attraction.region = "%s, %s" % (
                                             placemark['AddressDetails']['Country']['AdministrativeArea']['AdministrativeAreaName'],
                                             placemark['AddressDetails']['Country']['CountryName']
                                         )
                                         break;
                                     except KeyError:
                                         try:
                                             attraction.region = "%s, %s" % (
                                                 placemark['AddressDetails']['Country']['SubAdministrativeArea']['SubAdministrativeAreaName'],
                                                 placemark['AddressDetails']['Country']['CountryName']
                                             )
                                             break;
                                         except KeyError:
                                             attraction.region = 'Unknown location'
                     else:
                         attraction.region = 'Unknown location'
                 else:
                     attraction.region = 'Unknown location'
                 
                 attraction.put()
             
         elif count >= n:
             
             taskqueue.add(
                 url = '/fixregion',
                 params = {
                     'n': n + l,
                     'f': f
                 }
             )
             break
         
         count = count  + 1
Exemplo n.º 23
0
 def get(self, userid, type):
     
     query = User.all()
     query.filter("id =", userid)
     userObject = query.get()
     
     from google.appengine.api import users
     user = users.get_current_user()
     
     if self.getUserId(user) == userid:
         owner = True
     else:
         owner = False
     
     if not userObject and owner:
         userObject = self.getUserObject(user)
     
     if userObject:
         
         template_values = {
             'user': userObject,
             'owner': owner,
             'badges': self.badges
         }
         
         edited = Attraction.all()
         edited.filter("userid =", userid)
         edited.filter("next =", None)
         edited.order("-datetime")
         
         if edited.count() > 0:
             template_values['edited'] = edited.fetch(10)
             for attraction in template_values['edited']:
                 attraction.thumbnail = self.convertFlickrUrl(attraction.picture, 's')
         
         template_values['updated'] = None
         for attraction in edited:
             if template_values['updated'] == None or attraction.datetime > template_values['updated']:
                 template_values['updated'] = attraction.datetime
         
         recommended = Attraction.all()
         recommended.filter("root IN", userObject.recommended)
         recommended.filter("next =", None)
         recommended.order("-datetime")
         
         if recommended.count() > 0:
             template_values['recommended'] = recommended.fetch(10)
             for attraction in template_values['recommended']:
                 attraction.thumbnail = self.convertFlickrUrl(attraction.picture, 's')
         
         itinerary = Attraction.all()
         itinerary.filter("root IN", userObject.itinerary)
         itinerary.filter("next =", None)
         itinerary.order("-datetime")
         
         if itinerary.count() > 0:
             template_values['itinerary'] = itinerary.fetch(10)
             for attraction in template_values['itinerary']:
                 attraction.thumbnail = self.convertFlickrUrl(attraction.picture, 's')
         
         template_values['url'] = self.request.path
         template_values['atomtag'] = 'user:'******'atom'] = re.sub(r'\..+$', '.atom', self.request.path)
         template_values['html'] = re.sub(r'\..+$', '.html', self.request.path)
         template_values['kml'] = re.sub(r'\.[^.]+$', '.kml', self.request.url)
         
         self.output('user', type, template_values)
         
     else:
         self.output('404', 'html')
Exemplo n.º 24
0
    def get(self, userid, type):

        query = User.all()
        query.filter("id =", userid)
        userObject = query.get()

        from google.appengine.api import users

        user = users.get_current_user()

        if self.getUserId(user) == userid:
            owner = True
        else:
            owner = False

        if not userObject and owner:
            userObject = self.getUserObject(user)

        if userObject:

            template_values = {"user": userObject, "owner": owner, "badges": self.badges}

            edited = Attraction.all()
            edited.filter("userid =", userid)
            edited.filter("next =", None)
            edited.order("-datetime")

            if edited.count() > 0:
                template_values["edited"] = edited.fetch(10)
                for attraction in template_values["edited"]:
                    attraction.thumbnail = self.convertFlickrUrl(attraction.picture, "s")

            template_values["updated"] = None
            for attraction in edited:
                if template_values["updated"] == None or attraction.datetime > template_values["updated"]:
                    template_values["updated"] = attraction.datetime

            recommended = Attraction.all()
            recommended.filter("root IN", userObject.recommended)
            recommended.filter("next =", None)
            recommended.order("-datetime")

            if recommended.count() > 0:
                template_values["recommended"] = recommended.fetch(10)
                for attraction in template_values["recommended"]:
                    attraction.thumbnail = self.convertFlickrUrl(attraction.picture, "s")

            itinerary = Attraction.all()
            itinerary.filter("root IN", userObject.itinerary)
            itinerary.filter("next =", None)
            itinerary.order("-datetime")

            if itinerary.count() > 0:
                template_values["itinerary"] = itinerary.fetch(10)
                for attraction in template_values["itinerary"]:
                    attraction.thumbnail = self.convertFlickrUrl(attraction.picture, "s")

            template_values["url"] = self.request.path
            template_values["atomtag"] = "user:"******"atom"] = re.sub(r"\..+$", ".atom", self.request.path)
            template_values["html"] = re.sub(r"\..+$", ".html", self.request.path)
            template_values["kml"] = re.sub(r"\.[^.]+$", ".kml", self.request.url)

            self.output("user", type, template_values)

        else:
            self.output("404", "html")
Exemplo n.º 25
0
class SearchPage(Controller):
    def getAttractions(self,
                       lat=None,
                       lon=None,
                       format='html',
                       tag='',
                       bounds={}):

        attractions = []
        updated = None

        boxLat = round(lat, 1)
        boxLon = round(lon, 1)

        defaultAccuracy = 1

        try:
            boundsLat = bounds['north'] - bounds['south']
            boundsLon = bounds['east'] - bounds['west']
            if boundsLat < boundsLon:
                accuracy = boundsLat
            else:
                accuracy = boundsLon
        except KeyError:
            accuracy = defaultAccuracy

        if format == 'js' or accuracy < defaultAccuracy:
            lats = [boxLat]
            lons = [boxLon]
        else:
            lats = [boxLat - 0.1, boxLat, boxLat + 0.1]
            lons = [boxLon - 0.1, boxLon, boxLon + 0.1]

        for latitude in lats:
            for longitude in lons:

                query = Attraction.all()
                query.filter("next =", None)
                query.filter("geobox =", '%s,%s' % (latitude, longitude))
                if tag:
                    query.filter("tags =", tag)
                query.order("name")

                try:
                    for attraction in query:
                        if accuracy >= defaultAccuracy or (\
                            attraction.location.lat > lat - accuracy and \
                            attraction.location.lat < lat + accuracy and \
                            attraction.location.lon > lon - accuracy and \
                            attraction.location.lon < lon + accuracy
                        ):
                            attractions.append(attraction)
                except (IndexError, db.BadRequestError):
                    pass

        attractions.sort(lambda x, y: cmp(x.name, y.name))

        attractionCount = 64
        for attraction in attractions:
            attractionCount = attractionCount + 1
            if attractionCount < 91:
                attraction.label = chr(attractionCount)
            if attraction.picture:
                attraction.thumbnail = self.convertFlickrUrl(
                    attraction.picture, "s")
            if updated == None or attraction.datetime > updated:
                updated = attraction.datetime

        return (attractions, updated, accuracy)

    def get(self, format):

        search = self.request.get("q")
        coords = self.request.get("c")
        tag = self.request.get("t")
        attractions = self.request.get("a")

        template_values = {}

        template_values['q'] = search

        # special search strings
        if search[0:10] == "tagged as ":
            if " in " not in search:
                tag = search[10:].strip(" ")
                if tag in self.tags:
                    tag = self.tags[tag]
            search = search[10:]
        elif search[0:12] == "tagged with ":
            if " in " not in search:
                tag = search[12:].strip(" ")
                if tag in self.tags:
                    tag = self.tags[tag]
            search = search[12:]

        if search[-11:] == " everywhere":
            tag = search[0:-11].strip(" ")
            if tag in self.tags:
                tag = self.tags[tag]
        elif search[-9:] == " anywhere":
            tag = search[0:-9].strip(" ")
            if tag in self.tags:
                tag = self.tags[tag]

        if coords:

            coords = coords.split(',')
            try:
                template_values['coords'] = "%.2f,%.2f" % (float(
                    coords[0]), float(coords[1]))
            except ValueError:
                self.send404()
                return

            if format != 'js':

                url = "http://maps.google.com/maps/geo?q=%.2f,%.2f&sensor=false" % (
                    float(coords[0]), float(coords[1]))

                jsonString = urllib.urlopen(url).read()
                if jsonString:
                    data = simplejson.loads(jsonString)
                    try:
                        lat = data['Placemark'][0]['Point']['coordinates'][1]
                        lon = data['Placemark'][0]['Point']['coordinates'][0]
                        (template_values['attractions'],
                         template_values['updated'],
                         accuracy) = self.getAttractions(lat, lon, format)
                        location = self.getLocationName(data['Placemark'][0])
                        template_values['search'] = ', '.join(location).encode(
                            'utf-8')
                        try:
                            template_values['location'] = location[0].encode(
                                'utf-8')
                        except:
                            pass
                    except KeyError, IndexError:
                        pass
                else:
                    lat = float(coords[0])
                    lon = float(coords[1])
                    (template_values['attractions'],
                     template_values['updated'],
                     accuracy) = self.getAttractions(lat, lon, format)
            else:
                lat = float(coords[0])
                lon = float(coords[1])
                (template_values['attractions'], template_values['updated'],
                 accuracy) = self.getAttractions(lat, lon, format)

        elif tag:
            page = int(self.request.get("page", 1))

            attractionQuery = Attraction.all()
            attractionQuery.filter("tags =", tag)
            attractionQuery.filter("next =", None)
            try:
                template_values['attractions'] = attractionQuery.fetch(
                    26, (page - 1) * 26)
            except:
                template_values['attractions'] = []

            if page > 1:
                template_values[
                    'previous'] = self.request.path + '?t=' + tag + '&page=' + str(
                        page - 1)
            if len(template_values['attractions']) == 26:
                template_values[
                    'next'] = self.request.path + '?t=' + tag + '&page=' + str(
                        page + 1)

            template_values['updated'] = None
            attractionCount = 64
            for attraction in template_values['attractions']:
                attractionCount = attractionCount + 1
                if attractionCount < 91:
                    attraction.label = chr(attractionCount)
                if attraction.picture:
                    attraction.thumbnail = self.convertFlickrUrl(
                        attraction.picture, "s")
                if template_values[
                        'updated'] == None or attraction.datetime > template_values[
                            'updated']:
                    template_values['updated'] = attraction.datetime

            template_values['tag'] = tag.encode('utf-8')
Exemplo n.º 26
0
land_repository.delete_all()
park_repository.delete_all()

park1 = Park("Disneyland Park")
park_repository.save(park1)
park2 = Park("Walt Disney Studios Park")
park_repository.save(park2)

land1 = Land("Fantasyland", park1, True)
land_repository.save(land1)
land2 = Land("Discoveryland", park1, False)
land_repository.save(land2)
land3 = Land("Toon Studio", park2, False)
land_repository.save(land3)
land4 = Land("Adventureland", park1, False)
land_repository.save(land4)
land5 = Land("Production Courtyard", park2, False)
land_repository.save(land5)

attraction1 = Attraction("It's a small world", land1, True, "So cute! Song in my head forver now!!")
attraction_repository.save(attraction1)
attraction2 = Attraction("Space Mountain", land2, False, "Bit scared! Hope it's not too fast!!!")
attraction_repository.save(attraction2)
attraction3 = Attraction("Peter Pan's Flight", land1, False, "So excited I could cry!!!")
attraction_repository.save(attraction3)
attraction4 = Attraction("Crush's Coaster", land3, False, "Looks awesome, dude!")
attraction_repository.save(attraction4)



Exemplo n.º 27
0
 def post(self, attractionId = None):
     
     template_values = {}
     template_values['lat'] = 0
     template_values['lon'] = 0
     
     attraction = {}
     attraction['id'] = attractionId
     attraction['name'] = self.request.get('name')
     attraction['description'] = self.request.get('description')
     attraction['location'] = {}
     attraction['location']['lat'] = self.request.get('lat')
     attraction['location']['lon'] = self.request.get('lon')
     attraction['href'] = self.request.get('href')
     attraction['picture'] = self.request.get('picture')
     attraction['tags'] = self.request.get('tags').split(' ')
     
     if self.request.get('location.x') and self.request.get('location.y'):
         attraction['location']['lat'] = float(attraction['location']['lat']) - ((float(self.request.get('location.y')) - 75) / 18000) + 0.001
         attraction['location']['lon'] = float(attraction['location']['lon']) + ((float(self.request.get('location.x')) - 150) / 12000)
     
     errors = {}
     
     if self.request.get('title') != 'don\'t spam me bro!':
         try:
             self.redirect('/attractions/' + attractionId + '.html')
         except:
             self.redirect('/')
         return
     
     if len(attraction['name']) == 0:
         errors['name'] = True
         errors['name_empty'] = True
     if len(attraction['name']) > 100:
         errors['name'] = True
         errors['name_long'] = True
     
     if len(attraction['description']) > 5000:
         errors['description'] = True
     
     if not attraction['location']['lat'] or float(attraction['location']['lat']) < -90 or float(attraction['location']['lat']) > 90:
         errors['location'] = True
     
     if not attraction['location']['lon'] or float(attraction['location']['lon']) < -180 or float(attraction['location']['lon']) > 180:
         errors['location'] = True
     
     if not len(attraction['href']) == 0 and not re.match(r"^https?://.+$", attraction['href']):
         errors['href'] = True
     
     if not len(attraction['picture']) == 0 and not re.match(r"^https?://.+$", attraction['picture']):
         errors['picture'] = True
     
     for key, tag in enumerate(attraction['tags']):
         if tag == '':
             del attraction['tags'][key]
         elif not re.match(r"^[a-z0-9]+$", tag):
             errors['tags'] = True
     
     if errors or (self.request.get('location.x') and self.request.get('location.y')):
         
         attraction['picture'] = self.convertFlickrUrl(attraction['picture'], 'm')
         
         template_values['attraction'] = attraction,
         template_values['errors'] = errors
         
         self.output('edit', 'html', template_values)
         
     else:
         
         if attractionId: # editing
             next = attractionId
             while next: # walk to newest version of this attraction
                 query = Attraction.all()
                 query.filter("id =", next)
                 latestAttraction = query.get()
                 next = latestAttraction.next
             
         else: # creating
             
             latestAttraction = None
         
         try:
             user = self.getUserObject() # create user object if it doesn't exist
             if user:
                 
                 if latestAttraction:
                     newAttraction = db.run_in_transaction(self.createAttraction, latestAttraction.key(), attraction)
                     sameEditor = (user.id == latestAttraction.userid)
                 else:
                     newAttraction = db.run_in_transaction(self.createAttraction, None, attraction)
                     sameEditor = False
                 
                 # update stats
                 if not sameEditor:
                     self.addStat(user, 1) # new edit
                     if newAttraction.region != 'Unknown location':
                         parts = newAttraction.region.split(",")
                         region = ",".join(parts[-2:]).strip(" ")
                         self.addStat(user, 2, region) # edit location
                 if latestAttraction and newAttraction.picture != '' and latestAttraction.picture == '':
                     self.addStat(user, 4) # new picture
                 if latestAttraction and 'dupe' in newAttraction.tags and 'dupe' not in latestAttraction.tags:
                     self.addStat(user, 5) # new dupe tag added
                 if latestAttraction and 'delete' in newAttraction.tags and 'delete' not in latestAttraction.tags:
                     self.addStat(user, 12) # new delete tag added
                 if latestAttraction \
                     and newAttraction.name == latestAttraction.name \
                     and newAttraction.description == latestAttraction.description \
                     and newAttraction.href == latestAttraction.href \
                     and newAttraction.picture == latestAttraction.picture \
                     and newAttraction.tags == latestAttraction.tags:
                     self.addStat(user, 8) # no change idiot
                 
                 # type edit
                 if not sameEditor:
                     for badge in self.badges.items():
                         try:
                             if badge[1]['tag'] in newAttraction.tags:
                                 self.addStat(user, 11, badge[0])
                         except KeyError:
                             pass
                     
                     if newAttraction.region != 'Unknown location':
                         for badge in self.badges.items():
                             try:
                                 if str(badge[1]['location']) in newAttraction.region:
                                     self.addStat(user, 10, badge[0])
                             except:
                                 pass
                 
                 newBadges = self.updateBadges(user)
                 user.put()
                 
                 if newBadges:
                     self.redirect('/badges/%s.html' % newBadges.pop(0))
                     return
             
             try:
                 self.redirect('/attractions/' + newAttraction.id + '.html')
             except:
                 self.redirect('/')
             return
             
         except db.TransactionFailedError:
         
             template_values['attraction'] = attraction
             template_values['errors'] = {
                 'save': True
             }
             
             self.output('edit', 'html', template_values)
Exemplo n.º 28
0
                 self.output('500', 'html')
                 return
         except KeyError, IndexError:
             self.output('500', 'html')
             return
     else:
         self.output('500', 'html')
         return
         
 elif attractions:
     
     template_values['attractions'] = []
     
     for attractionId in attractions.split(","):
         
         query = Attraction.all()
         query.filter("id =", attractionId)
         
         attraction = query.get()
         if attraction:
             template_values['attractions'].append(attraction)
 
 if format == 'html':
     template_values['otherPlaces'] = []
     
     try:
         if accuracy:
             size = accuracy
         else:
             size = 0.05
         coords = [
Exemplo n.º 29
0
 def getAttractions(self, lat = None, lon = None, format = 'html', tag = '', bounds = {}):
     
     attractions = []
     updated = None
     
     boxLat = round(lat, 1)
     boxLon = round(lon, 1)
     
     defaultAccuracy = 1
     
     try:
         boundsLat = bounds['north'] - bounds['south']
         boundsLon = bounds['east'] - bounds['west']
         if boundsLat < boundsLon:
             accuracy = boundsLat
         else:
             accuracy = boundsLon
     except KeyError:
         accuracy = defaultAccuracy
     
     if format == 'js' or accuracy < defaultAccuracy:
         lats = [boxLat]
         lons = [boxLon]
     else:
         lats = [boxLat - 0.1, boxLat, boxLat + 0.1]
         lons = [boxLon - 0.1, boxLon, boxLon + 0.1]
     
     for latitude in lats:
         for longitude in lons:
             
             query = Attraction.all()
             query.filter("next =", None)
             query.filter("geobox =", '%s,%s' % (latitude, longitude))
             if tag:
                 query.filter("tags =", tag)
             query.order("name")
             
             try:
                 for attraction in query:
                     if accuracy >= defaultAccuracy or (\
                         attraction.location.lat > lat - accuracy and \
                         attraction.location.lat < lat + accuracy and \
                         attraction.location.lon > lon - accuracy and \
                         attraction.location.lon < lon + accuracy
                     ):
                         attractions.append(attraction)
             except (IndexError, db.BadRequestError):
                 pass
     
     attractions.sort(lambda x, y: cmp(x.name, y.name))
     
     attractionCount = 64
     for attraction in attractions:
         attractionCount = attractionCount + 1
         if attractionCount < 91:
             attraction.label = chr(attractionCount)
         if attraction.picture:
             attraction.thumbnail = self.convertFlickrUrl(attraction.picture, "s")
         if updated == None or attraction.datetime > updated:
             updated = attraction.datetime
         
     return (attractions, updated, accuracy)
Exemplo n.º 30
0
    def get(self, attractionId, type):

        attractions = []

        query = Attraction.all()
        query.filter("id =", attractionId)
        attraction = query.get()

        if attraction:

            while attraction.next != None:
                query = Attraction.all()
                query.filter("id =", attraction.next)
                attraction = query.get()
                attractions.insert(0, attraction)

            while attractionId:
                query = Attraction.all()
                query.filter("id =", attractionId)
                attraction = query.get()
                attractions.append(attraction)
                attractionId = attraction.previous if attraction.previous else False

            for index in range(0, len(attractions) - 1):
                oldAttr = attractions[index + 1]
                newAttr = attractions[index]
                attractions[index].diff = []

                diffString = "Name: %s\nRegion: %s\nMore info: %s\nTags: %s\n\n%s\n"

                old = diffString % (oldAttr.name, oldAttr.region, oldAttr.href,
                                    " ".join(
                                        oldAttr.tags), oldAttr.description)
                new = diffString % (newAttr.name, newAttr.region, newAttr.href,
                                    " ".join(
                                        newAttr.tags), newAttr.description)

                diff = difflib.unified_diff(old.splitlines(1),
                                            new.splitlines(1),
                                            n=3)
                for line in diff:
                    if line[0:3] != '---' and line[0:3] != '+++' and line[
                            0:2] != '@@':
                        if line[0:1] == '+':
                            attractions[index].diff.append(
                                ('add', line.strip(" \n+")))
                        elif line[0:1] == '-':
                            attractions[index].diff.append(
                                ('take', line.strip(" \n-")))
                        else:
                            attractions[index].diff.append(('', line.strip()))

                oldPic = self.convertFlickrUrl(oldAttr.picture, 's')
                newPic = self.convertFlickrUrl(newAttr.picture, 's')
                if oldPic != newPic:
                    attractions[index].diff.append(('pic', oldPic, newPic))

                if oldAttr.location.lat != newAttr.location.lat and oldAttr.location.lon != newAttr.location.lon:
                    attractions[index].diff.append(
                        ('loc', oldAttr.location, newAttr.location))

            template_values = {
                'name': attraction.name,
                'attractions': attractions,
                'atom': self.request.url.replace('.html', '.atom'),
                'atomtag': 'history:' + attraction.root,
                'url': self.request.url
            }

            self.output('history', type, template_values)

        else:

            self.output('404', 'html')
Exemplo n.º 31
0
 def get(self, type):
     
     coords = self.request.get("c")
     page = int(self.request.get("page", 1));
     
     template_values = {}
     
     if coords:
         coords = coords.split(',')
         
         lat = round(float(coords[0]), 1)
         lon = round(float(coords[1]), 1)
         
         lats = [lat - 0.1, lat, lat + 0.1]
         lons = [lon - 0.1, lon, lon + 0.1]
         
         attractions = []
         count = 0
         
         for latitude in lats:
             for longitude in lons:
                 
                 query = Attraction.all()
                 query.filter("next =", None)
                 query.filter("geobox =", '%s,%s' % (latitude, longitude))
                 query.order("-datetime")
                 
                 try:
                     #fetched = query.fetch(26, ((page - 1) * 26) + count)
                     #for attraction in fetched:
                     for attraction in query:
                         count = count + 1
                         if count > (page - 1) * 26:
                             attractions.append(attraction)
                         if count >= (page - 1) * 26 + 26:
                             break
                 except (IndexError, db.BadRequestError):
                     pass
                 
                 if count >= 26:
                     break
             if count >= 26:
                 break
                 
         attractions.sort()
         
         template_values['coords'] = '%.1f,%.1f' % (lat, lon)
         template_values['atomtag'] = 'recent:' + template_values['coords']
         
         if page > 1:
             template_values['previous'] = self.request.path + '?c=%.1f,%.1f&page=%d' % (lat, lon, page - 1)
         
         if count == 26:
             template_values['next'] = self.request.path + '?c=%.1f,%.1f&page=%d' % (lat, lon, page + 1)
         
     else:
         
         query = Attraction.all()
         query.filter("next =", None)
         query.order("-datetime")
         
         try:
             attractions = query.fetch(26, (page - 1) * 26)
         except (IndexError, db.BadRequestError):
             attractions = []
             
         if page > 1:
             template_values['previous'] = self.request.path + '?page=' + str(page - 1)
         
         if len(attractions) == 26:
             template_values['next'] = self.request.path + '?page=' + str(page + 1)
         
         template_values['atomtag'] = 'recent'
     
     updated = None
     numberOfAttractions = len(attractions)
     attractionCount = 64
     for attraction in attractions:
         attractionCount = attractionCount + 1
         if attractionCount < 91:
             attraction.label = chr(attractionCount)
         if updated == None or attraction.datetime > updated:
             updated = attraction.datetime
         if attraction.picture:
             attraction.thumbnail = self.convertFlickrUrl(attraction.picture, "s")
     
     template_values['attractions'] = attractions
     template_values['updated'] = updated
     
     template_values['url'] = self.request.url
     template_values['atom'] = re.sub(r'\..+$', '.atom', self.request.path)
     template_values['sitemap'] = re.sub(r'\..+$', '.xml', self.request.path)
     template_values['kml'] = re.sub(r'\.[^.]+$', '.kml', self.request.url)
     
     if type == 'xml':
         template_values['cities'] = self.cities
     
     self.output('recent', type, template_values)
Exemplo n.º 32
0
                        self.output('500', 'html')
                        return
                except KeyError, IndexError:
                    self.output('500', 'html')
                    return
            else:
                self.output('500', 'html')
                return

        elif attractions:

            template_values['attractions'] = []

            for attractionId in attractions.split(","):

                query = Attraction.all()
                query.filter("id =", attractionId)

                attraction = query.get()
                if attraction:
                    template_values['attractions'].append(attraction)

        if format == 'html':
            template_values['otherPlaces'] = []

            try:
                if accuracy:
                    size = accuracy
                else:
                    size = 0.05
                coords = [
Exemplo n.º 33
0
 def setUp(self):
     self.country = Country("France", "Europe")
     self.city = City("Paris", self.country)
     self.attraction = Attraction("Eiffel Tower", 25.90, self.city)
Exemplo n.º 34
0
    def getAttractions(self,
                       lat=None,
                       lon=None,
                       format='html',
                       tag='',
                       bounds={}):

        attractions = []
        updated = None

        boxLat = round(lat, 1)
        boxLon = round(lon, 1)

        defaultAccuracy = 1

        try:
            boundsLat = bounds['north'] - bounds['south']
            boundsLon = bounds['east'] - bounds['west']
            if boundsLat < boundsLon:
                accuracy = boundsLat
            else:
                accuracy = boundsLon
        except KeyError:
            accuracy = defaultAccuracy

        if format == 'js' or accuracy < defaultAccuracy:
            lats = [boxLat]
            lons = [boxLon]
        else:
            lats = [boxLat - 0.1, boxLat, boxLat + 0.1]
            lons = [boxLon - 0.1, boxLon, boxLon + 0.1]

        for latitude in lats:
            for longitude in lons:

                query = Attraction.all()
                query.filter("next =", None)
                query.filter("geobox =", '%s,%s' % (latitude, longitude))
                if tag:
                    query.filter("tags =", tag)
                query.order("name")

                try:
                    for attraction in query:
                        if accuracy >= defaultAccuracy or (\
                            attraction.location.lat > lat - accuracy and \
                            attraction.location.lat < lat + accuracy and \
                            attraction.location.lon > lon - accuracy and \
                            attraction.location.lon < lon + accuracy
                        ):
                            attractions.append(attraction)
                except (IndexError, db.BadRequestError):
                    pass

        attractions.sort(lambda x, y: cmp(x.name, y.name))

        attractionCount = 64
        for attraction in attractions:
            attractionCount = attractionCount + 1
            if attractionCount < 91:
                attraction.label = chr(attractionCount)
            if attraction.picture:
                attraction.thumbnail = self.convertFlickrUrl(
                    attraction.picture, "s")
            if updated == None or attraction.datetime > updated:
                updated = attraction.datetime

        return (attractions, updated, accuracy)
Exemplo n.º 35
0
 def createAttraction(self, key, attractionData):
     
     from google.appengine.api import users
     from django.utils import simplejson
     import urllib, md5
     
     user = users.get_current_user()
     if type(user) == users.User:
         attractionData['userid'] = self.getUserId(user.email())
         attractionData['username'] = user.nickname()
     else:
         attractionData['userid'] = None
         attractionData['username'] = self.request.remote_addr
     
     region = 'Unknown location'
     
     url = "http://maps.google.com/maps/geo?q=%.2f,%.2f&sensor=false" % (float(attractionData['location']['lat']), float(attractionData['location']['lon']))
     jsonString = urllib.urlopen(url).read()
     if jsonString:
         data = simplejson.loads(jsonString)
         for placemark in data['Placemark']:
             region = ", ".join(self.getLocationName(placemark))
             if region:
                 break
     
     if key:
         oldAttraction = db.get(key)
         attractionData['root'] = oldAttraction.root
         attractionData['previous'] = oldAttraction.id
         attractionData['free'] = oldAttraction.free
         attractionData['rating'] = oldAttraction.rating
         attractionData['free'] = oldAttraction.free
     else:
         oldAttraction = None
         attractionData['root'] = None
         attractionData['previous'] = None
         attractionData['free'] = True
         attractionData['rating'] = 0
         attractionData['free'] = True
     
     if not attractionData['free']:
         import difflib
         s = difflib.SequenceMatcher(None, oldAttraction.description, attractionData['description'])
         if s.ratio() < 0.5:
             attractionData['free'] = True
     
     newAttraction = Attraction(
         parent = oldAttraction,
         root = attractionData['root'],
         previous = attractionData['previous'],
         name = attractionData['name'],
         region = region,
         description = attractionData['description'],
         location = db.GeoPt(
             lat = attractionData['location']['lat'],
             lon = attractionData['location']['lon']
         ),
         geobox = str(round(float(attractionData['location']['lat']), 1)) + ',' + str(round(float(attractionData['location']['lon']), 1)),
         href = attractionData['href'],
         picture = attractionData['picture'],
         tags = attractionData['tags'],
         free = attractionData['free'],
         rating = attractionData['rating'],
         userid = attractionData['userid'],
         username = attractionData['username']
     )
     
     newAttraction.id = md5.new(unicode(newAttraction)).hexdigest()
     if not newAttraction.root:
         newAttraction.root = newAttraction.id
     newAttraction.put()
     
     if oldAttraction:
         oldAttraction.next = newAttraction.id
         oldAttraction.put()
     
     return newAttraction