def delete_poll(poll): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) toDelete = DB.find_one(collection='Poll', query={'_id': ObjectId(poll)}) if toDelete is None: flash('Please contact admin, DB error!') return redirect(url_for('polls')) for voter in toDelete['voters']: toRemove = DB.find_one(collection="Profile", query={"_id": voter}) if toRemove is None: flash('Please contact admin, DB error!') return redirect(url_for('polls')) DB.update_one(collection="Profile", filter={'_id': voter}, data={"$pull": { "polls": ObjectId(poll) }}) DB.update_one(collection="Profile", filter={'_id': user['_id']}, data={"$pull": { "polls": ObjectId(poll) }}) DB.remove(collection="Poll", condition={"_id": ObjectId(poll)}) flash('Deleted Poll!') return redirect(url_for('polls'))
def profile(profile_id, is_profile_owner=False): user = DB.find_one(collection="Profile", query={'_id': ObjectId(profile_id)}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) me = DB.find_one(collection="Profile", query={"email": current_user.email}) def are_we_friends(entry): return (entry['friend_id'] == me['_id'] and entry['status'] == 'accepted') is_friend = any(filter(are_we_friends, user['friends'])) eventList = [] for events in user['events']: events = DB.find_one(collection='Events', query={'_id': events}) if not events: continue event_dict = { 'title': events['name'], 'start': events['start'].strftime("%Y-%m-%d"), 'end': events['end'].strftime("%Y-%m-%d") } eventList.append(event_dict) if not eventList: eventList = {} return render_template('profile.html', profile=user, events=eventList, is_profile_owner=is_profile_owner, is_friend=is_friend)
def invite_voter(poll, email): friend = DB.find_one(collection="Profile", query={"email": email}) if friend is None: flash(f'Friend {email} not found!') return redirect(url_for('add_voter', poll=poll)) sent = DB.find_one(collection="Poll", query={ '$and': [{ '_id': ObjectId(poll) }, { 'voters': ObjectId(friend['_id']) }] }) if sent is not None: flash(f'Already added {email} as voter!') return redirect(url_for('add_voter', poll=poll)) DB.update_one(collection="Poll", filter={'_id': ObjectId(poll)}, data={'$push': { 'voters': ObjectId(friend['_id']) }}) DB.update_one(collection="Profile", filter={'_id': ObjectId(friend['_id'])}, data={'$push': { 'polls': ObjectId(poll) }}) flash(f'Successfully added {email} as voter!') return redirect(url_for('add_voter', poll=poll))
def delete_request(profile_id): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) # only can add user with a profile friend = DB.find_one(collection="Profile", query={"_id": ObjectId(profile_id)}) if friend is None: flash('User not found!') return redirect(url_for('friends')) for f in user['friends']: if friend['_id'] == f['friend_id'] and f['status'] == 'pending': DB.update_one(collection="Profile", filter={"_id": user['_id']}, data={'$pull': { "friends": f }}) flash('Friend request ' + friend['email'] + ' cancelled!') return redirect(url_for('friends')) for f in friend['friends']: if user['_id'] == f['friend_id'] and f['status'] == 'pending': DB.update_one(collection="Profile", filter={"_id": friend['_id']}, data={'$pull': { "friends": f }}) flash('Friend request ' + friend['email'] + ' rejected!') return redirect(url_for('friends')) flash('Please contact admin, DB issues!') return redirect(url_for('friends'))
def delete_friend(profile_id): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) added = DB.find_one(collection="Profile", query={ "$and": [{ "_id": user['_id'] }, { "friends": { "$elemMatch": { "friend_id": ObjectId(profile_id), "status": "accepted" } } }] }) added2 = DB.find_one(collection="Profile", query={ "$and": [{ "_id": ObjectId(profile_id) }, { "friends": { "$elemMatch": { "friend_id": user['_id'], "status": "accepted" } } }] }) if added is not None and added2 is not None: myFriendList = get_list(toFilterList=added['friends'], key="friend_id", query=ObjectId(profile_id)) DB.update_one(collection="Profile", filter={"_id": user['_id']}, data={'$pull': { "friends": myFriendList[0] }}) theirFriendList = get_list(toFilterList=added2['friends'], key="friend_id", query=user['_id']) DB.update_one(collection="Profile", filter={"_id": ObjectId(profile_id)}, data={'$pull': { "friends": theirFriendList[0] }}) flash(f'Delete friend successful!') return redirect(url_for('friends')) else: flash(f'Delete friend failed!') flash('pontential DB issue pls contact admin') return redirect(url_for('friends'))
def edit_event(eventId): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) event = DB.find_one(collection="Events", query={"_id": ObjectId(eventId)}) if event is None: flash('Please contact admin, DB issues!') return redirect(url_for('view_events')) form = EventForm() if form.validate_on_submit(): if form.pictureDir.data is not None: if event['pictureDir'] == 'event.jpg': filename = photos.save(form.pictureDir.data, name='event/' + str(event['_id']) + '.') filename = filename.split('/')[1] else: # delete existing photo filename = "app/static/images/event/" + event['pictureDir'] os.remove(os.path.join(filename)) filename = photos.save(form.pictureDir.data, name='event/' + str(event['_id']) + '.') filename = filename.split('/')[1] DB.update_one(collection="Events", filter={"_id": event['_id']}, data={"$set": { "pictureDir": filename }}) if form.eventType.data == 'private': event_type = True else: event_type = False DB.update_one(collection="Events", filter={"_id": event['_id']}, data={"$set": { "name": form.name.data.strip() }}) DB.update_one( collection="Events", filter={"_id": event['_id']}, data={"$set": { "description": form.description.data.strip() }}) DB.update_one(collection="Events", filter={"_id": event['_id']}, data={"$set": { "private": event_type }}) return redirect(url_for('view_events')) return render_template('edit-event.html', title="Edit Event Details", form=form, event=event)
def update_vote(poll): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) toUpdate = DB.find_one(collection='Poll', query={'_id': ObjectId(poll)}) if toUpdate is None: flash('Please contact admin, DB error!') return redirect(url_for('polls')) options = request.form.getlist('date') if request.form.get('add') == 'add': for dates in options: # dates = dates.split(' ')[0] dt = datetime.strptime(dates, "%Y-%m-%d %H:%M:%S") # test = DB.find_one(collection='Poll', query={'options': dt}) # print(test) index = get_index_1key(arrayList=toUpdate, key='options', query=dt) print(index) index = "options." + str(index) + ".voters" check = DB.find_one(collection='Poll', query={index: user['email']}) if check is not None: flash(f'You Already voted for {dt}') return redirect(url_for('polls')) DB.update_one(collection='Poll', filter={'_id': ObjectId(poll)}, data={'$push': { index: user['email'] }}) return redirect(url_for('polls')) elif request.form.get('del') == 'del': for dates in options: dt = datetime.strptime(dates, "%Y-%m-%d %H:%M:%S") index = get_index_1key(arrayList=toUpdate, key='options', query=dt) print(index) index = "options." + str(index) + ".voters" check = DB.find_one(collection='Poll', query={index: user['email']}) if check is None: flash(f'You haven\'t voted for {dt}') return redirect(url_for('polls')) DB.update_one(collection='Poll', filter={'_id': ObjectId(poll)}, data={'$pull': { index: user['email'] }}) return redirect(url_for('polls')) flash(f'Pick an option') return redirect(url_for('polls'))
def insert(self): if self.reviewId > 0: if not DB.find_one("RatingProcessed", {"reviewId": self.reviewId}): DB.insert(collection='RatingProcessed', data=self.json()) else: return True else: if not DB.find_one("RatingProcessed", {"userId": self.userId, "restId": self.restId}): DB.insert(collection='RatingProcessed', data=self.json()) else: return True return False
def get_initial_num(): a = DB.find_one("dianping_register", {"crawby": "jack"}) b = DB.find_one("Ratings", {"source": "dazhongdianping"}) if a: initial_num = a['initial_num'] elif b: c = DB.find_max( 'Ratings', {"source": "dazhongdianping"}, 'timestamp') if c: initial_num = b['reviewId'] else: initial_num = 706754427 else: initial_num = 706754427 return initial_num
def reset_pwd(token): try: serializer = URLSafeTimedSerializer(app.config['SECRET_KEY']) email = serializer.loads(token, salt=app.config['SECRET_KEY']) except: flash('Reset link is invalid or expired') return redirect(url_for('login')) form = PasswordForm() if form.validate_on_submit(): form.password.data = form.password.data.strip() user = DB.find_one(collection="User", query={"email": email}) if user is None: flash('Invalid account!') return redirect(url_for('login')) else: new_password = generate_password_hash(form.password.data) DB.update_one(collection="User", filter={"email": email}, data={"$set": { "password": new_password }}) return redirect(url_for('login')) return render_template('reset-password-token.html', form=form, token=token, email=email)
def delete(self, id): task = DB.find_one("Tasks", {"_id": id}) if task: DB.remove("Tasks", {"_id": id}) return jsonify("Task removed") return jsonify("No task matching given id")
def update(self, id, payload): print(payload) task = DB.find_one("Tasks", {"_id": id}) if task: if 'grade' and 'progress' in payload: DB.update("Tasks", {"_id": id}, { "$set": { "title": payload['title'], "deadline": payload['deadline'], "course_d": payload['course_id'], "description": payload['description'], "attachments": payload['attachments'], "grade": payload['grade'], "progress": payload['progress'] } }) else: DB.update("Tasks", {"_id": id}, { "$set": { "title": payload['title'], "deadline": payload['deadline'], "course_d": payload['course_id'], "description": payload['description'], "attachments": payload['attachments'] } }) return jsonify("Task updated") return jsonify("No task matching given id") return jsonify("No task matching given id")
def delete(self): if not DB.find_one("sinfo", {"name": self.name}): return 0 else: query_result = DB.delete(collection='sinfo', dcname={'name': self.name}) return (query_result.deleted_count)
def get_name(email): return DB.find_one(collection="Profile", query={"email": email}, projection={ "firstName": 1, "lastName": 1 })
def login(): if current_user.is_authenticated: return redirect(url_for('dashboard')) form = LoginForm() if form.validate_on_submit(): form.email.data = form.email.data.strip() user = DB.find_one(collection="User", query={"email": form.email.data}) if user and check_password_hash(user['password'], form.password.data): if user['confirmed']: user_obj = User(email=user['email'], password=user['password'], confirmed=user['confirmed']) # print(user_obj.email) login_user(user_obj) # flash(user_obj.name) return redirect(url_for('dashboard')) # next_page = request.args.get('next') # if not next_page or url_parse(next_page).netloc != '': # next_page = url_for('index') # return redirect(next_page) else: flash('Please confirm your email') return redirect(url_for('login')) else: flash("Invalid email or password") return render_template('login.html', title='Log In', form=form)
def my_profile(): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) return profile(str(user['_id']), is_profile_owner=True)
def deleteInvite(eventId, userId): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) # Delete user from the Event model from invitees # Get the list of invitees from Event model # also delete them from invitePrivleges if DB.find_one(collection="Events", query={ "_id": ObjectId(eventId), "invitePrivleges": { "$elemMatch": { "cohostId": ObjectId(userId) } } }): print("ASGASGASG") DB.update_one(collection="Events", filter={"_id": ObjectId(eventId)}, data={ "$pull": { "invitePrivleges": { "cohostId": ObjectId(userId) } } }) userEmail = DB.find_one(collection="Profile", query={"_id": ObjectId(userId)}, projection={"email": 1}) DB.update_one(collection="Events", filter={"_id": ObjectId(eventId)}, data={"$pull": { "invitees": { "id": ObjectId(userId) } }}) DB.update_one(collection="Profile", filter={"_id": ObjectId(userId)}, data={"$pull": { "events": ObjectId(eventId) }}) return redirect(url_for("display_event", id=eventId))
def update_db(initial_num): a = DB.find_one("dianping_register", {"crawby": "jack"}) if a: DB.update("dianping_register", {"crawby": "jack"}, { '$set': {'initial_num': initial_num}}) else: DB.insert('dianping_register', { "crawby": "jack", 'initial_num': initial_num}) pass
def insert(self): if not DB.find_one("Profile", {"polls._id": self.creator}): poll = DB.insert(collection='Poll', data=self.json()) DB.update_one(collection='Profile', filter={'_id': self.creator}, data={'$push': { 'polls': poll.inserted_id }}) return poll.inserted_id
def searchpersonalprofile(): username = session.get('user') collection = 'PersonalInfo' query = {'Email': username} personal = DB.find_one(collection, query) print(personal['Name']) return render_template('home.html', username=session.get('user'), personal=personal)
def update_student(id): student = DB.find_one("Students", {"_id": id}) sync = request.args.get('sync') if student and sync and sync == 'true': last_sync_date = datetime.datetime.utcnow() DB.update("Students", {"_id": id}, { "$set": {"last_sync_date": last_sync_date}}) return jsonify("Successfully upadted the student information") return jsonify("No student matching given id")
def insert(self,userEmail,userId): event = DB.insert(collection='Events', data=self.json()) DB.update_one(collection='Profile',filter={'email':userEmail}, data = {'$push': {'events':event.inserted_id}}) profilePic = DB.find_one(collection = "Profile", query = {"email": userEmail}, projection = {"pictureDir" : 1, 'firstName':1, 'lastName':1}) DB.update_one(collection = "Events", filter ={'_id':event.inserted_id}, data = {'$push': {"invitees": {"id":userId, "email": userEmail, "status": "going", "profilePic":profilePic['pictureDir'], "name":profilePic['firstName'] + " " + profilePic['lastName']}}}) return event.inserted_id
def accept_request(profile_id): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) # only can add user with a profile friend = DB.find_one(collection="Profile", query={"_id": ObjectId(profile_id)}) if friend is None: flash('User not found!') return redirect(url_for('friends')) if friend['friends'] != []: index = get_index_2key(arrayList=friend['friends'], key='friend_id', query=user['_id'], key2='status', query2='pending') if index == -1: flash('invalid request') return redirect(url_for('friends')) else: friend_status = "friends." + str(index) + ".status" DB.update_one(collection="Profile", filter={"_id": friend['_id']}, data={"$set": { friend_status: "accepted" }}) DB.update_one(collection="Profile", filter={"_id": user['_id']}, data={ "$push": { "friends": { "friend_id": friend['_id'], "status": "accepted" } } }) flash('Accepted %s\'s friend request!' % friend['email']) return redirect(url_for('friends')) flash('pontential DB issue pls contact admin') return redirect(url_for('friends'))
def insert(self): if self.reviewId != "": print('执行插入了1:', self.reviewId) if not DB.find_one("Ratings", {"reviewId": self.reviewId}): print() DB.insert(collection='Ratings', data=self.json()) insert_data = self.json() print('insert_data:', insert_data) else: return True else: print('执行插入了2') if not DB.find_one("Ratings", { "userId": self.userId, "restId": self.restId }): DB.insert(collection='Ratings', data=self.json()) else: return True return False
def delete_event(id): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) #delete the event from the id #first go through all the users that is associated with that id x = DB.find_one(collection="Events", query={"_id": ObjectId(id)}) profileList = x['invitees'] # Delete the event from all users in profile for profile in profileList: DB.update_one(collection="Profile", filter={"email": profile['email']}, data={"$pull": { "events": ObjectId(id) }}) #delete the actual event from the database DB.remove(collection="Events", condition={"_id": ObjectId(id)}) return redirect(url_for("view_events"))
def friends(): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) # all users users = list(DB.find_all(collection="Profile")) myFriendList = [] mySentList = [] for f in user['friends']: profile = DB.find_one(collection="Profile", query={'_id': f['friend_id']}) if f['status'] == 'accepted': myFriendList.append(profile) else: mySentList.append(profile) incoming = DB.find(collection="Profile", query={ "friends": { "$elemMatch": { "friend_id": user['_id'], "status": "pending" } } }) requests = get_cursor(cursor_obj=incoming, key="friends", subkey="friend_id", subkey2="status", query=user['_id'], query2="pending") return render_template('friend.html', title='Friend List', users=users, myFriendList=myFriendList, mySentList=mySentList, requests=requests)
def view_events(): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) allEvents = [] myEvents = [] if user['events'] != []: for event_id in user['events']: event = DB.find_one(collection='Events', query={'_id': event_id}) event_host = DB.find_one(collection='Profile', query={'_id': event['host']}) if user['_id'] == event_host['_id']: myEvents.append(event) else: allEvents.append({ '_id': event['_id'], 'name': event['name'], 'host': event_host['firstName'] + ' ' + event_host['lastName'], 'start': event['start'], 'end': event['end'], 'description': event['description'], 'pictureDir': event['pictureDir'] }) return render_template( 'events.html', title='View Events', me=user, myEvents=myEvents, invEvents=allEvents, )
def addPeople(userId=None, id=None): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) # we have the email and id of the user & event we want to invite, # we need to update the number of people in the invitees (add the profile to it) # also update the profile's thingy profileEvents = DB.find_one(collection="Profile", query={"_id": ObjectId(userId)}) pics = profileEvents email = profileEvents['email'] profileEvents = profileEvents['events'] if ObjectId(id) not in profileEvents: DB.update_one(collection="Events", filter={'_id': ObjectId(id)}, data={ '$push': { "invitees": { "id": ObjectId(userId), "email": email, "status": "invited", "profilePic": pics['pictureDir'], "name": pics['firstName'] + " " + pics['lastName'] } } }) DB.update_one(collection="Profile", filter={"email": email}, data={"$push": { "events": ObjectId(id) }}) return redirect(url_for("display_event", id=id))
def add_event_post(eventId): user = DB.find_one(collection="Profile", query={"email": current_user.email}) if user is None: flash('Please create your profile first!') return redirect(url_for('edit_profile')) author_id = user['_id'] timestamp = datetime.now() post_text = request.form['post_text'] newPost = Post(author_id, timestamp, post_text) newPostId = newPost.insert() Event.add_post_by_id(ObjectId(eventId), newPostId) return redirect(url_for('display_event', id=eventId))
def checklogin(): if request.method == 'POST': username = request.form['email'] password = request.form['password'] query = {'Email': username} collection = "LoginInfo" data = DB.find_one(collection, query) password2 = data['Password'] if check_password_hash(password2, password): session['user'] = username return redirect(url_for('success')) else: flash("Invalid username or password") return redirect(url_for('loginpage'))