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_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)
示例#3
0
 def accept_reject_invitation_request_for_team(
     from_user: int,
     from_username: str,
     to_user: int,
     sending_member: str,
     team_name: str,
     team_id: int,
     response: str,
 ):
     message = Message()
     message.message_type = MessageType.INVITATION_NOTIFICATION.value
     message.from_user_id = from_user
     message.to_user_id = to_user
     message.subject = "{} {}ed to join {}".format(
         MessageService.get_user_link(from_username),
         response,
         MessageService.get_team_link(team_name, team_id, True),
     )
     message.message = "{} has {}ed {}'s invitation to join the {} team.".format(
         MessageService.get_user_link(from_username),
         response,
         sending_member,
         MessageService.get_team_link(team_name, team_id, True),
     )
     message.add_message()
     message.save()
示例#4
0
    def send_welcome_message(user: User):
        """Sends welcome message to new user at Sign up"""
        org_code = current_app.config["ORG_CODE"]
        text_template = get_txt_template("welcome_message_en.txt")
        hot_welcome_section = get_txt_template("hot_welcome_section_en.txt")
        replace_list = [
            ["[USERNAME]", user.username],
            ["[ORG_CODE]", org_code],
            ["[ORG_NAME]", current_app.config["ORG_NAME"]],
            ["[SETTINGS_LINK]",
             MessageService.get_user_settings_link()],
            [
                "[HOT_WELCOME]",
                hot_welcome_section if org_code == "HOT" else ""
            ],
        ]
        text_template = template_var_replacing(text_template, replace_list)

        welcome_message = Message()
        welcome_message.message_type = MessageType.SYSTEM.value
        welcome_message.to_user_id = user.id
        welcome_message.subject = "Welcome to the {} Tasking Manager".format(
            org_code)
        welcome_message.message = text_template
        welcome_message.save()

        return welcome_message.id
    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)
示例#6
0
    def notify_level_upgrade(user_id: int, username: str, level: str):
        text_template = get_template("level_upgrade_message_en.txt")

        if username is not None:
            text_template = text_template.replace("[USERNAME]", username)

        text_template = text_template.replace("[LEVEL]", level)
        level_upgrade_message = Message()
        level_upgrade_message.to_user_id = user_id
        level_upgrade_message.subject = "Mapper Level Upgrade "
        level_upgrade_message.message = text_template
        level_upgrade_message.save()
    def send_invite_to_join_team(from_user: int, from_username: str,
                                 to_user: int, team_name: str) -> Message:
        message = Message()
        message.message_type = MessageType.INVITATION_NOTIFICATION.value
        message.from_user_id = from_user
        message.to_user_id = to_user
        message.subject = "Invitation to join the team"
        message.message = f'<a href="http://127.0.0.1:5000/user/{from_username}">{from_username}\
            </a> has invited you to join the {team_name} team'

        message.add_message()
        message.save()
 def accept_reject_request_to_join_team(
     from_user: int, from_username: str, to_user: int, team_name: str, response: str
 ) -> Message:
     message = Message()
     message.message_type = MessageType.REQUEST_TEAM_NOTIFICATION.value
     message.from_user_id = from_user
     message.to_user_id = to_user
     message.subject = "Request to join team"
     message.message = f'<a href="http://127.0.0.1:5000/user/{from_username}">{from_username}\
         </a> has {response}ed your request to join the {team_name} team'
     message.add_message()
     message.save()
    def send_request_to_join_team(from_user: int, from_username: str,
                                  to_user: int, team_name: str) -> Message:

        base_url = current_app.config["APP_BASE_URL"]
        message = Message()
        message.message_type = MessageType.REQUEST_TEAM_NOTIFICATION.value
        message.from_user_id = from_user
        message.to_user_id = to_user
        message.subject = "Request to join team"
        message.message = f'<a href="{base_url}/user/{from_username}">{from_username}\
            </a> has requested to join the {team_name} team'

        message.add_message()
        message.save()
示例#10
0
    def notify_level_upgrade(user_id: int, username: str, level: str):
        text_template = get_txt_template("level_upgrade_message_en.txt")
        replace_list = [
            ["[USERNAME]", username],
            ["[LEVEL]", level],
            ["[ORG_CODE]", current_app.config["ORG_CODE"]],
        ]
        text_template = template_var_replacing(text_template, replace_list)

        level_upgrade_message = Message()
        level_upgrade_message.to_user_id = user_id
        level_upgrade_message.subject = "Mapper level upgrade"
        level_upgrade_message.message = text_template
        level_upgrade_message.save()
示例#11
0
 def send_invite_to_join_team(from_user: int, from_username: str,
                              to_user: int, team_name: str, team_id: int):
     message = Message()
     message.message_type = MessageType.INVITATION_NOTIFICATION.value
     message.from_user_id = from_user
     message.to_user_id = to_user
     message.subject = "Invitation to join {}".format(
         MessageService.get_team_link(team_name, team_id, False))
     message.message = "{} has invited you to join the {} team.\
         Access the {}'s page to accept or reject that invitation.".format(
         MessageService.get_user_link(from_username),
         MessageService.get_team_link(team_name, team_id, False),
         MessageService.get_team_link(team_name, team_id, False),
     )
     message.add_message()
     message.save()
    def send_welcome_message(user: User):
        """ Sends welcome message to all new users at Sign up"""
        text_template = get_template("welcome_message_en.txt")

        text_template = text_template.replace("[USERNAME]", user.username)
        text_template = text_template.replace("[PROFILE_LINK]",
                                              get_profile_url(user.username))

        welcome_message = Message()
        welcome_message.message_type = MessageType.SYSTEM.value
        welcome_message.to_user_id = user.id
        welcome_message.subject = "Welcome to the HOT Tasking Manager"
        welcome_message.message = text_template
        welcome_message.save()

        return welcome_message.id
示例#13
0
 def send_request_to_join_team(from_user: int, from_username: str,
                               to_user: int, team_name: str, team_id: int):
     message = Message()
     message.message_type = MessageType.REQUEST_TEAM_NOTIFICATION.value
     message.from_user_id = from_user
     message.to_user_id = to_user
     message.subject = "{} requested to join {}".format(
         MessageService.get_user_link(from_username),
         MessageService.get_team_link(team_name, team_id, True),
     )
     message.message = "{} has requested to join the {} team.\
         Access the team management page to accept or reject that request.".format(
         MessageService.get_user_link(from_username),
         MessageService.get_team_link(team_name, team_id, True),
     )
     message.add_message()
     message.save()
 def accept_reject_invitation_request_for_team(
     from_user: int,
     from_username: str,
     to_user: int,
     sending_member: str,
     team_name: str,
     response: str,
 ) -> Message:
     message = Message()
     message.message_type = MessageType.INVITATION_NOTIFICATION.value
     message.from_user_id = from_user
     message.to_user_id = to_user
     message.subject = "Request to join team"
     message.message = f'<a href="http://127.0.0.1:5000/user/{from_username}">{from_username}\
         </a> has {response}ed {sending_member}\'s invitation to join the {team_name} team'
     message.add_message()
     message.save()
    def send_message_after_validation(
        status: int, validated_by: int, mapped_by: int, task_id: int, project_id: int
    ):
        """ Sends mapper a notification after their task has been marked valid or invalid """
        if validated_by == mapped_by:
            return  # No need to send a notification if you've verified your own task

        user = UserService.get_user_by_id(mapped_by)
        text_template = get_txt_template(
            "invalidation_message_en.txt"
            if status == TaskStatus.INVALIDATED
            else "validation_message_en.txt"
        )
        status_text = (
            "marked invalid" if status == TaskStatus.INVALIDATED else "validated"
        )
        task_link = MessageService.get_task_link(project_id, task_id)
        replace_list = [
            ["[USERNAME]", user.username],
            ["[TASK_LINK]", task_link],
            ["[ORG_NAME]", current_app.config["ORG_NAME"]],
        ]
        text_template = template_var_replacing(text_template, replace_list)

        messages = []
        validation_message = Message()
        validation_message.message_type = (
            MessageType.INVALIDATION_NOTIFICATION.value
            if status == TaskStatus.INVALIDATED
            else MessageType.VALIDATION_NOTIFICATION.value
        )
        validation_message.project_id = project_id
        validation_message.task_id = task_id
        validation_message.from_user_id = validated_by
        validation_message.to_user_id = mapped_by
        validation_message.subject = (
            f"{task_link} mapped by you in Project {project_id} has been {status_text}"
        )
        validation_message.message = text_template
        messages.append(dict(message=validation_message, user=user))

        # For email alerts
        MessageService._push_messages(messages)
示例#16
0
    def send_message_after_validation(
        status: int, validated_by: int, mapped_by: int, task_id: int, project_id: int
    ):
        """ Sends mapper a notification after their task has been marked valid or invalid """
        if validated_by == mapped_by:
            return  # No need to send a message to yourself

        user = UserService.get_user_by_id(mapped_by)
        if user.validation_message is False:
            return  # No need to send validation message
        if user.projects_notifications is False:
            return

        text_template = get_template(
            "invalidation_message_en.txt"
            if status == TaskStatus.INVALIDATED
            else "validation_message_en.txt"
        )
        status_text = (
            "marked invalid" if status == TaskStatus.INVALIDATED else "validated"
        )
        task_link = MessageService.get_task_link(project_id, task_id)
        text_template = text_template.replace("[USERNAME]", user.username)
        text_template = text_template.replace("[TASK_LINK]", task_link)

        validation_message = Message()
        validation_message.message_type = (
            MessageType.INVALIDATION_NOTIFICATION.value
            if status == TaskStatus.INVALIDATED
            else MessageType.VALIDATION_NOTIFICATION.value
        )
        validation_message.project_id = project_id
        validation_message.task_id = task_id
        validation_message.from_user_id = validated_by
        validation_message.to_user_id = mapped_by
        validation_message.subject = f"Your mapping in Project {project_id} on {task_link} has just been {status_text}"
        validation_message.message = text_template
        validation_message.add_message()

        SMTPService.send_email_alert(
            user.email_address, user.username, validation_message.id
        )
示例#17
0
 def accept_reject_request_to_join_team(
     from_user: int,
     from_username: str,
     to_user: int,
     team_name: str,
     team_id: int,
     response: str,
 ):
     message = Message()
     message.message_type = MessageType.REQUEST_TEAM_NOTIFICATION.value
     message.from_user_id = from_user
     message.to_user_id = to_user
     message.subject = "Request to join {} was {}ed".format(
         MessageService.get_team_link(team_name, team_id, False), response)
     message.message = "{} has {}ed your request to join the {} team.".format(
         MessageService.get_user_link(from_username),
         response,
         MessageService.get_team_link(team_name, team_id, False),
     )
     message.add_message()
     message.save()
示例#18
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)