def delete(self, id): #find the question client = getMongoClient() db = client["Project"] questions = db['questions'] id_query = {"id": id} my_question = getQuestionByID(id) if not my_question: return make_response( jsonify(status="error", error="No existing question ID"), 400) #Make sure this is the right user this_username = get_jwt_identity() question_username = my_question['user']['username'] if not this_username == question_username: return make_response( jsonify(status="error", error="Can't delete a question that isn't yours!"), 400) #delete the question delete_response = delete_question(my_question) #print(delete_response) if delete_response['status'] == "error": return make_response( jsonify(status="error", error="cannot delete question"), 400) #REFACTOR delete entry from 'questions' questions.delete_one(id_query) return make_response(jsonify(delete_response), 200)
def upvote_object(voter, obj, obj_owner): my_id = obj['id'] #print(voter) client = getMongoClient() db = client['Project'] col = db['users'] #remove downvote if my_id in voter['waived_downvoted']: #print("Removing waived downvote") obj['score'] += 1 voter['waived_downvoted'].remove(my_id) #col.update_one({"username":voter['username']}, {"$pull":{"waived_downvoted":my_id}}) elif obj['id'] in voter['downvoted']: #print("Removing normal downvote") obj['score'] += 1 voter['downvoted'].remove(my_id) #col.update_one({"username":voter['username']}, {"$pull":{"downvoted":my_id}}) obj_owner['reputation'] += 1 #obj['user']['reputation'] = obj_owner['reputation'] #unupvote if obj['id'] in voter['upvoted']: obj['score'] -= 1 #print("removing upvote") voter['upvoted'].remove(obj['id']) #col.update_one({"username":voter['username']}, {"$pull":{"upvoted":my_id}}) if obj_owner['reputation'] >= 2: obj_owner['reputation'] -= 1 # obj['user']['reputation'] = obj_owner['reputation'] #TODO: consider waiving removal for low rep user? #upvote else: #print('name of voter is ' + voter['username']) #print("NORMAL UPVOTE") #increment owner rep. increment object score. add to "upvoted" list obj['score'] += 1 obj_owner['reputation'] += 1 #obj['user']['reputation'] = obj_owner['reputation'] voter['upvoted'].append(obj['id']) #print('Voters upvoted array after appending id ' + str(voter['upvoted'])) #col.update_one({"username":voter['username']}, {"$push":{"upvoted":my_id}}) #print(voter) if voter['username'] == obj_owner['username']: voter['reputation'] = obj_owner['reputation'] upsertUser(voter) else: upsertUser(voter) upsertUser(obj_owner) #print("USERNAME OF VOTER: ", voter["username"]) #col.update_one({"username":voter['username']}, {"$set":{"upvoted":voter['upvoted']}}) #col.update_one({"username":voter['username']}, {"$set":{"downvoted":voter['downvoted']}}) #col.update_one({"username":voter['username']}, {"$set":{"waived_downvoted":voter['waived_downvoted']}}) if 'is_accepted' in obj: upsertAnswer(obj) else: obj['user']['reputation'] = obj_owner['reputation'] upsertQuestion(obj)
def getUserByName(my_name): start=time.time() client = getMongoClient() db = client["Project"] user_col = db["users"] my_query = {"username" : my_name} my_user = user_col.find_one(my_query) #print("USERTIME(name)", time.time()-start) return my_user
def getUserByEmail(my_email): start=time.time() client = getMongoClient() db = client["Project"] user_col = db["users"] my_query = {"email" : my_email} my_user = user_col.find_one(my_query) #print("USERTIME(email)", time.time()-start) return my_user
def get(self): client = getMongoClient() #TODO: change this to accomodate for sharding mydb = client['Project'] #mydb.command("dropDatabase") for col_name in mydb.list_collection_names(): mydb[col_name].delete_many({}) session = getCassandraSession() session.execute("TRUNCATE images")
def getAnswerByID(my_id): start=time.time() client = getMongoClient() db = client["Project"] answer_col = db['answers'] my_query = {"id" : my_id} my_answer = answer_col.find_one(my_query) end=time.time() #print("ANSWERTIME",end-start) return my_answer
def getQuestionByID(my_id): start = time.time() client = getMongoClient() db = client["Project"] question_col = db["questions"] my_query = {"id" : my_id} my_question = question_col.find_one(my_query) end = time.time() #print("QUESTIONTIME", end-start) return my_question
def removeMediaByID(media_id): client = getMongoClient() db = client["Project"] col = db["media"] my_media = col.find_one({"media_id": media_id}) if not my_media: return "error" col.delete_one({"media_id": media_id}) session = getCassandraSession() session.execute("DELETE FROM images WHERE id = %s", [media_id]) return "OK"
def generateNewID( ): #will generate random integer ID while avoiding collisions randomkey = ''.join([random.choice(string.digits) for n in range(16)]) client = getMongoClient() queryForID = {"id": randomkey} db = client["Project"] answerCol = db['answers'] questionCol = db['questions'] while answerCol.count(queryForID) != 0 or questionCol.count( queryForID) != 0: randomkey = ''.join([random.choice(string.digits) for n in range(16)]) queryForID = {"id": randomkey} # print(str(randomkey)) return randomkey
def associateMedia(media_id, object_id, username): client = getMongoClient() db = client["Project"] media_col = db["media"] my_media = media_col.find_one({"media_id": media_id}) #does not exist if not my_media: return "error" if not my_media['object_id'] is None: print("DUPLICATE EXISTS") return "error" if not username == my_media['username']: print("NOT THE RIGHT USER") return "error" else: media_col.update_one({"media_id": media_id}, {"$set": { "object_id": object_id }}) return "OK"
def get(self, id): #print("STARTING GET QUESTION") visit = {} username = get_jwt_identity() if username is None: #then we should check their IP visit['identifier'] = request.environ.get( 'HTTP_X_REAL_IP', request.remote_addr ) #proxy_set_header X-Real-IP $remote_addr; else: visit['identifier'] = username client = getMongoClient() db = client["Project"] questions = db["questions"] col = db["visits"] myquery2 = {"id": id, "identifier": visit['identifier']} #print("QUESTION ID type: ", id) my_question = getQuestionByID(id) if not my_question: return make_response( jsonify(status="error", error="No existing question ID"), 400) user = my_question['user']['username'] user = getUserByName(user) my_question['user']['reputation'] = user[ 'reputation'] #MIGHT NEED TO UPSERT THIS IF DOESN"T WORK BUT TRYING TO AVOID UPSERT OPERATION if col.count(myquery2) == 0: #unique visit! visit['id'] = id #REFACTOR new entry in 'visit' col.insert_one(visit) my_question['view_count'] = my_question['view_count'] + 1 #REFACTOR update 'view_count' in questions #questions.update_one(myquery, { "$set": { "view_count" : my_question['view_count']} } ) #upsertQuestion(my_question) upsertQuestion(my_question) my_question = json.loads(dumps(my_question)) #print("Question Contents: ", my_question) #my_question['id'] = my_question['id'] return jsonify(status="OK", question=my_question)
def delete_answer(answer_id): client = getMongoClient() db = client["Project"] answers = db['answers'] # answer_query = {'id' : answer_id} #my_answer = answers.find_one(answer_query) my_answer = getAnswerByID(answer_id) #if answer not found if not my_answer: print("No answer found when trying to delete. Answer ID: ", my_answer['id']) return #Delete user's reference to this answer my_username = my_answer['user'] # users = db['users'] # user_query = {"username": my_username} #my_user = users.find_one(user_query) my_user = getUserByName(my_username) answers_by_user = my_user['answers'] answers_by_user.remove(my_answer['id']) my_user['answers'] = answers_by_user my_user['reputation'] -= my_answer['score'] if my_user['reputation'] < 2: my_user['reputation'] = 1 #TODO: delete associated media for media_id in my_answer['media']: removeMediaByID(media_id) #REFACTOR update 'answers' in 'user' # users.update_one(user_query, {"$set": {"answers": answers_by_user}}) upsertUser(my_user) answers.delete_one({'id': answer_id})
def post(self): if request.is_json: my_json = request.get_json() else: return jsonify(status="error", error="Request isn't json") #defaults timestamp = time.time() limit = 25 accepted = "False" #keep parameters as a string q = None sort_by = "score" tags = [] has_media = "False" if 'timestamp' in my_json: timestamp = my_json['timestamp'] if 'limit' in my_json: limit = my_json['limit'] if limit > 100: limit = 100 if limit < 1: limit = 1 if 'accepted' in my_json: accepted = my_json['accepted'] if 'q' in my_json: q = my_json['q'] if 'sort_by' in my_json: sort_by = my_json['sort_by'] if 'tags' in my_json: tags = my_json['tags'] if 'has_media' in my_json: has_media = my_json['has_media'] results = [] #array of questions client = getMongoClient() db = client["Project"] col = db["questions"] my_query = {} #if query string specified, only return questions with matching title or body if q: index_name = "search_index" index_info = col.index_information() if index_name not in col.index_information(): col.create_index([('body', pymongo.TEXT), ('title', pymongo.TEXT)], name=index_name, default_language='none') #print("Search Query: ", q) #print("limit: ", limit) #print("timestamp: ", timestamp) my_query["$text"] = {"$search": q} my_query["timestamp"] = {"$lt": timestamp} #if "accepted" param is on, only give questions where acc_id is not None if accepted != "False": my_query["accepted_answer_id"] = {"$ne": None} if has_media != "False": my_query["media"] = {"$ne": []} if tags != []: my_query["tags"] = {"$all": tags} if q: #my_cursor = col.find(my_query, {'_score', {'$meta': 'textScore'}}) #my_cursor.sort([('_score', {'$meta': 'textScore'})]) #my_cursor = col.find(my_query).sort([("_txtscore",{"$meta":"textScore"})]) #TODO: use elasticsearch #my_cursor = col.find(my_query, {'_txtscore':{'$meta':'textScore'}}).sort([("_txtscore",{"$meta":"textScore"})]) if sort_by != "score": my_cursor = col.find(my_query, { '_txtscore': { '$meta': 'textScore' } }).sort([("_txtscore", { "$meta": "textScore" })]).limit(limit).sort("timestamp", pymongo.DESCENDING) else: my_cursor = col.find(my_query, { '_txtscore': { '$meta': 'textScore' } }).sort([("_txtscore", { "$meta": "textScore" })]).limit(limit).sort("score", pymongo.DESCENDING) else: if sort_by != "score": my_cursor = col.find(my_query).sort("timestamp", pymongo.DESCENDING) else: my_cursor = col.find(my_query).sort("score", pymongo.DESCENDING) for i in range(limit): question_element = next(my_cursor, None) if question_element: results.append(json.loads(dumps(question_element))) else: break return jsonify(status="OK", questions=results)
def post(self): error_out = False try: verify_jwt_in_request() except NoAuthorizationError: #return jsonify(status="error", error="not logged in") #request.headers.get('content-length') #response = Response() #response.headers.add('content-length', '71') error_out = True #print("plan to error out") #if error_out: #return jsonify(status="OK", id=id) #username = get_jwt_identity() #if username is None: #print(username) # return make_response(jsonify(status = "error", error = "not logged in"), 400) #print(request.headers) #for cookie in request.cookies: # print("COOKIE FOUND FOR MEDIA: ", cookie) #print("MADE IT INTO ADDMEDIA") #if request.is_json: # json = request.get_json() #else: # return make_response(jsonify(status="error", error ="request is not json"), 400) #content = json['content'] file = request.files['content'] filetype = file.content_type #file = file.read() #print(type(file)) # print('grabbed file') #session = getCassandraSession() # print('grabbed session') # print('generated ID') if error_out: return make_response( jsonify(status="error", error="not logged in"), 410) #print("QUEUING A CASSANDRA WRITE") if file is None: return make_response( jsonify(status="error", error="No file attached!"), 420) if filetype is None: filetype = "image/png" #return make_response(jsonify(status="error", error="No filetype!"), 430) id = generateNewMediaID() queueCassandraWrite(id, file, filetype) #session.execute("INSERT INTO images(id, contents, contenttype) VALUES (%s, %s, %s)", (id, file, filetype)) client = getMongoClient() db = client["Project"] media_col = db["media"] dToInsert = {} dToInsert["media_id"] = id dToInsert["object_id"] = None dToInsert["username"] = get_jwt_identity() media_col.insert_one(dToInsert) #session.execute("INSERT INTO images(id, contents, contenttype) VALUES (%s, %s, %s)", (id, file, filetype)) # print("made it past inserting into database") return jsonify(status="OK", id=id)
def post(self, id): question = getQuestionByID(id) if not question: return make_response( jsonify(status="error", error="no question with given ID"), 400) if request.is_json: json = request.get_json() else: return jsonify(status="error", error="Request isn't json") if not "body" in json: return make_response( jsonify(status="error", error="missing argument: 'body'"), 400) body = json['body'] media = [] if 'media' in json: media = json['media'] client = getMongoClient() db = client["Project"] col = db["answers"] dToInsert = {} answer_id = generateNewID() dToInsert['id'] = answer_id dToInsert['user'] = get_jwt_identity() dToInsert['body'] = body dToInsert['score'] = 0 dToInsert['is_accepted'] = False dToInsert['timestamp'] = time.time() dToInsert['media'] = media dToInsert['question'] = id #update the 'used' field of media for media_id in media: #create a document that maps a mediaID to an ObjectID result = associateMedia(media_id, dToInsert['id'], get_jwt_identity()) if result == "error": return make_response( jsonify( status="error", error="media already associated with another object"), 400) #print(dumps(dToInsert)) #REFACTOR new entry in 'answers' #col.insert_one(dToInsert) upsertAnswer(dToInsert) #add this answer to the question's answer list #questions = db["questions"] #myquery = {'id' : id} #question = questions.find_one(myquery) question['answers'].append(answer_id) question['answer_count'] = question['answer_count'] + 1 #REFACTOR update 'answers' in 'questions' #REFACTOR update 'answer_count' in 'questions' #questions.update_one(myquery, {"$set": {"answers" : question['answers']}}) #questions.update_one(myquery, {"$set": {"answer_count" : question['answer_count'] + 1}}) upsertQuestion(question) #user_col = db["users"] #user_query = {"username": get_jwt_identity()} #my_user = user_col.find_one(user_query) my_user = getUserByName(get_jwt_identity()) #my_answer_list = my_user['answers'] #my_answer_list.append(dToInsert['id']) my_user['answers'].append(dToInsert['id']) #REFACTOR update 'answers' in 'user' #user_col.update_one(user_query, {"$set": {'answers': my_answer_list}}) upsertUser(my_user) return jsonify(status="OK", id=answer_id)
def upsertQuestionNOW(my_question): client = getMongoClient() db = client["Project"] question_col = db["questions"] question_col.replace_one({"id" : my_question['id']}, my_question, upsert=True)
def upsertAnswer(my_answer): client = getMongoClient() db = client["Project"] answer_col = db['answers'] answer_col.replace_one({"id" : my_answer['id']}, my_answer, upsert=True)
def post(self): #server = smtplib.SMTP('localhost', 587) # server = smtplib.SMTP('localhost') #server.ehlo() #server.starttls(context = ssl.create_default_context()) #server.ehlo() #server.login("*****@*****.**", "dummyemail") #start_time = time.time() args = parser1.parse_args() username = args['username'] password = args['password'] email = args['email'] #print("Adding a user ", username) #print("With email ", email) #print("username: "******" password: "******" email: " + email) myclient = getMongoClient() mydb = myclient["Project"] mycol = mydb["users"] #print("mycol: " + str(mycol)) myquery = {"email": email} myquery2 = {"username": username} start = time.time() row1 = mycol.find_one(myquery) row2 = mycol.find_one(myquery2) #print("ADDUSERQUERIES: ", time.time() - start) if not row1 and not row2: #start_time = time.time() dataToInsert = {} dataToInsert['username'] = username dataToInsert['password'] = password dataToInsert['email'] = email dataToInsert['validated'] = False dataToInsert['verificationCode'] = getKey() dataToInsert['reputation'] = 1 dataToInsert['questions'] = [] #list of question IDs dataToInsert['answers'] = [] #list of answer IDs dataToInsert['upvoted'] = [] dataToInsert['downvoted'] = [] dataToInsert['waived_downvoted'] = [] #end_time = time.time() #REFACTOR new entry in 'user' # mycol.insert_one(dataToInsert) upsertUserNOW(dataToInsert) # upsertUserNOW(dataToInsert) msg2 = "\nHello " + username + "!\n validation key: <" + dataToInsert[ 'verificationCode'] + ">" #msg = "\nHello " + username + "!\n Please click this link to\ #print('right above queueMail in addUser') #verify your account for Stack.\n http://130.245.171.188/verify?email=" + email + "&key=" + dataToInsert['verificationCode'] queueMail(email, msg2) #print("QUEUED MAIL SUCCESSFULY\n") #end_time = time.time() #print(end_time - start_time) #print("NEW USER ADDED", username) return jsonify(status="OK") else: return make_response( jsonify(status="error", error="Account already exists!"), 401)
def upsertUserNOW(my_user): client = getMongoClient() db = client["Project"] user_col = db["users"] #if "_id" in my_user: user_col.replace_one({'username': my_user["username"]}, my_user, upsert=True)