def send_message_after_chat(chat_from: int, chat: str, project_id: int):
        """ Send alert to user if they were @'d in a chat message """
        current_app.logger.debug("Sending Message After Chat")
        usernames = MessageService._parse_message_for_username(
            chat, project_id)

        if len(usernames) == 0:
            return  # Nobody @'d so return

        link = MessageService.get_project_link(project_id,
                                               include_chat_section=True)

        messages = []
        for username in usernames:
            current_app.logger.debug(f"Searching for {username}")
            try:
                user = UserService.get_user_by_username(username)
            except NotFound:
                current_app.logger.error(f"Username {username} not found")
                continue  # If we can't find the user, keep going no need to fail

            message = Message()
            message.message_type = MessageType.MENTION_NOTIFICATION.value
            message.project_id = project_id
            message.from_user_id = chat_from
            message.to_user_id = user.id
            message.subject = f"You were mentioned in {link} chat"
            message.message = chat
            messages.append(dict(message=message, user=user))

        MessageService._push_messages(messages)

        query = (
            """ select user_id from project_favorites where project_id = :project_id"""
        )
        result = db.engine.execute(text(query), project_id=project_id)
        favorited_users = [r[0] for r in result]

        if len(favorited_users) != 0:
            project_link = MessageService.get_project_link(
                project_id, include_chat_section=True)
            # project_title = ProjectService.get_project_title(project_id)
            messages = []
            for user_id in favorited_users:

                try:
                    user = UserService.get_user_dto_by_id(user_id)
                except NotFound:
                    continue  # If we can't find the user, keep going no need to fail

                message = Message()
                message.message_type = MessageType.PROJECT_CHAT_NOTIFICATION.value
                message.project_id = project_id
                message.to_user_id = user.id
                message.subject = f"{chat_from} left a comment in {project_link}"
                message.message = chat
                messages.append(dict(message=message, user=user))

            # it's important to keep that line inside the if to avoid duplicated emails
            MessageService._push_messages(messages)
    def send_message_after_comment(comment_from: int, comment: str,
                                   task_id: int, project_id: int):
        """ Will send a canned message to anyone @'d in a comment """
        usernames = MessageService._parse_message_for_username(
            comment, project_id)
        if len(usernames) != 0:
            task_link = MessageService.get_task_link(project_id, task_id)

            messages = []
            for username in usernames:

                try:
                    user = UserService.get_user_by_username(username)
                except NotFound:
                    continue  # If we can't find the user, keep going no need to fail

                message = Message()
                message.message_type = MessageType.MENTION_NOTIFICATION.value
                message.project_id = project_id
                message.task_id = task_id
                message.from_user_id = comment_from
                message.to_user_id = user.id
                message.subject = f"You were mentioned in a comment in {task_link} of Project {project_id}"
                message.message = comment
                messages.append(dict(message=message, user=user))

            MessageService._push_messages(messages)

        # Notify all contributors except the user that created the comment.
        results = (TaskHistory.query.with_entities(
            TaskHistory.user_id.distinct()
        ).filter(TaskHistory.project_id == project_id).filter(
            TaskHistory.task_id == task_id).filter(
                TaskHistory.user_id != comment_from).filter(
                    TaskHistory.action == TaskAction.STATE_CHANGE.name).all())
        contributed_users = [r[0] for r in results]

        if len(contributed_users) != 0:
            user_from = User.query.get(comment_from)
            if user_from is None:
                raise ValueError("Username not found")

            task_link = MessageService.get_task_link(project_id, task_id)
            messages = []
            for user_id in contributed_users:
                try:
                    user = UserService.get_user_dto_by_id(user_id)
                except NotFound:
                    continue  # If we can't find the user, keep going no need to fail

                message = Message()
                message.message_type = MessageType.TASK_COMMENT_NOTIFICATION.value
                message.project_id = project_id
                message.task_id = task_id
                message.to_user_id = user.id
                message.subject = f"{user_from.username} left a comment in {task_link} of Project {project_id}"
                message.message = comment
                messages.append(dict(message=message, user=user))

            MessageService._push_messages(messages)
    def send_favorite_project_activities(user_id: int):
        current_app.logger.debug("Sending Favorite Project Activities")
        favorited_projects = UserService.get_projects_favorited(user_id)
        contributed_projects = UserService.get_projects_mapped(user_id)
        if contributed_projects is None:
            contributed_projects = []

        for favorited_project in favorited_projects.favorited_projects:
            contributed_projects.append(favorited_project.project_id)

        recently_updated_projects = (
            Project.query.with_entities(
                Project.id, func.DATE(Project.last_updated).label("last_updated")
            )
            .filter(Project.id.in_(contributed_projects))
            .filter(
                func.DATE(Project.last_updated)
                > datetime.date.today() - datetime.timedelta(days=300)
            )
        )
        user = UserService.get_user_dto_by_id(user_id)
        if user.projects_notifications is False:
            return
        messages = []
        for project in recently_updated_projects:
            activity_message = []
            query_last_active_users = """ select distinct(user_id) from
                                        (select user_id from task_history where project_id = :project_id
                                        order by action_date desc limit 15 ) t """
            last_active_users = db.engine.execute(
                text(query_last_active_users), project_id=project.id
            )

            for recent_user_id in last_active_users:
                recent_user_details = UserService.get_user_by_id(recent_user_id)
                user_profile_link = MessageService.get_user_profile_link(
                    recent_user_details.username
                )
                activity_message.append(user_profile_link)

            activity_message = str(activity_message)[1:-1]
            project_link = MessageService.get_project_link(project.id)
            message = Message()
            message.message_type = MessageType.PROJECT_ACTIVITY_NOTIFICATION.value
            message.project_id = project.id
            message.to_user_id = user.id
            message.subject = (
                "Recent activities from your contributed/favorited Projects"
            )
            message.message = (
                f"{activity_message} contributed to Project {project_link} recently"
            )
            messages.append(dict(message=message, user=user))

        MessageService._push_messages(messages)
示例#4
0
 def get(self, user_id):
     """
     Get user information by id
     ---
     tags:
       - users
     produces:
       - application/json
     parameters:
         - in: header
           name: Authorization
           description: Base64 encoded session token
           required: true
           type: string
           default: Token sessionTokenHere==
         - name: user_id
           in: path
           description: The id of the user
           required: true
           type: integer
           default: 1
     responses:
         200:
             description: User found
         401:
             description: Unauthorized - Invalid credentials
         404:
             description: User not found
         500:
             description: Internal Server Error
     """
     try:
         user_dto = UserService.get_user_dto_by_id(
             user_id, token_auth.current_user()
         )
         return user_dto.to_primitive(), 200
     except NotFound:
         return {"Error": "User not found"}, 404
     except Exception as e:
         error_msg = f"Userid GET - unhandled error: {str(e)}"
         current_app.logger.critical(error_msg)
         return {"Error": "Unable to fetch user details"}, 500
示例#5
0
    def send_message_after_chat(chat_from: int, chat: str, project_id: int):
        """ Send alert to user if they were @'d in a chat message """
        # Because message-all run on background thread it needs it's own app context
        app = create_app()
        with app.app_context():
            usernames = MessageService._parse_message_for_username(
                chat, project_id)
            if len(usernames) != 0:
                link = MessageService.get_project_link(
                    project_id, include_chat_section=True)
                messages = []
                for username in usernames:
                    current_app.logger.debug(f"Searching for {username}")
                    try:
                        user = UserService.get_user_by_username(username)
                    except NotFound:
                        current_app.logger.error(
                            f"Username {username} not found")
                        continue  # If we can't find the user, keep going no need to fail

                    message = Message()
                    message.message_type = MessageType.MENTION_NOTIFICATION.value
                    message.project_id = project_id
                    message.from_user_id = chat_from
                    message.to_user_id = user.id
                    message.subject = f"You were mentioned in {link} chat"
                    message.message = chat
                    messages.append(dict(message=message, user=user))

                MessageService._push_messages(messages)

            query = """ select user_id from project_favorites where project_id = :project_id"""
            favorited_users_results = db.engine.execute(text(query),
                                                        project_id=project_id)
            favorited_users = [r[0] for r in favorited_users_results]

            # Notify all contributors except the user that created the comment.
            contributed_users_results = (TaskHistory.query.with_entities(
                TaskHistory.user_id.distinct()
            ).filter(TaskHistory.project_id == project_id).filter(
                TaskHistory.user_id != chat_from).filter(
                    TaskHistory.action == TaskAction.STATE_CHANGE.name).all())
            contributed_users = [r[0] for r in contributed_users_results]

            users_to_notify = list(set(contributed_users + favorited_users))

            if len(users_to_notify) != 0:
                from_user = User.query.get(chat_from)
                from_user_link = MessageService.get_user_link(
                    from_user.username)
                project_link = MessageService.get_project_link(
                    project_id, include_chat_section=True)
                messages = []
                for user_id in users_to_notify:
                    try:
                        user = UserService.get_user_dto_by_id(user_id)
                    except NotFound:
                        continue  # If we can't find the user, keep going no need to fail
                    message = Message()
                    message.message_type = MessageType.PROJECT_CHAT_NOTIFICATION.value
                    message.project_id = project_id
                    message.from_user_id = chat_from
                    message.to_user_id = user.id
                    message.subject = (
                        f"{from_user_link} left a comment in {project_link}")
                    message.message = chat
                    messages.append(dict(message=message, user=user))

                # it's important to keep that line inside the if to avoid duplicated emails
                MessageService._push_messages(messages)