def carpool_join(): lookup = get_db()["carpool_members"].find_one( carpool_id=request.form["id"], member_id=current_user.id) if lookup is not None: return abort(401, "Already in this carpool") get_db().begin() try: get_db().query( "INSERT INTO carpool_members (carpool_id, member_id) VALUES (:carpool_id, :member_id)", **{ "carpool_id": request.form["id"], "member_id": current_user.id }) get_db().query( "INSERT INTO chat_messages (carpool_id, user_id, content, time) VALUES (:carpool_id, :user_id, :content, :time)", **{ "carpool_id": request.form["id"], "user_id": current_user.id, "content": "I joined this carpool!", "time": time.time() }) get_db().commit() except: get_db().rollback() return abort(401, "Fail") with get_neo_db().session() as session: for record in session.run( "MATCH (p:Carpool {id:$car_id})-[:FOR]->(c), (u:User {id:$user_id}) " "MERGE (u)-[:IN]->(p) " "MERGE (u)-[:LIKES]->(c)", car_id=int(request.form["id"]), user_id=current_user.id): pass return "Success"
def carpool_suggest(): if request.args.get("id") is None: result = [] with get_neo_db().session() as session: for r in session.run( "MATCH (u:User {id:$user_id}), (b:User) " "WHERE u <> b AND distance(b.location, u.location) < $radius " "WITH u, b " "MATCH (b)-[:IN]->(c) " "WHERE NOT (u)-[:IN]->(c) " "WITH DISTINCT u, c " "MATCH (b)-[:IN]->(c), (b)-[:LIKES]->(s)<-[:LIKES]-(u) " "WITH u, c, b, count(s) AS similarity_i " "WITH u, c, avg(similarity_i) AS similarity " "MATCH (b)-[:IN]->(c)-[:FOR]->(concert) " "RETURN c, similarity, min(distance(u.location, b.location)) AS dist, concert " "ORDER BY similarity DESC", radius=float(request.args.get("radius")), user_id=current_user.id): r2 = get_db().query("SELECT name FROM concerts WHERE id=:id", id=r["concert"].get("id")) result.append({ "id": r["c"].get("id"), "similarity": r["similarity"], "name": r2.next()["name"], "dist": r["dist"] }) return json.dumps(result) else: result = [] with get_neo_db().session() as session: for r in session.run( "MATCH (u:User {id:$user_id}), (b)-[:IN]->(p)-[:FOR]->(c:Concert {id:$for_id}) " "WITH p, min(distance(u.location, b.location)) AS dist " "RETURN p, dist " "ORDER BY dist", for_id=int(request.args.get("id")), user_id=current_user.id): r2 = get_db().query( "SELECT car_description FROM carpools WHERE id=:id", id=r["p"].get("id")) result.append({ "id": r["p"].get("id"), "dist": r["dist"], "desc": r2.next()["car_description"] }) return json.dumps(result)
def carpool_delete_like(): with get_neo_db().session() as session: for record in session.run( "MATCH (u:User {id: $id})-[r:LIKES]->(c:Concert {id: $concert_id}) DELETE r", id=current_user.id, concert_id=int(request.form["id"])): pass return "Success"
def get_location(): latitude = 0.0 longitude = 0.0 try: with get_neo_db().session() as session: for record in session.run( "MATCH (u:User {id: $id}) RETURN u.location", id=current_user.id): latitude = record["u.location"].latitude longitude = record["u.location"].longitude except: pass return json.dumps({"latitude": latitude, "longitude": longitude})
def carpool_get_likes(): likes = [] with get_neo_db().session() as session: for record in session.run( "MATCH (u:User {id: $id})-[:LIKES]->(c) RETURN c.id", id=current_user.id): likes.append(str(record["c.id"])) if len(likes) == 0: return json.dumps([]) r = get_db().query( "SELECT id, name FROM concerts WHERE id IN ({}) ORDER BY name".format( ",".join(likes))) return json.dumps([x for x in r])
def carpool_like_concert(): lookup = get_db()["concerts"].find_one(id=request.form["id"]) if lookup is None: return abort(401, "No such concert") with get_neo_db().session() as session: for record in session.run( "MATCH (u:User {id: $id}), (c:Concert {id:$concert_id}) MERGE (u)-[:LIKES]->(c)", id=current_user.id, concert_id=int(request.form["id"])): pass return "Success"
def carpool_create(): get_db().begin() try: get_db().query( "INSERT INTO carpools (arrival_time, driver_id, car_description, concert) VALUES (:a, :b, :c, :d)", a=request.form['arrival_time'], b=current_user.id, c=request.form['car_description'], d=request.form['concert']) car_id = next( iter(get_db().query( "SELECT MAX(id) FROM carpools").next().items()))[1] get_db().query( "INSERT INTO carpool_members (carpool_id, member_id) VALUES (:carpool_id, :member_id)", **{ "carpool_id": car_id, "member_id": current_user.id }) get_db().query( "INSERT INTO chat_messages (carpool_id, user_id, content, time) VALUES (:carpool_id, :user_id, :content, :time)", **{ "carpool_id": car_id, "user_id": current_user.id, "content": "I made this carpool!", "time": time.time() }) get_db().commit() except Exception as e: get_db().rollback() return abort(401, "Fail") with get_neo_db().session() as session: for record in session.run( "MERGE (p:Carpool {id:$car_id}) " "MERGE (c:Concert {id:$for_id}) " "MERGE (p)-[:FOR]->(c)", car_id=car_id, for_id=int(request.form['concert'])): pass for record in session.run( "MATCH (p:Carpool {id:$car_id})-[:FOR]->(c), (u:User {id:$user_id}) " "MERGE (u)-[:IN]->(p) " "MERGE (u)-[:LIKES]->(c)", car_id=car_id, user_id=current_user.id): pass return json.dumps({"id": car_id})
def reset(): get_db().begin() try: get_db()["concerts"].delete() get_db()["concert_artists"].delete() get_db()["carpools"].delete() get_db()["carpool_members"].delete() get_db()["chat_messages"].delete() get_db().commit() except Exception as e: get_db().rollback() return abort(401, "Fail") with get_neo_db().session() as session: for record in session.run("MATCH (a) DETACH DELETE a"): pass return "Success"
def update_account(): if request.method == 'POST': password = request.form['password'] lookup = get_db()["users"].find_one(id=current_user.id) m = hashlib.sha256() m.update((lookup["salt"] + password).encode('utf-8')) hash = m.hexdigest() lookup = get_db()["users"].find_one(id=current_user.id, password=hash) if lookup is None: return abort(401, "Wrong current password") displayname = request.form['displayname'] new_password = request.form['newpassword'] change = {"id": current_user.id, "displayname": displayname} if new_password != "": salt = generate_salt() m = hashlib.sha256() m.update((salt + new_password).encode('utf-8')) hash = m.hexdigest() change["password"] = hash change["salt"] = salt get_db().begin() try: get_db()["users"].update(change, ["id"]) get_db().commit() except: get_db().rollback() abort(401, "Registration error") user = get_user(current_user.id) login_user(user, remember=True) longitude = float(request.form['longitude']) latitude = float(request.form['latitude']) with get_neo_db().session() as session: for record in session.run( "MERGE (u:User {id: $id}) SET u.location=point({longitude:$longitude, latitude:$latitude})", id=current_user.id, longitude=float(request.form['longitude']), latitude=float(request.form['latitude'])): pass return redirect("/update_account") else: return render_template("dashboard/update_account.html")
def register(): if request.method == 'POST': username = request.form['username'].lower() password = request.form['password'] salt = generate_salt() m = hashlib.sha256() m.update((salt + password).encode('utf-8')) hash = m.hexdigest() get_db().begin() try: get_db()["users"].insert({ "username": username, "password": hash, "salt": salt, "displayname": username, "permissions": 2 }) get_db().commit() except: get_db().rollback() abort(401, "Registration error") lookup = get_db()["users"].find_one(username=username, password=hash) user = get_user(lookup["id"]) login_user(user, remember=True) with get_neo_db().session() as session: for record in session.run( "MERGE (u:User {id: $id}) SET u.location=point({longitude:$longitude, latitude:$latitude})", id=current_user.id, longitude=0.0, latitude=0.0): pass next = request.args.get("next") if next is None or not is_safe_url(next): next = "/" return redirect(next) else: return render_template("accounts/register.html")
def load_concerts(): params = ( ('classificationName', 'music'), ('dmaId', '249'), ('apikey', 'TC9A3O0V0EmuCwGVTcGGqXP4Nc8yqsVr'), ('size', '200'), ) response = requests.get( 'https://app.ticketmaster.com/discovery/v2/events.json', params=params) get_db().begin() try: #get_db()["concerts"].delete() #get_db()["concert_artists"].delete() data = response.json() for e in data["_embedded"]["events"]: name = e["name"] genre = "Undefined" if len(e["classifications"]) > 0: genre = e["classifications"][0]["genre"]["name"] venue_obj = e["_embedded"]["venues"][0] venue = venue_obj["name"] location = venue_obj["location"] artists = [a["name"] for a in e["_embedded"]["attractions"]] ts = 0 try: date_obj = dateutil.parser.parse( e["dates"]["start"]["dateTime"]).replace(tzinfo=None) tz = pytz.timezone("America/Chicago") dt_with_tz = tz.localize(date_obj, is_dst=None) ts = (dt_with_tz - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds() except: pass lookup = get_db()["concerts"].find_one(name=name, time=ts) if lookup is not None: continue pk = get_db()["concerts"].insert({ "genre": genre, "time": ts, "name": name, "location": json.dumps(location), "venue": venue }) for artist in artists: get_db()["concert_artists"].insert({ "artist": artist, "concert": pk }) with get_neo_db().session() as session: for record in session.run( "MERGE (c:Concert {id:$for_id, location:point({latitude:$lat, longitude:$lon})}) ", lat=float(location["latitude"]), lon=float(location["longitude"]), for_id=pk): pass get_db().commit() except Exception as e: get_db().rollback() return abort(401, "Fail") return "Success"
def carpool_leave(): delete_pool = False get_db().begin() try: get_db().query( "DELETE FROM carpool_members WHERE member_id=:a AND carpool_id=:b", a=current_user.id, b=request.form["id"]) get_db().query( "INSERT INTO chat_messages (carpool_id, user_id, content, time) VALUES (:carpool_id, :user_id, :content, :time)", **{ "carpool_id": request.form["id"], "user_id": current_user.id, "content": "I left this carpool!", "time": time.time() }) r = [ x for x in get_db().query( "SELECT * FROM carpool_members WHERE carpool_id=:id", id=request.form["id"]) ] if len(r) == 0: get_db().query("DELETE FROM carpools WHERE id=:a", a=request.form["id"]) delete_pool = True else: r = get_db().query("SELECT driver_id FROM carpools WHERE id=:id", id=request.form["id"]) driver_id = r.next()["driver_id"] r = get_db().query( "SELECT member_id FROM carpool_members WHERE carpool_id=:id", id=request.form["id"]) ids = [x["member_id"] for x in r] if driver_id not in ids: get_db().query( "UPDATE carpools SET driver_id=:driver_id, car_description=:car_description WHERE id=:id", **{ "id": request.form["id"], "driver_id": ids[0], "car_description": "Previous driver has left" }) get_db().commit() except Exception as e: print(str(e)) get_db().rollback() return abort(401, "Fail") if delete_pool: with get_neo_db().session() as session: for record in session.run( "MATCH (p:Carpool {id:$car_id}) " "DETACH DELETE p", car_id=int(request.form["id"])): pass else: with get_neo_db().session() as session: for record in session.run( "MATCH (p:Carpool {id:$car_id}), (u:User {id:$user_id}), (u)-[r:IN]->(p)" "DELETE r", car_id=int(request.form["id"]), user_id=current_user.id): pass return "Success"