def add_user(): user = current_user fmail = request.args.get('umail') plus = request.args.get('plus') if user.mail == fmail: flash('您不能添加自己!') elif Friend.is_friends(user.usrid, fmail): flash('您与 ' + fmail + ' 已是好友,不能重复添加!') else: Friend.add_friends(user.usrid, fmail) flash('添加好友成功!') return redirect('/search_result')
def check_friend(id): current_user = User.get_by_id(get_jwt_identity()) check_friend = User.get_by_id(id) check = Friend.get_or_none(user1_id=current_user.id, user2_id=check_friend.id) check2 = Friend.get_or_none(user1_id=check_friend.id, user2_id=current_user.id) if check or check2: return jsonify({"is_friend": True}) else: return jsonify({"is_friend": False})
def load(): file_path = os.path.join(os.path.dirname(__file__), 'test_data.json') f = open(file_path, 'r') content = f.read().decode('utf8') f.close() data = json.loads(content) users = data['users'] friends = data['friends'] for user in users: pw_md5 = hashlib.md5() pw_md5.update(user['password']) u = User(name=user['name'], password=pw_md5.hexdigest(), head_img_url=user['head_img_url'], last_login_time=datetime.now()) u.insert() for detail in user['user_details']: ud = UserDetail(user_id=u.id, field_name=detail['field_name'], field_value='%s,v' % detail['field_value'], updated_at=datetime.now()) ud.insert() ui = UserIndex(field_name=detail['field_name'], field_value=detail['field_value'], user_id=u.id) ui.insert() for friend in friends: user_id = UserIndex.get_user_id('phone', friend['user_phone']) friend_id = UserIndex.get_user_id('phone', friend['friend_phone']) f = Friend(user_id=user_id, friend_id=friend_id) f.insert() print "u_id: %d, f_id: %d" % (user_id, friend_id) f = Friend(user_id=friend_id, friend_id=user_id) f.insert() print "u_id: %d, f_id: %d" % (friend_id, user_id)
def add_friend_link(): """ Endpoint for adding friend link. Posted body: { "requester_id": int, "requested_id": int, "status": str } :return: """ session = Session() request_body = request.get_json() # Validate post body status = request_body.get('status') if not status or status not in [v.value for v in FriendStatus]: return "Request body needs a status of 'requested', 'accepted', 'ignored' or 'unfriend", 400 request_body['created'] = datetime.utcnow() try: friend = Friend.from_dict(request_body) except KeyError: return jsonify("Object missing required fields."), 400 # Check if friend link is already in the database # Add friend to DB session.add(friend) friend_json = friend.to_json() session.commit() session.close() return friend_json, 200
def build_model_form(username): sql_instance = SQL() results = sql_instance.get_friends(username=username) user_id = sql_instance.get_user_id(username, username) friends = [] for friend in results: friends.append( Friend(username=friend[0], user_id=friend[1], first_name=friend[2], last_name=friend[3])) model_results = sql_instance.get_models_for_user(username=username) models = [] for model in model_results: classification_results = sql_instance.get_all_classifications_for_model( model_id=model[0]) classifications = [] for c in classification_results: orig_path = c[6] print(orig_path) web_path = '../static/img/out/training/' + orig_path.split( '/')[-2] + '/' + orig_path.split('/')[-1] classifications.append( Classification(c[1], c[2], c[3], c[4], c[5], web_path)) models.append( ModelData(model_id=model[0], classifications=classifications, file_path=model[1])) x_vals, y_vals = get_training_data_distribution(username, sql_instance) return ModelsForm(user_id=user_id, friends=friends, models=models, x_vals=x_vals, y_vals=y_vals)
def build_edit_friend_form(home_username, friend_username, review): sql_instance = SQL() result = sql_instance.get_individual_friend( home_username=home_username, friend_username=friend_username) print(result) friend = Friend(username=result[0], user_id=result[1], first_name=result[2], last_name=result[3]) web_img_paths = [] if review: friend_path = os.path.abspath('static/img/out/needs_review/') print(friend_path) image_paths = list(paths.list_images(friend_path)) for image_path in image_paths: file_name = image_path.split('/')[-1] web_path = '../static/img/out/needs_review/' + file_name web_img_paths.append(web_path) print(web_img_paths) else: friend_path = os.path.abspath('static/img/data/' + str(friend.user_id)) print(friend_path) image_paths = list(paths.list_images(friend_path)) for image_path in image_paths: file_name = image_path.split('/')[-1] web_path = '../static/img/data/' + str( friend.user_id) + '/' + file_name web_img_paths.append(web_path) print(web_img_paths) return EditFriendForm(friend=friend, image_paths=web_img_paths)
def generate_friends(session): from faker import Faker import random from models.friend import Friend faker = Faker() profile_ids_available = list(range(1, 5001)) profiles_used = [] for i in range(1, 5001): profile_id = random.choice(profile_ids_available) while profile_id in profiles_used: profile_id = random.choice(profile_ids_available) friend = Friend() friend.friend_id = i friend.profile_id = profile_id session.add(friend) profiles_used.append(profile_id) session.commit()
def get(self): me = self.get_current_user() users = [] fus = Friend.get_friend_users(me.id) for fu in fus: users.append(dict(id=fu.id, name=fu.name, head_img_url=fu.head_img_url)) result = {'success':True, 'users':users} self.write(json.dumps(result))
def show_friend(): current_user = User.get_by_id(get_jwt_identity()) first_selection = Friend.select().where(Friend.user1_id == current_user.id) second_selection = Friend.select().where( Friend.user2_id == current_user.id) results = [] for f in first_selection: user = User.get_by_id(f.user2_id) data = {"name": user.username, "is_online": user.is_online} results.append(data) for s in second_selection: user = User.get_by_id(s.user1_id) data = {"name": user.username, "is_online": user.is_online} results.append(data) return jsonify({"data": results})
def new_friend(): current_user = User.get_by_id(get_jwt_identity()) approve_user = User.get_by_id(request.form.get("id")) friend = Friend(user1_id=current_user.id, user2_id=approve_user.id) if friend.save(): delete = FriendRequest.delete().where( FriendRequest.sender_id == approve_user.id, FriendRequest.recipient_id == current_user.id) delete.execute() return jsonify({ "successful": True, "message": "Friend request has been accepted!" }) else: return jsonify({"error": "Something went wrong!"})
def manage_request(): user = current_user search_info = request.args.get('search_str') if search_info is not None: result = Friend.find_user(search_info) return render_template('search_result.html', user=user, users=result, \ search_str=search_info, total=len(result)) else: return add_user()
def get(self): me = self.get_current_user() users = [] fus = Friend.get_friend_users(me.id) for fu in fus: users.append( dict(id=fu.id, name=fu.name, head_img_url=fu.head_img_url)) result = {'success': True, 'users': users} self.write(json.dumps(result))
def social(): user = Friend.objects(username=session["token"]).first() friends = user.friend friend_post = [] posts = Post.objects() for post in posts: if post.user in friends: friend_post.append(post) return render_template("social.html", posts=friend_post)
def unfollow(): user = Friend.objects(username=session["token"]).first() friend_list = user.friend if request.method == "GET": return render_template("unfollow.html", friends=friend_list) else: form = request.form unf = form["unfollow"] friend_list.remove(unf) user.save() return redirect("/social/unfollow")
def build_friends_form(username): sql_instance = SQL() results = sql_instance.get_friends(username=username) friends = [] for friend in results: friends.append( Friend(username=friend[0], user_id=friend[1], first_name=friend[2], last_name=friend[3])) return FriendsForm(friends=friends)
def list_group(): user = current_user uid = user.usrid friendships = Friend.get_friendship(uid) friends = [] for fs in friendships: if fs.usrid == uid: friends.append(User.get_by(usrid=fs.friendid)) else: friends.append(User.get_by(usrid=fs.usrid)) return render_template('friends.html', user=user, total=len(friends), friends=friends)
def follow(): error = None user = Friend.objects(username=session["token"]).first() friend_list = user.friend if request.method == "GET": return render_template("follow.html", friends=friend_list) else: form = request.form search_friend = form["add_friend"] exist_user = Friend.objects(username=search_friend).first() if exist_user == None: error = "user not found" elif exist_user.username == user.username: error = "cant follow yourself" elif exist_user.username in friend_list: error = "followed before" else: friend_list.append(search_friend) user.save() error = "done" return render_template("follow.html", error=error, friends=friend_list)
def follow(): error = None user = Friend.objects(username=session["token"]).first() friend_list = user.friend if request.method == "GET": return render_template("follow.html", friends=friend_list,name = session["token"],avt=user.avt) else: form = request.form search_friend = form["add_friend"] exist_user = Friend.objects(username=search_friend).first() if exist_user == None: error = "Không tìm thấy người dùng" elif exist_user.username == user.username: error = "Không thể tự theo dõi bản thân" elif exist_user.username in friend_list: error = "Đã theo dõi người dùng trước đó " else: friend_list.append(search_friend) user.save() error = "Thành công" return render_template("follow.html",error=error,friends = friend_list)
def GetHelper(self, msg): helper_conf = GameRule.helper_conf fb_friend_factor = helper_conf.get("facebook_friend_factor") favorite_factor = helper_conf.get("favorite_factor") friend_factor = helper_conf.get("friend_factor") helper_num = helper_conf.get("total_num") player_id = self.parent.pid friend = Friend(player_id=player_id) friends = set(friend.get_friend_list()) favorites = set(friend.get_favorite_list()) fb_friends = set(friend.get_facebook_list()) active_players = set(get_latest_login_players()) normal_p = active_players - friends - fb_friends - set([player_id]) favorites = favorites - fb_friends normal_f = friends - favorites - fb_friends # TODO - Design: filter normal_p players = (list(fb_friends) * fb_friend_factor + list(favorites) * favorite_factor + list(normal_f) * friend_factor + list(normal_p)) _players = set(players) if len(_players) <= helper_num: helper_ids = _players else: helper_ids = set() while len(helper_ids) < helper_num: _ids = random.sample(players, helper_num - len(helper_ids)) helper_ids.update(_ids) rep = GetHelperRep() helpers = [] for pid in helper_ids: h = Helper() player = Player(id=pid).load() player.set_info(h.player_info, simple_mode=True) h.creature.CopyFrom(player.get_help_creature().to_proto_class()) helpers.append(h) rep.helpers.extend(helpers) rep.result_code = GetHelperResultCode.Value("GET_HELPER_SUCCESS") return self.resp(rep)
def sign_up(): if request.method == "GET": return render_template("sign_up.html") else: form = request.form fullname = form["fullname"] username = form["username"] email = form["email"] password = form["password"] confirm = form["confirm"] bday = form["bday"] gender = form["gender"] phone = form["telephone"] existUsername = User.objects(username=username).first() existEmail = User.objects(email=email).first() error = None if fullname == "" or username == "" or email == "" or password == "" or confirm == "" or bday == "" or gender == "" or phone == "": error = "Bạn phải điền đầy đủ thông tin" return render_template("sign_up.html", error=error) elif existUsername is not None: error = "Tên đăng nhập đã tồn tại" return render_template("sign_up.html", error=error) elif len(username) < 8: error = "Tên người dùng không khả dụng" return render_template("sign_up.html", error=error) elif len(password) < 8: error = "Mật khẩu không khả dụng" return render_template("sign_up.html", error=error) elif confirm != password: error = "Rất tiếc. Xác nhận mật khẩu sai" return render_template("sign_up.html", error=error) else: m = User( fullname=fullname, username=username, email=email, password=password, birthday=bday, gender=gender, phone=phone, avt= "https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-512.png" ) m.save() att = Attribute(username=username) att.save() hstr_list = All_history(user=username) hstr_list.save() Friend(username=username).save() return redirect("/sign_in")
def respond_friend_request(json_req, user): status = 0 friend_mobile = json_req['friendMobile'] action = json_req['action'] # True: Accept, False: Reject friend_user = db_session.query(User).filter_by( Mobile=friend_mobile).first() if friend_user: user_id = user.UserID friend_user_id = friend_user.UserID if not (__friendship__(user_id, friend_user_id) or user_id == friend_user_id): friend_request_received = db_session.query( FriendRequest).filter_by(UserID=friend_user_id, FriendUserID=user_id, Deleted=False).first() if friend_request_received: if action: # True: Accept new_friend = Friend(UserID=friend_user_id, FriendUserID=user_id) db_session.add(new_friend) friend_request_received.AcceptanceStatus = action friend_request_received.Deleted = True friend_request_received.RespondOn = datetime.datetime.utcnow() db_session.commit() # FCM Notification data = dict(type=notification_type.FRIEND_REQUEST_RESPOND, acceptanceStatus=action, friendUserID=user_id, friendName=user.Name, friendMobile=user.Mobile, imageURL=images.get_serving_url(user.ImageKey, secure_url=True) if user.ImageKey else None) send_data(friend_user_id, data) status = 1 message = 'success' else: message = 'No such friend request' else: message = 'You are already friend' else: message = 'User with mobile {} doesn\'t exist'.format(friend_mobile) return jsonify(status=status, message=message)
def social(): user = Friend.objects(username=session["token"]).first() us = User.objects(username=session["token"]).first() friends = user.friend friend_post = [] posts = Post.objects() # commentss = [] for post in posts: if post.user in friends or post.user == session["token"]: friend_post.append(post) print(friend_post) # for post in friend_post: # commentss.append(post.comments) if request.method == "GET": return render_template("social.html", posts=friend_post, avt=us.avt, name=session["token"]) else: form = request.form for i in form: if "like" in i: like = form[i] if like != None: for j in range(len(friend_post)): if str(j + 1) in i: p = friend_post[j] print(p.like) if session["token"] not in p.wholike: p.like += 1 p.wholike.append(session["token"]) else: p.like -= 1 p.wholike.remove(session["token"]) else: comments = [] comment = {} comment["contain"] = form[i] comment["owner"] = session["token"] if comment["contain"] != None: for j in range(len(friend_post)): if str(j + 1) in i: p = friend_post[int(j)] p.comments.append(comment) p.save() return redirect(url_for("social"))
def social(): user = Friend.objects(username=session["token"]).first() friends = user.friend friend_post = [] posts = Post.objects() who_like = [] for post in posts: if post.user in friends: friend_post.append(post) if request.method == "GET": return render_template("social.html",posts=friend_post) else: form = request.form print(form) for i in form: if "like" in i: like = form[i] if like != None: for j in range(len(friend_post)): if str(j+1) in i: p = friend_post[j] if session["token"] not in p.wholike: p.like += 1 p.wholike.append(session["token"]) else: p.like -= 1 p.wholike.remove(session["token"]) else: comment = form[i] if comment != None: for j in range(len(friend_post)): if str(j+1) in i: p = friend_post[int(j)] p.comment.append(comment) p.save() return redirect(url_for("social"))
def create_friend(user, team): result = {"error_code": 0, "msg": "ok"} if not team: return {"error_code": 20501, "msg": "team not exist"} f_1 = Friend.select().where(Friend.user == user, Friend.team == team, Friend.ftype == "f").first() if f_1: if f_1.status != "normal": f_1.status = "normal" f_1.save() else: f_1 = Friend() f_1.user = user f_1.team = team f_1.ftype = "f" f_1.save() f_2 = Friend.select().where(Friend.user == user, Friend.team == team, Friend.ftype == "c").first() if f_2: if f_2.status != "normal": f_2.status = "normal" f_2.save() else: f_2 = Friend() f_2.user = user f_2.team = team f_2.ftype = "c" f_2.save() return result
def create_friend(user, team): result = {"error_code":0, "msg":"ok"} if not team: return {"error_code":20501, "msg":"team not exist"} f_1 = Friend.select().where(Friend.user == user, Friend.team == team, Friend.ftype=="f").first() if f_1: if f_1.status != "normal": f_1.status = "normal" f_1.save() else: f_1 = Friend() f_1.user = user f_1.team = team f_1.ftype = "f" f_1.save() f_2 = Friend.select().where(Friend.user == user, Friend.team == team, Friend.ftype=="c").first() if f_2: if f_2.status != "normal": f_2.status = "normal" f_2.save() else: f_2 = Friend() f_2.user = user f_2.team = team f_2.ftype = "c" f_2.save() return result
def all_users(): user = current_user result = Friend.find_user('') return render_template('search_result.html', user=user, users=result)
def GetFriendsInfo(self, msg): friend = Friend(self.parent.pid) resp = friend.get_friends_info() return self.resp(resp)
def break_friendship(): user = current_user fmail = request.args.get('fmail') Friend.del_friends(user.usrid, fmail) flash('好友 ' + fmail + '删除成功!') return redirect('/friends')