Beispiel #1
0
def activity_stream_follow_activity(logged_in_user, following_user):
    # Add this activity to the Activity Stream
    activity_stream_item = ActivityStreamItem(
        activity_context_vocab="https://www.w3.org/ns/activitystreams",
        activity_summary="{} {} started following {} {}".format(
            logged_in_user.name, logged_in_user.surname, following_user.name,
            following_user.surname),
        activity_type="Follow",
        activity_actor_type="Person",
        activity_actor_id=logged_in_user.id,
        activity_actor_name=(logged_in_user.name + " " +
                             logged_in_user.surname),
        activity_actor_image_url=profile_photo_link(
            logged_in_user.profile_photo, logged_in_user.id),
        activity_object_type="Person",
        activity_object_id=following_user.id,
        activity_object_name=following_user.name + " " +
        following_user.surname,
        activity_object_image_url=profile_photo_link(
            following_user.profile_photo, following_user.id))

    try:
        db.session.add(activity_stream_item)  # Creating a new database entry.
        db.session.commit()
    except:
        return make_response(jsonify({'error': 'Database Connection Error'}),
                             500)
Beispiel #2
0
def activity_stream_quit_workspace(user_id, form):
    try:
        current_user = User.query.filter(User.id == user_id).first()
        workspace = Workspace.query.filter(
            Workspace.id == form.workspace_id.data).first()
    except:
        return make_response(jsonify({'error': 'DB connection error'}), 500)

    activity_stream_entry = ActivityStreamItem(
        activity_context_vocab="https://www.w3.org/ns/activitystreams",
        activity_summary="{} {} left {} workspace".format(
            current_user.name, current_user.surname, workspace.title),
        activity_type="Leave",
        activity_actor_type="Person",
        activity_actor_id=current_user.id,
        activity_actor_name=(current_user.name + " " + current_user.surname),
        activity_actor_image_url=profile_photo_link(current_user.profile_photo,
                                                    current_user.id),
        activity_object_type="Group",
        activity_object_name=workspace.title,
        activity_object_id=workspace.id)
    try:
        db.session.add(activity_stream_entry)
        db.session.commit()
    except:
        return make_response(jsonify({'error': 'Database Connection Error'}),
                             500)

    return make_response(
        jsonify({"msg": "You successfully quited from workspace."}), 201)
Beispiel #3
0
def activity_stream_accept_collaboration_application(application):
    try:
        workspace = Workspace.query.filter(
            Workspace.id == application.workspace_id).first()
        current_user = User.query.filter(
            User.id == application.applicant_id).first()
    except:
        return make_response(
            jsonify({"error": "The server is not connected to the database."}),
            500)

    activity_stream_entry = ActivityStreamItem(
        activity_context_vocab="https://www.w3.org/ns/activitystreams",
        activity_summary="{} {} is now a contributor in {} workspace".format(
            current_user.name, current_user.surname, workspace.title),
        activity_type="Join",
        activity_actor_type="Person",
        activity_actor_id=current_user.id,
        activity_actor_name=(current_user.name + " " + current_user.surname),
        activity_actor_image_url=profile_photo_link(current_user.profile_photo,
                                                    current_user.id),
        activity_target_type="Group",
        activity_target_name=workspace.title,
        activity_target_id=workspace.id,
    )
    try:
        db.session.add(activity_stream_entry)
        db.session.commit()
    except:
        return make_response(jsonify({'error': 'Database Connection Error'}),
                             500)
Beispiel #4
0
 def get(requester_id, self):
     # Tries to connect to the database.
     # If it fails, an error is raised.
     try:
         logged_in_user = User.query.filter_by(id=requester_id).first()
         user_job = Jobs.query.filter(
             Jobs.id == logged_in_user.job_id).first()
     except:
         return make_response(
             jsonify(
                 {"error": "The server is not connected to the database."}),
             500)
     else:
         # Checks whether there is an already existing user in the database with the given user ID.
         # If yes, user information is returned.
         # If not, an error is raised.
         if logged_in_user is not None:
             try:
                 notification_status = NotificationStatus.query.get(
                     logged_in_user.id)
             except:
                 return make_response(
                     jsonify({
                         "error":
                         "The server is not connected to the database."
                     }), 500)
             account_information = {
                 "id":
                 logged_in_user.id,
                 "name":
                 logged_in_user.name,
                 "surname":
                 logged_in_user.surname,
                 "is_private":
                 logged_in_user.is_private,
                 "rate":
                 logged_in_user.rate,
                 "profile_photo":
                 profile_photo_link(logged_in_user.profile_photo,
                                    logged_in_user.id),
                 "e_mail":
                 logged_in_user.e_mail,
                 "google_scholar_name":
                 logged_in_user.google_scholar_name,
                 "researchgate_name":
                 logged_in_user.researchgate_name,
                 "job":
                 user_job.name,
                 "institution":
                 logged_in_user.institution,
                 "is_email_allowed":
                 notification_status.is_email_allowed,
                 "is_notification_allowed":
                 notification_status.is_notification_allowed
             }
             return make_response(jsonify(account_information), 200)
         else:
             return make_response(
                 jsonify({"error": "The user is not found."}), 404)
Beispiel #5
0
    def get(user_id, self):
        '''
            Returns a list of dictionaries with id, name, surname, e_mail, rate and is_private informations.
        '''
        form = GetFollowersForm(request.args)
        if form.validate():
            try:
                followSearch = Follow.query.filter(
                    Follow.following_id == form.following_id.data).all()
            except:
                return make_response(
                    jsonify({'error': 'Database Connection Error'}), 500)

            if followSearch is []:
                return make_response(jsonify({'error': 'User not found'}), 404)

            follower_users = []
            for follow in followSearch:
                follower_users.append(
                    User.query.filter(User.id == follow.follower_id).first())

            followers_list = [{
                'id':
                follower_user.id,
                'name':
                follower_user.name,
                'surname':
                follower_user.surname,
                'e_mail':
                follower_user.e_mail,
                'rate':
                follower_user.rate,
                'is_private':
                follower_user.is_private,
                'profile_photo':
                profile_photo_link(follower_user.profile_photo,
                                   follower_user.id)
            } for follower_user in follower_users]

            # Pagination functionality
            number_of_pages = 1
            if form.page.data is not None and form.per_page.data is not None:
                per_page = form.per_page.data
                number_of_pages = math.ceil(len(followers_list) / per_page)
                # Assign the page index to the maximum if it exceeds the max index
                page = form.page.data if form.page.data < number_of_pages else number_of_pages - 1
                followers_list = followers_list[page * per_page:(page + 1) *
                                                per_page]
            return make_response(
                jsonify({
                    'number_of_pages': number_of_pages,
                    'followers': followers_list
                }), 200)

        else:
            return make_response(jsonify({'error': 'Input Format Error'}), 400)
Beispiel #6
0
def activity_stream_create_issue(user_id, issue):
    try:
        current_user = User.query.filter(User.id == user_id).first()
    except:
        return make_response(
            jsonify({"error": "The server is not connected to the database."}),
            500)

    try:
        # Activity is added into Activity Stream
        activity_stream_entry = ActivityStreamItem(
            activity_context_vocab="https://www.w3.org/ns/activitystreams",
            activity_summary=
            "{} {} created an issue titled '{}' in the workspace '{}'".format(
                current_user.name, current_user.surname, issue.title,
                get_workspace_title_of_issue(issue)),
            activity_type="Create",
            activity_actor_type="Person",
            activity_actor_id=current_user.id,
            activity_actor_name=(current_user.name + " " +
                                 current_user.surname),
            activity_actor_image_url=profile_photo_link(
                current_user.profile_photo, current_user.id),
            activity_object_type="Note",
            activity_object_name=issue.title,
            activity_object_id=issue.id,
            activity_object_content=issue.description,
            activity_target_type="Group",
            activity_target_id=issue.workspace_id,
            activity_target_name=get_workspace_title_of_issue(issue))
    except:
        return make_response(
            jsonify({
                "error":
                "error happened while creating activity stream entry"
            }), 500)

    try:
        db.session.add(activity_stream_entry)
        db.session.commit()
    except:
        return make_response(jsonify({'error': 'Database Connection Error'}),
                             500)

    return make_response(
        jsonify({
            'msg': 'Issue is successfully created',
            "issue_id": issue.id,
            "workspace_id": issue.workspace_id,
            "title": issue.title,
            "description": issue.description,
            "deadline": issue.deadline,
            "is_open": issue.is_open,
            "creator_id": issue.creator_id
        }), 200)
Beispiel #7
0
def activity_stream_user_comment_activity(user_id, form, comment):
    try:
        current_user = User.query.filter(User.id == user_id).first()
        other_user = User.query.filter(
            User.id == form.commented_user_id.data).first()
    except:
        return make_response(jsonify({'error': 'DB connection error'}), 500)

    activity_stream_entry = ActivityStreamItem(
        activity_context_vocab="https://www.w3.org/ns/activitystreams",
        activity_context_ext='http://schema.org/Rating',
        activity_summary="{} {} commented and rated {} {}".format(
            current_user.name, current_user.surname, other_user.name,
            other_user.surname),
        activity_type="Add",
        activity_actor_type="Person",
        activity_actor_id=current_user.id,
        activity_actor_name=(current_user.name + " " + current_user.surname),
        activity_actor_image_url=profile_photo_link(current_user.profile_photo,
                                                    current_user.id),
        activity_object_type="Note",
        activity_object_name="Comment",
        activity_object_id=comment.id,
        activity_object_content=comment.text,
        activity_object_rating_value=comment.rate,
        activity_target_type="Person",
        activity_target_id=other_user.id,
        activity_target_name=other_user.name + " " + other_user.surname,
        activity_target_image_url=profile_photo_link(other_user.profile_photo,
                                                     other_user.id))
    try:
        db.session.add(activity_stream_entry)
        db.session.commit()
    except:
        return make_response(jsonify({'error': 'Database Connection Error'}),
                             500)
Beispiel #8
0
def activity_stream_delete_folder(user_id, workspace_id, path):
    try:
        current_user = User.query.filter(User.id == user_id).first()
        workspace = Workspace.query.filter(
            Workspace.id == workspace_id).first()
    except:
        return make_response(
            jsonify({"error": "The server is not connected to the database."}),
            500)

    folder_name = path.split("/")[-1]
    try:
        # Activity is added into Activity Stream
        activity_stream_entry = ActivityStreamItem(
            activity_context_vocab="https://www.w3.org/ns/activitystreams",
            activity_summary=
            "{} {} deleted the folder named '{}' in the workspace '{}'".format(
                current_user.name, current_user.surname, folder_name,
                workspace.title),
            activity_type="Create",
            activity_actor_type="Person",
            activity_actor_id=current_user.id,
            activity_actor_name=(current_user.name + " " +
                                 current_user.surname),
            activity_actor_image_url=profile_photo_link(
                current_user.profile_photo, current_user.id),
            activity_object_type="Document",
            activity_object_name=folder_name,
            activity_target_type="Group",
            activity_target_id=workspace.id,
            activity_target_name=workspace.title)
    except:
        return make_response(
            jsonify({
                "error":
                "error happened while creating activity stream entry"
            }), 500)

    try:
        db.session.add(activity_stream_entry)
        db.session.commit()
    except:
        return make_response(jsonify({'error': 'Database Connection Error'}),
                             500)

    return make_response(jsonify({"msg": "Folder is successfully deleted"}),
                         200)
Beispiel #9
0
 def get(user_id, self):
     form = UserForm(request.args)
     if form.validate():
         # Fetch recommendations from database
         try:
             all_recommendations = FollowRecommendationItem.query.filter_by(
                 owner_id=user_id).order_by(
                     FollowRecommendationItem.score.desc()).all()
         except:
             return make_response(
                 jsonify({"error": "Database Connection Error"}), 500)
         # Fetch the user information from database (Also reduce number of them to required number)
         try:
             all_users = [
                 User.query.get(recommendation.recommendation_id)
                 for recommendation in
                 all_recommendations[:form.number_of_recommendations.data]
             ]
         except:
             return make_response(
                 jsonify({"error": "Database Connection Error"}), 500)
         # Create the response format
         try:
             response = [{
                 'id':
                 user.id,
                 'name':
                 user.name,
                 'surname':
                 user.surname,
                 'profile_photo':
                 profile_photo_link(user.profile_photo, user.id),
                 "job":
                 Jobs.query.get(user.job_id).name,
                 "institution":
                 user.institution,
                 "is_private":
                 int(user.is_private)
             } for user in all_users]
         except:
             return make_response(
                 jsonify({"error": "Database Connection Error"}), 500)
         return make_response(jsonify({"recommendation_list": response}),
                              200)
     else:
         return make_response(jsonify({"error": "Input Format Error"}), 400)
Beispiel #10
0
def activity_stream_delete_workspace(requested_workspace, requester_id):
    if not requested_workspace.is_private:
        try:
            current_user = User.query.filter(User.id == requester_id).first()
        except:
            return make_response(
                jsonify(
                    {"error": "The server is not connected to the database."}),
                500)

        # Activity is added into Activity Stream
        activity_stream_entry = ActivityStreamItem(
            activity_context_vocab="https://www.w3.org/ns/activitystreams",
            activity_summary="{} {} deleted the workspace {}".format(
                current_user.name, current_user.surname,
                requested_workspace.title),
            activity_type="Delete",
            activity_actor_type="Person",
            activity_actor_id=current_user.id,
            activity_actor_name=(current_user.name + " " +
                                 current_user.surname),
            activity_actor_image_url=profile_photo_link(
                current_user.profile_photo, current_user.id),
            activity_object_type="Group",
            activity_object_name=requested_workspace.title,
            activity_object_id=requested_workspace.id,
        )
        try:
            db.session.add(activity_stream_entry)
            db.session.commit()
        except:
            return make_response(
                jsonify({'error': 'Database Connection Error'}), 500)

        return make_response(
            jsonify({"message": "Workspace has been successfully deleted."}),
            200)
Beispiel #11
0
    def get(requester_id, self):
        '''
        Returns the profile information of the requested user.
        '''
        # Parses the form data.
        form = GetUserForm(request.args)

        # Checks whether the data is in valid form.
        # If yes, starts processing the data.
        # If not, an error is raised.
        if form.validate():
            # Tries to connect to the database.
            # If it fails, an error is raised.
            try:
                existing_user = User.query.filter_by(
                    id=form.user_id.data).first()
                user_job = Jobs.query.filter(
                    Jobs.id == existing_user.job_id).first()
            except:
                return make_response(
                    jsonify({
                        "error":
                        "The server is not connected to the database."
                    }), 500)
            else:
                # Checks whether there is an already existing user in the database with the given user ID.
                # If yes, user information is returned.
                # If not, an error is raised.
                if existing_user is not None:
                    # Checks whether the requester user follows the requested user or not.
                    if Follow.query.filter_by(follower_id=requester_id,
                                              following_id=form.user_id.data
                                              ).first() is not None:
                        following_status = 1  # Represents that the requester user follows the requested user.
                    elif FollowRequests.query.filter_by(
                            follower_id=requester_id,
                            following_id=form.user_id.data).first(
                            ) is not None:
                        following_status = 0  # Represents that the requester user has already sent a follow request to the requested user and it is pending.
                    else:
                        following_status = -1  # Represents that the requester user does not follow the requested user and has not yet sent a request to follow them.

                    user_job = Jobs.query.filter(
                        Jobs.id == existing_user.job_id).first()
                    try:
                        collaboration = Collaboration.query.filter_by(
                            user_1_id=requester_id,
                            user_2_id=form.user_id.data).first()
                    except:
                        return make_response(
                            jsonify({
                                "error":
                                "The server is not connected to the database."
                            }), 500)
                    account_information = {
                        "id":
                        existing_user.id,
                        "name":
                        existing_user.name,
                        "surname":
                        existing_user.surname,
                        "e_mail":
                        existing_user.e_mail,
                        "is_private":
                        existing_user.is_private,
                        "following_status":
                        following_status,
                        "rate":
                        existing_user.rate,
                        "profile_photo":
                        profile_photo_link(existing_user.profile_photo,
                                           existing_user.id),
                        "google_scholar_name":
                        existing_user.google_scholar_name,
                        "researchgate_name":
                        existing_user.researchgate_name,
                        "job":
                        user_job.name,
                        "institution":
                        existing_user.institution,
                        "can_comment":
                        collaboration is not None
                    }
                    return make_response(jsonify(account_information), 200)
                else:
                    return make_response(
                        jsonify({"error": "The user is not found."}), 404)
        else:
            return make_response(
                jsonify({"error": "Missing data fields or invalid data."}),
                400)
Beispiel #12
0
 def get(user_id, self):
     '''
         Get Comments.
     '''
     form = GetCommentsForm(request.args)
     if form.validate():
         try:
             user_comments = Comments.query.filter(
                 Comments.commented_user_id ==
                 form.commented_user_id.data).order_by(
                     Comments.timestamp.desc()).all()
         except:
             return make_response(
                 jsonify({'error': 'Database Connection Error'}), 500)
         if len(user_comments) == 0:
             return make_response(jsonify({'result': []}), 200)
         return_list = []
         for comment in user_comments:
             try:
                 commenter = User.query.filter(
                     User.id == comment.owner_id).first()
             except:
                 return make_response(
                     jsonify({'error': 'Database Connection Error'}), 500)
             if commenter is None:
                 return make_response(
                     jsonify({'error': 'Commenter is None, smth wrong'}),
                     500)
             return_list.append({
                 "comment_id":
                 comment.id,
                 "owner_id":
                 comment.owner_id,
                 "owner_name":
                 commenter.name,
                 "owner_surname":
                 commenter.surname,
                 "owner_profile_photo":
                 profile_photo_link(commenter.profile_photo, commenter.id),
                 "commented_user_id":
                 comment.commented_user_id,
                 "timestamp":
                 comment.timestamp,
                 "rate":
                 comment.rate,
                 "text":
                 comment.text
             })
         # Pagination functionality
         number_of_pages = 1
         if form.page.data is not None and form.per_page.data is not None:
             per_page = form.per_page.data
             number_of_pages = math.ceil(len(return_list) / per_page)
             # Assign the page index to the maximum if it exceeds the max index
             page = form.page.data if form.page.data < number_of_pages else number_of_pages - 1
             return_list = return_list[page * per_page:(page + 1) *
                                       per_page]
         return make_response(
             jsonify({
                 'number_of_pages': number_of_pages,
                 'result': return_list
             }), 200)
     else:
         return make_response(jsonify({'error': 'Input Format Error'}), 400)
Beispiel #13
0
    def delete(user_id, self):
        '''
            Takes the follower_id and following_id as inputs and replies the corresponding Follow Request.
        '''
        form = ReplyFollowRequestsForm(request.form)
        if form.validate():

            # Current user should be the following.
            if user_id != form.following_id.data:
                return make_response(jsonify({'error': 'Unauthorized'}), 401)

            # Check if the given FollowRequest instance exists.
            try:
                followSearch = FollowRequests.query.filter(
                    FollowRequests.following_id == form.following_id.data,
                    FollowRequests.follower_id == form.follower_id.data).all()
            except:
                return make_response(
                    jsonify({'error': 'Database Connection Error'}), 500)

            if len(followSearch) == 0:
                return make_response(
                    jsonify({'error': 'Follow Request not found'}), 404)

            follow_request = followSearch[0]

            # Accept if the state of the reply is 1.
            if form.state.data == 1:
                new_follow_entry = Follow(follow_request.follower_id,
                                          follow_request.following_id)
                try:
                    db.session.add(new_follow_entry)
                    db.session.delete(follow_request)
                    db.session.commit()
                except:
                    return make_response(
                        jsonify({'error': 'Database Connection Error'}), 500)
                # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                # Add notification to follower that his/her follow request is accepted.
                try:
                    follower_user = User.query.filter(
                        User.id == follow_request.follower_id).first()
                    following_user = User.query.filter(
                        User.id == follow_request.following_id).first()
                    text = "{} accepted your follow request".format(
                        following_user.name + " " + following_user.surname)
                    NotificationManager.add_notification(
                        follower_user.id, [following_user.id], text)
                except:
                    return make_response(
                        jsonify({'error': 'Database Connection Error'}), 500)
                # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                # Add this activity into Activity Stream
                activity_stream_entry = ActivityStreamItem(
                    activity_context_vocab=
                    "https://www.w3.org/ns/activitystreams",
                    activity_summary="{} {} started following {} {}".format(
                        follower_user.name, follower_user.surname,
                        following_user.name, following_user.surname),
                    activity_type="Follow",
                    activity_actor_type="Person",
                    activity_actor_id=follower_user.id,
                    activity_actor_name=(follower_user.name + " " +
                                         follower_user.surname),
                    activity_actor_image_url=profile_photo_link(
                        follower_user.profile_photo, follower_user.id),
                    activity_object_type="Person",
                    activity_object_id=following_user.id,
                    activity_object_name=following_user.name + " " +
                    following_user.surname,
                    activity_object_image_url=profile_photo_link(
                        following_user.profile_photo, following_user.id))
                try:
                    db.session.add(activity_stream_entry)
                    db.session.commit()
                except:
                    return make_response(
                        jsonify({'error': 'Database Connection Error'}), 500)

            # Reject if the state of the reply is 2.
            elif form.state.data == 2:
                try:
                    db.session.delete(follow_request)
                    db.session.commit()
                except:
                    return make_response(
                        jsonify({'error': 'Database Connection Problem'}), 500)

            # Return error if the state of reply is other than 1 or 2.
            else:
                return make_response(
                    jsonify({
                        'error':
                        'State of FollowRequest answer can only be 1 or 2!'
                    }), 400)

            return make_response(
                jsonify({'msg': 'Follow Request is successfully replied'}),
                200)

        else:
            return make_response(jsonify({'error': 'Input Format Error'}), 400)
Beispiel #14
0
    def get(self):
        form = TagSearchForm(request.args)
        if form.validate():
            skill_list = json.loads(form.skills.data)
            # Find the ids of the skills
            try:
                skill_ids = [
                    Skills.query.filter_by(name=skill.title()).first().id
                    for skill in skill_list
                ]
            except:
                return make_response(
                    jsonify({"error": "Database Connection Problem."}), 500)
            result_lists = []
            # Return Users
            if form.search_type.data == 0:
                for skill_id in skill_ids:
                    try:
                        user_ids = [
                            user_skill.user_id
                            for user_skill in UserSkills.query.filter_by(
                                skill_id=skill_id).all()
                        ]
                    except:
                        return make_response(
                            jsonify({"error": "Database Connection Problem."}),
                            500)
                    result_lists.append(set(user_ids))
                result_list = set.intersection(*result_lists)
                result_response = []
                for user_id in result_list:
                    try:
                        user = User.query.get(user_id)
                        result_response.append({
                            "id":
                            user.id,
                            "name":
                            user.name,
                            "surname":
                            user.surname,
                            "profile_photo":
                            profile_photo_link(user.profile_photo, user.id),
                            "job":
                            Jobs.query.get(user.job_id).name,
                            "institution":
                            user.institution
                        })
                    except:
                        return make_response(
                            jsonify({"error": "Database Connection Problem."}),
                            500)
            else:
                for skill_id in skill_ids:
                    try:
                        ws_ids = [
                            ws_skill.workspace_id
                            for ws_skill in WorkspaceSkill.query.filter_by(
                                skill_id=skill_id).all()
                        ]
                    except:
                        return make_response(
                            jsonify({"error": "Database Connection Problem."}),
                            500)
                    result_lists.append(set(ws_ids))
                result_list = set.intersection(*result_lists)
                result_response = []
                for ws_id in result_list:
                    try:
                        ws = Workspace.query.get(ws_id)
                    except:
                        return make_response(
                            jsonify({"error": "Database Connection Problem."}),
                            500)
                    if ws.is_private:
                        continue
                    try:
                        contributors = Contribution.query.filter(
                            Contribution.workspace_id == ws.id).all()
                    except:
                        return make_response(
                            jsonify({"error": "Database Connection Error"}),
                            500)
                    contributor_list = []
                    for contributor in contributors:
                        try:
                            user = User.query.get(contributor.user_id)
                        except:
                            return make_response(
                                jsonify({"error":
                                         "Database Connection Error"}), 500)
                        contributor_list.append({
                            "id": user.id,
                            "name": user.name,
                            "surname": user.surname
                        })
                    try:
                        creator_info = User.query.filter(
                            User.id == ws.creator_id).first()
                    except:
                        return make_response(
                            jsonify({"error": "Database Connection Error"}),
                            500)
                    result_response.append({
                        "id":
                        ws.id,
                        "title":
                        ws.title,
                        "is_private":
                        int(ws.is_private),
                        "description":
                        ws.description,
                        "state":
                        ws.state,
                        "deadline":
                        ws.deadline,
                        "creation_time":
                        ws.timestamp,
                        "max_contributors":
                        ws.max_collaborators,
                        "contributor_list":
                        contributor_list,
                        "creator_id":
                        creator_info.id,
                        "creator_name":
                        creator_info.name,
                        "creator_surname":
                        creator_info.surname
                    })

            # Apply Pagination
            number_of_pages = 1
            if form.page.data is not None and form.per_page.data is not None:
                per_page = form.per_page.data
                number_of_pages = math.ceil(len(result_list) / per_page)
                page = form.page.data if form.page.data < number_of_pages else number_of_pages - 1
                result_response = result_response[page * per_page:(page + 1) *
                                                  per_page]

            return make_response(
                jsonify({
                    "result_list": result_response,
                    "number_of_pages": number_of_pages
                }), 200 + form.search_type.data)
        else:
            return make_response(
                jsonify({"error": "Missing data fields or invalid data."}),
                400)
Beispiel #15
0
    def get(self):

        form = UserSearchForm(request.args)
        if form.validate():
            search_query = form.search_query.data.lower()
            # Remove the punctuation in the search query
            search_query = SearchEngine.remove_punctuation(search_query)
            # Tokenize the search query
            tokens = search_query.split()
            # Get stopwords form the API
            stopwords = SearchEngine.get_stopwords()
            # Remove stopwords from the list of tokens
            tokens = list(set(tokens) - set(stopwords))
            # Get the semantically related list for our tokens
            tokens = SearchEngine.semantic_related_list(tokens)
            # List of user dictionaries that will be send as a search output
            result_list = []
            # Score of each user record
            result_id_score = []
            # Search tokens in Jobs Table
            for token, score in tokens:
                try:
                    related_job = Jobs.query.filter(
                        func.lower(Jobs.name) == token).first()
                except:
                    return make_response(
                        jsonify({"error": "Database Connection Problem."}),
                        500)
                if related_job is not None:
                    try:
                        owner_list = User.query.filter(
                            User.job_id == related_job.id).all()
                    except:
                        return make_response(
                            jsonify({"error": "Database Connection Problem."}),
                            500)
                    for user in owner_list:
                        id_list = [i[0] for i in result_id_score]
                        if user.id not in id_list:
                            if user.is_valid == 0:
                                continue
                            result_list.append({
                                "id":
                                user.id,
                                "name":
                                user.name,
                                "surname":
                                user.surname,
                                "profile_photo":
                                profile_photo_link(user.profile_photo,
                                                   user.id),
                                "is_private":
                                int(user.is_private),
                                "job_id":
                                user.job_id
                            })
                            result_id_score.append((user.id, score))
                        else:
                            id_index = id_list.index(user.id)
                            result_id_score[id_index] = (
                                user.id, result_id_score[id_index][1] + score)
            # Search tokens in Skills Table
            for token, score in tokens:
                try:
                    related_skill = Skills.query.filter(
                        func.lower(Skills.name) == token).first()
                except:
                    return make_response(
                        jsonify({"error": "Database Connection Problem."}),
                        500)
                if related_skill is not None:
                    try:
                        owner_id_list = UserSkills.query.filter(
                            UserSkills.skill_id == related_skill.id).all()
                    except:
                        return make_response(
                            jsonify({"error": "Database Connection Problem."}),
                            500)
                    for owner_id in owner_id_list:
                        # Creates the list of currently found ids
                        id_list = [i[0] for i in result_id_score]
                        if owner_id.user_id not in id_list:
                            # Take user information from the DB
                            try:
                                user = User.query.filter(
                                    User.id == owner_id.user_id).first()
                            except:
                                return make_response(
                                    jsonify({
                                        "error":
                                        "Database Connection Problem."
                                    }), 500)
                            if user.is_valid == 0:
                                continue
                            result_list.append({
                                "id":
                                user.id,
                                "name":
                                user.name,
                                "surname":
                                user.surname,
                                "profile_photo":
                                profile_photo_link(user.profile_photo,
                                                   user.id),
                                "is_private":
                                int(user.is_private),
                                "job_id":
                                user.job_id
                            })
                            result_id_score.append((user.id, score))
                        else:
                            id_index = id_list.index(owner_id.user_id)
                            result_id_score[id_index] = (
                                user.id, result_id_score[id_index][1] + score)
            # Search tokens for name, surname, institution or email match
            for token, score in tokens:
                try:
                    query = '(LOWER(name) REGEXP ".*{0}.*" OR LOWER(surname) REGEXP ".*{0}.*" \
                    OR LOWER(`e_mail`) REGEXP ".*{0}.*" OR LOWER(institution) REGEXP ".*{0}.*")' \
                    .format(token)
                    sql_statement = "SELECT id,name,surname,profile_photo,is_private,job_id,is_valid FROM users WHERE {}".format(
                        query)
                    result = db.engine.execute(sql_statement)
                    for user in result:
                        id_list = [i[0] for i in result_id_score]
                        if user[0] not in id_list:
                            if user[-1] == 0:
                                continue
                            result_list.append({
                                "id":
                                user[0],
                                "name":
                                user[1],
                                "surname":
                                user[2],
                                "profile_photo":
                                profile_photo_link(user[3], user[0]),
                                "is_private":
                                int(user[4]),
                                "job_id":
                                user.job_id
                            })
                            result_id_score.append((user[0], score))
                        else:
                            id_index = id_list.index(user[0])
                            result_id_score[id_index] = (
                                user[0], result_id_score[id_index][1] + score)
                except:
                    return make_response(
                        jsonify({"error": "Database Connection Problem."}),
                        500)
            sorted_result_list = []
            # Sort result ids according to their scores
            if form.sorting_criteria.data is None:
                sorted_id_list = SearchEngine.sort_ids(result_id_score)
                for user_id, score in sorted_id_list:
                    index = [user["id"] for user in result_list].index(user_id)
                    sorted_result_list.append(result_list[index])
            # Sort Results according to Sorting Criteria
            else:
                reverse = form.sorting_criteria.data == 1
                sorted_result_list = SearchEngine.sort_results(
                    result_list, ["name", "surname"], reverse)

            # Apply given filters
            if form.job_filter.data is not None:
                for i, user in enumerate(sorted_result_list):
                    if user["job_id"] != form.job_filter.data:
                        sorted_result_list.pop(i)
            number_of_pages = 1
            # Apply Pagination
            if form.page.data is not None and form.per_page.data is not None:
                per_page = form.per_page.data
                number_of_pages = math.ceil(len(sorted_result_list) / per_page)
                page = form.page.data if form.page.data < number_of_pages else number_of_pages - 1
                sorted_result_list = sorted_result_list[page *
                                                        per_page:(page + 1) *
                                                        per_page]
            # Add Search History Item
            try:
                auth_token = request.headers.get('auth_token')
                SearchEngine.add_search_history_item(decode_token(auth_token),
                                                     search_query,
                                                     int(SearchType.USER))
            except:
                pass
            # Remove Non-Valid Users
            return make_response(
                jsonify({
                    "number_of_pages": number_of_pages,
                    "result_list": sorted_result_list
                }))
        return make_response(
            jsonify({"error": "Missing data fields or invalid data."}), 400)