Esempio n. 1
0
    def get(self):
        if not WhiteTokenModel.is_jti_whitelisted(get_raw_jwt()["jti"]):
            return {'message': 'Not logged in'}, 205
        try:
            print("Starting", flush=True)
            current_user = get_jwt_identity()
            userid = request.args.get('userid')
            tripid = request.args.get('tripid')
            print("Got data", flush=True)

            # If a tripid is provided, it will return just that trip
            if (tripid):
                print("tripid was provided", flush=True)
                trip = Trip.find_by_tid(int(tripid))
                print("Found trip", flush=True)
                # Making sure that the user asking for the trip has access to it, either because the user owns it, or is friends with the owner
                isFriends = Friends.find_by_uid_and_fid(
                    current_user, trip.user_id)
                if (trip.user_id != current_user and isFriends == None):
                    print("No access", flush=True)
                    return {
                        "message": "You do not have access to that trip"
                    }, 203
                elif (isFriends.friend_status == "accepted"
                      or trip.user_id == current_user):
                    print("Returning", flush=True)
                    return {
                        "message":
                        "The trip with id {} was found".format(tripid),
                        "trips": [trip.trip_json],
                        "tid": trip.trip_id,
                        "username": User.find_by_uid(trip.user_id).user_name
                    }, 200

            if (not userid):
                userId = current_user
            else:
                userId = userid

            if (current_user == userId
                    or Friends.find_by_uid_and_fid(current_user, userId)):
                all_trips = Trip.find_all_public_trips(userId)
                return {
                    "message":
                    "The trips of user {} was found".format(
                        User.find_by_uid(userId).user_name),
                    "trips":
                    json.dumps(all_trips)
                }, 200
            else:
                return {
                    "message":
                    "You are not friends with the requested user, therefore you cannot get their trips"
                }, 203

        except Exception as error:
            return {
                "message": "Something went wrong on the server",
                "error": str(error)
            }, 500
Esempio n. 2
0
 def post_trip(user):
     body = request.get_json()
     new_trip = Trip(id_traveler=user['id'], needs_trip=body['needs_trip'], destination=body['destination'], first_day=body['first_day'], last_day=body['last_day'], description=body['description'])
     db.session.add(new_trip)
     db.session.commit()
 
     new_travel_json = new_trip.serialize()
     return jsonify(new_travel_json), 200
Esempio n. 3
0
 def insert_json_into_db(cls, username, json):
     user = cls.session.query(User).filter_by(username=username).first()
     user.trips.extend([
         Trip(trip=trip, srid=settings.TARGET_DATUM) for trip in json
         if len(trip['path']) > 1
     ])
     cls.session.commit()
Esempio n. 4
0
def get_trips_from_account_info(account_info):
    parent_key = get_parent_key(account_info.rose_username)
    trips = Trip.query(ancestor=parent_key).order(Trip.pick_up_time).fetch()
    trip_map ={}
    for trip in trips:
        trip_map[trip.key]=trip
    return trips, trip_map
Esempio n. 5
0
 def get(self):
     user,_,url,url_linktext = self.get_user()
     
     #get filters from url
     location = helper.creatList(self.request.get("locationfilter"))
     type = helper.creatList(self.request.get("typefilter"))
     season = helper.creatList(self.request.get("seasonfilter"))
     
     #get all trips
     trips_query = Trip.query(Trip.visibility==True)
     if location != ['']:
         trips_query = trips_query.filter(Trip.trip_tags.location.IN(location))
     if type != ['']:
         trips_query = trips_query.filter(Trip.trip_tags.type.IN(type))
     if season != ['']:
         trips_query = trips_query.filter(Trip.trip_tags.season.IN(season))
 
     trips = trips_query.fetch()
     
     #create template
     template_values = {'user': user, 'url': url, 'url_linktext': url_linktext,
                       'location':location,'type':type,'season':season,'trips':trips}
     template = JINJA_ENVIRONMENT.get_template('templates/new/search.html')
  
     self.response.write(template.render(template_values))
Esempio n. 6
0
    def get(self, trip_key):

        errors = []
        output = ""
        user = users.get_current_user()
        authz = Authz(user)
        self.response.headers["Content-type"] = "application/json"

        try:
            # get the trip
            trip = Trip.get(trip_key)

            # verify the user is authorized to read the trip
            authz.readTrip(trip)

            # format trip data
            output = GqlEncoder().encode(trip)

        except db.BadKeyError:
            errors.append({"message": "Invalid trip key"})
        except PermissionError:
            errors.append({"message": "You are not authorized to view that trip"})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error loading trip"})

        if len(errors) > 0:
            output = json.dumps({"error": errors})

        self.response.out.write(output)
Esempio n. 7
0
def make_track_tree(id,location,type,season):
    '''
    Create tree (http://www.ztree.me/v3/main.php#_zTreeInfo)
    '''
    #get all trips
    trips_query = Trip.query(ancestor=trip_key(id))
    if location != []:
        trips_query = trips_query.filter(Trip.trip_tags.location.IN(location))
    if type != []:
        trips_query = trips_query.filter(Trip.trip_tags.type.IN(type))
    if season != []:
        trips_query = trips_query.filter(Trip.trip_tags.season.IN(season))
    
    trips = trips_query.fetch()
      
    #create tree structure from trips
    tree = []
    i = 1
    of = 0
    tree.append({'id':0, 'pId':0, 'name':'My Trips','isParent': 'true','open':'true'})
    for trip in trips:
        tree.append({'id':i, 'pId':0, 'name':str(trip.trip_name),'isParent': 'true', 'click':"openTrip('"+ str(trip.key.urlsafe()) +"')"})
        #get tracks from trip
        track_query = Track.query(ancestor=trip.key).order(-Track.creation_date)
        tracks = track_query.fetch(20)
        for track in tracks:
            tree.append({'id':i+10+of, 'pId':i, 'name':str(track.track_name),'click':"openTrack('"+ str(track.key.urlsafe()) +"')"})
            of += 1
        i += 1
        
    return tree
Esempio n. 8
0
    def get(self, trip_key):

        errors = []
        output = ""
        user = users.get_current_user()
        authz = Authz(user)
        self.response.headers["Content-type"] = "application/json"

        try:
            # get the trip
            trip = Trip.get(trip_key)

            # verify the user is authorized to read the trip
            authz.readTrip(trip)

            # format trip data
            output = GqlEncoder().encode(trip)

        except db.BadKeyError:
            errors.append({"message": "Invalid trip key"})
        except PermissionError:
            errors.append(
                {"message": "You are not authorized to view that trip"})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error loading trip"})

        if len(errors) > 0:
            output = json.dumps({"error": errors})

        self.response.out.write(output)
Esempio n. 9
0
    def make_a_trip(self):
        from models import Trip, User, Origin, Destination

        session = self.get_session()

        user = User(username='******',
                    email='*****@*****.**',
                    phone='123456789',
                    auth0_id='123')
        session.save(user)

        origin = Origin(street='Baker St',
                        street_number='221B',
                        colony_or_district='Marylebone',
                        city='London',
                        state='Marylebone',
                        country='UK',
                        zipcode='NW1 6XE')
        session.save(origin)

        destination = Destination(street='Wallaby Way',
                                  street_number='42',
                                  colony_or_district='-',
                                  city='Sydney',
                                  state='New South Wales',
                                  country='Australia',
                                  zipcode='31351')
        session.save(destination)

        trip = Trip(drive_or_ride='Drive',
                    time=parser.parse('2110-10-20 03:17:52 UTC'),
                    origin=origin,
                    destination=destination,
                    user=user)
        session.save(trip)
Esempio n. 10
0
    def _expenseScaffold(self, trip_key):
        if trip_key == '':
            return "Pass in a trip key like this:  /expense<u>$tripkey</u>"

        trip = Trip.get(trip_key)

        return self._expenseScaffoldInternal(trip)
Esempio n. 11
0
def insert_trips(file_name):
    line_num = 0
    pick_up = True
    with open(file_name, 'r') as csv_file:
        reader = csv.reader(csv_file, delimiter=',')
        for row in reader:
            line_num += 1
            # Skip header
            if line_num == 1:
                print("Header row, skipping")
                continue

            if pick_up:
                pick_up = False
                date_object = datetime.strptime(row[0], '%m/%d/%Y %H:%M:%S')
                pickup_lat = float(row[1])
                pickup_lng = float(row[2])
                pickup_location = str(pickup_lat) + ',' + str(pickup_lng)
            else:
                pick_up = True
                drop_off_lat = float(row[1])
                drop_off_lng = float(row[2])
                drop_off_location = str(drop_off_lat) + ',' + str(drop_off_lng)

                # This statement will insert a single row into the table called trips
                db.session.add(Trip(date_object, pickup_lat, pickup_lng, drop_off_lat, drop_off_lng, pickup_location, drop_off_location))
                db.session.commit()
        print("Done iterating over file contents - the file has been closed now!")
Esempio n. 12
0
    def on_post(self, req, resp):
        print('POST!!!!!!!!!!!!!!!!!!')
        data = req.json
        if not self._is_valid_request_payload(data):
            raise falcon.HTTPBadRequest()

        try:
            origin = self._get_location(Origin, data['origin'])
            req.db.save(origin)
        except KeyError:
            raise falcon.HTTPBadRequest('Invalid origin payload')

        try:
            destination = self._get_location(Destination, data['destination'])
            req.db.save(destination)
        except KeyError:
            raise falcon.HTTPBadRequest('Invalid destination payload')

        trip = Trip(drive_or_ride=data['driveOrRide'],
                    origin=origin,
                    destination=destination,
                    user=req.current_user,
                    time=parser.parse(data['time'])
                    )  # data['time'] example: 2016-10-19T20:17:52.2891902Z
        req.db.save(trip)

        resp.json = self._get_serialize_trip(trip)
        resp.status = falcon.HTTP_CREATED
Esempio n. 13
0
def add():
    form = TripForm()
    if form.validate_on_submit():
        url = form.url.data
        description = form.description.data
        destination = form.destination.data
        outbound_date = form.outbound_date.data
        outbound_time = form.outbound_time.data
        inbound_date = form.inbound_date.data
        inbound_time = form.inbound_time.data
        tags = form.tags.data
        bm = Trip(user=current_user,
                  url=url,
                  description=description,
                  destination=destination,
                  tags=tags,
                  outbound_date=outbound_date,
                  outbound_time=outbound_time,
                  inbound_date=inbound_date,
                  inbound_time=inbound_time)
        db.session.add(bm)
        db.session.commit()
        flash("Stored trip '{}'".format(description))
        return redirect(url_for('index'))
    return render_template('trip_form.html', form=form, title="Add a Trip")
Esempio n. 14
0
    def get(self, trip_key, expense_key):

        errors = []
        output = ""
        user = users.get_current_user()
        authz = Authz(user)
        self.response.headers["Content-type"] = "application/json"

        # first, verify they have access to the trip
        try:
            # get the trip
            trip = Trip.get(trip_key)

            # verify the user is authorized to read the trip
            authz.readTrip(trip)

        except PermissionError:
            errors.append(
                {"message": "You are not authorized to view that trip"})
        except db.BadKeyError:
            errors.append({"message": "Invalid trip key"})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error loading trip"})

        # if errors encountered so far, bail
        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})
            self.response.out.write(output)
            return

        # this is a read of an existing expense
        # instead of directly authorizing the read of an expense, we
        # ensure that the expense is tied to the specified trip
        try:
            # get the expense
            expense = Expense.get(expense_key)

            # ensure the expense belongs to the trip
            if expense.parent_key() != trip.key():
                raise PermissionError("Expense is not tied to that trip")

            # format expense data
            output = GqlEncoder().encode(expense)

        except db.BadKeyError:
            errors.append({"message": "Invalid expense key"})
        except PermissionError as e:
            errors.append({"message": e.args})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error loading expense"})

        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})

        self.response.out.write(output)
Esempio n. 15
0
    def get(self, trip_key, expense_key):

        errors = []
        output = ""
        user = users.get_current_user()
        authz = Authz(user)
        self.response.headers["Content-type"] = "application/json"

        # first, verify they have access to the trip
        try:
            # get the trip
            trip = Trip.get(trip_key)

            # verify the user is authorized to read the trip
            authz.readTrip(trip)

        except PermissionError:
            errors.append({"message": "You are not authorized to view that trip"})
        except db.BadKeyError:
            errors.append({"message": "Invalid trip key"})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error loading trip"})

        # if errors encountered so far, bail
        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})
            self.response.out.write(output)
            return

        # this is a read of an existing expense
        # instead of directly authorizing the read of an expense, we
        # ensure that the expense is tied to the specified trip
        try:
            # get the expense
            expense = Expense.get(expense_key)

            # ensure the expense belongs to the trip
            if expense.parent_key() != trip.key():
                raise PermissionError("Expense is not tied to that trip")

            # format expense data
            output = GqlEncoder().encode(expense)

        except db.BadKeyError:
            errors.append({"message": "Invalid expense key"})
        except PermissionError as e:
            errors.append({"message": e.args})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error loading expense"})

        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})

        self.response.out.write(output)
Esempio n. 16
0
    def create_trip(jwt):
        body = request.get_json()
        name = body.get('name', None)
        start_date = body.get('start_date', None)
        end_date = body.get('end_date', None)

        if (name is None or name == ''):
            abort(400)

        try:
            new_trip = Trip(name=name,
                            start_date=start_date,
                            end_date=end_date)
            new_trip.insert()

            return jsonify({'success': True, 'trip_id': new_trip.id})
        except:
            abort(422)
Esempio n. 17
0
def insert_trip(trip_id, route_id, service_id, shape_id):
    """
    insert a new trip
    :param trip_id: str, id of trip
    :param route_id: str, id of route
    :param service_id: str, id of service,
    :param shape_id: str, id of shape
    :return:
    """
    route = Route.objects.get(route_id=route_id)
    service = Calender.objects.get(service_id=service_id)
    shape = Shape.objects.get(shape_id=shape_id)

    d = Trip(trip_id=trip_id,
             route_id=route,
             service_id=service,
             shape_id=shape)
    d.save()
Esempio n. 18
0
def make_test_trip():
    from models import Trip
    import datetime
    trip = Trip()
    trip.start_location = "Here"
    trip.end_location = "There"

    trip.start_datetime = datetime.datetime.now()
    trip.end_datetime = datetime.datetime.now()

    trip.save()
Esempio n. 19
0
 def get(self):
     
     user,id,url,url_linktext = self.get_user()
     
     #parameter mytrips = True if only users trips should be shown  
     mytrips = self.request.get('mytrips')
     
     if mytrips == 'True':
         trips_query = Trip.query(ancestor=helper.trip_key(id)).order(-Trip.creation_date)
     else:
         trips_query = Trip.query(Trip.visibility==True).order(-Trip.creation_date)
           
     trips, next_curs, more = trips_query.fetch_page(PAGE_SIZE)
     
     #return index page
     template_values = {'user': user, 'url': url, 'url_linktext': url_linktext,'trips':trips,'cursor':next_curs,
                        'more':more,'mytrips':mytrips}
     template = JINJA_ENVIRONMENT.get_template('templates/new/alltrips.html')
     self.response.write(template.render(template_values))
Esempio n. 20
0
 def get(self, stop_id):
     stop_id = unicode(unquote(stop_id))
     stop = Stop.get_by_key_name(stop_id)
     if stop:
         trips = Trip.all().filter('stops =', stop_id).fetch(1000)
         prefetch_refprop(trips, Trip.route)
         template_values = {'stop': stop, 'trips': trips}
         path = os.path.join(os.path.dirname(__file__), 'templates/stop_details.html')
         self.response.out.write(template.render(path, template_values))
     else:
         self.error(404)
         return self.response.out.write('Erro - Pagina nao encontrada')
Esempio n. 21
0
 def setUp(self):
     """Create test client, add sample data."""
     Trip.query.delete()
     User.query.delete()
     
     test_user = User(
         username = "******",
         password = "******",
         email = "*****@*****.**"
     )
     test_member_user = User(
         username= "******",
         password = "******",
         email= "*****@*****.**",
         member_status = True
     )
     db.session.add(test_user)
     db.session.add(test_member_user)
     db.session.commit()
     self.u1 = test_user
     self.id = test_user.id
     self.mu1 = test_member_user
     self.muID = test_member_user.id
     
     test_trip = Trip.encrypt_and_store_trip_data(
         start_point = "Main",
         end_point = "New York City",
         waypoint_names = ["Best Ice Cream","bobs burgers"],
         waypoint_latlng = ["(34.5,-86.34)","(45.54,-65.65)"],
         photo="/static/images/default_trip.jpg",
         user_id=self.id
     )
     db.session.add(test_trip)
     db.session.commit()
     
     self.client = app.test_client()
     
     
     self.coordinates_list = [[42.9634,-85.6681],[41.7075,-86.8950],[41.8781,-87.6298]]
     self.waypoints = ["State Park","Ice Cream"]
     self.initial_coord = (42.9634,-85.6681)
     self.last_coord = (41.8781,-87.6298)
     # long copy and pasted google data result to use 
     self.nearby_places_data = [{'business_status': 'OPERATIONAL', 'geometry': {'location': {'lat': 42.9544878, 'lng': -85.4886045}, 'viewport': {'northeast': {'lat': 42.95579032989272, 'lng': -85.48719497010727}, 'southwest': {'lat': 42.95309067010728, 'lng': -85.48989462989272}}}, 'icon': 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/shopping-71.png', 'name': "Scooper's Ice Cream Shoppe", 'opening_hours': {'open_now': True}, 'photos': [{'height': 3456, 'html_attributions': ['<a href="https://maps.google.com/maps/contrib/116817238352139987816">Tim Krueger</a>'], 'photo_reference': 'ATtYBwL-fZR1dojdwfvscLmrr8CapQGd5YBadZ2VYJNLxwc9G1ZrnQPIAW0uFI2MwMjFAAmqSHwwqmBb_vHEdtqn4Sqh2SCNlgdO6Tuk9bFnrNv4geg8imeGnXa1gSMtgiYDMov6DgpY7FScUSWa8uABQ8AraTji9rRk-vYpHuva7hlieB6K', 'width': 4608}], 'place_id': 'ChIJc265W7dRGIgRyZ5tMyesmSY', 'plus_code': {'compound_code': 'XG36+QH Ada, Michigan', 'global_code': '86JPXG36+QH'}, 'price_level': 1, 'rating': 5.0, 'reference': 'ChIJc265W7dRGIgRyZ5tMyesmSY', 'scope': 'GOOGLE', 'types': ['food', 'point_of_interest', 'store', 'establishment'], 'user_ratings_total': 105, 'vicinity': '591 Ada Dr SE, Ada'}, {'business_status': 'OPERATIONAL', 'geometry': {'location': {'lat': 42.8811019, 'lng': -85.60817779999999}, 'viewport': {'northeast': {'lat': 42.88252922989272, 'lng': -85.60671752010727}, 'southwest': {'lat': 42.87982957010728, 'lng': -85.60941717989272}}}, 'icon': 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/shopping-71.png', 'name': 'Iorio Gelato @ Horrocks Market', 'opening_hours': {'open_now': True}, 'place_id': 'ChIJI04erkKzGYgRReFWhsoV-CY', 'plus_code': {'compound_code': 'V9JR+CP Grand Rapids, Michigan', 'global_code': '86JPV9JR+CP'}, 'rating': 4.3, 'reference': 'ChIJI04erkKzGYgRReFWhsoV-CY', 'scope': 'GOOGLE', 'types': ['food', 'point_of_interest', 'store', 'establishment'], 'user_ratings_total': 3, 'vicinity': '4455 Breton Rd SE, Grand Rapids'}, {'business_status': 'OPERATIONAL', 'geometry': {'location': {'lat': 42.8685091, 'lng': -85.57026839999999}, 'viewport': {'northeast': {'lat': 42.86986267989272, 'lng': -85.56900882010727}, 'southwest': {'lat': 42.86716302010728, 'lng': -85.57170847989272}}}, 'icon': 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', 'name': "PJ's Pizza, Coffee & Ice Cream", 'opening_hours': {'open_now': False}, 'photos': [{'height': 1000, 'html_attributions': ['<a href="https://maps.google.com/maps/contrib/111286923329484073408">PJ&#39;s Pizza</a>'], 'photo_reference': 'ATtYBwIISgVfNrt3kb_QZJS47q9qaxCTfUoOVvn0hLqQZxfWYFM3gpE-wEd9aOMoF4NS_ygHC637GxNXy57z9FzE0_J3cPECthmeQlXRzv3aJi0dKgzlnEomSiPSdc1SucUMDjFqxvzFK4i_0U_IbE9Odpj4Ec3VoI-kX_QKxtohZNIx3Pnw', 'width': 1500}], 'place_id': 'ChIJsfQiOI5MGIgRFaTfrruXCYs', 'plus_code': {'compound_code': 'VC9H+CV Kentwood, Michigan', 'global_code': '86JPVC9H+CV'}, 'price_level': 1, 'rating': 4.4, 'reference': 'ChIJsfQiOI5MGIgRFaTfrruXCYs', 'scope': 'GOOGLE', 'types': ['meal_delivery', 'meal_takeaway', 'cafe', 'restaurant', 'food', 'point_of_interest', 'store', 'establishment'], 'user_ratings_total': 186, 'vicinity': '3836 52nd St SE, Kentwood'}]
     
     self.CURR_USER_KEY = "curr_user"
     self.MEMBER_STATUS = "member_status"
     self.Token = "secret"
     self.CSRF_HEADER = "anti-csrf-token"
     self.headers = {
             self.CSRF_HEADER:self.Token
         }
Esempio n. 22
0
 def get(self, trip_id, trip_headsign):
     trip_id = unquote(trip_id)
     trip = Trip.get_by_key_name('trip_' + trip_id)
     if trip:
         path = os.path.join(os.path.dirname(__file__), 'templates/trip.kml')
         template_values = {
             'trip': trip,
         }
         self.response.headers['Content-Type'] = 'application/vnd.google-earth.kml+xml'
         self.response.out.write(template.render(path, template_values))
     else:
         self.error(404)
         return self.response.out.write('Erro - Pagina nao encontrada')
Esempio n. 23
0
 def trip_list(self, request):
     trips = []
     p = 10
     if request.page:
         p = request.page
     
     if request.name:
         
         trip_query = Trip.query(Trip.trip_name==request.name)
     else:
         trip_query = Trip.query()
 
     for trip in trip_query.fetch(p):
         t = TripMes(trip_name=trip.trip_name)
         if trip.trip_avatar:
             t.trip_avatar = 'http://localhost:8080/img?img_id=' + trip.key.urlsafe()
         t.description = trip.description
         t.cities = trip.cities
         if request.stat == True:
             t.trip_statistic = StatisticMes(total_time=request.name)
         trips.append(t)
     return TripCollection(items=trips)
Esempio n. 24
0
def createNewTrip(user_id):
    if request.method == 'POST':
        phone_no = request.json.get('phone_no')
        traveling_from_state = request.json.get('traveling_from_state')
        traveling_from_city = request.json.get('traveling_from_city')
        traveling_to_state = request.json.get('traveling_to_state')
        traveling_to_city = request.json.get('traveling_to_city')
        traveling_date = request.json.get('traveling_date')
        posted_on = request.json.get('posted_on')
        time_updated = request.json.get('time_updated')
        user = session.query(User).filter_by(id=user_id).first()
        profile_image = user.picture
        user_first_name = user.first_name
        user_last_name = user.last_name
        user_id = user_id
        newTrip = Trip(phone_no=phone_no,
                       traveling_from_state=traveling_from_state,
                       traveling_from_city=traveling_from_city,
                       traveling_to_state=traveling_to_state,
                       traveling_to_city=traveling_to_city,
                       traveling_date=traveling_date,
                       posted_on=posted_on,
                       time_updated=time_updated,
                       profile_image=profile_image,
                       user_id=user_id,
                       user_first_name=user_first_name,
                       user_last_name=user_last_name)
        session.add(newTrip)
        session.commit()
        trip_payload = {}
        trip_payload['profile_image'] = user.picture
        trip_payload['id'] = newTrip.id
        trip_payload['phone_no'] = phone_no
        trip_payload['traveling_from_state'] = traveling_from_state
        trip_payload['traveling_from_city'] = traveling_to_city
        trip_payload['traveling_to_state'] = traveling_to_state
        trip_payload['traveling_to_city'] = traveling_to_city
        trip_payload['traveling_date'] = traveling_date
        trip_payload['posted_on'] = posted_on
        trip_payload['time_updated'] = time_updated
        trip_payload['user_id'] = user_id
        trip_payload['user_first_name'] = user_first_name
        trip_payload['user_last_name'] = user.last_name
        raw = {"data": trip_payload}

        trip_data = json.dumps(raw)
        #result = push_service.notify_single_device(registration_id = reg_id, data_message= payload)
        result = push_service.notify_topic_subscribers(
            topic_name=TRIP_TOPIC, data_message=trip_payload)
        pprint(result)
        return trip_data
Esempio n. 25
0
    def deleteTrip(self, trip):
        """Determines whether the user is allowed to delete a particular trip
        
        trip can be a trip key or a trip object"""
        if isinstance(trip, Trip):
            pass
        else:
            trip = Trip.get(trip)

        # logic determining whether the user can delete the trip
        if self.user == trip.owner:
            return

        raise PermissionError('User not allowed to delete this trip')
Esempio n. 26
0
 def deleteTrip(self, trip):
     """Determines whether the user is allowed to delete a particular trip
     
     trip can be a trip key or a trip object"""
     if isinstance(trip, Trip):
         pass
     else:
         trip = Trip.get(trip)
     
     # logic determining whether the user can delete the trip
     if self.user == trip.owner:
         return
     
     raise PermissionError('User not allowed to delete this trip')
Esempio n. 27
0
    def get(self, trip_key):

        errors = []
        output = ""
        user = users.get_current_user()
        authz = Authz(user)
        self.response.headers["Content-type"] = "application/json"

        # verify access to the trip
        try:
            # get the trip
            trip = Trip.get(trip_key)

            # verify the user is authorized to read the trip
            authz.readTrip(trip)

        except PermissionError:
            errors.append(
                {"message": "You are not authorized to view that trip"})
        except db.BadKeyError:
            errors.append({"message": "Invalid trip key"})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error loading trip"})

        # if errors encountered so far, bail
        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})
            self.response.out.write(output)
            return

        # next, get the list of expenses
        try:
            expenses = Expense.all()
            expenses.ancestor(trip)
            output = GqlEncoder().encode(expenses.fetch(limit=200))
        except db.BadKeyError:
            errors.append({"message": "Invalid trip key"})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error listing expenses"})

        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"errors": errors})

        self.response.headers["Content-type"] = "application/json"
        self.response.out.write(output)
Esempio n. 28
0
    def listTrips(self):
        """Give back a list of trips the user can read"""
        # pull 10 of the user's own trips
        my_trips_query = Trip.all()
        my_trips_query.filter('owner = ', self.user)
        my_trips = my_trips_query.fetch(limit=10)

        # pull 10 more trips the user can read
        tripaccess_query = TripAccess.all()
        tripaccess_query.filter('user = ', self.user)
        tripaccess = tripaccess_query.fetch(limit=10)
        for access in tripaccess:
            my_trips.append(access.trip)

        return my_trips
Esempio n. 29
0
def add_trip_form():
    if not current_user.is_authenticated:
        return redirect('/trips')
    if request.method == 'POST':
        name = request.form.get('name')
        photo_url = request.form.get('photo_url')
        published = request.form.get('published')
        try:
            trip = Trip(name=name, photo_url=photo_url, published=published)
            db.session.add(trip)
            db.session.commit()
            return "Trip added. trip id={}".format(trip.id)
        except Exception as e:
            return (str(e))
    return render_template("trips/new.html")
Esempio n. 30
0
 def listTrips(self):
     """Give back a list of trips the user can read"""
     # pull 10 of the user's own trips
     my_trips_query = Trip.all()
     my_trips_query.filter('owner = ', self.user)        
     my_trips = my_trips_query.fetch(limit=10)
     
     # pull 10 more trips the user can read
     tripaccess_query = TripAccess.all()
     tripaccess_query.filter('user = ', self.user)
     tripaccess = tripaccess_query.fetch(limit=10)
     for access in tripaccess:
         my_trips.append(access.trip)
     
     return my_trips
Esempio n. 31
0
    def handle_post(self, email):
        if self.request.get("trip_entity_key"):
            trip_key = ndb.Key(urlsafe=self.request.get("trip_entity_key"))
            trip = trip_key.get()
        else:
            trip = Trip(parent=utils.get_parent_key_for_email(email))
        
        trip.state = self.request.get("state")
        trip.city = self.request.get("city")
        trip.start_date = self.request.get("arrival-date")
        trip.end_date = self.request.get("departure-date")
        trip.description = self.request.get("description")
        # last touch modified time update? or nah?
        
        # image
        if self.get_uploads() and len(self.get_uploads()) == 1:
            logging.info("Received an image blob with this trip.")
            media_blob = self.get_uploads()[0]
            trip.media_blob_key = media_blob.key()
        else:
            logging.info("This is a trip without an image attachment.")

        trip.put()
        self.redirect(self.request.referer)
Esempio n. 32
0
    def get(self, trip_key):

        errors = []
        output = ""
        user = users.get_current_user()
        authz = Authz(user)
        self.response.headers["Content-type"] = "application/json"

        # verify access to the trip
        try:
            # get the trip
            trip = Trip.get(trip_key)

            # verify the user is authorized to read the trip
            authz.readTrip(trip)

        except PermissionError:
            errors.append({"message": "You are not authorized to view that trip"})
        except db.BadKeyError:
            errors.append({"message": "Invalid trip key"})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error loading trip"})

        # if errors encountered so far, bail
        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})
            self.response.out.write(output)
            return

        # next, get the list of expenses
        try:
            expenses = Expense.all()
            expenses.ancestor(trip)
            output = GqlEncoder().encode(expenses.fetch(limit=200))
        except db.BadKeyError:
            errors.append({"message": "Invalid trip key"})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error listing expenses"})

        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"errors": errors})

        self.response.headers["Content-type"] = "application/json"
        self.response.out.write(output)
Esempio n. 33
0
    def delete(self, trip_key):

        errors = []
        output = ""
        user = users.get_current_user()
        authz = Authz(user)
        self.response.headers["Content-type"] = "application/json"

        try:
            # get the trip
            trip = Trip.get(trip_key)

            # verify the user is authorized to delete the trip
            authz.deleteTrip(trip)

            # delete related expenses
            try:
                expenses = Expense.all()
                expenses.ancestor(trip)
                expenses.fetch(limit=200)
                db.delete(expenses)
            except Exception as e:
                logging.exception(e)
                errors.append({
                    "message":
                    "Unexpected error deleting associated expenses"
                })

            # delete the trip
            trip.delete()

        except db.BadKeyError:
            errors.append({"message": "Invalid trip key"})
        except PermissionError:
            errors.append(
                {"message": "You are not authorized to delete that trip"})
        except db.NotSavedError:
            errors.append({"message": "Unable to delete trip"})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error deleting trip"})

        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})

        self.response.out.write(output)
Esempio n. 34
0
    def delete(self, trip_key):

        errors = []
        output = ""
        user = users.get_current_user()
        authz = Authz(user)
        self.response.headers["Content-type"] = "application/json"

        try:
            # get the trip
            trip = Trip.get(trip_key)

            # verify the user is authorized to delete the trip
            authz.deleteTrip(trip)

            # delete related expenses
            try:
                expenses = Expense.all()
                expenses.ancestor(trip)
                expenses.fetch(limit=200)
                db.delete(expenses)
            except Exception as e:
                logging.exception(e)
                errors.append({"message": "Unexpected error deleting associated expenses"})

            # delete the trip
            trip.delete()

        except db.BadKeyError:
            errors.append({"message": "Invalid trip key"})
        except PermissionError:
            errors.append({"message": "You are not authorized to delete that trip"})
        except db.NotSavedError:
            errors.append({"message": "Unable to delete trip"})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error deleting trip"})

        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})

        self.response.out.write(output)
Esempio n. 35
0
 def post(self):
     
     trips_query = Trip.query(Trip.visibility==True).order(-Trip.creation_date)
            
     #get cursor to fetch only new trips
     curs = Cursor(urlsafe=self.request.get('cursor'))
     trips, next_curs, more = trips_query.fetch_page(PAGE_SIZE, start_cursor=curs)
     tripsstats = {}
     #get all statistics
     for trip in trips:
         stat_query = TrackStatistic.query(ancestor=trip.key).fetch(1)
         tripsstats[trip.key]=stat_query
     data = self.create_trip_html(trips,tripsstats)
     # Create an array
     array = {'trips': data,'next_curs':next_curs.urlsafe(),'more':more}
    
     # Output the JSON
     self.response.headers['Content-Type'] = 'application/json'
     self.response.out.write(json.dumps(array))
Esempio n. 36
0
    def updateTrip(self, trip):
        """Determines whether the user is allowed to update a particular trip
        
        trip can be a trip key or a trip object"""
        if isinstance(trip, Trip):
            pass
        else:
            trip = Trip.get(trip)

        # logic determining whether the user can update the trip
        # if the user is the owner, OK
        if self.user == trip.owner:
            return
        # if there is a TripAccess object, OK
        tripaccess_query = TripAccess.all()
        tripaccess_query.filter('user = '******'trip = ', trip)
        tripaccess = tripaccess_query.fetch(limit=10)
        if len(tripaccess) > 0:
            return

        raise PermissionError('User not allowed to update this trip')
Esempio n. 37
0
    def get(self, trip_id):
        "Returns encoded polyline path from trip_id"

        trip_id = unquote(trip_id)
        trip = Trip.get_by_key_name('trip_' + trip_id)
        stops = Stop.get_by_key_name(trip.stops)
        stops = filter(lambda s: s is not None, stops)
        stops = filter(lambda s: s.location is not None, stops)
        def serializable_stop(stop):
            return (stop.id,
                    stop.location.lat,
                    stop.location.lon,
                    stop.name)

        stop_locations = [serializable_stop(stop) for stop in stops]

        if trip:
            data = {'points': trip.shape_encoded_polyline,
                    'levels': trip.shape_encoded_levels,
                    'color': trip.route.color,
                    'stops': stop_locations}
            self.response.out.write(simplejson.dumps(data))
Esempio n. 38
0
    def deleteExpense(self, expense):
        """Determines whether the user is allowed to delete an expense"""
        if isinstance(expense, Expense):
            pass
        else:
            expense = Expense.get(expense)
        
        # determine if the user owns the related trip
        try:
            trip = Trip.get(expense.parent_key())
        except db.BadKeyError:
            raise PermissionError('User cannot delete this expense because the trip could not be loaded')
        
        # if yes, they are allowed to delete the expense
        if self.user == trip.owner:
            return
        
        # if they own the expense itself, then they can delete it
        if self.user == expense.creator:
            return

        raise PermissionError('User cannot delete this expense')
Esempio n. 39
0
 def updateTrip(self, trip):
     """Determines whether the user is allowed to update a particular trip
     
     trip can be a trip key or a trip object"""
     if isinstance(trip, Trip):
         pass
     else:
         trip = Trip.get(trip)
     
     # logic determining whether the user can update the trip
     # if the user is the owner, OK
     if self.user == trip.owner:
         return
     # if there is a TripAccess object, OK
     tripaccess_query = TripAccess.all()
     tripaccess_query.filter('user = '******'trip = ', trip)
     tripaccess = tripaccess_query.fetch(limit=10)
     if len(tripaccess) > 0:
         return
     
     raise PermissionError('User not allowed to update this trip')
Esempio n. 40
0
    def store_trip(from_bldg, to_bldg, method, time, timestamp):
        # convert time to int
        time = int(time)
        # validate all input
        if (not validate_building(from_bldg) or not validate_building(to_bldg)
                or not validate_method(method)):
            return ("Your input is invalid! Please try again.", 400)
        if (time < 1):
            return (
                "Your time seems really short... Have you started the timer?",
                400)

        trip = Trip(from_building=from_bldg,
                    to_building=to_bldg,
                    method=method,
                    time=time,
                    timestamp=timestamp)
        DBSession.add(trip)
        DBSession.commit()
        DBSession.close()

        return ("Thank you! Your trip has been recorded.", 201)
Esempio n. 41
0
    def get(self, route_id=None, description=None):
        route = Route.get_by_key_name(unquote(route_id))
        if route:
            trips = route.trip_set.fetch(1000)
            trip_id = self.request.get('trip') or trips[0].id

            trip = None
            for trip_loop in trips:
                if trip_loop.id == trip_id:
                    trip = trip_loop
                    break

            if trip is None:
                trip = trips[0]

            similars = Trip.get_by_key_name(trip.similars)

            template_values = {'route': route,
                               'trip': trip,
                               'trips': trips,
                               'similars': similars }
            path = os.path.join(os.path.dirname(__file__), 'templates/route.html')
            self.response.out.write(template.render(path, template_values))
        else:
            #Old urls used trip id. If this is the case, redirect
            trip_id = route_id
            trip = Trips.all().filter("trip_id =", unquote(trip_id)).get()

            if trip:
                route = Route.get_by_key_name(trip.route_id)
                if route:
                    self.redirect(route.get_absolute_url(), permanent=True)
                    return

            #Not found
            self.error(404)
            self.response.out.write('404 - Pagina nao encontrada')
Esempio n. 42
0
def edit(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)

    rec = None
    if id > 0:
        rec = Trip.query.get(id)
        if not rec:
            flash(
                printException(
                    "Could not edit that " + g.title + " record. ID=" +
                    str(id) + ")", 'error'))
            return redirect(g.listURL)

    form = TripForm(request.form, rec)
    ## choices need to be assigned before rendering the form
    # AND before attempting to validate it
    form.countEvent_ID.choices = getCountEventChoices()
    form.location_ID.choices = getLocationChoices()
    form.traveler_ID.choices = getTravelerChoices()
    form.turnDirection.choices = getTurnDirectionChoices()

    if request.method == 'POST' and form.validate():
        if not rec:
            rec = Trip(form.tripCount.data, form.tripDate.data,
                       form.turnDirection.data, form.seqNo.data,
                       form.location_ID.data, form.traveler_ID.data,
                       form.countEvent_ID.data)
            db.session.add(rec)
        form.populate_obj(rec)
        db.session.commit()
        return redirect(g.listURL)

    return render_template('genericEditForm.html', rec=rec, form=form)
Esempio n. 43
0
    def get(self):
        if not WhiteTokenModel.is_jti_whitelisted(get_raw_jwt()["jti"]):
            return {'message': 'Not logged in'}, 205

        try:
            current_user = get_jwt_identity()

            friends = Friends.find_by_uid(current_user)
            if len(friends) == 0:
                return {"message": "You have no friends"}, 204

            trips = []

            for friend in friends:
                if friend.friend_status == "accepted":
                    friendUser = User.find_by_uid(friend.friend_id)
                    friendsTrips = Trip.find_all_trips(friend.friend_id)

                    for trip in friendsTrips:
                        tripObject = {
                            "tripid": trip.trip_id,
                            "username": friendUser.user_name,
                            "tripjson": trip.trip_json
                        }
                        trips.append(tripObject)

            return {
                "message": "Your friends' trips were found",
                "trips": trips
            }, 200

        except Exception as error:
            return {
                "message": "Something went wrong on the server",
                "error": error
            }, 500
Esempio n. 44
0
    def deleteExpense(self, expense):
        """Determines whether the user is allowed to delete an expense"""
        if isinstance(expense, Expense):
            pass
        else:
            expense = Expense.get(expense)

        # determine if the user owns the related trip
        try:
            trip = Trip.get(expense.parent_key())
        except db.BadKeyError:
            raise PermissionError(
                'User cannot delete this expense because the trip could not be loaded'
            )

        # if yes, they are allowed to delete the expense
        if self.user == trip.owner:
            return

        # if they own the expense itself, then they can delete it
        if self.user == expense.creator:
            return

        raise PermissionError('User cannot delete this expense')
Esempio n. 45
0
    def post(self):
        if not WhiteTokenModel.is_jti_whitelisted(get_raw_jwt()["jti"]):
            return {'message': 'Not logged in'}, 205

        data = post_trip_parser.parse_args()
        print("Test print", flush=True)
        try:
            existing_trip = Trip.does_trip_exist(data["trip"])
            if (existing_trip["exists"]):
                return {"message": "The trip already exist"}, 200

            current_user = get_jwt_identity()
            if (not data["public"]):
                public = True
            else:
                public = bool(data["public"])

            if not data["trip"]:
                return {'message': 'You need to provide a trip'}
            else:
                #TODO: Improve this \/
                tid = random.randint(10000000, 99999999)
                while Trip.find_by_tid(tid):
                    if tid >= 99999999:
                        tid = 10000000
                    else:
                        tid += 1

                new_trip = Trip(trip_id=tid,
                                user_id=current_user,
                                trip_json=data["trip"],
                                is_public=public)
                new_trip.save_to_db()
                return {
                    "message": "The trips was uploaded successfully",
                    "tripid": tid
                }, 201
        except Exception as err:
            return {"message": str(err)}, 500
Esempio n. 46
0
 def get(self):
     trips = Trip.objects()
     return TripSchema().dump(trips, many=True)
Esempio n. 47
0
 def post(self):
     '''
     Adds trip to datastore
     '''
     
     _,id,_,_ = self.get_user()
     
     #TODO some checking      
     trip = Trip(parent=helper.trip_key(id))
     trip.trip_name = self.request.get('trip_name')
     
     trip.description = self.request.get('description')
     trip.cities =  self.get_cities(self.request.get('cities'))
     avatar = self.request.get('img')
     if  avatar:
         trip.trip_avatar = avatar
     
     
     try:
         trip.from_date = datetime.strptime( self.request.get('from_date'), '%d/%m/%Y')  
         trip.to_date = datetime.strptime(self.request.get('to_date'), '%d/%m/%Y')
     except:
         try:
             trip.from_date = datetime.strptime( self.request.get('from_date'), '%Y-%m-%d')  
             trip.to_date = datetime.strptime(self.request.get('to_date'), '%Y-%m-%d')
         except:
             trip.from_date = datetime.strptime( '2000-01-01', '%Y-%m-%d')  
             trip.to_date = datetime.strptime('2000-01-01', '%Y-%m-%d')
     
     if self.request.get('visibility') == 'True':
         trip.visibility = True
     else:
         trip.visibility = False
     
     #create statistic for trip 
     trip.trip_statistic = TrackStatistic(name="Trip Stat",total_distance=0,total_time="",
                                          avr_speed=0,total_climb=0,max_elev=-100)
     
     #crete tags for trip
     locationl = helper.creatList(self.request.get('location'))
     typel = helper.creatList(self.request.get('type'))
     seasonl = helper.creatList(self.request.get('season'))
     trip.trip_tags = Tags(location=locationl,type=typel,season=seasonl)
     
     trip.put()
            
     #put new tags in users tags
     tags_query = Tags.query(ancestor=helper.trip_key(id))
     tags = tags_query.fetch(1)
     if tags:
         tags = tags[0]
         tags.location = helper.union(tags.location,locationl)
         tags.type = helper.union(tags.type,typel)
         tags.season = helper.union(tags.season,seasonl)
                   
     else:
         new_loc_tags = locationl
         new_type_tags = typel
         new_seasion_tags = seasonl
         tags = Tags(parent=helper.trip_key(id),location=new_loc_tags,type=new_type_tags,season=new_seasion_tags)
     
     tags.put()
     
     #redirect to mytrips because showing all tips will only be consistent in scope of user
     # and only eventually consistent for whole datastore  
     self.redirect('/tripmanager')
Esempio n. 48
0
    def put(self, trip_key):

        errors = []
        output = ""
        user = users.get_current_user()
        authz = Authz(user)
        self.response.headers["Content-type"] = "application/json"

        try:
            # get the trip
            trip = Trip.get(trip_key)

            # verify the user is authorized to update the trip
            authz.updateTrip(trip)

        except db.BadKeyError:
            errors.append({"message": "Invalid trip key"})
        except PermissionError:
            errors.append({"message": "You are not authorized to view that trip"})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error loading trip"})

        # bail if we hit authz errors
        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})
            self.response.out.write(output)
            return

        # now that we know the user is authorized, perform the update
        logging.debug(self.request.body)
        try:
            data = TripUnpacker().unpack_put(self.request)
            logging.debug(data)

            properties = ("name", "password", "start_date", "end_date", "travelers")
            for prop in properties:
                if prop in data:
                    # TODO: validate the data (for instance, dates will almost
                    #       certainly fail without some scrubbing)
                    scrubbed = self._scrub(prop, data[prop])
                    setattr(trip, prop, scrubbed)

            trip.put()

            # per the Backbone documentation, this method needs to:
            #   "[w]hen returning a JSON response, send down the attributes of
            #   the model that have been changed by the server, and need to be
            #   updated on the client"
            # Dates need to be shown because their formatting can change
            output = GqlEncoder().encode(
                {"modify_date": trip.modify_date, "start_date": trip.start_date, "end_date": trip.end_date}
            )

        except NotImplementedError as e:
            errors.append({"message": e.args})
        except db.BadValueError as e:
            errors.append({"message": e.args})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error updating trip"})

        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})

        self.response.out.write(output)
Esempio n. 49
0
def index():
    return render_template('index.html', new_trips=Trip.newest(5))
Esempio n. 50
0
    def post(self, trip_key):
        errors = []
        output = ""
        user = users.get_current_user()
        authz = Authz(user)
        self.response.headers["Content-type"] = "application/json"

        # check for authorization to create expenses for this trip & verify this
        # is in fact a request to create a new expense
        try:
            # get the trip
            trip = Trip.get(trip_key)

            # verify the user is authorized to create an expense on this trip
            authz.createExpense(trip)

        except PermissionError as e:
            # this permission error could have come from authz or locally
            errors.append({"message": e.args})
        except db.BadKeyError:
            errors.append({"message": "Invalid trip key"})
        except Exception as e:
            logging.exception(e)
            errors.append({"message": "Unexpected error loading trip"})

        # bail if we hit authz errors
        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})
            self.response.out.write(output)
            return

        # having passed authz, let's try creating the expense
        data = ExpenseUnpacker().unpack_post(self.request)

        if data["description"] == "" or data["value"] == "" or data["payer"] == "":
            errors.append({"message": "Description, value, and payer are required."})
        elif len(data["travelers"]) == 0:
            errors.append({"message": "At least one person must be specified as a traveler."})
        else:
            try:
                expense = Expense(
                    parent=trip.key(),
                    creator=user,
                    description=data["description"],
                    value=int(data["value"]),
                    currency="USD",
                )

                # get the expense date
                expense_date = dateparse(data["expense_date"])
                expense.expense_date = expense_date.date()

                # TODO: make sure these travelers are actually on the trip
                expense.travelers = data["travelers"]

                # TODO: ensure the payer is actually a traveler
                expense.payer = data["payer"]

                expense.put()

                output = GqlEncoder().encode(
                    {
                        "id": "%s" % expense.key(),
                        "modify_date": expense.modify_date,
                        "expense_date": expense.expense_date,
                        "value": expense.value,
                    }
                )
            except Exception as e:
                logging.exception(e)
                errors.append({"message": "Unexpected error creating expense"})

        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})

        self.response.out.write(output)
Esempio n. 51
0
    def post(self):

        errors = []
        output = ""
        user = users.get_current_user()
        authz = Authz(user)
        self.response.headers["Content-type"] = "application/json"

        # check for authorization to create new trips & verify this is in fact
        # a request to create a new trip
        try:
            # user allowed to create trips?
            authz.createTrip()

        except PermissionError as e:
            # this permission error could have come from authz or locally
            errors.append({"message": e.args})

        # bail if we hit authz errors
        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})
            self.response.out.write(output)
            return

        # user is allowed, so go ahead and try to create this thing
        # logging.debug(self.request.body)

        data = TripUnpacker().unpack_post(self.request)
        # logging.debug(data)

        if data["name"] == "" or data["password"] == "":
            errors.append({"message": "Trip name and password are required."})
        else:
            try:
                trip = Trip(name=data["name"], password=data["password"], owner=user)

                # get traveler names
                raw_travelers = data["travelers"]
                if len(raw_travelers) > Config.limits.travelers_per_trip:
                    logging.warning("Attempt to add too many travelers: %s", user.nickname)
                    raw_travelers = raw_travelers[: Config.limits.travelers_per_trip]
                travelers = []
                for traveler in raw_travelers:
                    if traveler.strip() != "":
                        travelers.append(traveler.strip())
                trip.travelers = travelers

                # get dates
                # TODO: validation that these dates are sane and properly ordered
                start_date = dateparse(data["start_date"])
                end_date = dateparse(data["end_date"])
                trip.start_date = start_date.date()
                # logging.debug("start date = " + str(start_date.date()))
                trip.end_date = end_date.date()
                # logging.debug("end date = " + str(end_date.date()))

                trip.put()

                output = GqlEncoder().encode(
                    {
                        "id": "%s" % trip.key(),
                        "modify_date": trip.modify_date,
                        "start_date": trip.start_date,
                        "end_date": trip.end_date,
                    }
                )
            except Exception as e:
                logging.exception(e)
                errors.append({"message": "Unexpected error creating trip"})

        if len(errors) > 0:
            self.response.set_status(400)
            output = json.dumps({"error": errors})

        self.response.out.write(output)
Esempio n. 52
0
def count_trip():
    #theResult = "Unknown"
    try:
        # receive a json object containing the trips and other data
        data = request.get_json(force=True)
        
    except Exception as e:
        printException('Bad JSON data in post',"error",e)
        printException("json = " + request.data,"info")
        return '{"result":"success"}'
        
    # get the countEvent record because we need the timezone offset
    rec = CountEvent.query.get(int(data['countEvent']))
    try:
        if rec:
            startDate = getDatetimeFromString(rec.startDate)
            endDate = getDatetimeFromString(rec.endDate)
            localTime = getLocalTimeAtEvent(rec.timeZone,rec.isDST) # Get the current local time at the event location
        else:
            raise ValueError("CountEvent Record No Found")
            
    except Exception as e:
        printException("CountEvent Record No Found","error")
        #theResult = "CountEventError"
        return '{"result":"success"}'
        
    trip = dict()
    trip['action'] = data.get('action')
    trip['location_ID'] = cleanRecordID(data.get('location'))
    trip['countEvent_ID'] = cleanRecordID(data.get('countEvent'))
    
    ## There is an 'action' called as 'total' with no trips data.
    ##  This loop will not execute and only the current total will be returned
    
    for i in range(len(data['trips'])):
        #d = datetime.utcnow() + timedelta(hours=-7)
        temp = data['trips'][i] # get the dict for the trip
        trip['seqNo'] = cleanRecordID(temp.get('seqNo'))
        trip['tripCount'] = cleanRecordID(temp.get("count"))
        trip['tripDate'] = temp.get('tripDate', "").strip()
        trip['turnDirection'] = temp.get('direction', "").strip()
        trip['traveler_ID'] = cleanRecordID(temp.get('traveler'))
        
        tripDate = getDatetimeFromString(trip['tripDate'])
        if not tripDate:
            # bad date string, log it and go to the next record
            printException("Bad trip date: " + temp, "error")
            continue # do next loop
           
        if trip['action'] == "undo":
            ## don't allow old trips to be undone
            ### If the trip is more than 1 minute in the past, it can't be deleted
            if tripDate + timedelta(minutes= 1) > localTime:
                
                try:
                    rec = Trip.query.filter(Trip.location_ID == trip['location_ID'], \
                        Trip.countEvent_ID == trip['countEvent_ID'], \
                        Trip.seqNo == trip['seqNo'], \
                        Trip.tripDate == trip["tripDate"]).first()
                    
                    if rec:
                        db.session.delete(rec)
                        db.session.commit()
                
                except Exception as e:
                    printException('Could not undo Trip '+str(i),"error",e)
            

        if trip["action"] == "add":
            
            validTrip, errorMess = isValidTrip(trip,startDate,endDate,localTime)
            
            if validTrip or True: #### Always Valid for Now #####
                try:
                    cur = Trip(trip['tripCount'],trip['tripDate'],trip['turnDirection'],trip['seqNo'],trip['location_ID'],trip['traveler_ID'],trip['countEvent_ID'])
                    db.session.add(cur)
                    db.session.commit()            
                except Exception as e:
                    printException('Could not record Trip '+str(i),"error",e)
                    printException("trip data: " + str(data), "info" )
                    
            else:
                #not a valid trip, so save in provisionalTrip table
                try:
                    cur = ProvisionalTrip(trip['tripCount'],trip['tripDate'],trip['turnDirection'],trip['seqNo'],trip['location_ID'],trip['traveler_ID'],trip['countEvent_ID'])
                    db.session.add(cur)
                    cur.issue = errorMess
                    
                    # inform the responsible parties
                    #sendProvisionalTripEmail() #Sends an email no more than once a day
                    
                except Exception as e:
                    printException('Could not record provisional Trip',"error",e)
                    printException("trip data: " + str(data), "info" )
                    
        else:
            #Bad action request
            pass
            
    try:
        db.session.commit()
    except Exception as e:
        printException("Unable to commit to trip or provisionalTrip", "error", e)
        printException("trip data: " + str(data), "info" )
        
    #Get the total so far:
    totalCnt = getAssignmentTripTotal(trip["countEvent_ID"], trip["location_ID"])
    
    return '{"result":"success", "total": %d}' % (totalCnt)