def change_password(): try: userid = int(request.json['userid']) token = request.json['token'] password = request.json['password'] userdata = User.find_one({ "userid": userid, "active": True }, {"_id": 0}) if userdata is not None: salt = userdata['salt'] if request.json['password'].strip() != "": password = hashlib.md5( request.json['password'].strip()).hexdigest() + salt User.update({"userid": userid}, {"$set": {"password": password}}) return jsonify({ "status": 200, "message": "Password Successfully changed." }) else: return jsonify({"status": 202, "message": "No user is found."}) except Exception as e: return jsonify({"status": 500, "message": e.message})
def signout_mobile(): userid = request.json['userid'] session.clear() User.update({"userid": userid}, {"$set" :{"device_token": "", "version": "", "os": ""}}) return 'success'
def emailverifyhash(hashvalue): getuserdata = User.find_one({"emailhash" : hashvalue, "emailverified" :False}, {"_id" :0}) if getuserdata is not None: User.update({"emailhash" : hashvalue} ,{"$set" :{"emailverified" :True, "updateddatetime" : datetime.now()}}) return render_template("sample.html") else: return jsonify({"status" :200 ,"message" :"Email already Verified."})
def forgotpasswordhash(hashvalue): userid = "" token = "" getuserdata = list( User.find( { "$and": [{ "forgotpasswordJSON.forgotpasswordhash": hashvalue }, { "forgotpasswordJSON.forgotpassworduseddatetime": -1 }] }, {"_id": 0})) if len(getuserdata) == 1: for userdata in getuserdata: forgotpassworduseddatetime = datetime.now() User.update( { "userid": userdata['userid'], "forgotpasswordJSON.forgotpasswordhash": hashvalue }, { "$set": { "forgotpasswordJSON.$.forgotpassworduseddatetime": forgotpassworduseddatetime } }) userid = userdata['userid'] token = userdata['token'] return render_template("front_saveonjobs/forgot_password.html", userid=userid, token=token) else: return jsonify({"status": 200, "message": "URL not found."})
def bank_update(): try: userid = int(request.json['userid']) user_details = User.find_one({"userid": userid}, {"_id": 0}) bank_details = [] if user_details: User.update({"userid": userid}, {"$set": { "paypal_id": request.json['paypal_id'] }}) bank_details = User.find_one({"userid": userid}, { "_id": 0, "paypal_id": 1 }) return make_response( jsonify({ "status": 402, "message": "User not Connected", "bank_details": bank_details }), 200) except Exception as e: return make_response( jsonify({ "status": 500, "message": "Something went wrong, Please try again!" }), 500)
def reportuser(): userid = int(request.json['userid']) token = request.json['token'] touserid = int(request.json['touserid']) userreportedJSON = [] if (userid != None) and (token != None) and (touserid != None): userData = User.find_one({"userid": touserid}, {"_id": 0}) if userData is not None: userreportedJSON = userreportedJSON + userData['reportedJSON'] newReportedJSON = { "reportid": CommonUtils.generateRandomNo(Report, "reportid"), "byuserid": userid, "reportresolved": False, "reporteddatetime": datetime.now(), "reportresolveddatetime": -1, "active": True } userreportedJSON.append(newReportedJSON) User.update({"userid": touserid}, {"$set": { "reportedJSON": userreportedJSON }}) return jsonify({ "status": 200, "message": "Successfully Report Created." }) else: return jsonify({"status": 400, "message": "No data Recevied"})
def userlogin(): try: email = request.json['email'] password = request.json['password'] if email is not None and password is not None: salt = "" userdata = User.find_one({ "signupJSON.email": email, "isadmin": False, "active": True }) print(userdata) # if userData.count == 0 : # userdata = user.find_one({"signupJSON.mobile":int(email),"isadmin":False,"active":True}) if userdata is not None: salt = userdata['salt'] password = hashlib.md5(password.strip()).hexdigest() + salt print(password) result = User.find_one({"email": email, "password": password}) if result is not None: fullname = result['firstname'] + " " + result['lastname'] session['cookiesUserid'] = int(result['userid']) session['userValid'] = result['salt'] session['cookiesToken'] = str(result['token']) session['city'] = str(result['addressJSON']['city']) session['userloginName'] = fullname session['location'] = str(result['locationid']) session.permanent = True print(session) picPath = URL + imagePath print(request.cookies) return jsonify({ 'status': 200, 'message': 'success', 'userid': result['userid'], 'token': result['token'], 'city': result['addressJSON']['city'], 'location': result['locationid'], "firstname": result['firstname'], "lastname": result['lastname'], "picurl": result['picurl'], "picPath": picPath }) else: return jsonify({ 'status': 201, 'message': 'Invalid username and Password.' }) else: return jsonify({'status': 202, 'message': 'Invalid username.'}) else: return jsonify({ 'status': 203, 'message': "Email or Password not be null." }) except Exception as e: return jsonify({"status": 500, "message": "error"})
def verify_mobile_otp(): userid = int(request.json['userid']) token = request.json['token'] findUser = User.find_one({ "userid": userid, "token": token, "mobile": str(request.json['mobile']), "mobileotp": int(request.json['mobileotp']), "isdcode": int(request.json['isdcode']), "mobileverified": False, "active": True }) if findUser is not None: result = User.update( { "userid": userid, "token": token, "mobile": str(request.json['mobile']) }, {"$set": { "mobileverified": True, "proJSON.mobileverified": True }}) sendText = "Your Mobile Number is registered to SAVEonJOBS." full_mobile_number = "+" + str(request.json['isdcode']) + str( request.json['mobile']) message = msgclient.messages.create(body=sendText, to=full_mobile_number, from_=Constants.MSG_SEND_FROM) print(message.sid) MessageTracks.insert({ "messagetrackid": CommonUtils.generateRandomNo(MessageTracks, "messagetrackid"), "userid": userid, "mobile": full_mobile_number, "messagetext": sendText, "messagesid": message.sid, "createdatetime": datetime.now(), "updatedatetime": datetime.now() }) userdata = list(User.find({"userid": userid}, {"_id": 0})) return jsonify({ 'status': 200, 'message': 'Verify Successfully.', "userdata": userdata }) else: return jsonify({ 'status': 201, 'message': "OTP and Mobile Number doesn't match." })
def verify_email(): #Check authentications keys userid = int(request.json['userid']) token = request.json['token'] email = request.json['email'] findUser = User.find_one({ "userid": userid, "token": token, "email": request.json['email'], "active": True }) if findUser is not None: emailhash = CommonUtils.getHashValue() result = User.update( { "userid": userid, "token": token, "email": request.json['email'] }, {"$set": { "emailhash": emailhash }}) # Send email verification reset_password_link = str(URL) + "emailverify__" + str(emailhash) subject = "Your SAVEonJOBS.comAccount Email Verification" msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[email]) msg.html = render_template( '/emailTemplates/email_verification_template.html', name=findUser['firstname'], resetLink=reset_password_link, email=email) Mail.send(msg) EmailTracks.insert({ "emailtrackid": CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"), "userid": userid, "email": request.json['email'], "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now() }) return jsonify({'status': 200, 'message': 'Send Successfully.'}) else: return jsonify({'status': 201, 'message': "Email doesn't match."})
def save_token(): userid = int(request.json['userid']) token = request.json['token'] devicetoken = request.json['devicetoken'] version = request.json['version'] os = request.json['os'] User.update( {"userid": userid}, {"$set": { "device_token": devicetoken, "version": version, "os": os }}) return jsonify({"status": 200, "message": "Successfully updated."})
def notify_bid_reverse(cls, userid, jobid, bidid, job_collection, bidderfullname, job_bid_detail): notificationtext = "You reverse bid on the job title " + job_collection[ 'title'] + " for bidder : " + str(bidderfullname) from jobwork.models.user import User registration_id = User.find_FCM_id(job_bid_detail['userid']) if registration_id: data_message = { "body": notificationtext, } push_service.notify_single_device(registration_id=registration_id, message_title="Reverse Bid", message_body=notificationtext, data_message=data_message) from jobwork.models.notification import Notifications Notifications.insert({ "notificationid": CommonUtils.generateRandomNo(Notifications, "notificationid"), "notificationtext": notificationtext, "notificationtype": "Bid", "notificationtouserid": int(job_bid_detail['userid']), "notificationfromuserid": userid, "jobid": int(jobid), "jobbidid": int(bidid), "commentid": -1, "createddatetime": datetime.datetime.now(), "updatedatetime": datetime.datetime.now(), "isread": False })
def notify_bid_accepted(cls, userid, jobid, bidid, job_collection, jobberfullname, final_bid): notificationtext = "Your Bid on job title '" + job_collection[ 'title'] + "' is accepted by Jobber : " + jobberfullname from jobwork.models.user import User registration_id = User.find_FCM_id(final_bid['userid']) if registration_id: data_message = { "body": notificationtext, } push_service.notify_single_device(registration_id=registration_id, message_title="Bid Accepted", message_body=notificationtext, data_message=data_message) # Notification entry from jobwork.models.notification import Notifications Notifications.insert({ "notificationid": CommonUtils.generateRandomNo(Notifications, "notificationid"), "notificationtext": notificationtext, "notificationtype": "Bid", "notificationtouserid": int(final_bid['userid']), "notificationfromuserid": userid, "jobid": int(jobid), "jobbidid": int(bidid), "commentid": -1, "createddatetime": datetime.datetime.now(), "updatedatetime": datetime.datetime.now(), "isread": False })
def job_comment_list(): # Check authentications keys response = [] jobid = int(request.json['jobid']) jobCommentsList = db.jobcomments.find({ "jobid": jobid, "active": True }, {"_id": 0}) job = Jobs.find_one({"jobid": jobid}) jobowner = job['creatinguserid'] for data in jobCommentsList: userId = User.find_one({"userid": data['userid']}) username = userId['firstname'] + " " + userId['lastname'] data.update({"username": username}) if (data['userid'] == jobowner): data.update({"jobowner": True}) else: data.update({"jobowner": False}) response.append(data) if len(response) != 0: return jsonify({ "status": 200, "message": "Job Comments List.", "jobCommentsList": response, "error": False }) else: return jsonify({ "status": 200, "message": "Job Comments List empty", "jobCommentsList": [], "error": True })
def emailverifyhash(hashvalue): getuserdata = User.find_one( { "emailhash": hashvalue, "emailverified": False }, {"_id": 0}) if getuserdata is not None: User.update({"emailhash": hashvalue}, { "$set": { "emailverified": True, "updateddatetime": datetime.now() } }) # userid = getuserdata['userid'] # token = getuserdata['token'] return render_template("front_saveonjobs/email_verify.html") else: return jsonify({"status": 200, "message": "Email already Verified."})
def delUser(): email = request.json['email'] result = User.find_one({"email": email}) if result is not None: db.user.remove({"email": email}) return jsonify({"status": 200, "msg": "account deleted!"}) else: return jsonify({"status": 201, "msg": "not found!"})
def find_FCM_id(userid): try: result = User.find_one({"userid": int(userid)}) if "device_token" in result: return result['device_token'] else: return False except Exception as e: raise e
def decorated_function(*args, **kwargs): if request.json.get('userid', False) == False or request.json.get('token', False) == False: return make_response(jsonify({"status": 400, "message": "1 Authentication keys are missing."}), 400) userid = int(request.json['userid']) token = request.json['token'] result = User.find_one({"userid": int(userid), "token": str(token)}) if not result: return make_response(jsonify({"status": 401, "message": " No mach found.","error":True,"response":[]}), 401) else: return f(*args, **kwargs)
def user_forgotpassword_email(): try: email = request.json['email'] if email is not None: getuserdata = User.find_one({"email": email, "active": True}, {"_id": 0}) # data = user.find_one({"$or" : {"email" : email},{"mobile" : mobile}}) addforgotpasswordJSON = [] if getuserdata is not None: oldJSON = getuserdata['forgotpasswordJSON'] forgotpassworduseddatetime = -1 forgopassworddatetime = datetime.now() forgotpasswordhash = CommonUtils.getHashValue() addforgotpasswordJSON = addforgotpasswordJSON + oldJSON addforgotpasswordJSON.append({"forgopassworddatetime": forgopassworddatetime, "forgotpasswordhash": forgotpasswordhash, "forgotpassworduseddatetime": forgotpassworduseddatetime }) User.update({"email": email}, {"$set": {"forgotpasswordJSON": addforgotpasswordJSON}}) reset_password_link = str(URL) + "forgotpassword__" + str(forgotpasswordhash) subject = "Your SAVEonJOBS Password" msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[email]) msg.html = render_template('/emailTemplates/Reset_password_template.html', name=getuserdata['firstname'], resetLink=reset_password_link) mail.send(msg) EmailTracks.insert( {"emailtrackid": CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"), "userid": getuserdata['userid'], "email": email, "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now()}) return jsonify({"status": 200, "message": "Successfully mail sent."}) else: return jsonify({"status": 200, "message": "No data."}) else: return jsonify({"status": 200, "message": "email not found."}) except Exception as e: print(e) return jsonify({"status": 500, "message": "error"})
def userDataResponse(emailhash): #return jsonify({"ok": "k"}) user = list(User.find({"emailhash": emailhash}, {"_id": 0})) response = dict() if len(user) != 0: response.update({'userid': user[0]['userid']}) response.update({'firstname': user[0]['firstname']}) response.update({'lastname': user[0]['lastname']}) response.update({'gender': user[0]['gender']}) #response.update({'addressJSON': user[0]['addressJSON']}) response.update({'registeredfrom': user[0]['registeredfrom']}) response.update({'email': user[0]['email']}) response.update({'picurl': user[0]['picurl']}) response.update({'token': user[0]['token']}) if user[0]['addressJSON']['city'] != '': city = list( db.city.find({"cityid": user[0]['addressJSON']['city']}, {"_id": 0})) response.update({"city": city[0]['city']}) else: response.update({"city": ""}) if user[0]['addressJSON']['state'] != '': state = list( db.state.find({"stateid": user[0]['addressJSON']['state']}, {"_id": 0})) response.update({"state": state[0]['state']}) else: response.update({"state": ""}) if user[0]['addressJSON']['country'] != '': country = list( db.country.find( {"countryid": user[0]['addressJSON']['country']}, {"_id": 0})) response.update({"country": country[0]['country']}) else: response.update({"country": ""}) #return response response.update({'address1': user[0]['addressJSON']['address1']}) response.update({'address2': user[0]['addressJSON']['address2']}) response.update({'pincode': user[0]['addressJSON']['pincode']}) response.update({'registeredfrom': user[0]['registeredfrom']}) response.update({'emailverified': user[0]['emailverified']}) return response else: return response
def reportData(): try: by_userid = request.json['userid'] to_userid = request.json['to_userid'] token = request.json['token'] reporteddatetime = datetime.now() reportresolved = False reportresolveddatetime = datetime.now() temp = [] temp.append({"by_userid": by_userid}) temp.append({"reportresolved": reportresolved}) temp.append({"reporteddatetime": reporteddatetime}) temp.append({"reportresolveddatetime": reportresolveddatetime}) User.update({"userid": to_userid}, {"$set": {"reportedJSON": temp}}) return jsonify({ "status": 200, "message": "Successfully Report Created." }) except Exception as e: return jsonify({"status": 500, "message": e.message})
def bank_fetch(): try: userid = int(request.json['userid']) response = User.find_one({"userid": userid}, { "_id": 0, "paypal_id": 1 }) # response = User.find_one({"userid": userid}, {"_id": 0}) return make_response( jsonify({ "bank_details": response, "status": 200 }), 200) except Exception as e: print(e) return make_response( jsonify({ "status": 500, "message": "Something went wrong, Please try again!" }), 500)
def notification_list(): URL = Constants.URL imagePath = Constants.IMAGE_PATH userid = int(request.json['userid']) token = request.json['token'] notificationArray = [] notificationData = list( Notifications.find({ "notificationtouserid": userid }, { "_id": 0 }).sort("createddatetime", -1)) notificationUnread = list( Notifications.find({ "notificationtouserid": userid, "isread": False }, {"_id": 0})) print(notificationData) if len(notificationData) > 0: for collections in notificationData: jobber = {} if collections['notificationfromuserid'] != -1: jobber = Jobs.find_one({"jobid": int(collections['jobid'])}, { "_id": 0, "creatinguserid": 1 }) userData = User.find_one( {"userid": int(collections['notificationfromuserid'])}, {"_id": 0}) if userData is not None: fullname = userData['firstname'] + " " + userData[ 'lastname'] if userData['picurl'] != "": picurl = URL + imagePath + userData['picurl'] else: picurl = URL + imagePath + "user-no-image.jpg" if userData['addressJSON']['city'] != "": cityNamedata = CityCollections.find_one( {"cityid": userData['addressJSON']['city']}, { "_id": 0, "city": 1 }) cityName = cityNamedata['city'] else: cityName = "" else: fullname = "" picurl = URL + imagePath + "user-no-image.jpg" cityName = "" else: fullname = "SAVEonJOBS" picurl = URL + "static/front_end/images/logo1.png" cityName = "" userDataCollection = { "fullname": fullname, "cityname": cityName, "picurl": picurl, "jobber": jobber } collections.update(userDataCollection) notificationArray.append(collections) return jsonify({ "status": 200, "message": "Notification Data.", "notificationArray": notificationArray, "notificationUnread": len(notificationUnread) }) else: return jsonify({ "status": 200, "message": "No Notification data Found.", "notificationArray": [], "notificationUnread": notificationUnread })
def get_or_create_user(user_data, user_type, facebook_token): email = user_data.get("email", "") if email: is_user_exists = User.count({"signupJSON.email": email}) if is_user_exists == 0: mobile, mobileotp = "", "" # emailhash = send_email(email) emailhash = CommonUtils.getHashValue() firstname = user_data.get('first_name', "") lastname = user_data.get('last_name', "") usertype = user_type city, location, device_token = "", "", "" fullname = user_data.get("name", "") password = CommonUtils.generateRandomName() if fullname and usertype: salt = CommonUtils.generateRandomName() # random.randrange(1000, 9999) signupJSON = SignupUtils.get_signup_json(email, fbid=user_data.get("id", ""), fbaccesstoken=facebook_token) addressJSON = SignupUtils.get_user_address_json(city) proJSON = SignupUtils.get_pro_json() paymentdetailsJSON = SignupUtils.get_payment_detail_json() if password: password = CommonUtils.password_hash(password, salt) token = request.json.get('token', "") userid = request.json.get('userid', "") if not userid: userid = CommonUtils.generateRandomNo(User, "userid") if not token: token = CommonUtils.generateRandomName() User.insert({ "userid": userid, "email": email, "mobile": mobile, "mobileotp": str(mobileotp), "emailhash": emailhash, "password": password, "salt": salt, "token": token, "usertype": usertype, "firstname": firstname, "lastname": lastname, "device_token": device_token, "signupJSON": signupJSON, "emailverified": False, "mobileverified": False, "isdcode": None, "fbid": "", "fbaccesstoken": "", "isadmin": False, "createddatetime": datetime.datetime.now(), "updateddatetime": datetime.datetime.now(), "addressJSON": addressJSON, "paymentdetailsJSON": paymentdetailsJSON, "skillsJSON": [], "languagesJSON": [], "educationCSV": [], "workplaceCSV": [], "certificateJSON": [], "proJSON": proJSON, "forgotpasswordJSON": [], "gender": "", "dob": "", "locationid": location, "aboutme": "", "picurl": "user-no-image.jpg", "reportedJSON": [], "notificationJSON": [], "socaillogin": False, "facebookpicurl": "", "active": True, "paypal_id": "" }) session['cookiesUserid'] = int(userid) session['userValid'] = str(salt) session['cookiesToken'] = str(token) session['city'] = str(city) session['userloginName'] = str(fullname) session['location'] = str(location) session.permanent = True # Onboard Push notification PushNotificationUtils.notify_onboard(userid, fullname, device_token) # Onboard Email EmailUtils.send_onboard_email(userid, email, emailhash, firstname) return { 'status': 200, 'message': 'Successfull Register', 'userid': userid, 'token': token, 'city': city, 'location': location, "firstname": firstname, "lastname": lastname, "picurl": "user-no-image.jpg", "picPath": Constants.PROFIL_PIC_STATIC_PATH } else: return {'status': 400, 'message': 'Data can not be null.'} else: user = User.find_one({"email": email}, {"_id": 0, "userid": 1, "token": 1, "city": 1, "location": 1, "firstname": 1, "lastname": 1, "picurl": 1, "picPath": Constants.PROFIL_PIC_STATIC_PATH}) return { 'status': 200, 'message': 'Successfull Register', }.update(user) else: return {'status': 202, 'message': 'Data can not be null.'}
def register(): try: firstname = request.json['fname'] lastname = request.json['lname'] email = request.json['email'] regtype = int(request.json['regtype']) mobile = request.json['mobile'] cityid = request.json['city'] skill = request.json['skill'] stateid = request.json['state'] countryid = request.json['country'] picurl = request.json['picurl'] gender = request.json['gender'] locationid = request.json['locationid'] if locationid != "": locationid = int(locationid) if picurl == '': picurl = "default-image.jpg" ''' if city!="": citylist=db.city.find_one({"city":city},{"_id":0,"cityid":1}) cityid=citylist['cityid'] else: cityid="" if state!="": statelist=db.state.find_one({"state":state},{"_id":0,"stateid":1}) stateid=statelist['stateid'] else: stateid="" if country!="": countrylist=db.country.find_one({"country":country},{"_id":0,"countryid":1}) countryid=countrylist['countryid'] else: countryid="" ''' addressJSON = { "address1": request.json['address1'], "address2": request.json['address2'], "city": cityid, "state": stateid, "country": countryid, "pincode": request.json['pincode'] } salt = CommonUtils.generateRandomName() emailhash = CommonUtils.getHashValue() token = CommonUtils.generateRandomName() if regtype == 0: password = request.json['password'] password = CommonUtils.password_hash(password, salt) sociallogin = False emailverified = False fbid = "" fbaccesstoken = "" registeredfrom = "jobwork" else: password = "" sociallogin = True emailverified = True fbid = request.json['fbid'] fbaccesstoken = request.json['fbaccesstoken'] if regtype == 1: registeredfrom = "facebook" elif regtype == 2: registeredfrom = "gmail" #return jsonify({"ok":1}) userdata = list(User.find({"email": email}, {"_id": 0})) if User.count({"email": email}) == 0: userid = CommonUtils.generateRandomNo(User, "userid") User.insert({ "userid": userid, "signupJSON": "", "email": email, "emailverified": emailverified, "emailhash": emailhash, "mobile": mobile, "mobileverified": False, "mobileotp": "", "isdcode": None, "fbid": fbid, "fbaccesstoken": fbaccesstoken, "password": password, "salt": salt, "token": token, "firstname": firstname, "lastname": lastname, "isadmin": False, "createddatetime": datetime.now(), "updateddatetime": datetime.now(), "addressJSON": addressJSON, "paymentdetailsJSON": [], "skillsJSON": skill, "languagesJSON": [], "educationCSV": [], "workplaceCSV": [], "certificateJSON": [], "proJSON": [], "forgotpasswordJSON": [], "gender": gender, "dob": "", "locationid": locationid, "aboutme": "", "picurl": picurl, "reportedJSON": [], "notificationJSON": [], "socaillogin": sociallogin, "facebookpicurl": "", "active": True, "paypal_id": "", "registeredfrom": registeredfrom }) if regtype != 0: response = userDataResponse(email) # user = list(User.find({"email": email}, {"_id": 0})) return jsonify({ "status": 200, "response": response, "message": "", "error": False, "registedfrom": registeredfrom }) else: emailhash = CommonUtils.getHashValue() result = User.update( { "userid": userid, "token": token, "email": request.json['email'] }, {"$set": { "emailhash": emailhash }}) # Send email verification reset_password_link = str(URL) + "emailverify/" + str( emailhash) subject = "Your jobwork.io Account Email Verification" msg = Message(subject, sender=("JobWork", "*****@*****.**"), recipients=[email]) msg.html = render_template( '/emailTemplates/email_verification_template.html', name=firstname, resetLink=reset_password_link, email=email) mail.send(msg) EmailTracks.insert({ "emailtrackid": CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"), "userid": userid, "email": request.json['email'], "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now() }) return jsonify({ "status": 200, "response": {}, "message": "verification mail sent", "error": True, "registedfrom": registeredfrom }) elif userdata[0]['emailverified'] == False: emailhash = CommonUtils.getHashValue() userid = CommonUtils.generateRandomNo(User, "userid") db.user.remove({"email": email}) User.insert({ "userid": userid, "signupJSON": "", "email": email, "emailverified": emailverified, "emailhash": emailhash, "mobile": mobile, "mobileverified": False, "mobileotp": "", "isdcode": None, "fbid": fbid, "fbaccesstoken": fbaccesstoken, "password": password, "salt": salt, "token": token, "firstname": firstname, "lastname": lastname, "isadmin": False, "createddatetime": datetime.now(), "updateddatetime": datetime.now(), "addressJSON": addressJSON, "paymentdetailsJSON": [], "skillsJSON": skill, "languagesJSON": [], "educationCSV": [], "workplaceCSV": [], "certificateJSON": [], "proJSON": [], "forgotpasswordJSON": [], "gender": gender, "dob": "", "locationid": locationid, "aboutme": "", "picurl": picurl, "reportedJSON": [], "notificationJSON": [], "socaillogin": sociallogin, "facebookpicurl": "", "active": True, "paypal_id": "", "registeredfrom": registeredfrom }) if regtype != 0: response = userDataResponse(email) return jsonify({ "status": 200, "response": response, "message": "existed now updated", "error": False, "registedfrom": registeredfrom }) else: emailhash = CommonUtils.getHashValue() result = User.update( { "userid": userid, "token": token, "email": request.json['email'] }, {"$set": { "emailhash": emailhash }}) # Send email verification reset_password_link = str(URL) + "emailverify/" + str( emailhash) subject = "Your jobwork.io Account Email Verification" msg = Message(subject, sender=("JobWork", "*****@*****.**"), recipients=[email]) msg.html = render_template( '/emailTemplates/email_verification_template.html', name=firstname, resetLink=reset_password_link, email=email) mail.send(msg) EmailTracks.insert({ "emailtrackid": CommonUtils.generateRandomNo(EmailTracks, "emailtrackid"), "userid": userid, "email": request.json['email'], "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now() }) return jsonify({ "status": 200, "response": {}, "message": "mail id exist but not verified yet verification mail sent", "error": True, "registedfrom": registeredfrom }) elif regtype != 0: verify = False user = list(User.find({"email": email}, {"_id": 0})) if regtype == 1 and user[0]['registeredfrom'] == "facebook": verify = True elif regtype == 2 and user[0]['registeredfrom'] == "gmail": verify = True else: message = "account already registered from " + user[0][ 'registeredfrom'] return jsonify({ "status": 200, "messsage": message, "registedfrom": user[0]['registeredfrom'], "response": {}, "error": True }) #user = list(User.find({"email": email}, {"_id": 0})) if verify == True: #print(userdata[0]['cityname'][0]) response = userDataResponse(email) print((response)) return jsonify({ "status": 200, "response": response, "message": "", "error": False, "registedfrom": user[0]['registeredfrom'] }) else: return jsonify({ "status": 200, "messsage": "email id already used", "response": {}, "error": True, "registedfrom": userdata[0]['registeredfrom'] }) except Exception as e: return json.dumps(e, indent=4, default=json_util.default)
def job_bid_create(): userid = request.json['userid'] userInfo = User.find_one({"userid": int(userid)}, {"_id": 0}) if userInfo is not None: if userInfo['emailverified'] is False: return jsonify({ "status": 202, "message": "Email not verified. Please verify your email to bid" }) jobCollection = Jobs.find_one( { "jobid": int(request.json['jobid']), "active": True }, {"_id": 0}) #if jobCollection['personsselected'] >= jobCollection['personsrequired']: # return jsonify({"status": 203, "message": "Jobber's requirement has already been fulfilled"}) jobberUser = User.find_one({"userid": jobCollection['creatinguserid']}, {"_id": 0}) userCollection = User.find_one({"userid": userid}, {"_id": 0}) if userCollection is not None: fullname = userCollection['firstname'] + " " + userCollection[ 'lastname'] bidderEmail = userCollection['email'] else: fullname = "" bidderEmail = None if jobberUser is not None: jobberfullname = jobberUser['firstname'] + " " + jobberUser['lastname'] jobberEmail = jobberUser['email'] else: jobberfullname = None jobberEmail = None if jobCollection is not None: if request.json['bidid'] == "": check_status = JobBids.find( { "jobid": int(request.json['jobid']), "userid": userid, "active": True }, {"_id": 0}) if check_status.count() == 0: reverseBidData = { "reversebidamount": None, "reversebiddatetime": None } bidid = CommonUtils.generateRandomNo(JobBids, "bidid") JobBids.insert({ "jobid": int(request.json['jobid']), "bidid": bidid, "userid": userid, "selected": False, "bidamount": float(request.json['bidamount']), "finalbidamount": None, "bidcomment": request.json['bidcomment'], "createdatetime": datetime.now(), "bidcanceldatetime": "", "bidcancellationreason": "", "status": "pending", "reversebid": reverseBidData, "completionstatus": "pending", "completionremarks": "", "active": True }) notificationtext = "Your job title " + jobCollection[ 'title'] + " is bid by : " + fullname '''registration_id = find_FCM_id(jobCollection['creatinguserid']) if (registration_id): data_message = { "body": notificationtext, } result = push_service.notify_single_device(registration_id=registration_id, message_title="New Bid", message_body=notificationtext, data_message=data_message, click_action="FCM_PLUGIN_ACTIVITY")''' Notifications.insert({ "notificationid": CommonUtils.generateRandomNo(Notifications, "notificationid"), "notificationtext": notificationtext, "notificationtype": "Bid", "notificationtouserid": int(jobCollection['creatinguserid']), "notificationfromuserid": userid, "jobid": jobCollection['jobid'], "bidid": bidid, "commentid": -1, "createddatetime": datetime.now(), "updatedatetime": datetime.now(), "isread": False }) ''' # Sending Email if jobberEmail is not None: subject = "Bid Created." msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[jobberEmail]) msg.html = render_template('/emailTemplates/bid-receive.html', name=jobberfullname, title=str(jobCollection['title']), bidder=fullname, amount=int(request.json['bidamount'])) mail.send(msg) emailtracks.insert({"emailtrackid": generateRandomNo(emailtracks, "emailtrackid"), "userid": int(jobCollection['creatinguserid']), "email": jobberEmail, "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now()}) else: print "No email of jobber." ''' new_bid = list(JobBids.find({"bidid": bidid}, {"_id": 0})) return jsonify({ "status": 200, "message": "Successfully created.", "response": new_bid, "error": False }) else: new_bid = list( JobBids.find({"bidid": check_status['bidid']}, {"_id": 0})) return jsonify({ "status": 200, "message": "bid status intercepted.", "bidUpdate": new_bid }) else: job_bid_detail = JobBids.find_one( {"bidid": int(request.json['bidid'])}, {"_id": 0}) if job_bid_detail is not None: if job_bid_detail['status'] == 'pending': finalbidamount = float(request.json['reversebid']) # updating bidamount array and reverse bid array reverseBidData = { "reversebidamount": request.json['reversebid'], "reversebiddatetime": datetime.now() } JobBids.update({"bidid": int(request.json['bidid'])}, { "$set": { "status": "reversebid", "bidcomment": request.json['bidcomment'], "reversebid": reverseBidData, "finalbidamount": finalbidamount } }) commission = float(finalbidamount * 0.1) finalbidamount = float(finalbidamount - commission) Ledgers.insert({ "userid": userid, "ledgerid": CommonUtils.generateRandomNo(Ledgers, "ledgerid"), "amount": float(finalbidamount), "datetime": datetime.now(), "type": "escrow", "jobid": int(jobCollection['jobid']), "paymentdetailsJSON": "", "refundinitateddatetime": "", "refunddetailsJSON": "", "refundcompletiondatetime": "", "payingdatetime": "", "remark": "", "active": True }) Ledgers.insert({ "userid": userid, "ledgerid": CommonUtils.generateRandomNo(Ledgers, "ledgerid"), "amount": float(commission), "datetime": datetime.now(), "type": "commission", "jobid": int(jobCollection['jobid']), "paymentdetailsJSON": datetime.now(), "refundinitateddatetime": "", "refunddetailsJSON": "", "refundcompletiondatetime": "", "active": True }) notificationtext = "Jobber reverse bid on the job title " + jobCollection[ 'title'] + " for bidder : " + fullname '''registration_id = find_FCM_id(job_bid_detail['userid']) if (registration_id): data_message = { "body": notificationtext, } result = push_service.notify_single_device(registration_id=registration_id, message_title="Reverse Bid", message_body=notificationtext, data_message=data_message, click_action="FCM_PLUGIN_ACTIVITY")''' Notifications.insert({ "notificationid": CommonUtils.generateRandomNo(Notifications, "notificationid"), "notificationtext": notificationtext, "notificationtype": "Bid", "notificationtouserid": int(job_bid_detail['userid']), "notificationfromuserid": userid, "jobid": jobCollection['jobid'], "bidid": int(request.json['bidid']), "commentid": -1, "createddatetime": datetime.now(), "updatedatetime": datetime.now(), "isread": False }) ''' if bidderEmail is not None: subject = "Reverse Bid on Job." msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[bidderEmail]) msg.html = render_template('/emailTemplates/reverse-bid.html', name=bidderfullname, title=jobCollection['title'], jobber=jobberfullname, amount=int(request.form['payment'])) mail.send(msg) emailtracks.insert({"emailtrackid": generateRandomNo(emailtracks, "emailtrackid"), "userid": finalBid['userid'], "email": bidderEmail, "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now()}) else: print "No email of bidder." ''' update_bid = list( JobBids.find({"bidid": int(request.json['bidid'])}, {"_id": 0})) return jsonify({ "status": 200, "message": "Bid Successfully set.", "response": update_bid, "error": False }) else: update_bid = list( JobBids.find({"bidid": int(request.json['bidid'])}, {"_id": 0})) return jsonify({ "status": 200, "message": "bid update", "Response": update_bid, "error": False }) else: return jsonify({ "status": 200, "message": "Bid not found.", "response": [], "error": True }) else: return jsonify({ "status": 402, "message": "Job Not Found.", "response": [], "error": True })
def paypal_payment(): try: userid = int(request.json['userid']) pay_id = request.json['payid'] print(pay_id) payment = Payment.find(pay_id) print(payment) transactions = [] transaction_amount = {} # credit_card = {} sales_id = 0 soj_transaction_id = 0 transactionstatus = "" # for card_details in payment.payer.funding_instruments: # if card_details.has_key('credit_card_token'): # credit_card = {"expire_year":card_details.credit_card_token.expire_year, # "type":card_details.credit_card_token.type,"number":card_details.credit_card_token.number, # "expire_month":card_details.credit_card_token.expire_month} # elif card_details.has_key('credit_card'): # credit_card = {"expire_year":card_details.credit_card.expire_year, # "type":card_details.credit_card.type,"number":card_details.credit_card.number, # "expire_month":card_details.credit_card.expire_month} # transactions.append(credit_card) for transaction_details in payment.transactions: transaction_amount = {"currency": transaction_details.amount.currency, "total": transaction_details.amount.total} sales_link = transaction_details['related_resources'][0]['sale']['links'][0]['href'] sales_list = sales_link.split('sale')[1] sales_id = sales_list.split('/')[1] soj_transaction_id = int(transaction_details.description) transactionstatus = int(request.json['transactionid']) transactions.append(transaction_amount) payment_details = {"payment": payment.id, "sales_id": sales_id, "paymenttype": payment.payer.payment_method, "state": payment.state, "transaction_details": transactions} if payment.state == "approved": print(soj_transaction_id) TransactionTrack.update({ "transactionid": soj_transaction_id }, { "$set": { "transactionstatus": transactionstatus, "transactionresponse": payment_details, "responsedatetime": datetime.datetime.now() } }) transactions_details_from_database = TransactionTrack.find_one({"transactionid": soj_transaction_id}, {"_id": 0}) print(transactions_details_from_database) bidid = transactions_details_from_database['jobbid'] jobid = transactions_details_from_database['jobid'] final_bid = JobBids.find_one({"bidid": int(bidid)}, {"_id": 0}) completionremarks = "" # completionstatus = "" bidcanceldatetime = "" bidcancellationreason = "" # bidselected = False jobberfullname = "" # jobberEmail = None # jobberMobile = None bidderfullname = "" bidder_email = None # bidderMobile = None person_selected = 0 if final_bid is not None: job_collection = Jobs.find_one({"jobid": final_bid['jobid']}, {"_id": 0}) if job_collection: try: person_selected = int(job_collection['personsselected']) except ValueError: pass user_jobber_collection = User.find_one({"userid": job_collection['creatinguserid']}, {"_id": 0}) if user_jobber_collection is not None: jobberfullname = user_jobber_collection['firstname'] + " " + user_jobber_collection['lastname'] # jobberEmail = user_jobber_collection['email'] # jobberMobile = user_jobber_collection['mobile'] user_bidder_collection = User.find_one({"userid": final_bid['userid']}, {"_id": 0}) if user_bidder_collection is not None: bidderfullname = user_bidder_collection['firstname'] + " " + user_bidder_collection['lastname'] bidder_email = user_bidder_collection['email'] # bidderMobile = user_bidder_collection['mobile'] else: print("No jobs") if request.json['status'] == "selectedbyjobber": if final_bid['status'] == "pending": print(transaction_amount) JobBids.update({ "bidid": int(bidid) }, { "$set": { "selected": True, "final_bidamount": int(float(transaction_amount['total'])), "bidcanceldatetime": bidcanceldatetime, "bidcancellationreason": bidcancellationreason, "status": "selectedbyjobber", "completionstatus": "pending", "completionremarks": completionremarks } }) if job_collection['personsrequired'] > person_selected: if job_collection['personsrequired'] == person_selected + 1: Jobs.update({"jobid": int(jobid)}, {"$set": { "personsselected": int(person_selected + 1), "jobstatus": "allotted" }}) else: Jobs.update({"jobid": int(jobid)}, {"$set": { "personsselected": int(person_selected + 1) }}) # Ledger Entries Ledgers.bid_selection_entries(userid, jobid, bidid, final_bid, payment_details) # Push Notification Bid Accepted PushNotificationUtils.notify_bid_accepted(userid, jobid, bidid, job_collection, jobberfullname, final_bid) # Bid Accepted Email EmailUtils.send_bid_accpeted_mail(final_bid['userid'], bidder_email, job_collection['title'], bidderfullname, jobberfullname, transaction_amount['total']) elif request.json['status'] == "reversebid": job_bid_detail = JobBids.find_one({"bidid": int(bidid)}, {"_id": 0}) if job_bid_detail is not None: if job_bid_detail['status'] == 'pending': total_bid_amount = int(float(transaction_amount['total'])) # updating bidamount array and reverse bid array reverse_bid_data = {"reversebidamount": int(float(transaction_amount['total'])), "reversebiddatetime": datetime.datetime.now()} JobBids.update({"bidid": int(bidid)}, {"$set": {"status": "reversebid", "reversebid": reverse_bid_data, "final_bidamount": total_bid_amount }}) # Bid Reverse Entried Ledgers.bid_reverse_entries(userid, jobid, bidid, final_bid, payment_details) # Bid Reverse Push Notification PushNotificationUtils.notify_bid_reverse(userid, jobid, bidid, job_collection, bidderfullname, job_bid_detail) # Bid Reverse Email EmailUtils.send_reverse_bid_mail(final_bid['userid'], bidder_email, job_collection['title'], bidderfullname, jobberfullname, transaction_amount['total']) return make_response(jsonify({"status": 200, "message": "Payment Successful"}), 200) except ResourceNotFound as e: print("Payment Not Found") print(str(e)) return make_response(jsonify({"status": 500, "message": "Something went wrong, Please try again!"}), 500) except Exception as e: print(str(e)) return make_response(jsonify({"status": 500, "message": "Something went wrong, Please try again!"}), 500)
def job_comment_create(): # Check authentications keys if request.json.has_key('userid') == False or request.json.has_key( 'token') == False: return jsonify({ "status": 401, "message": "Authentication keys are missing." }) userid = int(request.json['userid']) token = request.json['token'] # Authenticate credentials if authentication(userid, token) == False: return jsonify({"status": 400, "message": "Authentication Failed."}) jobData = Jobs.find_one({"jobid": int(request.json['jobid'])}, {"_id": 0}) if jobData is not None: userCollection = User.find_one({"userid": userid}, {"_id": 0}) if userCollection is not None: fullname = userCollection['firstname'] + " " + userCollection[ 'lastname'] if userCollection['picurl'] != "": picurl = URL + imagePath + userCollection['picurl'] else: picurl = URL + imagePath + "user-no-image.jpg" else: fullname = "" commentid = CommonUtils.generateRandomNo(JobComments, "commentid") JobComments.insert({ "commentid": commentid, "jobid": int(request.json['jobid']), "userid": userid, "comment": request.json['comment'], "reportedJSON": [], "createdatetime": datetime.now(), "updatedatetime": datetime.now(), "active": True, "picurl": picurl }) commentData = list( JobComments.find({"jobid": int(request.json['jobid'])}, { "_id": 0, "userid": 1 })) if len(commentData) > 0: userArray = [] for commentCollection in commentData: if commentCollection['userid'] != jobData[ 'creatinguserid'] and commentCollection[ 'userid'] != userid: userArray.append(commentCollection['userid']) userArrayList = list(set(userArray)) if jobData['creatinguserid'] != userid: notificationtext = fullname + " commented on your job - title " + jobData[ 'title'] registration_id = find_FCM_id(jobData['creatinguserid']) if (registration_id): data_message = { "body": notificationtext, } result = push_service.notify_single_device( registration_id=registration_id, message_title="New comment", message_body=notificationtext, data_message=data_message, click_action="FCM_PLUGIN_ACTIVITY") Notifications.insert({ "notificationid": CommonUtils.generateRandomNo(Notifications, "notificationid"), "notificationtext": notificationtext, "notificationtype": "Comment", "notificationtouserid": int(jobData['creatinguserid']), "notificationfromuserid": userid, "jobid": jobData['jobid'], "bidid": -1, "commentid": commentid, "createddatetime": datetime.now(), "updatedatetime": datetime.now(), "isread": False }) else: print("job created userid and userid is same.") for userArrayListData in userArrayList: notificationtext = fullname + " commented on your job - title " + jobData[ 'title'] registration_id = find_FCM_id(userArrayListData) if (registration_id): data_message = { "body": notificationtext, } result = push_service.notify_single_device( registration_id=registration_id, message_title="New Comment", message_body=notificationtext, data_message=data_message, click_action="FCM_PLUGIN_ACTIVITY") Notifications.insert({ "notificationid": CommonUtils.generateRandomNo(Notifications, "notificationid"), "notificationtext": notificationtext, "notificationtype": "Comment", "notificationtouserid": int(userArrayListData), "notificationfromuserid": userid, "jobid": jobData['jobid'], "bidid": -1, "commentid": commentid, "createddatetime": datetime.now(), "updatedatetime": datetime.now(), "isread": False }) else: print("No comment data.") print(commentid) getNewJobComment = list( JobComments.find({"commentid": commentid}, {"_id": 0})) print(getNewJobComment) return jsonify({ "status": 200, "message": "Comments created.", "getNewJobComment": getNewJobComment }) else: return jsonify({ "status": 200, "message": "No Job Found.", "getNewJobComment": [] })
def user_forgotpassword_set(): try: email = request.json['email'] if request.json is not None: if request.json['hashData'] != "" and request.json[ 'email'] != "" and request.json['password'] != "": getuserdata = User.find_one \ ({"forgotpasswordJSON.forgotpasswordhash" : request.json['hashData'] ,"email" :request.json['email']}, {"_id" :0}) if getuserdata is not None: salt = getuserdata['salt'] if request.json['password'].strip() != "": password = hashlib.md5(request.json['password'].strip( )).hexdigest() + salt User.update( { "userid": getuserdata['userid'], "email": request.json['email'] }, {"$set": { "password": password }}) subject = "Your SAVEonJOBS password has changed" msg = Message(subject, sender=("SAVEonJOBS", "*****@*****.**"), recipients=[email]) msg.html = render_template( '/emailTemplates/password_changed.html', name=getuserdata['firstname'] + " " + getuserdata['lastname']) Mail.send(msg) EmailTracks.insert({ "emailtrackid": CommonUtils.generateRandomNo( EmailTracks, "emailtrackid"), "userid": getuserdata['userid'], "email": email, "subject": subject, "emailtext": msg.html, "createdatetime": datetime.now(), "updatedatetime": datetime.now() }) return jsonify({ "status": 200, "message": "Password Successfully changed." }) else: return jsonify({ "status": 402, "message": "No user is found." }) else: return jsonify({"status": 402, "message": "Data is empty."}) else: return jsonify({"status": 402, "message": "No Data."}) except Exception as e: return jsonify({"status": 500, "message": e.message})
def conversation_messages_list(): #return jsonify({"ok": 1}) URL = Constants.URL imagePath = Constants.IMAGE_PATH userid = int(request.json['userid']) allMessageData = [] converstaionCollection = Conversations.find_one({ "conversationid": int(request.json['conversationid']), "active": True }) displayuserCollection = { "displayfullname": "", "displaycityname": "", "displaypicurl": "", "displayuserid": "", "conversationid": int(request.json['conversationid']) } userDisplayData = Conversations.find_one( { "conversationid": int(request.json['conversationid']), "active": True }, { "_id": 0, "userid1": 1, "userid2": 1 }) if userDisplayData is not None: # messages.update({"conversationid":request.json['conversationid']},{"$set":{"isread" : True}}, True, True) messageData = list( Messages.find( { "conversationid": request.json['conversationid'], "isread": False }, {"_id": 0})) if len(messageData) > 0: for messageCollection in messageData: Messages.update( { "createdatetimeinseconds": messageCollection['createdatetimeinseconds'] }, {"$set": { "isread": True }}) else: print("No unread Message.") if userDisplayData['userid1'] != userid: userData = User.find_one({"userid": userDisplayData['userid1']}, {"_id": 0}) if userData is not None: cityName = {} fullname = userData['firstname'] + " " + userData['lastname'] if userData['picurl'] != "": picurl = URL + imagePath + userData['picurl'] else: picurl = URL + imagePath + "user-no-image.jpg" if userData['addressJSON']['city'] != "": cityName = CityCollections.find_one( {"cityid": userData['addressJSON']['city']}, { "_id": 0, "city": 1 }) else: cityName['city'] = "" displayuserCollection = { "displayfullname": fullname, "displaycityname": cityName['city'], "displaypicurl": picurl, "displayuserid": userDisplayData['userid1'], "conversationid": int(request.json['conversationid']) } if userDisplayData['userid2'] != userid: userData = User.find_one({"userid": userDisplayData['userid2']}, {"_id": 0}) if userData is not None: fullname = userData['firstname'] + " " + userData['lastname'] if userData['picurl'] != "": picurl = URL + imagePath + userData['picurl'] else: picurl = URL + imagePath + "user-no-image.jpg" cityName = CityCollections.find_one( {"cityid": userData['addressJSON']['city']}, { "_id": 0, "city": 1 }) displayuserCollection = { "displayfullname": fullname, "displaycityname": cityName['city'], "displaypicurl": picurl, "displayuserid": userDisplayData['userid2'], "conversationid": int(request.json['conversationid']) } else: return jsonify({"status": 402, "message": "No Data."}) if converstaionCollection is not None: messageData = list( Messages.find( { "conversationid": int(request.json['conversationid']) }, { "_id": 0 }).sort("createddatetime", 1)) if len(messageData) > 0: for messageListData in messageData: userData = User.find_one( {"userid": int(messageListData['userid'])}, {"_id": 0}) if userData is not None: fullname = userData['firstname'] + " " + userData[ 'lastname'] if userData['picurl'] != "": picurl = URL + imagePath + userData['picurl'] else: picurl = URL + imagePath + "user-no-image.jpg" cityName = CityCollections.find_one( {"cityid": userData['addressJSON']['city']}, { "_id": 0, "city": 1 }) userDataCollection = { "fullname": fullname, "cityname": cityName['city'], "picurl": picurl } messageListData.update(userDataCollection) allMessageData.append(messageListData) return jsonify({ "status": 200, "message": "Message Data.", "messageListData": allMessageData, "displayuserCollection": displayuserCollection }) else: return jsonify({ "status": 200, "message": "No Message data Found.", "messageListData": [], "displayuserCollection": displayuserCollection }) else: return jsonify({ "status": 200, "message": "No Message data Found.", "messageListData": [], "displayuserCollection": displayuserCollection })
def conversations_list(): userid = int(request.json['userid']) token = request.json['token'] allconversationListData = [] URL = Constants.URL imagePath = Constants.IMAGE_PATH conversationData = list( Conversations.find( { "$or": [{ "userid1": userid }, { "userid2": userid }], "active": True }, { "_id": 0 }).sort("lastdatetime", -1)) if len(conversationData) > 0: for conversationListData in conversationData: messageUnreadCount = Messages.find( { "conversationid": conversationListData['conversationid'], "isread": False }, { "_id": 0 }).count() conversationListData.update( {"messageUnreadCount": messageUnreadCount}) # Users Detail userData1 = User.find_one( {"userid": int(conversationListData['userid1'])}, {"_id": 0}) if userData1 is not None: fullname1 = userData1['firstname'] + " " + userData1['lastname'] cityName1 = {} if userData1['picurl'] != "": picurl1 = URL + imagePath + userData1['picurl'] else: picurl1 = URL + imagePath + "user-no-image.jpg" if userData1['addressJSON']['city'] != "": cityName1 = CityCollections.find_one( {"cityid": userData1['addressJSON']['city']}, { "_id": 0, "city": 1 }) else: cityName1['city'] = "" if conversationListData['userid1'] != userid: lastMessageDetail = { "lastuserfullname": fullname1, "lastusercityname": cityName1['city'], "lastuserpicurl": picurl1 } conversationListData.update(lastMessageDetail) userDataCollection1 = { "fullname1": fullname1, "cityname1": cityName1['city'], "picurl1": picurl1 } conversationListData.update(userDataCollection1) userData2 = User.find_one( {"userid": int(conversationListData['userid2'])}, {"_id": 0}) if userData2 is not None: fullname2 = userData2['firstname'] + " " + userData2['lastname'] cityName2 = {} if userData2['picurl'] != "": picurl2 = URL + imagePath + userData2['picurl'] else: picurl2 = URL + imagePath + "user-no-image.jpg" if userData2['addressJSON']['city'] != "": cityName2 = CityCollections.find_one( {"cityid": userData2['addressJSON']['city']}, { "_id": 0, "city": 1 }) else: cityName2['city'] = "" if conversationListData['userid2'] != userid: lastMessageDetail = { "lastuserfullname": fullname2, "lastusercityname": cityName2['city'], "lastuserpicurl": picurl2 } conversationListData.update(lastMessageDetail) userDataCollection2 = { "fullname2": fullname2, "cityname2": cityName2['city'], "picurl2": picurl2 } conversationListData.update(userDataCollection2) allconversationListData.append(conversationListData) return jsonify({ "status": 200, "message": "Conversation Data.", "conversationListData": allconversationListData }) else: return jsonify({ "status": 200, "message": "No Conversation data Found.", "conversationListData": [] })